blob: 34115c03d1cdb8e4da49ac2e4ba649eb195b8780 [file] [log] [blame]
Tony-LunarG73719992020-01-15 10:20:28 -07001/* Copyright (c) 2015-2020 The Khronos Group Inc.
2 * Copyright (c) 2015-2020 Valve Corporation
3 * Copyright (c) 2015-2020 LunarG, Inc.
4 * Copyright (C) 2015-2020 Google Inc.
Chris Forbes47567b72017-06-09 12:09:45 -07005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Chris Forbes <chrisf@ijw.co.nz>
Dave Houlton51653902018-06-22 17:32:13 -060019 * Author: Dave Houlton <daveh@lunarg.com>
Chris Forbes47567b72017-06-09 12:09:45 -070020 */
21
Petr Kraus25810d02019-08-27 17:41:15 +020022#include "shader_validation.h"
23
Chris Forbes47567b72017-06-09 12:09:45 -070024#include <cassert>
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +020025#include <chrono>
Petr Kraus25810d02019-08-27 17:41:15 +020026#include <cinttypes>
Jeff Bolzf234bf82019-11-04 14:07:15 -060027#include <cmath>
Petr Kraus25810d02019-08-27 17:41:15 +020028#include <map>
Chris Forbes47567b72017-06-09 12:09:45 -070029#include <sstream>
Petr Kraus25810d02019-08-27 17:41:15 +020030#include <string>
31#include <unordered_map>
32#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.
115 if (func_set.offset)
116 func_set.op_lists.insert({insn.opcode(), insn.offset()});
117 else if (entry_point) {
118 entry_point->decorate_list.insert({insn.opcode(), insn.offset()});
119 }
120
Chris Forbes47567b72017-06-09 12:09:45 -0700121 switch (insn.opcode()) {
122 // Types
123 case spv::OpTypeVoid:
124 case spv::OpTypeBool:
125 case spv::OpTypeInt:
126 case spv::OpTypeFloat:
127 case spv::OpTypeVector:
128 case spv::OpTypeMatrix:
129 case spv::OpTypeImage:
130 case spv::OpTypeSampler:
131 case spv::OpTypeSampledImage:
132 case spv::OpTypeArray:
133 case spv::OpTypeRuntimeArray:
134 case spv::OpTypeStruct:
135 case spv::OpTypeOpaque:
136 case spv::OpTypePointer:
137 case spv::OpTypeFunction:
138 case spv::OpTypeEvent:
139 case spv::OpTypeDeviceEvent:
140 case spv::OpTypeReserveId:
141 case spv::OpTypeQueue:
142 case spv::OpTypePipe:
Shannon McPherson0fa28232018-11-01 11:59:02 -0600143 case spv::OpTypeAccelerationStructureNV:
Jeff Bolze4356752019-03-07 11:23:46 -0600144 case spv::OpTypeCooperativeMatrixNV:
Chris Forbes47567b72017-06-09 12:09:45 -0700145 def_index[insn.word(1)] = insn.offset();
146 break;
147
148 // Fixed constants
149 case spv::OpConstantTrue:
150 case spv::OpConstantFalse:
151 case spv::OpConstant:
152 case spv::OpConstantComposite:
153 case spv::OpConstantSampler:
154 case spv::OpConstantNull:
155 def_index[insn.word(2)] = insn.offset();
156 break;
157
158 // Specialization constants
159 case spv::OpSpecConstantTrue:
160 case spv::OpSpecConstantFalse:
161 case spv::OpSpecConstant:
162 case spv::OpSpecConstantComposite:
163 case spv::OpSpecConstantOp:
164 def_index[insn.word(2)] = insn.offset();
165 break;
166
167 // Variables
168 case spv::OpVariable:
169 def_index[insn.word(2)] = insn.offset();
170 break;
171
172 // Functions
173 case spv::OpFunction:
174 def_index[insn.word(2)] = insn.offset();
locke-lunargde3f0fa2020-09-10 11:55:31 -0600175 func_set.id = insn.word(2);
176 func_set.offset = insn.offset();
177 func_set.op_lists.clear();
Chris Forbes47567b72017-06-09 12:09:45 -0700178 break;
179
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800180 // Decorations
181 case spv::OpDecorate: {
182 auto targetId = insn.word(1);
183 decorations[targetId].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
184 } break;
185 case spv::OpGroupDecorate: {
186 auto const &src = decorations[insn.word(1)];
187 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
188 } break;
189
John Zulauf14c355b2019-06-27 16:09:37 -0600190 // Entry points ... add to the entrypoint table
191 case spv::OpEntryPoint: {
192 // Entry points do not have an id (the id is the function id) and thus need their own table
193 auto entrypoint_name = (char const *)&insn.word(3);
194 auto execution_model = insn.word(1);
195 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
locke-lunargde3f0fa2020-09-10 11:55:31 -0600196 entry_points.emplace(entrypoint_name,
197 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
198
199 auto range = entry_points.equal_range(entrypoint_name);
200 for (auto it = range.first; it != range.second; ++it) {
201 if (it->second.offset == insn.offset()) {
202 entry_point = &(it->second);
203 break;
204 }
205 }
206 assert(entry_point != nullptr);
207 break;
208 }
209 case spv::OpFunctionEnd: {
210 assert(entry_point != nullptr);
211 func_set.length = insn.offset() - func_set.offset;
212 entry_point->function_set_list.emplace_back(func_set);
John Zulauf14c355b2019-06-27 16:09:37 -0600213 break;
214 }
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800215
Chris Forbes47567b72017-06-09 12:09:45 -0700216 default:
217 // We don't care about any other defs for now.
218 break;
219 }
220 }
221}
222
Jeff Bolz105d6492018-09-29 15:46:44 -0500223unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
224 switch (mode) {
225 case spv::ExecutionModelVertex:
226 return VK_SHADER_STAGE_VERTEX_BIT;
227 case spv::ExecutionModelTessellationControl:
228 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
229 case spv::ExecutionModelTessellationEvaluation:
230 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
231 case spv::ExecutionModelGeometry:
232 return VK_SHADER_STAGE_GEOMETRY_BIT;
233 case spv::ExecutionModelFragment:
234 return VK_SHADER_STAGE_FRAGMENT_BIT;
235 case spv::ExecutionModelGLCompute:
236 return VK_SHADER_STAGE_COMPUTE_BIT;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600237 case spv::ExecutionModelRayGenerationNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700238 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600239 case spv::ExecutionModelAnyHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700240 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600241 case spv::ExecutionModelClosestHitNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700242 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600243 case spv::ExecutionModelMissNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700244 return VK_SHADER_STAGE_MISS_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600245 case spv::ExecutionModelIntersectionNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700246 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600247 case spv::ExecutionModelCallableNV:
Eric Werness30127fd2018-10-31 21:01:03 -0700248 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
Jeff Bolz105d6492018-09-29 15:46:44 -0500249 case spv::ExecutionModelTaskNV:
250 return VK_SHADER_STAGE_TASK_BIT_NV;
251 case spv::ExecutionModelMeshNV:
252 return VK_SHADER_STAGE_MESH_BIT_NV;
253 default:
254 return 0;
255 }
256}
257
locke-lunargde3f0fa2020-09-10 11:55:31 -0600258const SHADER_MODULE_STATE::EntryPoint *FindEntrypointStruct(SHADER_MODULE_STATE const *src, char const *name,
259 VkShaderStageFlagBits stageBits) {
260 auto range = src->entry_points.equal_range(name);
261 for (auto it = range.first; it != range.second; ++it) {
262 if (it->second.stage == stageBits) {
263 return &(it->second);
264 }
265 }
266 return nullptr;
267}
268
locke-lunargd9a069d2019-09-17 01:50:19 -0600269spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
John Zulauf14c355b2019-06-27 16:09:37 -0600270 auto range = src->entry_points.equal_range(name);
271 for (auto it = range.first; it != range.second; ++it) {
272 if (it->second.stage == stageBits) {
273 return src->at(it->second.offset);
Chris Forbes47567b72017-06-09 12:09:45 -0700274 }
275 }
Chris Forbes47567b72017-06-09 12:09:45 -0700276 return src->end();
277}
278
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600279static char const *StorageClassName(unsigned sc) {
Chris Forbes47567b72017-06-09 12:09:45 -0700280 switch (sc) {
281 case spv::StorageClassInput:
282 return "input";
283 case spv::StorageClassOutput:
284 return "output";
285 case spv::StorageClassUniformConstant:
286 return "const uniform";
287 case spv::StorageClassUniform:
288 return "uniform";
289 case spv::StorageClassWorkgroup:
290 return "workgroup local";
291 case spv::StorageClassCrossWorkgroup:
292 return "workgroup global";
293 case spv::StorageClassPrivate:
294 return "private global";
295 case spv::StorageClassFunction:
296 return "function";
297 case spv::StorageClassGeneric:
298 return "generic";
299 case spv::StorageClassAtomicCounter:
300 return "atomic counter";
301 case spv::StorageClassImage:
302 return "image";
303 case spv::StorageClassPushConstant:
304 return "push constant";
Chris Forbes9f89d752018-03-07 12:57:48 -0800305 case spv::StorageClassStorageBuffer:
306 return "storage buffer";
Chris Forbes47567b72017-06-09 12:09:45 -0700307 default:
308 return "unknown";
309 }
310}
311
312// Get the value of an integral constant
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600313unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
Chris Forbes47567b72017-06-09 12:09:45 -0700314 auto value = src->get_def(id);
315 assert(value != src->end());
316
317 if (value.opcode() != spv::OpConstant) {
318 // TODO: Either ensure that the specialization transform is already performed on a module we're
319 // considering here, OR -- specialize on the fly now.
320 return 1;
321 }
322
323 return value.word(3);
324}
325
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600326static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700327 auto insn = src->get_def(type);
328 assert(insn != src->end());
329
330 switch (insn.opcode()) {
331 case spv::OpTypeBool:
332 ss << "bool";
333 break;
334 case spv::OpTypeInt:
335 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
336 break;
337 case spv::OpTypeFloat:
338 ss << "float" << insn.word(2);
339 break;
340 case spv::OpTypeVector:
341 ss << "vec" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600342 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700343 break;
344 case spv::OpTypeMatrix:
345 ss << "mat" << insn.word(3) << " of ";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600346 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700347 break;
348 case spv::OpTypeArray:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600349 ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
350 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700351 break;
Chris Forbes062f1222018-08-21 15:34:15 -0700352 case spv::OpTypeRuntimeArray:
353 ss << "runtime arr[] of ";
354 DescribeTypeInner(ss, src, insn.word(2));
355 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700356 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600357 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
358 DescribeTypeInner(ss, src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700359 break;
360 case spv::OpTypeStruct: {
361 ss << "struct of (";
362 for (unsigned i = 2; i < insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600363 DescribeTypeInner(ss, src, insn.word(i));
Chris Forbes47567b72017-06-09 12:09:45 -0700364 if (i == insn.len() - 1) {
365 ss << ")";
366 } else {
367 ss << ", ";
368 }
369 }
370 break;
371 }
372 case spv::OpTypeSampler:
373 ss << "sampler";
374 break;
375 case spv::OpTypeSampledImage:
376 ss << "sampler+";
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600377 DescribeTypeInner(ss, src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700378 break;
379 case spv::OpTypeImage:
380 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
381 break;
Shannon McPherson0fa28232018-11-01 11:59:02 -0600382 case spv::OpTypeAccelerationStructureNV:
Jeff Bolz105d6492018-09-29 15:46:44 -0500383 ss << "accelerationStruture";
384 break;
Chris Forbes47567b72017-06-09 12:09:45 -0700385 default:
386 ss << "oddtype";
387 break;
388 }
389}
390
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600391static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700392 std::ostringstream ss;
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600393 DescribeTypeInner(ss, src, type);
Chris Forbes47567b72017-06-09 12:09:45 -0700394 return ss.str();
395}
396
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600397static bool IsNarrowNumericType(spirv_inst_iter type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700398 if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
399 return type.word(2) < 64;
400}
401
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600402static 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 -0600403 bool b_arrayed, bool relaxed) {
Chris Forbes47567b72017-06-09 12:09:45 -0700404 // Walk two type trees together, and complain about differences
405 auto a_insn = a->get_def(a_type);
406 auto b_insn = b->get_def(b_type);
407 assert(a_insn != a->end());
408 assert(b_insn != b->end());
409
Chris Forbes062f1222018-08-21 15:34:15 -0700410 // Ignore runtime-sized arrays-- they cannot appear in these interfaces.
411
Chris Forbes47567b72017-06-09 12:09:45 -0700412 if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600413 return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700414 }
415
416 if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
417 // 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 -0600418 return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700419 }
420
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600421 if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
422 return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700423 }
424
425 if (a_insn.opcode() != b_insn.opcode()) {
426 return false;
427 }
428
429 if (a_insn.opcode() == spv::OpTypePointer) {
430 // Match on pointee type. storage class is expected to differ
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600431 return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
Chris Forbes47567b72017-06-09 12:09:45 -0700432 }
433
434 if (a_arrayed || b_arrayed) {
435 // If we havent resolved array-of-verts by here, we're not going to.
436 return false;
437 }
438
439 switch (a_insn.opcode()) {
440 case spv::OpTypeBool:
441 return true;
442 case spv::OpTypeInt:
443 // Match on width, signedness
444 return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
445 case spv::OpTypeFloat:
446 // Match on width
447 return a_insn.word(2) == b_insn.word(2);
448 case spv::OpTypeVector:
449 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600450 if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
451 if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
Chris Forbes47567b72017-06-09 12:09:45 -0700452 return a_insn.word(3) >= b_insn.word(3);
453 } else {
454 return a_insn.word(3) == b_insn.word(3);
455 }
456 case spv::OpTypeMatrix:
457 // Match on element type, count.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600458 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
Dave Houltona9df0ce2018-02-07 10:51:23 -0700459 a_insn.word(3) == b_insn.word(3);
Chris Forbes47567b72017-06-09 12:09:45 -0700460 case spv::OpTypeArray:
461 // Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
462 // 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 -0600463 return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
464 GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700465 case spv::OpTypeStruct:
466 // Match on all element types
Dave Houltona9df0ce2018-02-07 10:51:23 -0700467 {
468 if (a_insn.len() != b_insn.len()) {
469 return false; // Structs cannot match if member counts differ
Chris Forbes47567b72017-06-09 12:09:45 -0700470 }
Chris Forbes47567b72017-06-09 12:09:45 -0700471
Dave Houltona9df0ce2018-02-07 10:51:23 -0700472 for (unsigned i = 2; i < a_insn.len(); i++) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600473 if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700474 return false;
475 }
476 }
477
478 return true;
479 }
Chris Forbes47567b72017-06-09 12:09:45 -0700480 default:
481 // Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
482 return false;
483 }
484}
485
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600486static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Chris Forbes47567b72017-06-09 12:09:45 -0700487 auto insn = src->get_def(type);
488 assert(insn != src->end());
489
490 switch (insn.opcode()) {
491 case spv::OpTypePointer:
492 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
493 // pointers around.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600494 return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
Chris Forbes47567b72017-06-09 12:09:45 -0700495 case spv::OpTypeArray:
496 if (strip_array_level) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600497 return GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700498 } else {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600499 return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700500 }
501 case spv::OpTypeMatrix:
502 // Num locations is the dimension * element size
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600503 return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700504 case spv::OpTypeVector: {
505 auto scalar_type = src->get_def(insn.word(2));
506 auto bit_width =
507 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
508
509 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
510 return (bit_width * insn.word(3) + 127) / 128;
511 }
512 default:
513 // Everything else is just 1.
514 return 1;
515
516 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
517 }
518}
519
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600520static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200521 auto insn = src->get_def(type);
522 assert(insn != src->end());
523
524 switch (insn.opcode()) {
525 case spv::OpTypePointer:
526 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
527 // pointers around.
528 return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
529 case spv::OpTypeStruct: {
530 uint32_t sum = 0;
531 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
532 sum += GetComponentsConsumedByType(src, insn.word(i), false);
533 }
534 return sum;
535 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -0500536 case spv::OpTypeArray:
537 if (strip_array_level) {
538 return GetComponentsConsumedByType(src, insn.word(2), false);
539 } else {
540 return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200541 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +0200542 case spv::OpTypeMatrix:
543 // Num locations is the dimension * element size
544 return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
545 case spv::OpTypeVector: {
546 auto scalar_type = src->get_def(insn.word(2));
547 auto bit_width =
548 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
549 // One component is 32-bit
550 return (bit_width * insn.word(3) + 31) / 32;
551 }
552 case spv::OpTypeFloat: {
553 auto bit_width = insn.word(2);
554 return (bit_width + 31) / 32;
555 }
556 case spv::OpTypeInt: {
557 auto bit_width = insn.word(2);
558 return (bit_width + 31) / 32;
559 }
560 case spv::OpConstant:
561 return GetComponentsConsumedByType(src, insn.word(1), false);
562 default:
563 return 0;
564 }
565}
566
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600567static unsigned GetLocationsConsumedByFormat(VkFormat format) {
Chris Forbes47567b72017-06-09 12:09:45 -0700568 switch (format) {
569 case VK_FORMAT_R64G64B64A64_SFLOAT:
570 case VK_FORMAT_R64G64B64A64_SINT:
571 case VK_FORMAT_R64G64B64A64_UINT:
572 case VK_FORMAT_R64G64B64_SFLOAT:
573 case VK_FORMAT_R64G64B64_SINT:
574 case VK_FORMAT_R64G64B64_UINT:
575 return 2;
576 default:
577 return 1;
578 }
579}
580
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600581static unsigned GetFormatType(VkFormat fmt) {
Dave Houltona9df0ce2018-02-07 10:51:23 -0700582 if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
583 if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
584 if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
585 if (fmt == VK_FORMAT_UNDEFINED) return 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700586 // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
587 return FORMAT_TYPE_FLOAT;
588}
589
590// 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 -0700591// also used for input attachments, as we statically know their format.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600592static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
Chris Forbes47567b72017-06-09 12:09:45 -0700593 auto insn = src->get_def(type);
594 assert(insn != src->end());
595
596 switch (insn.opcode()) {
597 case spv::OpTypeInt:
598 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
599 case spv::OpTypeFloat:
600 return FORMAT_TYPE_FLOAT;
601 case spv::OpTypeVector:
Chris Forbes47567b72017-06-09 12:09:45 -0700602 case spv::OpTypeMatrix:
Chris Forbes47567b72017-06-09 12:09:45 -0700603 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -0700604 case spv::OpTypeRuntimeArray:
605 case spv::OpTypeImage:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600606 return GetFundamentalType(src, insn.word(2));
Chris Forbes47567b72017-06-09 12:09:45 -0700607 case spv::OpTypePointer:
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600608 return GetFundamentalType(src, insn.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -0700609
610 default:
611 return 0;
612 }
613}
614
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600615static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
Chris Forbes47567b72017-06-09 12:09:45 -0700616 uint32_t bit_pos = uint32_t(u_ffs(stage));
617 return bit_pos - 1;
618}
619
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600620static 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 -0700621 while (true) {
622 if (def.opcode() == spv::OpTypePointer) {
623 def = src->get_def(def.word(3));
624 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
625 def = src->get_def(def.word(2));
626 is_array_of_verts = false;
627 } else if (def.opcode() == spv::OpTypeStruct) {
628 return def;
629 } else {
630 return src->end();
631 }
632 }
633}
634
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600635static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800636 bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
637 int /*first_location*/) {
Chris Forbes47567b72017-06-09 12:09:45 -0700638 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600639 auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800640 if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700641 // This isn't an interface block.
Chris Forbesa313d772017-06-13 13:59:41 -0700642 return false;
Chris Forbes47567b72017-06-09 12:09:45 -0700643 }
644
645 std::unordered_map<unsigned, unsigned> member_components;
646 std::unordered_map<unsigned, unsigned> member_relaxed_precision;
Chris Forbesa313d772017-06-13 13:59:41 -0700647 std::unordered_map<unsigned, unsigned> member_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700648
649 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
650 for (auto insn : *src) {
651 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
652 unsigned member_index = insn.word(2);
653
654 if (insn.word(3) == spv::DecorationComponent) {
655 unsigned component = insn.word(4);
656 member_components[member_index] = component;
657 }
658
659 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
660 member_relaxed_precision[member_index] = 1;
661 }
Chris Forbesa313d772017-06-13 13:59:41 -0700662
663 if (insn.word(3) == spv::DecorationPatch) {
664 member_patch[member_index] = 1;
665 }
Chris Forbes47567b72017-06-09 12:09:45 -0700666 }
667 }
668
Chris Forbesa313d772017-06-13 13:59:41 -0700669 // TODO: correctly handle location assignment from outside
670
Chris Forbes47567b72017-06-09 12:09:45 -0700671 // Second pass -- produce the output, from Location decorations
672 for (auto insn : *src) {
673 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
674 unsigned member_index = insn.word(2);
675 unsigned member_type_id = type.word(2 + member_index);
676
677 if (insn.word(3) == spv::DecorationLocation) {
678 unsigned location = insn.word(4);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600679 unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
Chris Forbes47567b72017-06-09 12:09:45 -0700680 auto component_it = member_components.find(member_index);
681 unsigned component = component_it == member_components.end() ? 0 : component_it->second;
682 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
Dave Houltona9df0ce2018-02-07 10:51:23 -0700683 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700684
685 for (unsigned int offset = 0; offset < num_locations; offset++) {
686 interface_var v = {};
687 v.id = id;
688 // TODO: member index in interface_var too?
689 v.type_id = member_type_id;
690 v.offset = offset;
Chris Forbesa313d772017-06-13 13:59:41 -0700691 v.is_patch = member_is_patch;
Chris Forbes47567b72017-06-09 12:09:45 -0700692 v.is_block_member = true;
693 v.is_relaxed_precision = is_relaxed_precision;
694 (*out)[std::make_pair(location + offset, component)] = v;
695 }
696 }
697 }
698 }
Chris Forbesa313d772017-06-13 13:59:41 -0700699
700 return true;
Chris Forbes47567b72017-06-09 12:09:45 -0700701}
702
Ari Suonpaa696b3432019-03-11 14:02:57 +0200703static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800704 assert(entrypoint.opcode() == spv::OpEntryPoint);
705
Ari Suonpaa696b3432019-03-11 14:02:57 +0200706 std::vector<uint32_t> interfaces;
707 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
708 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
709 uint32_t word = 3;
710 while (entrypoint.word(word) & 0xff000000u) {
711 ++word;
712 }
713 ++word;
714
715 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
716
717 return interfaces;
718}
719
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600720static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600721 spv::StorageClass sinterface, bool is_array_of_verts) {
Chris Forbes47567b72017-06-09 12:09:45 -0700722 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
723
Chris Forbes47567b72017-06-09 12:09:45 -0700724 std::map<location_t, interface_var> out;
725
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800726 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
727 auto insn = src->get_def(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700728 assert(insn != src->end());
729 assert(insn.opcode() == spv::OpVariable);
730
731 if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800732 auto d = src->get_decorations(iid);
Chris Forbes47567b72017-06-09 12:09:45 -0700733 unsigned id = insn.word(2);
734 unsigned type = insn.word(1);
735
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800736 int location = d.location;
737 int builtin = d.builtin;
738 unsigned component = d.component;
739 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
740 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
Chris Forbes47567b72017-06-09 12:09:45 -0700741
Dave Houltona9df0ce2018-02-07 10:51:23 -0700742 if (builtin != -1)
743 continue;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -0800744 else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
Chris Forbes47567b72017-06-09 12:09:45 -0700745 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
746 // one result for each.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600747 unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
Chris Forbes47567b72017-06-09 12:09:45 -0700748 for (unsigned int offset = 0; offset < num_locations; offset++) {
749 interface_var v = {};
750 v.id = id;
751 v.type_id = type;
752 v.offset = offset;
753 v.is_patch = is_patch;
754 v.is_relaxed_precision = is_relaxed_precision;
755 out[std::make_pair(location + offset, component)] = v;
756 }
Chris Forbes47567b72017-06-09 12:09:45 -0700757 }
758 }
759 }
760
761 return out;
762}
763
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600764static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
Ari Suonpaa696b3432019-03-11 14:02:57 +0200765 uint32_t storageClass) {
766 std::vector<uint32_t> variables;
767 std::vector<uint32_t> builtinStructMembers;
768 std::vector<uint32_t> builtinDecorations;
769
770 for (auto insn : *src) {
771 switch (insn.opcode()) {
772 // Find all built-in member decorations
773 case spv::OpMemberDecorate:
774 if (insn.word(3) == spv::DecorationBuiltIn) {
775 builtinStructMembers.push_back(insn.word(1));
776 }
777 break;
778 // Find all built-in decorations
779 case spv::OpDecorate:
780 switch (insn.word(2)) {
781 case spv::DecorationBlock: {
782 uint32_t blockID = insn.word(1);
783 for (auto builtInBlockID : builtinStructMembers) {
784 // Check if one of the members of the block are built-in -> the block is built-in
785 if (blockID == builtInBlockID) {
786 builtinDecorations.push_back(blockID);
787 break;
788 }
789 }
790 break;
791 }
792 case spv::DecorationBuiltIn:
793 builtinDecorations.push_back(insn.word(1));
794 break;
795 default:
796 break;
797 }
798 break;
799 default:
800 break;
801 }
802 }
803
804 // Find all interface variables belonging to the entrypoint and matching the storage class
805 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
806 auto def = src->get_def(id);
807 assert(def != src->end());
808 assert(def.opcode() == spv::OpVariable);
809
810 if (def.word(3) == storageClass) variables.push_back(def.word(1));
811 }
812
813 // Find all members belonging to the builtin block selected
814 std::vector<uint32_t> builtinBlockMembers;
815 for (auto &var : variables) {
816 auto def = src->get_def(src->get_def(var).word(3));
817
818 // It could be an array of IO blocks. The element type should be the struct defining the block contents
819 if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
820
821 // Now find all members belonging to the struct defining the IO block
822 if (def.opcode() == spv::OpTypeStruct) {
823 for (auto builtInID : builtinDecorations) {
824 if (builtInID == def.word(1)) {
825 for (int i = 2; i < (int)def.len(); i++)
826 builtinBlockMembers.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
827 // These shouldn't be left after replacing.
828 for (auto insn : *src) {
829 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == builtInID &&
830 insn.word(3) == spv::DecorationBuiltIn) {
831 auto structIndex = insn.word(2);
832 assert(structIndex < builtinBlockMembers.size());
833 builtinBlockMembers[structIndex] = insn.word(4);
834 }
835 }
836 }
837 }
838 }
839 }
840
841 return builtinBlockMembers;
842}
843
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600844static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
Mark Lobodzinski3c59d972019-04-25 11:28:14 -0600845 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
Chris Forbes47567b72017-06-09 12:09:45 -0700846 std::vector<std::pair<uint32_t, interface_var>> out;
847
848 for (auto insn : *src) {
849 if (insn.opcode() == spv::OpDecorate) {
850 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
851 auto attachment_index = insn.word(3);
852 auto id = insn.word(1);
853
854 if (accessible_ids.count(id)) {
855 auto def = src->get_def(id);
856 assert(def != src->end());
locke-lunarg9a16ebb2020-07-30 16:56:33 -0600857 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -0600858 auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
Chris Forbes47567b72017-06-09 12:09:45 -0700859 for (unsigned int offset = 0; offset < num_locations; offset++) {
860 interface_var v = {};
861 v.id = id;
862 v.type_id = def.word(1);
863 v.offset = offset;
864 out.emplace_back(attachment_index + offset, v);
865 }
866 }
867 }
868 }
869 }
870 }
871
872 return out;
873}
874
locke-lunarg25b6c352020-08-06 17:44:18 -0600875static bool AtomicOperation(uint32_t opcode) {
876 switch (opcode) {
877 case spv::OpAtomicLoad:
878 case spv::OpAtomicStore:
879 case spv::OpAtomicExchange:
880 case spv::OpAtomicCompareExchange:
881 case spv::OpAtomicCompareExchangeWeak:
882 case spv::OpAtomicIIncrement:
883 case spv::OpAtomicIDecrement:
884 case spv::OpAtomicIAdd:
885 case spv::OpAtomicISub:
886 case spv::OpAtomicSMin:
887 case spv::OpAtomicUMin:
888 case spv::OpAtomicSMax:
889 case spv::OpAtomicUMax:
890 case spv::OpAtomicAnd:
891 case spv::OpAtomicOr:
892 case spv::OpAtomicXor:
893 case spv::OpAtomicFAddEXT:
894 return true;
895 default:
896 return false;
897 }
898 return false;
899}
900
locke-lunarg12d20992020-09-21 12:46:49 -0600901bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<unsigned> &operator_members,
902 const std::unordered_map<unsigned, unsigned> &load_members,
903 const std::unordered_map<unsigned, std::pair<unsigned, unsigned>> &accesschain_members) {
904 for (auto load_id : operator_members) {
locke-lunargd3da0422020-09-23 01:02:11 -0600905 if (object_id == load_id) return true;
locke-lunarg12d20992020-09-21 12:46:49 -0600906 auto load_it = load_members.find(load_id);
907 if (load_it == load_members.end()) {
908 continue;
909 }
910 if (load_it->second == object_id) {
911 return true;
912 }
913
914 auto accesschain_it = accesschain_members.find(load_it->second);
915 if (accesschain_it == accesschain_members.end()) {
916 continue;
917 }
918 if (accesschain_it->second.first == object_id) {
919 return true;
920 }
921 }
922 return false;
923}
924
locke-lunargae2a43c2020-09-22 17:21:57 -0600925bool CheckImageOperandsBiasOffset(uint32_t type) {
926 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
927 spv::ImageOperandsConstOffsetsMask)
928 ? true
929 : false;
930}
931
locke-lunargd3da0422020-09-23 01:02:11 -0600932struct shader_module_used_operators {
933 bool updated;
934 std::vector<unsigned> imagwrite_members;
935 std::vector<unsigned> atomic_members;
936 std::vector<unsigned> store_members;
937 std::vector<unsigned> atomic_store_members;
938 std::vector<unsigned> sampler_implicitLod_dref_proj_members; // sampler Load id
939 std::vector<unsigned> sampler_bias_offset_members; // sampler Load id
940 std::vector<std::pair<unsigned, unsigned>> sampledImage_members;
941 std::unordered_map<unsigned, unsigned> load_members;
942 std::unordered_map<unsigned, std::pair<unsigned, unsigned>> accesschain_members;
943 std::unordered_map<unsigned, unsigned> image_texel_pointer_members;
944
945 shader_module_used_operators() : updated(false) {}
946
947 void update(SHADER_MODULE_STATE const *module) {
948 if (updated) return;
949 updated = true;
950
951 for (auto insn : *module) {
952 switch (insn.opcode()) {
953 case spv::OpImageSampleImplicitLod:
954 case spv::OpImageSampleProjImplicitLod:
955 case spv::OpImageSampleProjExplicitLod:
956 case spv::OpImageSparseSampleImplicitLod:
957 case spv::OpImageSparseSampleProjImplicitLod:
958 case spv::OpImageSparseSampleProjExplicitLod: {
959 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
960 // ImageOperands in index: 5
961 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
962 sampler_bias_offset_members.emplace_back(insn.word(3));
963 }
964 break;
965 }
966 case spv::OpImageSampleDrefImplicitLod:
967 case spv::OpImageSampleDrefExplicitLod:
968 case spv::OpImageSampleProjDrefImplicitLod:
969 case spv::OpImageSampleProjDrefExplicitLod:
970 case spv::OpImageSparseSampleDrefImplicitLod:
971 case spv::OpImageSparseSampleDrefExplicitLod:
972 case spv::OpImageSparseSampleProjDrefImplicitLod:
973 case spv::OpImageSparseSampleProjDrefExplicitLod: {
974 sampler_implicitLod_dref_proj_members.emplace_back(insn.word(3)); // Load id
975 // ImageOperands in index: 6
976 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
977 sampler_bias_offset_members.emplace_back(insn.word(3));
978 }
979 break;
980 }
981 case spv::OpImageSampleExplicitLod:
982 case spv::OpImageSparseSampleExplicitLod: {
983 // ImageOperands in index: 5
984 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
985 sampler_bias_offset_members.emplace_back(insn.word(3));
986 }
987 break;
988 }
989 case spv::OpStore: {
990 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
991 break;
992 }
993 case spv::OpImageWrite: {
994 imagwrite_members.emplace_back(insn.word(1)); // Load id
995 break;
996 }
997 case spv::OpSampledImage: {
998 // 3: image load id, 4: sampler load id
999 sampledImage_members.emplace_back(std::pair<unsigned, unsigned>(insn.word(3), insn.word(4)));
1000 break;
1001 }
1002 case spv::OpLoad: {
1003 // 2: Load id, 3: object id or AccessChain id
1004 load_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1005 break;
1006 }
1007 case spv::OpAccessChain: {
1008 // 2: AccessChain id, 3: object id, 4: object id of array index
1009 accesschain_members.insert(
1010 std::make_pair(insn.word(2), std::pair<unsigned, unsigned>(insn.word(3), insn.word(4))));
1011 break;
1012 }
1013 case spv::OpImageTexelPointer: {
1014 // 2: ImageTexelPointer id, 3: object id
1015 image_texel_pointer_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1016 break;
1017 }
1018 default: {
1019 if (AtomicOperation(insn.opcode())) {
1020 if (insn.opcode() == spv::OpAtomicStore) {
1021 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1022 } else {
1023 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1024 }
1025 }
1026 break;
1027 }
1028 }
1029 }
1030 }
1031};
1032
locke-lunarg25b6c352020-08-06 17:44:18 -06001033// Check writable, image atomic operation
1034static void IsSpecificDescriptorType(SHADER_MODULE_STATE const *module, const spirv_inst_iter &id_it, bool is_storage_buffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001035 bool is_check_writable, interface_var &out_interface_var,
1036 shader_module_used_operators &used_operators) {
locke-lunarg6f760f12020-06-05 16:19:37 -06001037 uint32_t type_id = id_it.word(1);
locke-lunarg36045992020-08-20 16:54:37 -06001038 unsigned int id = id_it.word(2);
1039
Chris Forbes8af24522018-03-07 11:37:45 -08001040 auto type = module->get_def(type_id);
1041
1042 // 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 -06001043 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1044 type.opcode() == spv::OpTypeSampledImage) {
1045 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1046 type.opcode() == spv::OpTypeSampledImage) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001047 type = module->get_def(type.word(2)); // Element type
Chris Forbes8af24522018-03-07 11:37:45 -08001048 } else {
locke-lunarg36045992020-08-20 16:54:37 -06001049 type = module->get_def(type.word(3)); // Pointer type
Chris Forbes8af24522018-03-07 11:37:45 -08001050 }
1051 }
Chris Forbes8af24522018-03-07 11:37:45 -08001052 switch (type.opcode()) {
1053 case spv::OpTypeImage: {
1054 auto dim = type.word(3);
locke-lunarg36045992020-08-20 16:54:37 -06001055 if (dim != spv::DimSubpassData) {
locke-lunargd3da0422020-09-23 01:02:11 -06001056 used_operators.update(module);
locke-lunarg25b6c352020-08-06 17:44:18 -06001057
locke-lunargd3da0422020-09-23 01:02:11 -06001058 if (CheckObjectIDFromOpLoad(id, used_operators.imagwrite_members, used_operators.load_members,
1059 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001060 out_interface_var.is_writable = true;
locke-lunarg12d20992020-09-21 12:46:49 -06001061 }
1062 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1063 used_operators.accesschain_members)) {
1064 out_interface_var.is_sampler_implicitLod_dref_proj = true;
locke-lunarg25b6c352020-08-06 17:44:18 -06001065 }
locke-lunargd3da0422020-09-23 01:02:11 -06001066 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1067 used_operators.accesschain_members)) {
locke-lunargae2a43c2020-09-22 17:21:57 -06001068 out_interface_var.is_sampler_bias_offset = true;
1069 }
locke-lunargd3da0422020-09-23 01:02:11 -06001070 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1071 used_operators.accesschain_members) ||
1072 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1073 used_operators.accesschain_members)) {
1074 out_interface_var.is_atomic_operation = true;
1075 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001076
locke-lunargd3da0422020-09-23 01:02:11 -06001077 for (auto &itp_id : used_operators.sampledImage_members) {
locke-lunarg36045992020-08-20 16:54:37 -06001078 // Find if image id match.
1079 uint32_t image_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001080 auto load_it = used_operators.load_members.find(itp_id.first);
1081 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001082 continue;
1083 } else {
1084 if (load_it->second != id) {
locke-lunargd3da0422020-09-23 01:02:11 -06001085 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1086 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001087 continue;
1088 } else {
1089 if (accesschain_it->second.first != id) {
1090 continue;
1091 }
1092 image_index = GetConstantValue(module, accesschain_it->second.second);
1093 }
1094 }
1095 }
1096 // Find sampler's set binding.
locke-lunargd3da0422020-09-23 01:02:11 -06001097 load_it = used_operators.load_members.find(itp_id.second);
1098 if (load_it == used_operators.load_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001099 continue;
1100 } else {
1101 uint32_t sampler_id = load_it->second;
1102 uint32_t sampler_index = 0;
locke-lunargd3da0422020-09-23 01:02:11 -06001103 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1104 if (accesschain_it != used_operators.accesschain_members.end()) {
locke-lunarg36045992020-08-20 16:54:37 -06001105 sampler_id = accesschain_it->second.first;
1106 sampler_index = GetConstantValue(module, accesschain_it->second.second);
1107 }
1108 auto sampler_dec = module->get_decorations(sampler_id);
1109 out_interface_var.samplers_used_by_image.emplace_back(SamplerUsedByImage{
1110 image_index, descriptor_slot_t{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
1111 }
1112 }
locke-lunarg6f760f12020-06-05 16:19:37 -06001113 }
locke-lunarg25b6c352020-08-06 17:44:18 -06001114 return;
Chris Forbes8af24522018-03-07 11:37:45 -08001115 }
1116
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001117 case spv::OpTypeStruct: {
1118 std::unordered_set<unsigned> nonwritable_members;
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001119 if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Chris Forbes8af24522018-03-07 11:37:45 -08001120 for (auto insn : *module) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001121 if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
1122 insn.word(3) == spv::DecorationNonWritable) {
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001123 nonwritable_members.insert(insn.word(2));
Chris Forbes8af24522018-03-07 11:37:45 -08001124 }
1125 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001126
1127 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1128 // as nonwritable.
locke-lunarg6f760f12020-06-05 16:19:37 -06001129 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
locke-lunargd3da0422020-09-23 01:02:11 -06001130 used_operators.update(module);
locke-lunarg6f760f12020-06-05 16:19:37 -06001131
locke-lunargd3da0422020-09-23 01:02:11 -06001132 for (auto oid : used_operators.store_members) {
1133 if (id == oid) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001134 out_interface_var.is_writable = true;
1135 return;
1136 }
locke-lunargd3da0422020-09-23 01:02:11 -06001137 auto accesschain_it = used_operators.accesschain_members.find(oid);
1138 if (accesschain_it == used_operators.accesschain_members.end()) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001139 continue;
1140 }
locke-lunargd3da0422020-09-23 01:02:11 -06001141 if (accesschain_it->second.first == id) {
1142 out_interface_var.is_writable = true;
1143 return;
1144 }
1145 }
1146 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1147 used_operators.accesschain_members)) {
locke-lunarg25b6c352020-08-06 17:44:18 -06001148 out_interface_var.is_writable = true;
1149 return;
locke-lunarg6f760f12020-06-05 16:19:37 -06001150 }
1151 }
Chris Forbes8d31e5d2018-10-08 17:19:15 -07001152 }
Chris Forbes8af24522018-03-07 11:37:45 -08001153 }
Chris Forbes8af24522018-03-07 11:37:45 -08001154}
1155
locke-lunargd9a069d2019-09-17 01:50:19 -06001156std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
locke-lunarg63e4daf2020-08-17 17:53:25 -06001157 SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids, bool *has_writable_descriptor,
1158 bool *has_atomic_descriptor) {
Chris Forbes47567b72017-06-09 12:09:45 -07001159 std::vector<std::pair<descriptor_slot_t, interface_var>> out;
locke-lunargd3da0422020-09-23 01:02:11 -06001160 shader_module_used_operators operators;
1161
Chris Forbes47567b72017-06-09 12:09:45 -07001162 for (auto id : accessible_ids) {
1163 auto insn = src->get_def(id);
1164 assert(insn != src->end());
1165
1166 if (insn.opcode() == spv::OpVariable &&
Chris Forbes9f89d752018-03-07 12:57:48 -08001167 (insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
1168 insn.word(3) == spv::StorageClassStorageBuffer)) {
Chris Forbes8a6d8cb2019-02-14 14:33:08 -08001169 auto d = src->get_decorations(insn.word(2));
1170 unsigned set = d.descriptor_set;
1171 unsigned binding = d.binding;
Chris Forbes47567b72017-06-09 12:09:45 -07001172
1173 interface_var v = {};
1174 v.id = insn.word(2);
1175 v.type_id = insn.word(1);
Chris Forbes8af24522018-03-07 11:37:45 -08001176
locke-lunarg25b6c352020-08-06 17:44:18 -06001177 IsSpecificDescriptorType(src, insn, insn.word(3) == spv::StorageClassStorageBuffer,
locke-lunargd3da0422020-09-23 01:02:11 -06001178 !(d.flags & decoration_set::nonwritable_bit), v, operators);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001179 if (v.is_writable) *has_writable_descriptor = true;
1180 if (v.is_atomic_operation) *has_atomic_descriptor = true;
locke-lunarg9a16ebb2020-07-30 16:56:33 -06001181 if (d.flags & decoration_set::input_attachment_index_bit) {
1182 v.input_index = d.input_attachment_index;
1183 }
locke-lunarg654e3692020-06-04 17:19:15 -06001184 out.emplace_back(std::make_pair(set, binding), v);
Chris Forbes47567b72017-06-09 12:09:45 -07001185 }
1186 }
1187
1188 return out;
1189}
1190
locke-lunargde3f0fa2020-09-10 11:55:31 -06001191void DefineStructMember(const SHADER_MODULE_STATE &src, const spirv_inst_iter &it,
1192 const std::vector<uint32_t> &memberDecorate_offsets, shader_struct_member &data) {
1193 const auto struct_it = GetStructType(&src, it, false);
1194 assert(struct_it != src.end());
1195 data.size = 0;
1196
1197 shader_struct_member data1;
1198 uint32_t i = 2;
1199 uint32_t local_offset = 0;
1200 std::vector<uint32_t> offsets;
1201 offsets.resize(struct_it.len() - i);
1202
1203 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
1204 for (const auto offset : memberDecorate_offsets) {
1205 const auto member_decorate = src.at(offset);
1206 if (member_decorate.word(1) != struct_it.word(1)) {
1207 continue;
1208 }
1209
1210 offsets[member_decorate.word(2)] = member_decorate.word(4);
1211 }
1212
1213 for (const auto offset : offsets) {
1214 local_offset = offset;
1215 data1 = {};
1216 data1.root = data.root;
1217 data1.offset = local_offset;
1218 auto def_member = src.get_def(struct_it.word(i));
1219
1220 // Array could be multi-dimensional
1221 while (def_member.opcode() == spv::OpTypeArray) {
1222 const auto len_id = def_member.word(3);
1223 const auto def_len = src.get_def(len_id);
1224 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
1225 def_member = src.get_def(def_member.word(2));
1226 }
1227
1228 if (def_member.opcode() == spv::OpTypeStruct || def_member.opcode() == spv::OpTypePointer) {
1229 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
1230 DefineStructMember(src, def_member, memberDecorate_offsets, data1);
1231 } else {
1232 if (def_member.opcode() == spv::OpTypeMatrix) {
1233 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
1234 def_member = src.get_def(def_member.word(2));
1235 }
1236
1237 if (def_member.opcode() == spv::OpTypeVector) {
1238 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
1239 def_member = src.get_def(def_member.word(2));
1240 }
1241
1242 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
1243 data1.size = (def_member.word(2) / 8);
1244 }
1245 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
1246 if (array_length_hierarchy_szie > 0) {
1247 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
1248
1249 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
1250 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
1251 }
1252 }
1253 data.struct_members.emplace_back(data1);
1254 ++i;
1255 }
1256 uint32_t total_array_length = 1;
1257 for (const auto length : data1.array_length_hierarchy) {
1258 total_array_length *= length;
1259 }
1260 data.size = local_offset + data1.size * total_array_length;
1261}
1262
1263uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1264 int array_indices_size = static_cast<int>(array_indices.size());
1265 if (array_indices_size) {
1266 uint32_t array_index = 0;
1267 uint32_t i = 0;
1268 for (const auto index : array_indices) {
1269 array_index += (data.array_block_size[i] * index);
1270 ++i;
1271 }
1272 offset += (array_index * data.size);
1273 }
1274 return offset;
1275}
1276
1277void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
1278 int array_indices_size = static_cast<int>(array_indices.size());
1279 uint32_t block_memory_size = data.size;
1280 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
1281 block_memory_size *= data.array_length_hierarchy[i];
1282 }
1283
1284 offset = UpdateOffset(offset, array_indices, data);
1285
1286 uint32_t end = offset + block_memory_size;
1287 auto used_bytes = data.GetUsedbytes();
1288 if (used_bytes->size() < end) {
1289 used_bytes->resize(end, 0);
1290 }
1291 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
1292}
1293
1294void RunUsedArray(const SHADER_MODULE_STATE &src, uint32_t offset, std::vector<uint32_t> array_indices,
1295 uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1296 if (access_chain_word_index < access_chain_it.len()) {
1297 if (data.array_length_hierarchy.size() > array_indices.size()) {
1298 auto def_it = src.get_def(access_chain_it.word(access_chain_word_index));
1299 ++access_chain_word_index;
1300
1301 if (def_it != src.end() && def_it.opcode() == spv::OpConstant) {
1302 array_indices.emplace_back(def_it.word(3));
1303 RunUsedArray(src, offset, array_indices, access_chain_word_index, access_chain_it, data);
1304 } else {
1305 // If it is a variable, set the all array is used.
1306 if (access_chain_word_index < access_chain_it.len()) {
1307 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1308 for (uint32_t i = 0; i < array_length; ++i) {
1309 auto array_indices2 = array_indices;
1310 array_indices2.emplace_back(i);
1311 RunUsedArray(src, offset, array_indices2, access_chain_word_index, access_chain_it, data);
1312 }
1313 } else {
1314 SetUsedBytes(offset, array_indices, data);
1315 }
1316 }
1317 } else {
1318 offset = UpdateOffset(offset, array_indices, data);
1319 RunUsedStruct(src, offset, access_chain_word_index, access_chain_it, data);
1320 }
1321 } else {
1322 SetUsedBytes(offset, array_indices, data);
1323 }
1324}
1325
1326void RunUsedStruct(const SHADER_MODULE_STATE &src, uint32_t offset, uint32_t access_chain_word_index,
1327 spirv_inst_iter &access_chain_it, const shader_struct_member &data) {
1328 std::vector<uint32_t> array_indices_emptry;
1329
1330 if (access_chain_word_index < access_chain_it.len()) {
1331 auto strcut_member_index = GetConstantValue(&src, access_chain_it.word(access_chain_word_index));
1332 ++access_chain_word_index;
1333
1334 auto data1 = data.struct_members[strcut_member_index];
1335 RunUsedArray(src, offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1336 }
1337}
1338
1339void SetUsedStructMember(const SHADER_MODULE_STATE &src, const uint32_t variable_id,
1340 const std::vector<function_set> &function_set_list, const shader_struct_member &data) {
1341 for (const auto &func_set : function_set_list) {
1342 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1343 for (auto it = range.first; it != range.second; ++it) {
1344 auto access_chain = src.at(it->second);
1345 if (access_chain.word(3) == variable_id) {
1346 RunUsedStruct(src, 0, 4, access_chain, data);
1347 }
1348 }
1349 }
1350}
1351
1352void SetPushConstantUsedInShader(SHADER_MODULE_STATE &src) {
1353 for (auto &entrypoint : src.entry_points) {
1354 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1355 for (auto it = range.first; it != range.second; ++it) {
1356 const auto def_insn = src.at(it->second);
1357
1358 if (def_insn.word(3) == spv::StorageClassPushConstant) {
1359 spirv_inst_iter type = src.get_def(def_insn.word(1));
1360 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1361 std::vector<uint32_t> offsets;
1362
1363 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
1364 auto member_decorate = src.at(it2->second);
1365 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1366 offsets.emplace_back(member_decorate.offset());
1367 }
1368 }
1369 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
1370 DefineStructMember(src, type, offsets, entrypoint.second.push_constant_used_in_shader);
1371 SetUsedStructMember(src, def_insn.word(2), entrypoint.second.function_set_list,
1372 entrypoint.second.push_constant_used_in_shader);
1373 }
1374 }
1375 }
1376}
1377
locke-lunarg96dc9632020-06-10 17:22:18 -06001378std::unordered_set<uint32_t> CollectWritableOutputLocationinFS(const SHADER_MODULE_STATE &module,
1379 const VkPipelineShaderStageCreateInfo &stage_info) {
1380 std::unordered_set<uint32_t> location_list;
1381 if (stage_info.stage != VK_SHADER_STAGE_FRAGMENT_BIT) return location_list;
1382 const auto entrypoint = FindEntrypoint(&module, stage_info.pName, stage_info.stage);
1383 const auto outputs = CollectInterfaceByLocation(&module, entrypoint, spv::StorageClassOutput, false);
1384 std::unordered_set<unsigned> store_members;
1385 std::unordered_map<unsigned, unsigned> accesschain_members;
1386
1387 for (auto insn : module) {
1388 switch (insn.opcode()) {
1389 case spv::OpStore:
1390 case spv::OpAtomicStore: {
1391 store_members.insert(insn.word(1)); // object id or AccessChain id
1392 break;
1393 }
1394 case spv::OpAccessChain: {
1395 // 2: AccessChain id, 3: object id
1396 if (insn.word(3)) accesschain_members.insert(std::make_pair(insn.word(2), insn.word(3)));
1397 break;
1398 }
1399 default:
1400 break;
1401 }
1402 }
1403 if (store_members.empty()) {
1404 return location_list;
1405 }
1406 for (auto output : outputs) {
1407 auto store_it = store_members.find(output.second.id);
1408 if (store_it != store_members.end()) {
1409 location_list.insert(output.first.first);
1410 store_members.erase(store_it);
1411 continue;
1412 }
1413 store_it = store_members.begin();
1414 while (store_it != store_members.end()) {
1415 auto accesschain_it = accesschain_members.find(*store_it);
1416 if (accesschain_it == accesschain_members.end()) {
1417 ++store_it;
1418 continue;
1419 }
1420 if (accesschain_it->second == output.second.id) {
1421 location_list.insert(output.first.first);
1422 store_members.erase(store_it);
1423 accesschain_members.erase(accesschain_it);
1424 break;
1425 }
1426 ++store_it;
1427 }
1428 }
1429 return location_list;
1430}
1431
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001432bool CoreChecks::ValidateViConsistency(VkPipelineVertexInputStateCreateInfo const *vi) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001433 // Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
1434 // be specified only once.
1435 std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
1436 bool skip = false;
1437
1438 for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
1439 auto desc = &vi->pVertexBindingDescriptions[i];
1440 auto &binding = bindings[desc->binding];
1441 if (binding) {
Dave Houlton78d09922018-05-17 15:48:45 -06001442 // TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001443 skip |= LogError(device, kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
1444 desc->binding);
Chris Forbes47567b72017-06-09 12:09:45 -07001445 } else {
1446 binding = desc;
1447 }
1448 }
1449
1450 return skip;
1451}
1452
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001453bool CoreChecks::ValidateViAgainstVsInputs(VkPipelineVertexInputStateCreateInfo const *vi, SHADER_MODULE_STATE const *vs,
1454 spirv_inst_iter entrypoint) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001455 bool skip = false;
1456
Petr Kraus25810d02019-08-27 17:41:15 +02001457 const auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
Chris Forbes47567b72017-06-09 12:09:45 -07001458
1459 // Build index by location
Petr Kraus25810d02019-08-27 17:41:15 +02001460 std::map<uint32_t, const VkVertexInputAttributeDescription *> attribs;
Chris Forbes47567b72017-06-09 12:09:45 -07001461 if (vi) {
Petr Kraus25810d02019-08-27 17:41:15 +02001462 for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; ++i) {
1463 const auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
1464 for (uint32_t j = 0; j < num_locations; ++j) {
Chris Forbes47567b72017-06-09 12:09:45 -07001465 attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
1466 }
1467 }
1468 }
1469
Petr Kraus25810d02019-08-27 17:41:15 +02001470 struct AttribInputPair {
1471 const VkVertexInputAttributeDescription *attrib = nullptr;
1472 const interface_var *input = nullptr;
1473 };
1474 std::map<uint32_t, AttribInputPair> location_map;
1475 for (const auto &attrib_it : attribs) location_map[attrib_it.first].attrib = attrib_it.second;
1476 for (const auto &input_it : inputs) location_map[input_it.first.first].input = &input_it.second;
Chris Forbes47567b72017-06-09 12:09:45 -07001477
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001478 for (const auto &location_it : location_map) {
Petr Kraus25810d02019-08-27 17:41:15 +02001479 const auto location = location_it.first;
1480 const auto attrib = location_it.second.attrib;
1481 const auto input = location_it.second.input;
Mark Lobodzinski7caa39c2018-07-25 15:48:34 -06001482
Petr Kraus25810d02019-08-27 17:41:15 +02001483 if (attrib && !input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001484 skip |= LogPerformanceWarning(vs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1485 "Vertex attribute at location %" PRIu32 " not consumed by vertex shader", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001486 } else if (!attrib && input) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001487 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1488 "Vertex shader consumes input at location %" PRIu32 " but not provided", location);
Petr Kraus25810d02019-08-27 17:41:15 +02001489 } else if (attrib && input) {
1490 const auto attrib_type = GetFormatType(attrib->format);
1491 const auto input_type = GetFundamentalType(vs, input->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001492
1493 // Type checking
1494 if (!(attrib_type & input_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001495 skip |= LogError(vs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1496 "Attribute type of `%s` at location %" PRIu32 " does not match vertex shader input type of `%s`",
1497 string_VkFormat(attrib->format), location, DescribeType(vs, input->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001498 }
Petr Kraus25810d02019-08-27 17:41:15 +02001499 } else { // !attrib && !input
1500 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001501 }
1502 }
1503
1504 return skip;
1505}
1506
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001507bool CoreChecks::ValidateFsOutputsAgainstRenderPass(SHADER_MODULE_STATE const *fs, spirv_inst_iter entrypoint,
1508 PIPELINE_STATE const *pipeline, uint32_t subpass_index) const {
Petr Kraus25810d02019-08-27 17:41:15 +02001509 bool skip = false;
Chris Forbes8bca1652017-07-20 11:10:09 -07001510
Petr Kraus25810d02019-08-27 17:41:15 +02001511 const auto rpci = pipeline->rp_state->createInfo.ptr();
1512
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001513 struct Attachment {
1514 const VkAttachmentReference2KHR *reference = nullptr;
1515 const VkAttachmentDescription2KHR *attachment = nullptr;
1516 const interface_var *output = nullptr;
1517 };
1518 std::map<uint32_t, Attachment> location_map;
1519
Petr Kraus25810d02019-08-27 17:41:15 +02001520 const auto subpass = rpci->pSubpasses[subpass_index];
1521 for (uint32_t i = 0; i < subpass.colorAttachmentCount; ++i) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001522 auto const &reference = subpass.pColorAttachments[i];
1523 location_map[i].reference = &reference;
1524 if (reference.attachment != VK_ATTACHMENT_UNUSED &&
1525 rpci->pAttachments[reference.attachment].format != VK_FORMAT_UNDEFINED) {
1526 location_map[i].attachment = &rpci->pAttachments[reference.attachment];
Chris Forbes47567b72017-06-09 12:09:45 -07001527 }
1528 }
1529
Chris Forbes47567b72017-06-09 12:09:45 -07001530 // TODO: dual source blend index (spv::DecIndex, zero if not provided)
1531
Petr Kraus25810d02019-08-27 17:41:15 +02001532 const auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001533 for (const auto &output_it : outputs) {
1534 auto const location = output_it.first.first;
1535 location_map[location].output = &output_it.second;
1536 }
Chris Forbes47567b72017-06-09 12:09:45 -07001537
Petr Kraus25810d02019-08-27 17:41:15 +02001538 const bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
1539 pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
Chris Forbes47567b72017-06-09 12:09:45 -07001540
Jamie Madillc1f7ca82020-03-16 17:08:26 -04001541 for (const auto &location_it : location_map) {
Jeremy Hayes3699c7c2019-10-09 12:24:55 -06001542 const auto reference = location_it.second.reference;
1543 if (reference != nullptr && reference->attachment == VK_ATTACHMENT_UNUSED) {
1544 continue;
1545 }
1546
Petr Kraus25810d02019-08-27 17:41:15 +02001547 const auto location = location_it.first;
1548 const auto attachment = location_it.second.attachment;
1549 const auto output = location_it.second.output;
Petr Kraus25810d02019-08-27 17:41:15 +02001550 if (attachment && !output) {
1551 if (pipeline->attachments[location].colorWriteMask != 0) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001552 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
1553 "Attachment %" PRIu32
1554 " not written by fragment shader; undefined values will be written to attachment",
1555 location);
Petr Kraus25810d02019-08-27 17:41:15 +02001556 }
1557 } else if (!attachment && output) {
1558 if (!(alphaToCoverageEnabled && location == 0)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001559 skip |= LogWarning(fs->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
1560 "fragment shader writes to output location %" PRIu32 " with no matching attachment", location);
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001561 }
Petr Kraus25810d02019-08-27 17:41:15 +02001562 } else if (attachment && output) {
1563 const auto attachment_type = GetFormatType(attachment->format);
1564 const auto output_type = GetFundamentalType(fs, output->type_id);
Chris Forbes47567b72017-06-09 12:09:45 -07001565
1566 // Type checking
Petr Kraus25810d02019-08-27 17:41:15 +02001567 if (!(output_type & attachment_type)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001568 skip |=
1569 LogWarning(fs->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
1570 "Attachment %" PRIu32
1571 " of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
1572 location, string_VkFormat(attachment->format), DescribeType(fs, output->type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001573 }
Petr Kraus25810d02019-08-27 17:41:15 +02001574 } else { // !attachment && !output
1575 assert(false); // at least one exists in the map
Chris Forbes47567b72017-06-09 12:09:45 -07001576 }
1577 }
1578
Petr Kraus25810d02019-08-27 17:41:15 +02001579 const auto output_zero = location_map.count(0) ? location_map[0].output : nullptr;
1580 bool locationZeroHasAlpha = output_zero && fs->get_def(output_zero->type_id) != fs->end() &&
1581 GetComponentsConsumedByType(fs, output_zero->type_id, false) == 4;
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001582 if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001583 skip |= LogError(fs->vk_shader_module, kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
1584 "fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
Ari Suonpaa412b23b2019-02-26 07:56:58 +02001585 }
1586
Chris Forbes47567b72017-06-09 12:09:45 -07001587 return skip;
1588}
1589
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001590// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
1591// This function examines instructions in the static call tree for a write to this variable.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001592static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001593 auto type = builtin_instr.opcode();
1594 uint32_t target_id = builtin_instr.word(1);
1595 bool init_complete = false;
1596
1597 if (type == spv::OpMemberDecorate) {
1598 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1599 auto insn = entrypoint;
1600 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1601 switch (insn.opcode()) {
1602 case spv::OpTypePointer:
1603 if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
1604 target_id = insn.word(1);
1605 }
1606 break;
1607 case spv::OpVariable:
1608 if (insn.word(1) == target_id) {
1609 target_id = insn.word(2);
1610 init_complete = true;
1611 }
1612 break;
1613 }
1614 insn++;
1615 }
1616 }
1617
Mark Lobodzinskif84b0b42018-09-11 14:54:32 -06001618 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1619
1620 bool found_write = false;
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06001621 std::unordered_set<uint32_t> worklist;
1622 worklist.insert(entrypoint.word(2));
1623
1624 // Follow instructions in call graph looking for writes to target
1625 while (!worklist.empty() && !found_write) {
1626 auto id_iter = worklist.begin();
1627 auto id = *id_iter;
1628 worklist.erase(id_iter);
1629
1630 auto insn = src->get_def(id);
1631 if (insn == src->end()) {
1632 continue;
1633 }
1634
1635 if (insn.opcode() == spv::OpFunction) {
1636 // Scan body of function looking for other function calls or items in our ID chain
1637 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1638 switch (insn.opcode()) {
1639 case spv::OpAccessChain:
1640 if (insn.word(3) == target_id) {
1641 if (type == spv::OpMemberDecorate) {
1642 auto value = GetConstantValue(src, insn.word(4));
1643 if (value == builtin_instr.word(2)) {
1644 target_id = insn.word(2);
1645 }
1646 } else {
1647 target_id = insn.word(2);
1648 }
1649 }
1650 break;
1651 case spv::OpStore:
1652 if (insn.word(1) == target_id) {
1653 found_write = true;
1654 }
1655 break;
1656 case spv::OpFunctionCall:
1657 worklist.insert(insn.word(3));
1658 break;
1659 }
1660 }
1661 }
1662 }
1663 return found_write;
1664}
1665
Chris Forbes47567b72017-06-09 12:09:45 -07001666// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
1667// important for identifying the set of shader resources actually used by an entrypoint, for example.
1668// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
1669// - NOT the shader input/output interfaces.
1670//
1671// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
1672// converting parts of this to be generated from the machine-readable spec instead.
locke-lunargd9a069d2019-09-17 01:50:19 -06001673std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
Chris Forbes47567b72017-06-09 12:09:45 -07001674 std::unordered_set<uint32_t> ids;
1675 std::unordered_set<uint32_t> worklist;
1676 worklist.insert(entrypoint.word(2));
1677
1678 while (!worklist.empty()) {
1679 auto id_iter = worklist.begin();
1680 auto id = *id_iter;
1681 worklist.erase(id_iter);
1682
1683 auto insn = src->get_def(id);
1684 if (insn == src->end()) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001685 // 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 -07001686 // that we may not care about.
1687 continue;
1688 }
1689
1690 // Try to add to the output set
1691 if (!ids.insert(id).second) {
1692 continue; // If we already saw this id, we don't want to walk it again.
1693 }
1694
1695 switch (insn.opcode()) {
1696 case spv::OpFunction:
1697 // Scan whole body of the function, enlisting anything interesting
1698 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
1699 switch (insn.opcode()) {
1700 case spv::OpLoad:
Chris Forbes47567b72017-06-09 12:09:45 -07001701 worklist.insert(insn.word(3)); // ptr
1702 break;
1703 case spv::OpStore:
Chris Forbes47567b72017-06-09 12:09:45 -07001704 worklist.insert(insn.word(1)); // ptr
1705 break;
1706 case spv::OpAccessChain:
1707 case spv::OpInBoundsAccessChain:
1708 worklist.insert(insn.word(3)); // base ptr
1709 break;
1710 case spv::OpSampledImage:
1711 case spv::OpImageSampleImplicitLod:
1712 case spv::OpImageSampleExplicitLod:
1713 case spv::OpImageSampleDrefImplicitLod:
1714 case spv::OpImageSampleDrefExplicitLod:
1715 case spv::OpImageSampleProjImplicitLod:
1716 case spv::OpImageSampleProjExplicitLod:
1717 case spv::OpImageSampleProjDrefImplicitLod:
1718 case spv::OpImageSampleProjDrefExplicitLod:
1719 case spv::OpImageFetch:
1720 case spv::OpImageGather:
1721 case spv::OpImageDrefGather:
1722 case spv::OpImageRead:
1723 case spv::OpImage:
1724 case spv::OpImageQueryFormat:
1725 case spv::OpImageQueryOrder:
1726 case spv::OpImageQuerySizeLod:
1727 case spv::OpImageQuerySize:
1728 case spv::OpImageQueryLod:
1729 case spv::OpImageQueryLevels:
1730 case spv::OpImageQuerySamples:
1731 case spv::OpImageSparseSampleImplicitLod:
1732 case spv::OpImageSparseSampleExplicitLod:
1733 case spv::OpImageSparseSampleDrefImplicitLod:
1734 case spv::OpImageSparseSampleDrefExplicitLod:
1735 case spv::OpImageSparseSampleProjImplicitLod:
1736 case spv::OpImageSparseSampleProjExplicitLod:
1737 case spv::OpImageSparseSampleProjDrefImplicitLod:
1738 case spv::OpImageSparseSampleProjDrefExplicitLod:
1739 case spv::OpImageSparseFetch:
1740 case spv::OpImageSparseGather:
1741 case spv::OpImageSparseDrefGather:
1742 case spv::OpImageTexelPointer:
1743 worklist.insert(insn.word(3)); // Image or sampled image
1744 break;
1745 case spv::OpImageWrite:
1746 worklist.insert(insn.word(1)); // Image -- different operand order to above
1747 break;
1748 case spv::OpFunctionCall:
1749 for (uint32_t i = 3; i < insn.len(); i++) {
1750 worklist.insert(insn.word(i)); // fn itself, and all args
1751 }
1752 break;
1753
1754 case spv::OpExtInst:
1755 for (uint32_t i = 5; i < insn.len(); i++) {
1756 worklist.insert(insn.word(i)); // Operands to ext inst
1757 }
1758 break;
locke-lunarg25b6c352020-08-06 17:44:18 -06001759
1760 default: {
1761 if (AtomicOperation(insn.opcode())) {
1762 if (insn.opcode() == spv::OpAtomicStore) {
1763 worklist.insert(insn.word(1)); // ptr
1764 } else {
1765 worklist.insert(insn.word(3)); // ptr
1766 }
1767 }
1768 break;
1769 }
Chris Forbes47567b72017-06-09 12:09:45 -07001770 }
1771 }
1772 break;
1773 }
1774 }
1775
1776 return ids;
1777}
1778
locke-lunargde3f0fa2020-09-10 11:55:31 -06001779// return: 0: pass, 1: not set, 2: not update
1780int CoreChecks::ValidatePushConstantSetUpdate(const std::vector<int8_t> &push_constant_data_update,
1781 const shader_struct_member &push_constant_used_in_shader,
1782 uint32_t &out_issue_index) const {
1783 const auto *used_bytes = push_constant_used_in_shader.GetUsedbytes();
1784 if (used_bytes->size() == 0) {
1785 return 0;
1786 }
1787 uint32_t i = 0;
1788 for (const auto used : *used_bytes) {
1789 if (used) {
1790 if (i >= push_constant_data_update.size() || push_constant_data_update[i] == -1) {
1791 out_issue_index = i;
1792 return 1; // not set
1793 } else if (push_constant_data_update[i] == 0) {
1794 out_issue_index = i;
1795 return 2; // not update
1796 }
1797 }
1798 ++i;
1799 }
1800 return 0; // pass
1801}
1802
1803bool CoreChecks::ValidatePushConstantUsage(const PIPELINE_STATE &pipeline, SHADER_MODULE_STATE const *src,
1804 VkPipelineShaderStageCreateInfo const *pStage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001805 bool skip = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001806 // 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 -06001807 const auto *entrypoint = FindEntrypointStruct(src, pStage->pName, pStage->stage);
1808 if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) {
1809 return skip;
1810 }
1811 std::vector<VkPushConstantRange> const *push_constant_ranges = pipeline.pipeline_layout->push_constant_ranges.get();
Chris Forbes47567b72017-06-09 12:09:45 -07001812
locke-lunargde3f0fa2020-09-10 11:55:31 -06001813 bool found_stage = false;
1814 for (auto const &range : *push_constant_ranges) {
1815 if (range.stageFlags & pStage->stage) {
1816 found_stage = true;
1817 std::string location_desc;
1818 std::vector<int8_t> push_constant_bytes_set;
1819 if (range.offset > 0) {
1820 push_constant_bytes_set.resize(range.offset, -1);
1821 }
1822 push_constant_bytes_set.resize(range.offset + range.size, 1);
1823 uint32_t issue_index = 0;
1824 int ret = ValidatePushConstantSetUpdate(push_constant_bytes_set, entrypoint->push_constant_used_in_shader, issue_index);
Chris Forbes47567b72017-06-09 12:09:45 -07001825
locke-lunargde3f0fa2020-09-10 11:55:31 -06001826 // "not set" error has been printed in ValidatePushConstantUsage.
1827 if (ret == 1) {
1828 const auto loc_descr = entrypoint->push_constant_used_in_shader.GetLocationDesc(issue_index);
1829 LogObjectList objlist(src->vk_shader_module);
1830 objlist.add(pipeline.pipeline_layout->layout);
1831 skip |= LogError(objlist, kVUID_Core_Shader_PushConstantOutOfRange,
1832 "Push-constant buffer:%s in %s is out of range in %s.", loc_descr.c_str(),
1833 string_VkShaderStageFlags(pStage->stage).c_str(),
1834 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str());
1835 break;
Chris Forbes47567b72017-06-09 12:09:45 -07001836 }
1837 }
1838 }
1839
locke-lunargde3f0fa2020-09-10 11:55:31 -06001840 if (!found_stage) {
1841 LogObjectList objlist(src->vk_shader_module);
1842 objlist.add(pipeline.pipeline_layout->layout);
1843 skip |= LogError(
1844 objlist, kVUID_Core_Shader_PushConstantOutOfRange, "Push constant is used in %s of %s. But %s doesn't set %s.",
1845 string_VkShaderStageFlags(pStage->stage).c_str(), report_data->FormatHandle(src->vk_shader_module).c_str(),
1846 report_data->FormatHandle(pipeline.pipeline_layout->layout).c_str(), string_VkShaderStageFlags(pStage->stage).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07001847 }
Chris Forbes47567b72017-06-09 12:09:45 -07001848 return skip;
1849}
1850
1851// Validate that data for each specialization entry is fully contained within the buffer.
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001852bool CoreChecks::ValidateSpecializationOffsets(VkPipelineShaderStageCreateInfo const *info) const {
Chris Forbes47567b72017-06-09 12:09:45 -07001853 bool skip = false;
1854
1855 VkSpecializationInfo const *spec = info->pSpecializationInfo;
1856
1857 if (spec) {
1858 for (auto i = 0u; i < spec->mapEntryCount; i++) {
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001859 if (spec->pMapEntries[i].offset >= spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001860 skip |= LogError(device, "VUID-VkSpecializationInfo-offset-00773",
1861 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1862 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1863 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1864 spec->pMapEntries[i].offset + spec->dataSize - 1, spec->dataSize);
Jeremy Hayes6c555c32019-09-09 17:14:09 -06001865
1866 continue;
1867 }
Chris Forbes47567b72017-06-09 12:09:45 -07001868 if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001869 skip |= LogError(device, "VUID-VkSpecializationInfo-pMapEntries-00774",
1870 "Specialization entry %u (for constant id %u) references memory outside provided specialization "
1871 "data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
1872 i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
1873 spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
Chris Forbes47567b72017-06-09 12:09:45 -07001874 }
1875 }
1876 }
1877
1878 return skip;
1879}
1880
Jeff Bolz38b3ce72018-09-19 12:53:38 -05001881// TODO (jbolz): Can this return a const reference?
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06001882static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
Chris Forbes47567b72017-06-09 12:09:45 -07001883 auto type = module->get_def(type_id);
Chris Forbes9f89d752018-03-07 12:57:48 -08001884 bool is_storage_buffer = false;
Chris Forbes47567b72017-06-09 12:09:45 -07001885 descriptor_count = 1;
Jeff Bolze54ae892018-09-08 12:16:29 -05001886 std::set<uint32_t> ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001887
1888 // 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 -05001889 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
1890 if (type.opcode() == spv::OpTypeRuntimeArray) {
1891 descriptor_count = 0;
1892 type = module->get_def(type.word(2));
1893 } else if (type.opcode() == spv::OpTypeArray) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06001894 descriptor_count *= GetConstantValue(module, type.word(3));
Chris Forbes47567b72017-06-09 12:09:45 -07001895 type = module->get_def(type.word(2));
1896 } else {
Chris Forbes9f89d752018-03-07 12:57:48 -08001897 if (type.word(2) == spv::StorageClassStorageBuffer) {
1898 is_storage_buffer = true;
1899 }
Chris Forbes47567b72017-06-09 12:09:45 -07001900 type = module->get_def(type.word(3));
1901 }
1902 }
1903
1904 switch (type.opcode()) {
1905 case spv::OpTypeStruct: {
1906 for (auto insn : *module) {
1907 if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
1908 if (insn.word(2) == spv::DecorationBlock) {
Chris Forbes9f89d752018-03-07 12:57:48 -08001909 if (is_storage_buffer) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001910 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1911 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1912 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001913 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001914 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
1915 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
1916 ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
1917 return ret;
Chris Forbes9f89d752018-03-07 12:57:48 -08001918 }
Chris Forbes47567b72017-06-09 12:09:45 -07001919 } else if (insn.word(2) == spv::DecorationBufferBlock) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001920 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1921 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
1922 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001923 }
1924 }
1925 }
1926
1927 // Invalid
Jeff Bolze54ae892018-09-08 12:16:29 -05001928 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001929 }
1930
1931 case spv::OpTypeSampler:
Jeff Bolze54ae892018-09-08 12:16:29 -05001932 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
1933 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1934 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001935
Chris Forbes73c00bf2018-06-22 16:28:06 -07001936 case spv::OpTypeSampledImage: {
1937 // Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
1938 // buffer descriptor doesn't really provide one. Allow this slight mismatch.
1939 auto image_type = module->get_def(type.word(2));
1940 auto dim = image_type.word(3);
1941 auto sampled = image_type.word(7);
1942 if (dim == spv::DimBuffer && sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001943 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1944 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001945 }
Chris Forbes73c00bf2018-06-22 16:28:06 -07001946 }
Jeff Bolze54ae892018-09-08 12:16:29 -05001947 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1948 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001949
1950 case spv::OpTypeImage: {
1951 // Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
1952 // SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
1953 auto dim = type.word(3);
1954 auto sampled = type.word(7);
1955
1956 if (dim == spv::DimSubpassData) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001957 ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
1958 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001959 } else if (dim == spv::DimBuffer) {
1960 if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001961 ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
1962 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001963 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001964 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
1965 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001966 }
1967 } else if (sampled == 1) {
Jeff Bolze54ae892018-09-08 12:16:29 -05001968 ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
1969 ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
1970 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001971 } else {
Jeff Bolze54ae892018-09-08 12:16:29 -05001972 ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
1973 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001974 }
1975 }
Shannon McPherson0fa28232018-11-01 11:59:02 -06001976 case spv::OpTypeAccelerationStructureNV:
Eric Werness30127fd2018-10-31 21:01:03 -07001977 ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
Jeff Bolz105d6492018-09-29 15:46:44 -05001978 return ret;
Chris Forbes47567b72017-06-09 12:09:45 -07001979
1980 // We shouldn't really see any other junk types -- but if we do, they're a mismatch.
1981 default:
Jeff Bolze54ae892018-09-08 12:16:29 -05001982 return ret; // Matches nothing
Chris Forbes47567b72017-06-09 12:09:45 -07001983 }
1984}
1985
Jeff Bolze54ae892018-09-08 12:16:29 -05001986static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
Chris Forbes73c00bf2018-06-22 16:28:06 -07001987 std::stringstream ss;
Jeff Bolze54ae892018-09-08 12:16:29 -05001988 for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
1989 if (ss.tellp()) ss << ", ";
1990 ss << string_VkDescriptorType(VkDescriptorType(*it));
Chris Forbes73c00bf2018-06-22 16:28:06 -07001991 }
1992 return ss.str();
1993}
1994
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07001995bool CoreChecks::RequirePropertyFlag(VkBool32 check, char const *flag, char const *structure) const {
Jeff Bolzee743412019-06-20 22:24:32 -05001996 if (!check) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07001997 if (LogError(device, kVUID_Core_Shader_ExceedDeviceLimit,
1998 "Shader requires flag %s set in %s but it is not set on the device", flag, structure)) {
Jeff Bolzee743412019-06-20 22:24:32 -05001999 return true;
2000 }
2001 }
2002
2003 return false;
2004}
2005
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002006bool CoreChecks::RequireFeature(VkBool32 feature, char const *feature_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002007 if (!feature) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002008 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device",
2009 feature_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002010 return true;
2011 }
2012 }
2013
2014 return false;
2015}
2016
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002017bool CoreChecks::RequireExtension(bool extension, char const *extension_name) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002018 if (!extension) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002019 if (LogError(device, kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
2020 extension_name)) {
Chris Forbes47567b72017-06-09 12:09:45 -07002021 return true;
2022 }
2023 }
2024
2025 return false;
2026}
2027
John Zulaufac4c6e12019-07-01 16:05:58 -06002028bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07002029 bool skip = false;
2030
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002031 struct FeaturePointer {
2032 // Callable object to test if this feature is enabled in the given aggregate feature struct
2033 const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
2034
2035 // Test if feature pointer is populated
2036 explicit operator bool() const { return static_cast<bool>(IsEnabled); }
2037
2038 // Default and nullptr constructor to create an empty FeaturePointer
2039 FeaturePointer() : IsEnabled(nullptr) {}
2040 FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
2041
2042 // Constructors to populate FeaturePointer based on given pointer to member
2043 FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
2044 : IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002045 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan11Features::*ptr)
2046 : IsEnabled([=](const DeviceFeatures &features) { return features.core11.*ptr; }) {}
2047 FeaturePointer(VkBool32 VkPhysicalDeviceVulkan12Features::*ptr)
2048 : IsEnabled([=](const DeviceFeatures &features) { return features.core12.*ptr; }) {}
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07002049 FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
2050 : IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
Jeff Bolze4356752019-03-07 11:23:46 -06002051 FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
2052 : IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
Jason Macnakc5a621d2019-06-10 12:42:50 -07002053 FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
2054 : IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
Jason Macnak325e8b52019-06-10 13:33:10 -07002055 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
2056 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
Jason Macnakd7fddf82019-06-13 09:52:49 -07002057 FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
2058 : IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
Jeff Bolz38f6cb52019-06-30 16:26:44 -05002059 FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
2060 : IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
Jeff Bolza38fd3b2019-07-21 11:42:11 -05002061 FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
2062 : IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002063 FeaturePointer(VkBool32 VkPhysicalDeviceRayTracingFeaturesKHR::*ptr)
2064 : IsEnabled([=](const DeviceFeatures &features) { return features.ray_tracing_features.*ptr; }) {}
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002065 };
2066
Chris Forbes47567b72017-06-09 12:09:45 -07002067 struct CapabilityInfo {
2068 char const *name;
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002069 FeaturePointer feature;
Tony-LunarG2ec96bb2019-11-26 13:43:02 -07002070 ExtEnabled DeviceExtensions::*extension;
Chris Forbes47567b72017-06-09 12:09:45 -07002071 };
2072
Chris Forbes47567b72017-06-09 12:09:45 -07002073 // clang-format off
Dave Houltoneb10ea82017-12-22 12:21:50 -07002074 static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
Chris Forbes47567b72017-06-09 12:09:45 -07002075 // Capabilities always supported by a Vulkan 1.0 implementation -- no
2076 // feature bits.
2077 {spv::CapabilityMatrix, {nullptr}},
2078 {spv::CapabilityShader, {nullptr}},
2079 {spv::CapabilityInputAttachment, {nullptr}},
2080 {spv::CapabilitySampled1D, {nullptr}},
2081 {spv::CapabilityImage1D, {nullptr}},
2082 {spv::CapabilitySampledBuffer, {nullptr}},
Toni Merilehtib13a4a22019-05-21 12:58:44 +03002083 {spv::CapabilityStorageImageExtendedFormats, {nullptr}},
Chris Forbes47567b72017-06-09 12:09:45 -07002084 {spv::CapabilityImageQuery, {nullptr}},
2085 {spv::CapabilityDerivativeControl, {nullptr}},
2086
2087 // Capabilities that are optionally supported, but require a feature to
2088 // be enabled on the device
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002089 {spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
2090 {spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
2091 {spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
2092 {spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
2093 {spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
2094 {spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
2095 {spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
2096 {spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
2097 {spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
2098 {spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
2099 {spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
2100 {spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
2101 {spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
2102 {spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
2103 {spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
2104 {spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
2105 {spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
2106 {spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
2107 {spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
2108 {spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002109 {spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
2110 {spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
2111 {spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
2112 {spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
Jeff Bolzfdf96072018-04-10 14:32:18 -05002113
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002114 {spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002115 {spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::runtimeDescriptorArray", &VkPhysicalDeviceVulkan12Features::runtimeDescriptorArray}},
2116 {spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayDynamicIndexing}},
2117 {spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayDynamicIndexing}},
2118 {spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayDynamicIndexing}},
2119 {spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformBufferArrayNonUniformIndexing}},
2120 {spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderSampledImageArrayNonUniformIndexing}},
2121 {spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageBufferArrayNonUniformIndexing}},
2122 {spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageImageArrayNonUniformIndexing}},
2123 {spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderInputAttachmentArrayNonUniformIndexing}},
2124 {spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderUniformTexelBufferArrayNonUniformIndexing}},
2125 {spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeatures::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceVulkan12Features::shaderStorageTexelBufferArrayNonUniformIndexing}},
Chris Forbes47567b72017-06-09 12:09:45 -07002126
2127 // Capabilities that require an extension
Mike Schuchardt8ed5ea02018-07-20 18:24:17 -06002128 {spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
2129 {spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
2130 {spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
2131 {spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
2132 {spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
2133 {spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
2134 {spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
2135 {spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
Jason Macnakb7d091c2019-06-10 11:13:11 -07002136 {spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
aqnuep7033c702018-09-11 18:03:29 +02002137 {spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
amhaganfa0b34d2019-10-15 16:03:53 -04002138 {spv::CapabilityShaderClockKHR, {VK_KHR_SHADER_CLOCK_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_clock }},
Alexander Galazin3bd8e342018-06-14 15:49:07 +02002139
Jason Macnakc5a621d2019-06-10 12:42:50 -07002140 {spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
2141 {spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
Jason Macnakf7019582019-06-13 10:07:26 -07002142 {spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
Jason Macnakc5a621d2019-06-10 12:42:50 -07002143
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002144 {spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
2145 {spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDeviceVulkan12Features::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
2146 {spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDeviceVulkan12Features::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
Brett Lawsonbebfb6f2018-10-23 16:58:50 -07002147
Jason Macnakf7019582019-06-13 10:07:26 -07002148 {spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
2149 {spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
Jose-Emilio Munoz-Lopez1109b452018-08-21 09:44:07 +01002150
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002151 {spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceVulkan12Features::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
2152 {spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceVulkan12Features::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
Jeff Bolze4356752019-03-07 11:23:46 -06002153
Jason Macnakd7fddf82019-06-13 09:52:49 -07002154 {spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
2155
Jeff Bolze4356752019-03-07 11:23:46 -06002156 {spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00002157
Graeme Leese41e6b842019-08-02 10:49:14 +01002158 {spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
2159 {spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserve", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
2160 {spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZero", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
2161 {spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTE", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
2162 {spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZ", nullptr, &DeviceExtensions::vk_khr_shader_float_controls}},
Jeff Bolz38f6cb52019-06-30 16:26:44 -05002163
2164 {spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
2165 {spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
2166 {spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
Jeff Bolza38fd3b2019-07-21 11:42:11 -05002167 {spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06002168
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002169 {spv::CapabilityPhysicalStorageBufferAddresses, {"VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_ext_buffer_device_address}},
Jeff Bolz4563f2a2019-12-10 13:30:30 -06002170 // Should be non-EXT token, but Android SPIRV-Headers are out of date, and the token value is the same anyway
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002171 {spv::CapabilityPhysicalStorageBufferAddressesEXT, {"VkPhysicalDeviceBufferDeviceAddressFeaturesEXT::bufferDeviceAddress", &VkPhysicalDeviceVulkan12Features::bufferDeviceAddress, &DeviceExtensions::vk_khr_buffer_device_address}},
Jeff Bolz443c2ca2020-03-19 12:11:51 -05002172
2173 {spv::CapabilityRayTracingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracing, &DeviceExtensions::vk_khr_ray_tracing}},
2174 {spv::CapabilityRayQueryProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery", &VkPhysicalDeviceRayTracingFeaturesKHR::rayQuery, &DeviceExtensions::vk_khr_ray_tracing}},
2175 {spv::CapabilityRayTraversalPrimitiveCullingProvisionalKHR, {"VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling", &VkPhysicalDeviceRayTracingFeaturesKHR::rayTracingPrimitiveCulling, &DeviceExtensions::vk_khr_ray_tracing}},
Chris Forbes47567b72017-06-09 12:09:45 -07002176 };
2177 // clang-format on
2178
2179 for (auto insn : *src) {
2180 if (insn.opcode() == spv::OpCapability) {
Dave Houltoneb10ea82017-12-22 12:21:50 -07002181 size_t n = capabilities.count(insn.word(1));
2182 if (1 == n) { // key occurs exactly once
2183 auto it = capabilities.find(insn.word(1));
2184 if (it != capabilities.end()) {
2185 if (it->second.feature) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002186 skip |= RequireFeature(it->second.feature.IsEnabled(enabled_features), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07002187 }
2188 if (it->second.extension) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002189 skip |= RequireExtension(IsExtEnabled((device_extensions.*(it->second.extension))), it->second.name);
Dave Houltoneb10ea82017-12-22 12:21:50 -07002190 }
Chris Forbes47567b72017-06-09 12:09:45 -07002191 }
Dave Houltoneb10ea82017-12-22 12:21:50 -07002192 } else if (1 < n) { // key occurs multiple times, at least one must be enabled
2193 bool needs_feature = false, has_feature = false;
2194 bool needs_ext = false, has_ext = false;
2195 std::string feature_names = "(one of) [ ";
2196 std::string extension_names = feature_names;
2197 auto caps = capabilities.equal_range(insn.word(1));
2198 for (auto it = caps.first; it != caps.second; ++it) {
2199 if (it->second.feature) {
2200 needs_feature = true;
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06002201 has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
Dave Houltoneb10ea82017-12-22 12:21:50 -07002202 feature_names += it->second.name;
2203 feature_names += " ";
2204 }
2205 if (it->second.extension) {
2206 needs_ext = true;
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06002207 has_ext = has_ext || device_extensions.*(it->second.extension);
Dave Houltoneb10ea82017-12-22 12:21:50 -07002208 extension_names += it->second.name;
2209 extension_names += " ";
2210 }
2211 }
2212 if (needs_feature) {
2213 feature_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002214 skip |= RequireFeature(has_feature, feature_names.c_str());
Dave Houltoneb10ea82017-12-22 12:21:50 -07002215 }
2216 if (needs_ext) {
2217 extension_names += "]";
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002218 skip |= RequireExtension(has_ext, extension_names.c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07002219 }
Graeme Leesec82dbe02019-08-02 10:44:21 +01002220 }
2221
2222 { // Do group non-uniform checks
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002223 const VkSubgroupFeatureFlags supportedOperations = phys_dev_props_core11.subgroupSupportedOperations;
2224 const VkSubgroupFeatureFlags supportedStages = phys_dev_props_core11.subgroupSupportedStages;
Jeff Bolzee743412019-06-20 22:24:32 -05002225
2226 switch (insn.word(1)) {
2227 default:
2228 break;
2229 case spv::CapabilityGroupNonUniform:
2230 case spv::CapabilityGroupNonUniformVote:
2231 case spv::CapabilityGroupNonUniformArithmetic:
2232 case spv::CapabilityGroupNonUniformBallot:
2233 case spv::CapabilityGroupNonUniformShuffle:
2234 case spv::CapabilityGroupNonUniformShuffleRelative:
2235 case spv::CapabilityGroupNonUniformClustered:
2236 case spv::CapabilityGroupNonUniformQuad:
2237 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002238 RequirePropertyFlag(supportedStages & stage, string_VkShaderStageFlagBits(stage),
Jeff Bolzee743412019-06-20 22:24:32 -05002239 "VkPhysicalDeviceSubgroupProperties::supportedStages");
2240 break;
2241 }
2242
2243 switch (insn.word(1)) {
2244 default:
2245 break;
2246 case spv::CapabilityGroupNonUniform:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002247 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT, "VK_SUBGROUP_FEATURE_BASIC_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002248 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2249 break;
2250 case spv::CapabilityGroupNonUniformVote:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002251 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT, "VK_SUBGROUP_FEATURE_VOTE_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002252 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2253 break;
2254 case spv::CapabilityGroupNonUniformArithmetic:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002255 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002256 "VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
2257 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2258 break;
2259 case spv::CapabilityGroupNonUniformBallot:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002260 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT, "VK_SUBGROUP_FEATURE_BALLOT_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002261 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2262 break;
2263 case spv::CapabilityGroupNonUniformShuffle:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002264 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002265 "VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
2266 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2267 break;
2268 case spv::CapabilityGroupNonUniformShuffleRelative:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002269 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002270 "VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
2271 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2272 break;
2273 case spv::CapabilityGroupNonUniformClustered:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002274 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
Jeff Bolzee743412019-06-20 22:24:32 -05002275 "VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
2276 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2277 break;
2278 case spv::CapabilityGroupNonUniformQuad:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002279 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT, "VK_SUBGROUP_FEATURE_QUAD_BIT",
Jeff Bolzee743412019-06-20 22:24:32 -05002280 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2281 break;
2282 case spv::CapabilityGroupNonUniformPartitionedNV:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002283 RequirePropertyFlag(supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
Jeff Bolzee743412019-06-20 22:24:32 -05002284 "VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
2285 "VkPhysicalDeviceSubgroupProperties::supportedOperations");
2286 break;
2287 }
Chris Forbes47567b72017-06-09 12:09:45 -07002288 }
baldurk4095f932020-02-16 13:24:42 +00002289 } else if (insn.opcode() == spv::OpExtension) {
2290 std::string extension_name = (char const *)&insn.word(1);
2291
2292 if (extension_name == "SPV_KHR_non_semantic_info") {
2293 skip |= RequireExtension(IsExtEnabled(device_extensions.vk_khr_shader_non_semantic_info),
2294 VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME);
2295 }
Chris Forbes47567b72017-06-09 12:09:45 -07002296 }
2297 }
2298
Jeff Bolzee743412019-06-20 22:24:32 -05002299 return skip;
2300}
2301
locke-lunarg63e4daf2020-08-17 17:53:25 -06002302bool CoreChecks::ValidateShaderStageWritableOrAtomicDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor,
2303 bool has_atomic_descriptor) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002304 bool skip = false;
2305
locke-lunarg63e4daf2020-08-17 17:53:25 -06002306 if (has_writable_descriptor || has_atomic_descriptor) {
Chris Forbes349b3132018-03-07 11:38:08 -08002307 switch (stage) {
2308 case VK_SHADER_STAGE_COMPUTE_BIT:
Jeff Bolz148d94e2018-12-13 21:25:56 -06002309 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2310 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2311 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2312 case VK_SHADER_STAGE_MISS_BIT_NV:
2313 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2314 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2315 case VK_SHADER_STAGE_TASK_BIT_NV:
2316 case VK_SHADER_STAGE_MESH_BIT_NV:
Chris Forbes349b3132018-03-07 11:38:08 -08002317 /* No feature requirements for writes and atomics from compute
Jeff Bolz148d94e2018-12-13 21:25:56 -06002318 * raytracing, or mesh stages */
Chris Forbes349b3132018-03-07 11:38:08 -08002319 break;
2320 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002321 skip |= RequireFeature(enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08002322 break;
2323 default:
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002324 skip |= RequireFeature(enabled_features.core.vertexPipelineStoresAndAtomics, "vertexPipelineStoresAndAtomics");
Chris Forbes349b3132018-03-07 11:38:08 -08002325 break;
2326 }
2327 }
2328
Chris Forbes47567b72017-06-09 12:09:45 -07002329 return skip;
2330}
2331
Jeff Bolz526f2d52019-09-18 13:18:08 -05002332bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage) const {
Jeff Bolzee743412019-06-20 22:24:32 -05002333 bool skip = false;
2334
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002335 auto const subgroup_props = phys_dev_props_core11;
Jeff Bolzee743412019-06-20 22:24:32 -05002336
Jeff Bolz526f2d52019-09-18 13:18:08 -05002337 for (auto inst : *module) {
Jeff Bolzee743412019-06-20 22:24:32 -05002338 // Check the quad operations.
2339 switch (inst.opcode()) {
2340 default:
2341 break;
2342 case spv::OpGroupNonUniformQuadBroadcast:
2343 case spv::OpGroupNonUniformQuadSwap:
2344 if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002345 skip |= RequireFeature(subgroup_props.subgroupQuadOperationsInAllStages,
Jeff Bolzee743412019-06-20 22:24:32 -05002346 "VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
2347 }
2348 break;
2349 }
Jeff Bolz526f2d52019-09-18 13:18:08 -05002350
Piers Daniell41b8c5d2020-01-10 15:42:00 -07002351 if (!enabled_features.core12.shaderSubgroupExtendedTypes) {
Jeff Bolz526f2d52019-09-18 13:18:08 -05002352 switch (inst.opcode()) {
2353 default:
2354 break;
2355 case spv::OpGroupNonUniformAllEqual:
2356 case spv::OpGroupNonUniformBroadcast:
2357 case spv::OpGroupNonUniformBroadcastFirst:
2358 case spv::OpGroupNonUniformShuffle:
2359 case spv::OpGroupNonUniformShuffleXor:
2360 case spv::OpGroupNonUniformShuffleUp:
2361 case spv::OpGroupNonUniformShuffleDown:
2362 case spv::OpGroupNonUniformIAdd:
2363 case spv::OpGroupNonUniformFAdd:
2364 case spv::OpGroupNonUniformIMul:
2365 case spv::OpGroupNonUniformFMul:
2366 case spv::OpGroupNonUniformSMin:
2367 case spv::OpGroupNonUniformUMin:
2368 case spv::OpGroupNonUniformFMin:
2369 case spv::OpGroupNonUniformSMax:
2370 case spv::OpGroupNonUniformUMax:
2371 case spv::OpGroupNonUniformFMax:
2372 case spv::OpGroupNonUniformBitwiseAnd:
2373 case spv::OpGroupNonUniformBitwiseOr:
2374 case spv::OpGroupNonUniformBitwiseXor:
2375 case spv::OpGroupNonUniformLogicalAnd:
2376 case spv::OpGroupNonUniformLogicalOr:
2377 case spv::OpGroupNonUniformLogicalXor:
2378 case spv::OpGroupNonUniformQuadBroadcast:
2379 case spv::OpGroupNonUniformQuadSwap: {
2380 auto type = module->get_def(inst.word(1));
2381
2382 if (type.opcode() == spv::OpTypeVector) {
2383 // Get the element type
2384 type = module->get_def(type.word(2));
2385 }
2386
2387 if (type.opcode() == spv::OpTypeBool) {
2388 break;
2389 }
2390
2391 // Both OpTypeInt and OpTypeFloat the width is in the 2nd word.
2392 const uint32_t width = type.word(2);
2393
2394 if ((type.opcode() == spv::OpTypeFloat && width == 16) ||
2395 (type.opcode() == spv::OpTypeInt && (width == 8 || width == 16 || width == 64))) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07002396 skip |= RequireFeature(enabled_features.core12.shaderSubgroupExtendedTypes,
Tony-LunarGa74d3fe2019-11-22 15:43:20 -07002397 "VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures::shaderSubgroupExtendedTypes");
Jeff Bolz526f2d52019-09-18 13:18:08 -05002398 }
2399 break;
2400 }
2401 }
2402 }
Jeff Bolzee743412019-06-20 22:24:32 -05002403 }
2404
2405 return skip;
2406}
2407
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002408bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002409 const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002410 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
2411 pStage->stage == VK_SHADER_STAGE_ALL) {
2412 return false;
2413 }
2414
2415 bool skip = false;
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07002416 auto const &limits = phys_dev_props.limits;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002417
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002418 std::set<uint32_t> patchIDs;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002419 struct Variable {
2420 uint32_t baseTypePtrID;
2421 uint32_t ID;
2422 uint32_t storageClass;
2423 };
2424 std::vector<Variable> variables;
2425
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002426 uint32_t numVertices = 0;
2427
Jeff Bolzf234bf82019-11-04 14:07:15 -06002428 auto entrypointVariables = FindEntrypointInterfaces(entrypoint);
2429
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002430 for (auto insn : *src) {
2431 switch (insn.opcode()) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002432 // Find all Patch decorations
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002433 case spv::OpDecorate:
2434 switch (insn.word(2)) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002435 case spv::DecorationPatch: {
2436 patchIDs.insert(insn.word(1));
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002437 break;
2438 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002439 default:
2440 break;
2441 }
2442 break;
2443 // Find all input and output variables
2444 case spv::OpVariable: {
2445 Variable var = {};
2446 var.storageClass = insn.word(3);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002447 if ((var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) &&
2448 // Only include variables in the entrypoint's interface
2449 find(entrypointVariables.begin(), entrypointVariables.end(), insn.word(2)) != entrypointVariables.end()) {
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002450 var.baseTypePtrID = insn.word(1);
2451 var.ID = insn.word(2);
2452 variables.push_back(var);
2453 }
2454 break;
2455 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002456 case spv::OpExecutionMode:
2457 if (insn.word(1) == entrypoint.word(2)) {
2458 switch (insn.word(2)) {
2459 default:
2460 break;
2461 case spv::ExecutionModeOutputVertices:
2462 numVertices = insn.word(3);
2463 break;
2464 }
2465 }
2466 break;
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002467 default:
2468 break;
2469 }
2470 }
2471
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002472 bool strip_output_array_level =
2473 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
2474 bool strip_input_array_level =
2475 (pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
2476 pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
2477
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002478 uint32_t numCompIn = 0, numCompOut = 0;
Jeff Bolzf234bf82019-11-04 14:07:15 -06002479 int maxCompIn = 0, maxCompOut = 0;
2480
2481 auto inputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassInput, strip_input_array_level);
2482 auto outputs = CollectInterfaceByLocation(src, entrypoint, spv::StorageClassOutput, strip_output_array_level);
2483
2484 // Find max component location used for input variables.
2485 for (auto &var : inputs) {
2486 int location = var.first.first;
2487 int component = var.first.second;
2488 interface_var &iv = var.second;
2489
2490 // Only need to look at the first location, since we use the type's whole size
2491 if (iv.offset != 0) {
2492 continue;
2493 }
2494
2495 if (iv.is_patch) {
2496 continue;
2497 }
2498
2499 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_input_array_level);
2500 maxCompIn = std::max(maxCompIn, location * 4 + component + numComponents);
2501 }
2502
2503 // Find max component location used for output variables.
2504 for (auto &var : outputs) {
2505 int location = var.first.first;
2506 int component = var.first.second;
2507 interface_var &iv = var.second;
2508
2509 // Only need to look at the first location, since we use the type's whole size
2510 if (iv.offset != 0) {
2511 continue;
2512 }
2513
2514 if (iv.is_patch) {
2515 continue;
2516 }
2517
2518 int numComponents = GetComponentsConsumedByType(src, iv.type_id, strip_output_array_level);
2519 maxCompOut = std::max(maxCompOut, location * 4 + component + numComponents);
2520 }
2521
2522 // XXX TODO: Would be nice to rewrite this to use CollectInterfaceByLocation (or something similar),
2523 // but that doesn't include builtins.
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002524 for (auto &var : variables) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002525 // Check if the variable is a patch. Patches can also be members of blocks,
2526 // but if they are then the top-level arrayness has already been stripped
2527 // by the time GetComponentsConsumedByType gets to it.
2528 bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002529
2530 if (var.storageClass == spv::StorageClassInput) {
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002531 numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002532 } else { // var.storageClass == spv::StorageClassOutput
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002533 numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002534 }
2535 }
2536
2537 switch (pStage->stage) {
2538 case VK_SHADER_STAGE_VERTEX_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002539 if (numCompOut > limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002540 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2541 "Invalid Pipeline CreateInfo State: Vertex shader exceeds "
2542 "VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
2543 "components by %u components",
2544 limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002545 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002546 if (maxCompOut > (int)limits.maxVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002547 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2548 "Invalid Pipeline CreateInfo State: Vertex shader output variable uses location that "
2549 "exceeds component limit VkPhysicalDeviceLimits::maxVertexOutputComponents (%u)",
2550 limits.maxVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002551 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002552 break;
2553
2554 case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002555 if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002556 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2557 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2558 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
2559 "components by %u components",
2560 limits.maxTessellationControlPerVertexInputComponents,
2561 numCompIn - limits.maxTessellationControlPerVertexInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002562 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002563 if (maxCompIn > (int)limits.maxTessellationControlPerVertexInputComponents) {
2564 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002565 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2566 "Invalid Pipeline CreateInfo State: Tessellation control shader input variable uses location that "
2567 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents (%u)",
2568 limits.maxTessellationControlPerVertexInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002569 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002570 if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002571 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2572 "Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
2573 "VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
2574 "components by %u components",
2575 limits.maxTessellationControlPerVertexOutputComponents,
2576 numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002577 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002578 if (maxCompOut > (int)limits.maxTessellationControlPerVertexOutputComponents) {
2579 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002580 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2581 "Invalid Pipeline CreateInfo State: Tessellation control shader output variable uses location that "
2582 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents (%u)",
2583 limits.maxTessellationControlPerVertexOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002584 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002585 break;
2586
2587 case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002588 if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002589 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2590 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2591 "VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
2592 "components by %u components",
2593 limits.maxTessellationEvaluationInputComponents,
2594 numCompIn - limits.maxTessellationEvaluationInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002595 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002596 if (maxCompIn > (int)limits.maxTessellationEvaluationInputComponents) {
2597 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002598 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2599 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader input variable uses location that "
2600 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents (%u)",
2601 limits.maxTessellationEvaluationInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002602 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002603 if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002604 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2605 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
2606 "VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
2607 "components by %u components",
2608 limits.maxTessellationEvaluationOutputComponents,
2609 numCompOut - limits.maxTessellationEvaluationOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002610 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002611 if (maxCompOut > (int)limits.maxTessellationEvaluationOutputComponents) {
2612 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002613 LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2614 "Invalid Pipeline CreateInfo State: Tessellation evaluation shader output variable uses location that "
2615 "exceeds component limit VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents (%u)",
2616 limits.maxTessellationEvaluationOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002617 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002618 break;
2619
2620 case VK_SHADER_STAGE_GEOMETRY_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002621 if (numCompIn > limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002622 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2623 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2624 "VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
2625 "components by %u components",
2626 limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002627 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002628 if (maxCompIn > (int)limits.maxGeometryInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002629 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2630 "Invalid Pipeline CreateInfo State: Geometry shader input variable uses location that "
2631 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryInputComponents (%u)",
2632 limits.maxGeometryInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002633 }
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002634 if (numCompOut > limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002635 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2636 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2637 "VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
2638 "components by %u components",
2639 limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002640 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002641 if (maxCompOut > (int)limits.maxGeometryOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002642 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2643 "Invalid Pipeline CreateInfo State: Geometry shader output variable uses location that "
2644 "exceeds component limit VkPhysicalDeviceLimits::maxGeometryOutputComponents (%u)",
2645 limits.maxGeometryOutputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002646 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002647 if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002648 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2649 "Invalid Pipeline CreateInfo State: Geometry shader exceeds "
2650 "VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
2651 "components by %u components",
2652 limits.maxGeometryTotalOutputComponents,
2653 numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05002654 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002655 break;
2656
2657 case VK_SHADER_STAGE_FRAGMENT_BIT:
Mark Lobodzinski57a44272019-02-27 12:40:50 -07002658 if (numCompIn > limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002659 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2660 "Invalid Pipeline CreateInfo State: Fragment shader exceeds "
2661 "VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
2662 "components by %u components",
2663 limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002664 }
Jeff Bolzf234bf82019-11-04 14:07:15 -06002665 if (maxCompIn > (int)limits.maxFragmentInputComponents) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002666 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_ExceedDeviceLimit,
2667 "Invalid Pipeline CreateInfo State: Fragment shader input variable uses location that "
2668 "exceeds component limit VkPhysicalDeviceLimits::maxFragmentInputComponents (%u)",
2669 limits.maxFragmentInputComponents);
Jeff Bolzf234bf82019-11-04 14:07:15 -06002670 }
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002671 break;
2672
Jeff Bolz148d94e2018-12-13 21:25:56 -06002673 case VK_SHADER_STAGE_RAYGEN_BIT_NV:
2674 case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
2675 case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
2676 case VK_SHADER_STAGE_MISS_BIT_NV:
2677 case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
2678 case VK_SHADER_STAGE_CALLABLE_BIT_NV:
2679 case VK_SHADER_STAGE_TASK_BIT_NV:
2680 case VK_SHADER_STAGE_MESH_BIT_NV:
2681 break;
2682
Daniel Fedai Larsenc939abc2018-08-07 10:01:58 +02002683 default:
2684 assert(false); // This should never happen
2685 }
2686 return skip;
2687}
2688
sfricke-samsungdc96f302020-03-18 20:42:10 -07002689bool CoreChecks::ValidateShaderStageMaxResources(VkShaderStageFlagBits stage, const PIPELINE_STATE *pipeline) const {
2690 bool skip = false;
2691 uint32_t total_resources = 0;
2692
2693 // Only currently testing for graphics and compute pipelines
2694 // TODO: Add check and support for Ray Tracing pipeline VUID 03428
2695 if ((stage & (VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT)) == 0) {
2696 return false;
2697 }
2698
2699 if (stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
2700 // "For the fragment shader stage the framebuffer color attachments also count against this limit"
2701 total_resources += pipeline->rp_state->createInfo.pSubpasses[pipeline->graphicsPipelineCI.subpass].colorAttachmentCount;
2702 }
2703
2704 // TODO: This reuses a lot of GetDescriptorCountMaxPerStage but currently would need to make it agnostic in a way to handle
2705 // input from CreatePipeline and CreatePipelineLayout level
2706 for (auto set_layout : pipeline->pipeline_layout->set_layouts) {
2707 if ((set_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) != 0) {
2708 continue;
2709 }
2710
2711 for (uint32_t binding_idx = 0; binding_idx < set_layout->GetBindingCount(); binding_idx++) {
2712 const VkDescriptorSetLayoutBinding *binding = set_layout->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx);
2713 // Bindings with a descriptorCount of 0 are "reserved" and should be skipped
2714 if (((stage & binding->stageFlags) != 0) && (binding->descriptorCount > 0)) {
2715 // Check only descriptor types listed in maxPerStageResources description in spec
2716 switch (binding->descriptorType) {
2717 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2718 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
2719 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
2720 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2721 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2722 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2723 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2724 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2725 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
2726 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2727 total_resources += binding->descriptorCount;
2728 break;
2729 default:
2730 break;
2731 }
2732 }
2733 }
2734 }
2735
2736 if (total_resources > phys_dev_props.limits.maxPerStageResources) {
2737 const char *vuid = (stage == VK_SHADER_STAGE_COMPUTE_BIT) ? "VUID-VkComputePipelineCreateInfo-layout-01687"
2738 : "VUID-VkGraphicsPipelineCreateInfo-layout-01688";
2739 skip |= LogError(pipeline->pipeline, vuid,
2740 "Invalid Pipeline CreateInfo State: Shader Stage %s exceeds component limit "
2741 "VkPhysicalDeviceLimits::maxPerStageResources (%u)",
2742 string_VkShaderStageFlagBits(stage), phys_dev_props.limits.maxPerStageResources);
2743 }
2744
2745 return skip;
2746}
2747
Jeff Bolze4356752019-03-07 11:23:46 -06002748// copy the specialization constant value into buf, if it is present
2749void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
2750 VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
2751
2752 if (spec && spec_id < spec->mapEntryCount) {
2753 memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
2754 }
2755}
2756
2757// Fill in value with the constant or specialization constant value, if available.
2758// Returns true if the value has been accurately filled out.
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002759static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002760 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
2761 auto type_id = src->get_def(insn.word(1));
2762 if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
2763 return false;
2764 }
2765 switch (insn.opcode()) {
2766 case spv::OpSpecConstant:
2767 *value = insn.word(3);
2768 GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
2769 return true;
2770 case spv::OpConstant:
2771 *value = insn.word(3);
2772 return true;
2773 default:
2774 return false;
2775 }
2776}
2777
2778// Map SPIR-V type to VK_COMPONENT_TYPE enum
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002779VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
Jeff Bolze4356752019-03-07 11:23:46 -06002780 switch (insn.opcode()) {
2781 case spv::OpTypeInt:
2782 switch (insn.word(2)) {
2783 case 8:
2784 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
2785 case 16:
2786 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
2787 case 32:
2788 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
2789 case 64:
2790 return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
2791 default:
2792 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2793 }
2794 case spv::OpTypeFloat:
2795 switch (insn.word(2)) {
2796 case 16:
2797 return VK_COMPONENT_TYPE_FLOAT16_NV;
2798 case 32:
2799 return VK_COMPONENT_TYPE_FLOAT32_NV;
2800 case 64:
2801 return VK_COMPONENT_TYPE_FLOAT64_NV;
2802 default:
2803 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2804 }
2805 default:
2806 return VK_COMPONENT_TYPE_MAX_ENUM_NV;
2807 }
2808}
2809
2810// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
2811// in SPIRV-Tools (e.g. due to specialization constant usage).
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002812bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
John Zulaufac4c6e12019-07-01 16:05:58 -06002813 const PIPELINE_STATE *pipeline) const {
Jeff Bolze4356752019-03-07 11:23:46 -06002814 bool skip = false;
2815
2816 // Map SPIR-V result ID to specialization constant id (SpecId decoration value)
2817 std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
2818 // Map SPIR-V result ID to the ID of its type.
2819 std::unordered_map<uint32_t, uint32_t> id_to_type_id;
2820
2821 struct CoopMatType {
2822 uint32_t scope, rows, cols;
2823 VkComponentTypeNV component_type;
2824 bool all_constant;
2825
2826 CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
2827
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06002828 void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
Jeff Bolze4356752019-03-07 11:23:46 -06002829 const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
2830 spirv_inst_iter insn = src->get_def(id);
2831 uint32_t component_type_id = insn.word(2);
2832 uint32_t scope_id = insn.word(3);
2833 uint32_t rows_id = insn.word(4);
2834 uint32_t cols_id = insn.word(5);
2835 auto component_type_iter = src->get_def(component_type_id);
2836 auto scope_iter = src->get_def(scope_id);
2837 auto rows_iter = src->get_def(rows_id);
2838 auto cols_iter = src->get_def(cols_id);
2839
2840 all_constant = true;
2841 if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
2842 all_constant = false;
2843 }
2844 if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
2845 all_constant = false;
2846 }
2847 if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
2848 all_constant = false;
2849 }
2850 component_type = GetComponentType(component_type_iter, src);
2851 }
2852 };
2853
2854 bool seen_coopmat_capability = false;
2855
2856 for (auto insn : *src) {
2857 // Whitelist instructions whose result can be a cooperative matrix type, and
2858 // keep track of their types. It would be nice if SPIRV-Headers generated code
2859 // to identify which instructions have a result type and result id. Lacking that,
2860 // this whitelist is based on the set of instructions that
2861 // SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
2862 switch (insn.opcode()) {
2863 case spv::OpLoad:
2864 case spv::OpCooperativeMatrixLoadNV:
2865 case spv::OpCooperativeMatrixMulAddNV:
2866 case spv::OpSNegate:
2867 case spv::OpFNegate:
2868 case spv::OpIAdd:
2869 case spv::OpFAdd:
2870 case spv::OpISub:
2871 case spv::OpFSub:
2872 case spv::OpFDiv:
2873 case spv::OpSDiv:
2874 case spv::OpUDiv:
2875 case spv::OpMatrixTimesScalar:
2876 case spv::OpConstantComposite:
2877 case spv::OpCompositeConstruct:
2878 case spv::OpConvertFToU:
2879 case spv::OpConvertFToS:
2880 case spv::OpConvertSToF:
2881 case spv::OpConvertUToF:
2882 case spv::OpUConvert:
2883 case spv::OpSConvert:
2884 case spv::OpFConvert:
2885 id_to_type_id[insn.word(2)] = insn.word(1);
2886 break;
2887 default:
2888 break;
2889 }
2890
2891 switch (insn.opcode()) {
2892 case spv::OpDecorate:
2893 if (insn.word(2) == spv::DecorationSpecId) {
2894 id_to_spec_id[insn.word(1)] = insn.word(3);
2895 }
2896 break;
2897 case spv::OpCapability:
2898 if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
2899 seen_coopmat_capability = true;
2900
2901 if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002902 skip |= LogError(
2903 pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixSupportedStages,
2904 "OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
2905 phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
Jeff Bolze4356752019-03-07 11:23:46 -06002906 }
2907 }
2908 break;
2909 case spv::OpMemoryModel:
2910 // If the capability isn't enabled, don't bother with the rest of this function.
2911 // OpMemoryModel is the first required instruction after all OpCapability instructions.
2912 if (!seen_coopmat_capability) {
2913 return skip;
2914 }
2915 break;
2916 case spv::OpTypeCooperativeMatrixNV: {
2917 CoopMatType M;
2918 M.Init(insn.word(1), src, pStage, id_to_spec_id);
2919
2920 if (M.all_constant) {
2921 // Validate that the type parameters are all supported for one of the
2922 // operands of a cooperative matrix property.
2923 bool valid = false;
2924 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2925 if (cooperative_matrix_properties[i].AType == M.component_type &&
2926 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
2927 cooperative_matrix_properties[i].scope == M.scope) {
2928 valid = true;
2929 break;
2930 }
2931 if (cooperative_matrix_properties[i].BType == M.component_type &&
2932 cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2933 cooperative_matrix_properties[i].scope == M.scope) {
2934 valid = true;
2935 break;
2936 }
2937 if (cooperative_matrix_properties[i].CType == M.component_type &&
2938 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2939 cooperative_matrix_properties[i].scope == M.scope) {
2940 valid = true;
2941 break;
2942 }
2943 if (cooperative_matrix_properties[i].DType == M.component_type &&
2944 cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
2945 cooperative_matrix_properties[i].scope == M.scope) {
2946 valid = true;
2947 break;
2948 }
2949 }
2950 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002951 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixType,
2952 "OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
2953 insn.word(1));
Jeff Bolze4356752019-03-07 11:23:46 -06002954 }
2955 }
2956 break;
2957 }
2958 case spv::OpCooperativeMatrixMulAddNV: {
2959 CoopMatType A, B, C, D;
2960 if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
2961 id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
2962 id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
2963 id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
Mike Schuchardte48dc142019-04-18 09:12:03 -07002964 // Couldn't find type of matrix
2965 assert(false);
Jeff Bolze4356752019-03-07 11:23:46 -06002966 break;
2967 }
2968 D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
2969 A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
2970 B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
2971 C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
2972
2973 if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
2974 // Validate that the type parameters are all supported for the same
2975 // cooperative matrix property.
2976 bool valid = false;
2977 for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
2978 if (cooperative_matrix_properties[i].AType == A.component_type &&
2979 cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
2980 cooperative_matrix_properties[i].scope == A.scope &&
2981
2982 cooperative_matrix_properties[i].BType == B.component_type &&
2983 cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
2984 cooperative_matrix_properties[i].scope == B.scope &&
2985
2986 cooperative_matrix_properties[i].CType == C.component_type &&
2987 cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
2988 cooperative_matrix_properties[i].scope == C.scope &&
2989
2990 cooperative_matrix_properties[i].DType == D.component_type &&
2991 cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
2992 cooperative_matrix_properties[i].scope == D.scope) {
2993 valid = true;
2994 break;
2995 }
2996 }
2997 if (!valid) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07002998 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_CooperativeMatrixMulAdd,
2999 "OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
3000 "VkCooperativeMatrixPropertiesNV",
3001 insn.word(2));
Jeff Bolze4356752019-03-07 11:23:46 -06003002 }
3003 }
3004 break;
3005 }
3006 default:
3007 break;
3008 }
3009 }
3010
3011 return skip;
3012}
3013
John Zulaufac4c6e12019-07-01 16:05:58 -06003014bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003015 auto entrypoint_id = entrypoint.word(2);
3016
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003017 // The first denorm execution mode encountered, along with its bit width.
3018 // Used to check if SeparateDenormSettings is respected.
3019 std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003020
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003021 // The first rounding mode encountered, along with its bit width.
3022 // Used to check if SeparateRoundingModeSettings is respected.
3023 std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003024
3025 bool skip = false;
3026
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003027 uint32_t verticesOut = 0;
3028 uint32_t invocations = 0;
3029
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003030 for (auto insn : *src) {
3031 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3032 auto mode = insn.word(2);
3033 switch (mode) {
3034 case spv::ExecutionModeSignedZeroInfNanPreserve: {
3035 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003036 if ((bit_width == 16 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat16) ||
3037 (bit_width == 32 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat32) ||
3038 (bit_width == 64 && !phys_dev_props_core12.shaderSignedZeroInfNanPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003039 skip |= LogError(
3040 device, kVUID_Core_Shader_FeatureNotEnabled,
3041 "Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
3042 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003043 }
3044 break;
3045 }
3046
3047 case spv::ExecutionModeDenormPreserve: {
3048 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003049 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormPreserveFloat16) ||
3050 (bit_width == 32 && !phys_dev_props_core12.shaderDenormPreserveFloat32) ||
3051 (bit_width == 64 && !phys_dev_props_core12.shaderDenormPreserveFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003052 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3053 "Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
3054 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003055 }
3056
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003057 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
3058 // Register the first denorm execution mode found
3059 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003060 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003061 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003062 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
3063 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003064 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3065 "Shader uses different denorm execution modes for 16 and 64-bit but "
3066 "denormBehaviorIndependence is "
3067 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003068 }
3069 break;
3070
3071 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
3072 break;
3073
3074 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003075 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3076 "Shader uses different denorm execution modes for different bit widths but "
3077 "denormBehaviorIndependence is "
3078 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003079 break;
3080
3081 default:
3082 break;
3083 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003084 }
3085 break;
3086 }
3087
3088 case spv::ExecutionModeDenormFlushToZero: {
3089 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003090 if ((bit_width == 16 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat16) ||
3091 (bit_width == 32 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat32) ||
3092 (bit_width == 64 && !phys_dev_props_core12.shaderDenormFlushToZeroFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003093 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3094 "Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
3095 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003096 }
3097
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003098 if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
3099 // Register the first denorm execution mode found
3100 first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003101 } else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003102 switch (phys_dev_props_core12.denormBehaviorIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003103 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
3104 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003105 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3106 "Shader uses different denorm execution modes for 16 and 64-bit but "
3107 "denormBehaviorIndependence is "
3108 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003109 }
3110 break;
3111
3112 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
3113 break;
3114
3115 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003116 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3117 "Shader uses different denorm execution modes for different bit widths but "
3118 "denormBehaviorIndependence is "
3119 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003120 break;
3121
3122 default:
3123 break;
3124 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003125 }
3126 break;
3127 }
3128
3129 case spv::ExecutionModeRoundingModeRTE: {
3130 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003131 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTEFloat16) ||
3132 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTEFloat32) ||
3133 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTEFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003134 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3135 "Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
3136 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003137 }
3138
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003139 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3140 // Register the first rounding mode found
3141 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003142 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003143 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003144 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
3145 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003146 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3147 "Shader uses different rounding modes for 16 and 64-bit but "
3148 "roundingModeIndependence is "
3149 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003150 }
3151 break;
3152
3153 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
3154 break;
3155
3156 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003157 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3158 "Shader uses different rounding modes for different bit widths but "
3159 "roundingModeIndependence is "
3160 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003161 break;
3162
3163 default:
3164 break;
3165 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003166 }
3167 break;
3168 }
3169
3170 case spv::ExecutionModeRoundingModeRTZ: {
3171 auto bit_width = insn.word(3);
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003172 if ((bit_width == 16 && !phys_dev_props_core12.shaderRoundingModeRTZFloat16) ||
3173 (bit_width == 32 && !phys_dev_props_core12.shaderRoundingModeRTZFloat32) ||
3174 (bit_width == 64 && !phys_dev_props_core12.shaderRoundingModeRTZFloat64)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003175 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3176 "Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
3177 bit_width);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003178 }
3179
Attilio Provenzanof6c0e852019-04-09 11:01:18 +01003180 if (first_rounding_mode.first == spv::ExecutionModeMax) {
3181 // Register the first rounding mode found
3182 first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003183 } else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width) {
Piers Daniell41b8c5d2020-01-10 15:42:00 -07003184 switch (phys_dev_props_core12.roundingModeIndependence) {
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003185 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR:
3186 if (first_rounding_mode.second != 32 && bit_width != 32) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003187 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3188 "Shader uses different rounding modes for 16 and 64-bit but "
3189 "roundingModeIndependence is "
3190 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003191 }
3192 break;
3193
3194 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR:
3195 break;
3196
3197 case VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR:
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003198 skip |= LogError(device, kVUID_Core_Shader_FeatureNotEnabled,
3199 "Shader uses different rounding modes for different bit widths but "
3200 "roundingModeIndependence is "
3201 "VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR on the device");
Jason Ekstrande1e06de2019-08-05 11:43:43 -05003202 break;
3203
3204 default:
3205 break;
3206 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003207 }
3208 break;
3209 }
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003210
3211 case spv::ExecutionModeOutputVertices: {
3212 verticesOut = insn.word(3);
3213 break;
3214 }
3215
3216 case spv::ExecutionModeInvocations: {
3217 invocations = insn.word(3);
3218 break;
3219 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003220 }
3221 }
3222 }
3223
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003224 if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
3225 if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003226 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00714",
3227 "Geometry shader entry point must have an OpExecutionMode instruction that "
3228 "specifies a maximum output vertex count that is greater than 0 and less "
3229 "than or equal to maxGeometryOutputVertices. "
3230 "OutputVertices=%d, maxGeometryOutputVertices=%d",
3231 verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003232 }
3233
3234 if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003235 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00715",
3236 "Geometry shader entry point must have an OpExecutionMode instruction that "
3237 "specifies an invocation count that is greater than 0 and less "
3238 "than or equal to maxGeometryShaderInvocations. "
3239 "Invocations=%d, maxGeometryShaderInvocations=%d",
3240 invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003241 }
3242 }
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003243 return skip;
3244}
3245
locke-lunargd9a069d2019-09-17 01:50:19 -06003246uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
Chris Forbes47567b72017-06-09 12:09:45 -07003247 auto type = module->get_def(type_id);
3248
3249 while (true) {
3250 switch (type.opcode()) {
3251 case spv::OpTypeArray:
Chris Forbes062f1222018-08-21 15:34:15 -07003252 case spv::OpTypeRuntimeArray:
Chris Forbes47567b72017-06-09 12:09:45 -07003253 case spv::OpTypeSampledImage:
3254 type = module->get_def(type.word(2));
3255 break;
3256 case spv::OpTypePointer:
3257 type = module->get_def(type.word(3));
3258 break;
3259 case spv::OpTypeImage: {
3260 auto dim = type.word(3);
3261 auto arrayed = type.word(5);
3262 auto msaa = type.word(6);
3263
Chris Forbes74ba2232018-08-27 15:19:27 -07003264 uint32_t bits = 0;
3265 switch (GetFundamentalType(module, type.word(2))) {
3266 case FORMAT_TYPE_FLOAT:
3267 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
3268 break;
3269 case FORMAT_TYPE_UINT:
3270 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
3271 break;
3272 case FORMAT_TYPE_SINT:
3273 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
3274 break;
3275 default:
3276 break;
3277 }
3278
Chris Forbes47567b72017-06-09 12:09:45 -07003279 switch (dim) {
3280 case spv::Dim1D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003281 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
3282 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003283 case spv::Dim2D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003284 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3285 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
3286 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003287 case spv::Dim3D:
Chris Forbes74ba2232018-08-27 15:19:27 -07003288 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
3289 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003290 case spv::DimCube:
Chris Forbes74ba2232018-08-27 15:19:27 -07003291 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
3292 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003293 case spv::DimSubpassData:
Chris Forbes74ba2232018-08-27 15:19:27 -07003294 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
3295 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003296 default: // buffer, etc.
Chris Forbes74ba2232018-08-27 15:19:27 -07003297 return bits;
Chris Forbes47567b72017-06-09 12:09:45 -07003298 }
3299 }
3300 default:
3301 return 0;
3302 }
3303 }
3304}
3305
3306// For given pipelineLayout verify that the set_layout_node at slot.first
3307// has the requested binding at slot.second and return ptr to that binding
Mark Lobodzinskica6ebe32019-04-25 11:43:37 -06003308static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003309 descriptor_slot_t slot) {
Chris Forbes47567b72017-06-09 12:09:45 -07003310 if (!pipelineLayout) return nullptr;
3311
3312 if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
3313
3314 return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
3315}
3316
Sam Wallsd7ab6db2020-06-19 20:41:54 +01003317int32_t GetShaderResourceDimensionality(const SHADER_MODULE_STATE *module, const interface_var &resource) {
3318 if (module == nullptr) return -1;
3319
3320 auto type = module->get_def(resource.type_id);
3321 while (true) {
3322 switch (type.opcode()) {
3323 case spv::OpTypeSampledImage:
3324 type = module->get_def(type.word(2));
3325 break;
3326 case spv::OpTypePointer:
3327 type = module->get_def(type.word(3));
3328 break;
3329 case spv::OpTypeImage:
3330 return type.word(3);
3331 default:
3332 return -1;
3333 }
3334 }
3335}
3336
3337bool FindLocalSize(SHADER_MODULE_STATE const *src, uint32_t &local_size_x, uint32_t &local_size_y, uint32_t &local_size_z) {
Locke1ec6d952019-04-02 11:57:21 -06003338 for (auto insn : *src) {
3339 if (insn.opcode() == spv::OpEntryPoint) {
3340 auto executionModel = insn.word(1);
3341 auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
3342 if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
3343 auto entrypoint_id = insn.word(2);
3344 for (auto insn1 : *src) {
3345 if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
3346 insn1.word(2) == spv::ExecutionModeLocalSize) {
3347 local_size_x = insn1.word(3);
3348 local_size_y = insn1.word(4);
3349 local_size_z = insn1.word(5);
3350 return true;
3351 }
3352 }
3353 }
3354 }
3355 }
3356 return false;
3357}
3358
locke-lunargd9a069d2019-09-17 01:50:19 -06003359void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
Jeff Bolz105d6492018-09-29 15:46:44 -05003360 auto entrypoint_id = entrypoint.word(2);
Chris Forbes0771b672018-03-22 21:13:46 -07003361 bool is_point_mode = false;
3362
3363 for (auto insn : *src) {
3364 if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
3365 switch (insn.word(2)) {
3366 case spv::ExecutionModePointMode:
3367 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
3368 is_point_mode = true;
3369 break;
3370
3371 case spv::ExecutionModeOutputPoints:
3372 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3373 break;
3374
3375 case spv::ExecutionModeIsolines:
3376 case spv::ExecutionModeOutputLineStrip:
3377 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
3378 break;
3379
3380 case spv::ExecutionModeTriangles:
3381 case spv::ExecutionModeQuads:
3382 case spv::ExecutionModeOutputTriangleStrip:
3383 pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
3384 break;
3385 }
3386 }
3387 }
3388
3389 if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
3390}
3391
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003392// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
3393// o If there is only a vertex shader : gl_PointSize must be written when using points
3394// o If there is a geometry or tessellation shader:
3395// - If shaderTessellationAndGeometryPointSize feature is enabled:
3396// * gl_PointSize must be written in the final geometry stage
3397// - If shaderTessellationAndGeometryPointSize feature is disabled:
3398// * gl_PointSize must NOT be written and a default of 1.0 is assumed
Mark Lobodzinski3c59d972019-04-25 11:28:14 -06003399bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
John Zulaufac4c6e12019-07-01 16:05:58 -06003400 spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003401 if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3402 return false;
3403 }
3404
3405 bool pointsize_written = false;
3406 bool skip = false;
3407
3408 // Search for PointSize built-in decorations
3409 std::vector<uint32_t> pointsize_builtin_offsets;
3410 spirv_inst_iter insn = entrypoint;
3411 while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
3412 if (insn.opcode() == spv::OpMemberDecorate) {
3413 if (insn.word(3) == spv::DecorationBuiltIn) {
3414 if (insn.word(4) == spv::BuiltInPointSize) {
3415 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
3416 }
3417 }
3418 } else if (insn.opcode() == spv::OpDecorate) {
3419 if (insn.word(2) == spv::DecorationBuiltIn) {
3420 if (insn.word(3) == spv::BuiltInPointSize) {
3421 pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
3422 }
3423 }
3424 }
3425
3426 insn++;
3427 }
3428
3429 if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
Mark Lobodzinskid7b03cc2019-04-19 14:23:10 -06003430 !enabled_features.core.shaderTessellationAndGeometryPointSize) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003431 if (pointsize_written) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003432 skip |= LogError(pipeline->pipeline, kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
3433 "Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
3434 "is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003435 }
3436 } else if (!pointsize_written) {
3437 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003438 LogError(pipeline->pipeline, kVUID_Core_Shader_MissingPointSizeBuiltIn,
3439 "Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
3440 string_VkShaderStageFlagBits(stage));
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003441 }
3442 return skip;
3443}
John Zulauf14c355b2019-06-27 16:09:37 -06003444
3445bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
3446 const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
John Zulaufac4c6e12019-07-01 16:05:58 -06003447 const spirv_inst_iter &entrypoint, bool check_point_size) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003448 bool skip = false;
3449
3450 // Check the module
3451 if (!module->has_valid_spirv) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003452 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter",
3453 "%s does not contain valid spirv for stage %s.",
3454 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003455 }
3456
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003457 // If specialization-constant values are given and specialization-constant instructions are present in the shader, the
3458 // specializations should be applied and validated.
3459 if (pStage->pSpecializationInfo != nullptr && pStage->pSpecializationInfo->mapEntryCount > 0 &&
3460 pStage->pSpecializationInfo->pMapEntries != nullptr && module->has_specialization_constants) {
3461 // Gather the specialization-constant values.
3462 auto const &specialization_info = pStage->pSpecializationInfo;
Jeremy Hayes521221d2020-01-15 16:48:49 -07003463 auto const &specialization_data = reinterpret_cast<uint8_t const *>(specialization_info->pData);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003464 std::unordered_map<uint32_t, std::vector<uint32_t>> id_value_map;
3465 id_value_map.reserve(specialization_info->mapEntryCount);
3466 for (auto i = 0u; i < specialization_info->mapEntryCount; ++i) {
3467 auto const &map_entry = specialization_info->pMapEntries[i];
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003468
Jeremy Hayes521221d2020-01-15 16:48:49 -07003469 // Expect only scalar types.
3470 assert(map_entry.size == 1 || map_entry.size == 2 || map_entry.size == 4 || map_entry.size == 8);
3471 auto entry = id_value_map.emplace(map_entry.constantID, std::vector<uint32_t>(map_entry.size > 4 ? 2 : 1));
3472 memcpy(entry.first->second.data(), specialization_data + map_entry.offset, map_entry.size);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003473 }
3474
3475 // Apply the specialization-constant values and revalidate the shader module.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003476 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003477 spvtools::Optimizer optimizer(spirv_environment);
3478 spvtools::MessageConsumer consumer = [&skip, &module, &pStage, this](spv_message_level_t level, const char *source,
3479 const spv_position_t &position, const char *message) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003480 skip |= LogError(
3481 device, "VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s. %s",
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003482 report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage), message);
3483 };
3484 optimizer.SetMessageConsumer(consumer);
3485 optimizer.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(id_value_map));
3486 optimizer.RegisterPass(spvtools::CreateFreezeSpecConstantValuePass());
3487 std::vector<uint32_t> specialized_spirv;
3488 auto const optimized =
3489 optimizer.Run(module->words.data(), module->words.size(), &specialized_spirv, spvtools::ValidatorOptions(), true);
3490 assert(optimized == true);
3491
3492 if (optimized) {
3493 spv_context ctx = spvContextCreate(spirv_environment);
3494 spv_const_binary_t binary{specialized_spirv.data(), specialized_spirv.size()};
3495 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003496 spvtools::ValidatorOptions options;
3497 AdjustValidatorOptions(device_extensions, enabled_features, options);
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003498 auto const spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
3499 if (spv_valid != SPV_SUCCESS) {
sfricke-samsungd3793802020-08-18 22:55:03 -07003500 skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-module-04145",
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003501 "After specialization was applied, %s does not contain valid spirv for stage %s.",
3502 report_data->FormatHandle(module->vk_shader_module).c_str(),
3503 string_VkShaderStageFlagBits(pStage->stage));
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003504 }
3505
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003506 spvDiagnosticDestroy(diag);
3507 spvContextDestroy(ctx);
3508 }
3509 }
3510
John Zulauf14c355b2019-06-27 16:09:37 -06003511 // Check the entrypoint
3512 if (entrypoint == module->end()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003513 skip |=
3514 LogError(device, "VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
3515 pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
John Zulauf14c355b2019-06-27 16:09:37 -06003516 }
3517 if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
3518
3519 // Mark accessible ids
3520 auto &accessible_ids = stage_state.accessible_ids;
3521
Chris Forbes47567b72017-06-09 12:09:45 -07003522 // Validate descriptor set layout against what the entrypoint actually uses
John Zulauf14c355b2019-06-27 16:09:37 -06003523 bool has_writable_descriptor = stage_state.has_writable_descriptor;
3524 auto &descriptor_uses = stage_state.descriptor_uses;
Chris Forbes47567b72017-06-09 12:09:45 -07003525
Chris Forbes349b3132018-03-07 11:38:08 -08003526 // Validate shader capabilities against enabled device features
Jeff Bolzee743412019-06-20 22:24:32 -05003527 skip |= ValidateShaderCapabilities(module, pStage->stage);
locke-lunarg63e4daf2020-08-17 17:53:25 -06003528 skip |=
3529 ValidateShaderStageWritableOrAtomicDescriptor(pStage->stage, has_writable_descriptor, stage_state.has_atomic_descriptor);
Jeff Bolze9ee3d82019-05-29 13:45:13 -05003530 skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
sfricke-samsungdc96f302020-03-18 20:42:10 -07003531 skip |= ValidateShaderStageMaxResources(pStage->stage, pipeline);
Jeff Bolz526f2d52019-09-18 13:18:08 -05003532 skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage);
Attilio Provenzanoc5d50102019-03-25 17:40:37 +00003533 skip |= ValidateExecutionModes(module, entrypoint);
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003534 skip |= ValidateSpecializationOffsets(pStage);
locke-lunargde3f0fa2020-09-10 11:55:31 -06003535 skip |= ValidatePushConstantUsage(*pipeline, module, pStage);
Jeff Bolze54ae892018-09-08 12:16:29 -05003536 if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
Mark Lobodzinski518eadc2019-03-09 12:07:30 -07003537 skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003538 }
Jeff Bolze4356752019-03-07 11:23:46 -06003539 skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
Chris Forbes47567b72017-06-09 12:09:45 -07003540
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003541 std::string vuid_layout_mismatch;
3542 if (pipeline->graphicsPipelineCI.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) {
3543 vuid_layout_mismatch = "VUID-VkGraphicsPipelineCreateInfo-layout-00756";
3544 } else if (pipeline->computePipelineCI.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) {
3545 vuid_layout_mismatch = "VUID-VkComputePipelineCreateInfo-layout-00703";
3546 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_KHR) {
3547 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoKHR-layout-03427";
3548 } else if (pipeline->raytracingPipelineCI.sType == VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV) {
3549 vuid_layout_mismatch = "VUID-VkRayTracingPipelineCreateInfoNV-layout-03427";
3550 }
3551
Chris Forbes47567b72017-06-09 12:09:45 -07003552 // Validate descriptor use
3553 for (auto use : descriptor_uses) {
Chris Forbes47567b72017-06-09 12:09:45 -07003554 // Verify given pipelineLayout has requested setLayout with requested binding
Jeff Bolze7fc67b2019-10-04 12:29:31 -05003555 const auto &binding = GetDescriptorBinding(pipeline->pipeline_layout.get(), use.first);
Chris Forbes47567b72017-06-09 12:09:45 -07003556 unsigned required_descriptor_count;
Jeff Bolze54ae892018-09-08 12:16:29 -05003557 std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
Chris Forbes47567b72017-06-09 12:09:45 -07003558
3559 if (!binding) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003560 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003561 "Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
3562 use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003563 } else if (~binding->stageFlags & pStage->stage) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003564 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003565 "Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
3566 use.first.second, string_VkShaderStageFlagBits(pStage->stage));
Jeff Bolze54ae892018-09-08 12:16:29 -05003567 } else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003568 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003569 "Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
3570 use.first.second, string_descriptorTypes(descriptor_types).c_str(),
3571 string_VkDescriptorType(binding->descriptorType));
Chris Forbes47567b72017-06-09 12:09:45 -07003572 } else if (binding->descriptorCount < required_descriptor_count) {
locke-lunarg9a16ebb2020-07-30 16:56:33 -06003573 skip |= LogError(device, vuid_layout_mismatch,
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003574 "Shader expects at least %u descriptors for binding %u.%u but only %u provided",
3575 required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
Chris Forbes47567b72017-06-09 12:09:45 -07003576 }
3577 }
3578
3579 // Validate use of input attachments against subpass structure
3580 if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003581 auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
Chris Forbes47567b72017-06-09 12:09:45 -07003582
Petr Krause91f7a12017-12-14 20:57:36 +01003583 auto rpci = pipeline->rp_state->createInfo.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003584 auto subpass = pipeline->graphicsPipelineCI.subpass;
3585
3586 for (auto use : input_attachment_uses) {
3587 auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
3588 auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
Dave Houltona9df0ce2018-02-07 10:51:23 -07003589 ? input_attachments[use.first].attachment
3590 : VK_ATTACHMENT_UNUSED;
Chris Forbes47567b72017-06-09 12:09:45 -07003591
3592 if (index == VK_ATTACHMENT_UNUSED) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003593 skip |= LogError(device, kVUID_Core_Shader_MissingInputAttachment,
3594 "Shader consumes input attachment index %d but not provided in subpass", use.first);
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003595 } else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
Chris Forbes47567b72017-06-09 12:09:45 -07003596 skip |=
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003597 LogError(device, kVUID_Core_Shader_InputAttachmentTypeMismatch,
3598 "Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
3599 string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003600 }
3601 }
3602 }
Lockeaa8fdc02019-04-02 11:59:20 -06003603 if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
3604 skip |= ValidateComputeWorkGroupSizes(module);
3605 }
Chris Forbes47567b72017-06-09 12:09:45 -07003606 return skip;
3607}
3608
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003609bool CoreChecks::ValidateInterfaceBetweenStages(SHADER_MODULE_STATE const *producer, spirv_inst_iter producer_entrypoint,
3610 shader_stage_attributes const *producer_stage, SHADER_MODULE_STATE const *consumer,
3611 spirv_inst_iter consumer_entrypoint,
3612 shader_stage_attributes const *consumer_stage) const {
Chris Forbes47567b72017-06-09 12:09:45 -07003613 bool skip = false;
3614
3615 auto outputs =
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003616 CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
3617 auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
Chris Forbes47567b72017-06-09 12:09:45 -07003618
3619 auto a_it = outputs.begin();
3620 auto b_it = inputs.begin();
3621
3622 // Maps sorted by key (location); walk them together to find mismatches
3623 while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
3624 bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
3625 bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
3626 auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
3627 auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
3628
3629 if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003630 skip |= LogPerformanceWarning(producer->vk_shader_module, kVUID_Core_Shader_OutputNotConsumed,
3631 "%s writes to output location %u.%u which is not consumed by %s", producer_stage->name,
3632 a_first.first, a_first.second, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003633 a_it++;
3634 } else if (a_at_end || a_first > b_first) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003635 skip |= LogError(consumer->vk_shader_module, kVUID_Core_Shader_InputNotProduced,
3636 "%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
3637 b_first.second, producer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003638 b_it++;
3639 } else {
3640 // subtleties of arrayed interfaces:
3641 // - if is_patch, then the member is not arrayed, even though the interface may be.
3642 // - if is_block_member, then the extra array level of an arrayed interface is not
3643 // expressed in the member type -- it's expressed in the block type.
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003644 if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
3645 producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
3646 consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003647 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3648 "Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
3649 DescribeType(producer, a_it->second.type_id).c_str(),
3650 DescribeType(consumer, b_it->second.type_id).c_str());
Chris Forbes47567b72017-06-09 12:09:45 -07003651 }
3652 if (a_it->second.is_patch != b_it->second.is_patch) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003653 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3654 "Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
3655 a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
3656 b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003657 }
3658 if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003659 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3660 "Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
3661 a_first.second, producer_stage->name, consumer_stage->name);
Chris Forbes47567b72017-06-09 12:09:45 -07003662 }
3663 a_it++;
3664 b_it++;
3665 }
3666 }
3667
Ari Suonpaa696b3432019-03-11 14:02:57 +02003668 if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
3669 auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
3670 auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
3671
3672 if (!builtins_producer.empty() && !builtins_consumer.empty()) {
3673 if (builtins_producer.size() != builtins_consumer.size()) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003674 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3675 "Number of elements inside builtin block differ between stages (%s %d vs %s %d).",
3676 producer_stage->name, (int)builtins_producer.size(), consumer_stage->name,
3677 (int)builtins_consumer.size());
Ari Suonpaa696b3432019-03-11 14:02:57 +02003678 } else {
3679 auto it_producer = builtins_producer.begin();
3680 auto it_consumer = builtins_consumer.begin();
3681 while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
3682 if (*it_producer != *it_consumer) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003683 skip |= LogError(producer->vk_shader_module, kVUID_Core_Shader_InterfaceTypeMismatch,
3684 "Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
3685 consumer_stage->name);
Ari Suonpaa696b3432019-03-11 14:02:57 +02003686 break;
3687 }
3688 it_producer++;
3689 it_consumer++;
3690 }
3691 }
3692 }
3693 }
3694
Chris Forbes47567b72017-06-09 12:09:45 -07003695 return skip;
3696}
3697
John Zulauf14c355b2019-06-27 16:09:37 -06003698static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003699 uint32_t stage_mask = 0;
3700 if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
3701 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3702 stage_mask |= pCreateInfo->pStages[i].stage;
3703 }
3704 // Determine which shader in which PointSize should be written (the final geometry stage)
Jeff Bolz105d6492018-09-29 15:46:44 -05003705 if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
3706 stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
3707 } else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003708 stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
3709 } else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
3710 stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
3711 } else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
3712 stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003713 }
3714 }
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003715 return stage_mask;
Mark Lobodzinski2c984cc2018-07-31 09:57:46 -06003716}
3717
Chris Forbes47567b72017-06-09 12:09:45 -07003718// Validate that the shaders used by the given pipeline and store the active_slots
3719// that are actually used by the pipeline into pPipeline->active_slots
John Zulaufac4c6e12019-07-01 16:05:58 -06003720bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
Chris Forbesa400a8a2017-07-20 13:10:24 -07003721 auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003722 int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3723 int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003724
John Zulauf14c355b2019-06-27 16:09:37 -06003725 const SHADER_MODULE_STATE *shaders[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003726 memset(shaders, 0, sizeof(shaders));
Jeff Bolz7e35c392018-09-04 15:30:41 -05003727 spirv_inst_iter entrypoints[32];
Chris Forbes47567b72017-06-09 12:09:45 -07003728 memset(entrypoints, 0, sizeof(entrypoints));
3729 bool skip = false;
3730
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003731 uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
3732
Chris Forbes47567b72017-06-09 12:09:45 -07003733 for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3734 auto pStage = &pCreateInfo->pStages[i];
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003735 auto stage_id = GetShaderStageId(pStage->stage);
John Zulauf14c355b2019-06-27 16:09:37 -06003736 shaders[stage_id] = GetShaderModuleState(pStage->module);
3737 entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
3738 skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
Mark Lobodzinski1b4a8ed2018-08-07 08:47:05 -06003739 (pointlist_stage_mask == pStage->stage));
Chris Forbes47567b72017-06-09 12:09:45 -07003740 }
3741
3742 // if the shader stages are no good individually, cross-stage validation is pointless.
3743 if (skip) return true;
3744
3745 auto vi = pCreateInfo->pVertexInputState;
3746
3747 if (vi) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003748 skip |= ValidateViConsistency(vi);
Chris Forbes47567b72017-06-09 12:09:45 -07003749 }
3750
3751 if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003752 skip |= ValidateViAgainstVsInputs(vi, shaders[vertex_stage], entrypoints[vertex_stage]);
Chris Forbes47567b72017-06-09 12:09:45 -07003753 }
3754
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003755 int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
3756 int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
Chris Forbes47567b72017-06-09 12:09:45 -07003757
3758 while (!shaders[producer] && producer != fragment_stage) {
3759 producer++;
3760 consumer++;
3761 }
3762
3763 for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
3764 assert(shaders[producer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003765 if (shaders[consumer]) {
3766 if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003767 skip |= ValidateInterfaceBetweenStages(shaders[producer], entrypoints[producer], &shader_stage_attribs[producer],
3768 shaders[consumer], entrypoints[consumer], &shader_stage_attribs[consumer]);
Chris Forbesdbb43fc2018-02-16 16:59:23 -08003769 }
Chris Forbes47567b72017-06-09 12:09:45 -07003770
3771 producer = consumer;
3772 }
3773 }
3774
3775 if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
Mark Lobodzinskid8d658e2020-01-30 15:05:51 -07003776 skip |= ValidateFsOutputsAgainstRenderPass(shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
Shannon McPhersonc06c33d2018-06-28 17:21:12 -06003777 pCreateInfo->subpass);
Chris Forbes47567b72017-06-09 12:09:45 -07003778 }
3779
3780 return skip;
3781}
3782
sfricke-samsunge72a85e2020-02-29 21:48:37 -08003783bool CoreChecks::ValidateComputePipelineShaderState(PIPELINE_STATE *pipeline) const {
John Zulauf14c355b2019-06-27 16:09:37 -06003784 const auto &stage = *pipeline->computePipelineCI.stage.ptr();
Chris Forbes47567b72017-06-09 12:09:45 -07003785
John Zulauf14c355b2019-06-27 16:09:37 -06003786 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3787 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Chris Forbes47567b72017-06-09 12:09:45 -07003788
John Zulauf14c355b2019-06-27 16:09:37 -06003789 return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
Chris Forbes47567b72017-06-09 12:09:45 -07003790}
Chris Forbes4ae55b32017-06-09 14:42:56 -07003791
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003792bool CoreChecks::ValidateRayTracingPipeline(PIPELINE_STATE *pipeline, bool isKHR) const {
John Zulaufe4474e72019-07-01 17:28:27 -06003793 bool skip = false;
Jason Macnak15f95e82019-08-21 21:52:02 -04003794
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003795 if (isKHR) {
3796 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth) {
3797 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-maxRecursionDepth-03464", ": %d > %d",
3798 pipeline->raytracingPipelineCI.maxRecursionDepth,
3799 phys_dev_ext_props.ray_tracing_propsKHR.maxRecursionDepth);
3800 }
sourav parmar83c31b12020-05-06 12:30:54 -07003801 for (uint32_t i = 0; i < pipeline->raytracingPipelineCI.libraries.libraryCount; ++i) {
3802 const PIPELINE_STATE *pLibrary_pipelinestate = GetPipelineState(pipeline->raytracingPipelineCI.libraries.pLibraries[i]);
3803 if (pLibrary_pipelinestate->raytracingPipelineCI.maxRecursionDepth !=
3804 pipeline->raytracingPipelineCI.maxRecursionDepth) {
3805 skip |= LogError(
3806 device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03467",
3807 "vkCreateRayTracingPipelinesKHR: Each element (%d) of the pLibraries member of libraries must have been"
3808 "created with the value of maxRecursionDepth (%d) equal to that in this pipeline (%d) .",
3809 i, pLibrary_pipelinestate->raytracingPipelineCI.maxRecursionDepth,
3810 pipeline->raytracingPipelineCI.maxRecursionDepth);
3811 }
3812 if (pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxAttributeSize !=
3813 pipeline->raytracingPipelineCI.pLibraryInterface->maxAttributeSize ||
3814 pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxPayloadSize !=
3815 pipeline->raytracingPipelineCI.pLibraryInterface->maxPayloadSize ||
3816 pLibrary_pipelinestate->raytracingPipelineCI.pLibraryInterface->maxCallableSize !=
3817 pipeline->raytracingPipelineCI.pLibraryInterface->maxCallableSize) {
3818 skip |=
3819 LogError(device, "VUID-VkRayTracingPipelineCreateInfoKHR-pLibraries-03469",
3820 "vkCreateRayTracingPipelinesKHR: Each element of the pLibraries member of libraries must have been "
3821 "created with values of the maxPayloadSize,"
3822 "maxAttributeSize, and maxCallableSize members of pLibraryInterface equal to those in this pipeline.");
3823 }
3824 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003825 } else {
3826 if (pipeline->raytracingPipelineCI.maxRecursionDepth > phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth) {
3827 skip |= LogError(device, "VUID-VkRayTracingPipelineCreateInfoNV-maxRecursionDepth-03457", ": %d > %d",
3828 pipeline->raytracingPipelineCI.maxRecursionDepth,
3829 phys_dev_ext_props.ray_tracing_propsNV.maxRecursionDepth);
3830 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003831 }
Jason Macnak15f95e82019-08-21 21:52:02 -04003832 const auto *stages = pipeline->raytracingPipelineCI.ptr()->pStages;
3833 const auto *groups = pipeline->raytracingPipelineCI.ptr()->pGroups;
3834
3835 uint32_t raygen_stages_found = 0;
John Zulaufe4474e72019-07-01 17:28:27 -06003836 for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
Jason Macnak15f95e82019-08-21 21:52:02 -04003837 const auto &stage = stages[stage_index];
Jeff Bolzfbe51582018-09-13 10:01:35 -05003838
John Zulaufe4474e72019-07-01 17:28:27 -06003839 const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
3840 const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
Jeff Bolzfbe51582018-09-13 10:01:35 -05003841
John Zulaufe4474e72019-07-01 17:28:27 -06003842 skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
Jason Macnak15f95e82019-08-21 21:52:02 -04003843
3844 if (stage.stage == VK_SHADER_STAGE_RAYGEN_BIT_NV) {
3845 raygen_stages_found++;
3846 }
3847 }
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003848 if (raygen_stages_found == 0) {
3849 skip |= LogError(
3850 device,
3851 isKHR ? "VUID-VkRayTracingPipelineCreateInfoKHR-stage-03425" : "VUID-VkRayTracingPipelineCreateInfoNV-stage-03425",
3852 " : zero raygen stages specified");
Jason Macnak15f95e82019-08-21 21:52:02 -04003853 }
3854
3855 for (uint32_t group_index = 0; group_index < pipeline->raytracingPipelineCI.groupCount; group_index++) {
3856 const auto &group = groups[group_index];
3857
3858 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV) {
3859 if (group.generalShader >= pipeline->raytracingPipelineCI.stageCount ||
3860 (stages[group.generalShader].stage != VK_SHADER_STAGE_RAYGEN_BIT_NV &&
3861 stages[group.generalShader].stage != VK_SHADER_STAGE_MISS_BIT_NV &&
3862 stages[group.generalShader].stage != VK_SHADER_STAGE_CALLABLE_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003863 skip |= LogError(device,
3864 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03474"
3865 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02413",
3866 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003867 }
3868 if (group.anyHitShader != VK_SHADER_UNUSED_NV || group.closestHitShader != VK_SHADER_UNUSED_NV ||
3869 group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003870 skip |= LogError(device,
3871 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03475"
3872 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02414",
3873 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003874 }
3875 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV) {
3876 if (group.intersectionShader >= pipeline->raytracingPipelineCI.stageCount ||
3877 stages[group.intersectionShader].stage != VK_SHADER_STAGE_INTERSECTION_BIT_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003878 skip |= LogError(device,
3879 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03476"
3880 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02415",
3881 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003882 }
3883 } else if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3884 if (group.intersectionShader != VK_SHADER_UNUSED_NV) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003885 skip |= LogError(device,
3886 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-type-03477"
3887 : "VUID-VkRayTracingShaderGroupCreateInfoNV-type-02416",
3888 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003889 }
3890 }
3891
3892 if (group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV ||
3893 group.type == VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV) {
3894 if (group.anyHitShader != VK_SHADER_UNUSED_NV && (group.anyHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3895 stages[group.anyHitShader].stage != VK_SHADER_STAGE_ANY_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003896 skip |= LogError(device,
3897 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-anyHitShader-03479"
3898 : "VUID-VkRayTracingShaderGroupCreateInfoNV-anyHitShader-02418",
3899 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003900 }
3901 if (group.closestHitShader != VK_SHADER_UNUSED_NV &&
3902 (group.closestHitShader >= pipeline->raytracingPipelineCI.stageCount ||
3903 stages[group.closestHitShader].stage != VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV)) {
Jeff Bolz443c2ca2020-03-19 12:11:51 -05003904 skip |= LogError(device,
3905 isKHR ? "VUID-VkRayTracingShaderGroupCreateInfoKHR-closestHitShader-03478"
3906 : "VUID-VkRayTracingShaderGroupCreateInfoNV-closestHitShader-02417",
3907 ": pGroups[%d]", group_index);
Jason Macnak15f95e82019-08-21 21:52:02 -04003908 }
3909 }
John Zulaufe4474e72019-07-01 17:28:27 -06003910 }
3911 return skip;
Jeff Bolzfbe51582018-09-13 10:01:35 -05003912}
3913
Dave Houltona9df0ce2018-02-07 10:51:23 -07003914uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
Chris Forbes9a61e082017-07-24 15:35:29 -07003915
Dave Houltona9df0ce2018-02-07 10:51:23 -07003916static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
John Zulauf25ea2432019-04-05 10:07:38 -06003917 const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
3918 if (validation_cache_ci) {
John Zulauf146ee802019-04-05 15:31:06 -06003919 return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
Chris Forbes9a61e082017-07-24 15:35:29 -07003920 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003921 return nullptr;
3922}
3923
Mark Lobodzinskib56bbb92019-02-18 11:49:59 -07003924bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003925 const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) const {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003926 bool skip = false;
3927 spv_result_t spv_valid = SPV_SUCCESS;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003928
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -06003929 if (disabled[shader_validation]) {
Chris Forbes4ae55b32017-06-09 14:42:56 -07003930 return false;
3931 }
3932
Mark Lobodzinskif45e45f2019-04-19 14:15:39 -06003933 auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
Chris Forbes4ae55b32017-06-09 14:42:56 -07003934
3935 if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003936 skip |= LogError(device, "VUID-VkShaderModuleCreateInfo-pCode-01376",
3937 "SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
3938 pCreateInfo->codeSize);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003939 } else {
Chris Forbes9a61e082017-07-24 15:35:29 -07003940 auto cache = GetValidationCacheInfo(pCreateInfo);
3941 uint32_t hash = 0;
3942 if (cache) {
3943 hash = ValidationCache::MakeShaderHash(pCreateInfo);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003944 if (cache->Contains(hash)) return false;
Chris Forbes9a61e082017-07-24 15:35:29 -07003945 }
3946
Jeremy Hayesb3e4d532019-08-16 10:08:49 -06003947 // Use SPIRV-Tools validator to try and catch any issues with the module itself. If specialization constants are present,
3948 // the default values will be used during validation.
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06003949 spv_target_env spirv_environment = PickSpirvEnv(api_version, (device_extensions.vk_khr_spirv_1_4 != kNotEnabled));
Dave Houlton0ea2d012018-06-21 14:00:26 -06003950 spv_context ctx = spvContextCreate(spirv_environment);
Dave Houltona9df0ce2018-02-07 10:51:23 -07003951 spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
Chris Forbes4ae55b32017-06-09 14:42:56 -07003952 spv_diagnostic diag = nullptr;
Tony-LunarG9fe69a42020-07-23 15:09:37 -06003953 spvtools::ValidatorOptions options;
3954 AdjustValidatorOptions(device_extensions, enabled_features, options);
Karl Schultzfda1b382018-08-08 18:56:11 -06003955 spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
Chris Forbes4ae55b32017-06-09 14:42:56 -07003956 if (spv_valid != SPV_SUCCESS) {
3957 if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003958 if (spv_valid == SPV_WARNING) {
3959 skip |= LogWarning(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3960 diag && diag->error ? diag->error : "(no error text)");
3961 } else {
3962 skip |= LogError(device, kVUID_Core_Shader_InconsistentSpirv, "SPIR-V module not valid: %s",
3963 diag && diag->error ? diag->error : "(no error text)");
3964 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003965 }
Chris Forbes9a61e082017-07-24 15:35:29 -07003966 } else {
3967 if (cache) {
3968 cache->Insert(hash);
3969 }
Chris Forbes4ae55b32017-06-09 14:42:56 -07003970 }
3971
3972 spvDiagnosticDestroy(diag);
3973 spvContextDestroy(ctx);
3974 }
3975
Chris Forbes4ae55b32017-06-09 14:42:56 -07003976 return skip;
Mark Lobodzinski01734072019-02-13 17:39:15 -07003977}
3978
John Zulaufac4c6e12019-07-01 16:05:58 -06003979bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
Lockeaa8fdc02019-04-02 11:59:20 -06003980 bool skip = false;
3981 uint32_t local_size_x = 0;
3982 uint32_t local_size_y = 0;
3983 uint32_t local_size_z = 0;
3984 if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
3985 if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003986 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3987 "%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
3988 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3989 phys_dev_props.limits.maxComputeWorkGroupSize[0]);
Lockeaa8fdc02019-04-02 11:59:20 -06003990 }
3991 if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003992 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3993 "%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
3994 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
3995 phys_dev_props.limits.maxComputeWorkGroupSize[1]);
Lockeaa8fdc02019-04-02 11:59:20 -06003996 }
3997 if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07003998 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
3999 "%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
4000 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
4001 phys_dev_props.limits.maxComputeWorkGroupSize[2]);
Lockeaa8fdc02019-04-02 11:59:20 -06004002 }
4003
4004 uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
4005 uint64_t invocations = local_size_x * local_size_y;
4006 // Prevent overflow.
4007 bool fail = false;
4008 if (invocations > UINT32_MAX || invocations > limit) {
4009 fail = true;
4010 }
4011 if (!fail) {
4012 invocations *= local_size_z;
4013 if (invocations > UINT32_MAX || invocations > limit) {
4014 fail = true;
4015 }
4016 }
4017 if (fail) {
Mark Lobodzinski12b9be92020-01-30 15:25:55 -07004018 skip |= LogError(shader->vk_shader_module, "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
4019 "%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
4020 ") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
4021 report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
4022 limit);
Lockeaa8fdc02019-04-02 11:59:20 -06004023 }
4024 }
4025 return skip;
4026}
Tony-LunarG8a51b7d2020-07-01 15:57:23 -06004027
4028spv_target_env PickSpirvEnv(uint32_t api_version, bool spirv_1_4) {
4029 if (api_version >= VK_API_VERSION_1_2) {
4030 return SPV_ENV_VULKAN_1_2;
4031 } else if (api_version >= VK_API_VERSION_1_1) {
4032 if (spirv_1_4) {
4033 return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
4034 } else {
4035 return SPV_ENV_VULKAN_1_1;
4036 }
4037 }
4038 return SPV_ENV_VULKAN_1_0;
4039}
Tony-LunarG9fe69a42020-07-23 15:09:37 -06004040
4041void AdjustValidatorOptions(const DeviceExtensions device_extensions, const DeviceFeatures enabled_features,
4042 spvtools::ValidatorOptions &options) {
4043 if (device_extensions.vk_khr_relaxed_block_layout) {
4044 options.SetRelaxBlockLayout(true);
4045 }
4046 if (device_extensions.vk_khr_uniform_buffer_standard_layout && enabled_features.core12.uniformBufferStandardLayout == VK_TRUE) {
4047 options.SetUniformBufferStandardLayout(true);
4048 }
4049 if (device_extensions.vk_ext_scalar_block_layout && enabled_features.core12.scalarBlockLayout == VK_TRUE) {
4050 options.SetScalarBlockLayout(true);
4051 }
4052}