blob: 0872deb9853bcfd6061d7e508bfb1f1581497f3e [file] [log] [blame]
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001/* Copyright (c) 2021-2022 The Khronos Group Inc.
sfricke-samsung962cad92021-04-13 00:46:29 -07002 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 *
15 * Author: Spencer Fricke <s.fricke@samsung.com>
16 */
17
18#include "shader_module.h"
19
20#include <sstream>
21#include <string>
22
23#include "vk_layer_data.h"
24#include "vk_layer_utils.h"
Jeremy Gebben5d970742021-05-31 16:04:14 -060025#include "pipeline_state.h"
26#include "descriptor_sets.h"
sfricke-samsung3c5dee22021-10-14 09:58:14 -070027#include "spirv_grammar_helper.h"
sfricke-samsung962cad92021-04-13 00:46:29 -070028
29void decoration_set::merge(decoration_set const &other) {
30 if (other.flags & location_bit) location = other.location;
31 if (other.flags & component_bit) component = other.component;
32 if (other.flags & input_attachment_index_bit) input_attachment_index = other.input_attachment_index;
33 if (other.flags & descriptor_set_bit) descriptor_set = other.descriptor_set;
34 if (other.flags & binding_bit) binding = other.binding;
35 if (other.flags & builtin_bit) builtin = other.builtin;
36 flags |= other.flags;
37}
38
39void decoration_set::add(uint32_t decoration, uint32_t value) {
40 switch (decoration) {
41 case spv::DecorationLocation:
42 flags |= location_bit;
43 location = value;
44 break;
45 case spv::DecorationPatch:
46 flags |= patch_bit;
47 break;
48 case spv::DecorationRelaxedPrecision:
49 flags |= relaxed_precision_bit;
50 break;
51 case spv::DecorationBlock:
52 flags |= block_bit;
53 break;
54 case spv::DecorationBufferBlock:
55 flags |= buffer_block_bit;
56 break;
57 case spv::DecorationComponent:
58 flags |= component_bit;
59 component = value;
60 break;
61 case spv::DecorationInputAttachmentIndex:
62 flags |= input_attachment_index_bit;
63 input_attachment_index = value;
64 break;
65 case spv::DecorationDescriptorSet:
66 flags |= descriptor_set_bit;
67 descriptor_set = value;
68 break;
69 case spv::DecorationBinding:
70 flags |= binding_bit;
71 binding = value;
72 break;
73 case spv::DecorationNonWritable:
74 flags |= nonwritable_bit;
75 break;
76 case spv::DecorationBuiltIn:
77 flags |= builtin_bit;
78 builtin = value;
79 break;
Lionel Landwerlin38d2e122021-07-21 14:21:47 +030080 case spv::DecorationNonReadable:
81 flags |= nonreadable_bit;
82 break;
ziga-lunarg9e94e112021-09-27 00:21:10 +020083 case spv::DecorationPerVertexNV:
84 flags |= per_vertex_bit;
85 break;
86 case spv::DecorationPassthroughNV:
87 flags |= passthrough_bit;
88 break;
sfricke-samsung962cad92021-04-13 00:46:29 -070089 }
90}
91
92std::string shader_struct_member::GetLocationDesc(uint32_t index_used_bytes) const {
93 std::string desc = "";
94 if (array_length_hierarchy.size() > 0) {
95 desc += " index:";
96 for (const auto block_size : array_block_size) {
97 desc += "[";
98 desc += std::to_string(index_used_bytes / (block_size * size));
99 desc += "]";
100 index_used_bytes = index_used_bytes % (block_size * size);
101 }
102 }
103 const int struct_members_size = static_cast<int>(struct_members.size());
104 if (struct_members_size > 0) {
105 desc += " member:";
106 for (int i = struct_members_size - 1; i >= 0; --i) {
107 if (index_used_bytes > struct_members[i].offset) {
108 desc += std::to_string(i);
109 desc += struct_members[i].GetLocationDesc(index_used_bytes - struct_members[i].offset);
110 break;
111 }
112 }
113 } else {
114 desc += " offset:";
115 desc += std::to_string(index_used_bytes);
116 }
117 return desc;
118}
119
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800120static uint32_t ExecutionModelToShaderStageFlagBits(uint32_t mode) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700121 switch (mode) {
122 case spv::ExecutionModelVertex:
123 return VK_SHADER_STAGE_VERTEX_BIT;
124 case spv::ExecutionModelTessellationControl:
125 return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
126 case spv::ExecutionModelTessellationEvaluation:
127 return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
128 case spv::ExecutionModelGeometry:
129 return VK_SHADER_STAGE_GEOMETRY_BIT;
130 case spv::ExecutionModelFragment:
131 return VK_SHADER_STAGE_FRAGMENT_BIT;
132 case spv::ExecutionModelGLCompute:
133 return VK_SHADER_STAGE_COMPUTE_BIT;
134 case spv::ExecutionModelRayGenerationNV:
135 return VK_SHADER_STAGE_RAYGEN_BIT_NV;
136 case spv::ExecutionModelAnyHitNV:
137 return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
138 case spv::ExecutionModelClosestHitNV:
139 return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
140 case spv::ExecutionModelMissNV:
141 return VK_SHADER_STAGE_MISS_BIT_NV;
142 case spv::ExecutionModelIntersectionNV:
143 return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
144 case spv::ExecutionModelCallableNV:
145 return VK_SHADER_STAGE_CALLABLE_BIT_NV;
146 case spv::ExecutionModelTaskNV:
147 return VK_SHADER_STAGE_TASK_BIT_NV;
148 case spv::ExecutionModelMeshNV:
149 return VK_SHADER_STAGE_MESH_BIT_NV;
150 default:
151 return 0;
152 }
153}
154
155// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
156// important for identifying the set of shader resources actually used by an entrypoint, for example.
157// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
158// - NOT the shader input/output interfaces.
159//
160// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
161// converting parts of this to be generated from the machine-readable spec instead.
162layer_data::unordered_set<uint32_t> SHADER_MODULE_STATE::MarkAccessibleIds(spirv_inst_iter entrypoint) const {
163 layer_data::unordered_set<uint32_t> ids;
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600164 if (entrypoint == end() || !has_valid_spirv) {
165 return ids;
166 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700167 layer_data::unordered_set<uint32_t> worklist;
168 worklist.insert(entrypoint.word(2));
169
170 while (!worklist.empty()) {
171 auto id_iter = worklist.begin();
172 auto id = *id_iter;
173 worklist.erase(id_iter);
174
175 auto insn = get_def(id);
176 if (insn == end()) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600177 // ID is something we didn't collect in SpirvStaticData. that's OK -- we'll stumble across all kinds of things here
sfricke-samsung962cad92021-04-13 00:46:29 -0700178 // that we may not care about.
179 continue;
180 }
181
182 // Try to add to the output set
183 if (!ids.insert(id).second) {
184 continue; // If we already saw this id, we don't want to walk it again.
185 }
186
187 switch (insn.opcode()) {
188 case spv::OpFunction:
189 // Scan whole body of the function, enlisting anything interesting
190 while (++insn, insn.opcode() != spv::OpFunctionEnd) {
191 switch (insn.opcode()) {
192 case spv::OpLoad:
193 worklist.insert(insn.word(3)); // ptr
194 break;
195 case spv::OpStore:
196 worklist.insert(insn.word(1)); // ptr
197 break;
198 case spv::OpAccessChain:
199 case spv::OpInBoundsAccessChain:
200 worklist.insert(insn.word(3)); // base ptr
201 break;
202 case spv::OpSampledImage:
203 case spv::OpImageSampleImplicitLod:
204 case spv::OpImageSampleExplicitLod:
205 case spv::OpImageSampleDrefImplicitLod:
206 case spv::OpImageSampleDrefExplicitLod:
207 case spv::OpImageSampleProjImplicitLod:
208 case spv::OpImageSampleProjExplicitLod:
209 case spv::OpImageSampleProjDrefImplicitLod:
210 case spv::OpImageSampleProjDrefExplicitLod:
211 case spv::OpImageFetch:
212 case spv::OpImageGather:
213 case spv::OpImageDrefGather:
214 case spv::OpImageRead:
215 case spv::OpImage:
216 case spv::OpImageQueryFormat:
217 case spv::OpImageQueryOrder:
218 case spv::OpImageQuerySizeLod:
219 case spv::OpImageQuerySize:
220 case spv::OpImageQueryLod:
221 case spv::OpImageQueryLevels:
222 case spv::OpImageQuerySamples:
223 case spv::OpImageSparseSampleImplicitLod:
224 case spv::OpImageSparseSampleExplicitLod:
225 case spv::OpImageSparseSampleDrefImplicitLod:
226 case spv::OpImageSparseSampleDrefExplicitLod:
227 case spv::OpImageSparseSampleProjImplicitLod:
228 case spv::OpImageSparseSampleProjExplicitLod:
229 case spv::OpImageSparseSampleProjDrefImplicitLod:
230 case spv::OpImageSparseSampleProjDrefExplicitLod:
231 case spv::OpImageSparseFetch:
232 case spv::OpImageSparseGather:
233 case spv::OpImageSparseDrefGather:
234 case spv::OpImageTexelPointer:
235 worklist.insert(insn.word(3)); // Image or sampled image
236 break;
237 case spv::OpImageWrite:
238 worklist.insert(insn.word(1)); // Image -- different operand order to above
239 break;
240 case spv::OpFunctionCall:
241 for (uint32_t i = 3; i < insn.len(); i++) {
242 worklist.insert(insn.word(i)); // fn itself, and all args
243 }
244 break;
245
246 case spv::OpExtInst:
247 for (uint32_t i = 5; i < insn.len(); i++) {
248 worklist.insert(insn.word(i)); // Operands to ext inst
249 }
250 break;
251
252 default: {
253 if (AtomicOperation(insn.opcode())) {
254 if (insn.opcode() == spv::OpAtomicStore) {
255 worklist.insert(insn.word(1)); // ptr
256 } else {
257 worklist.insert(insn.word(3)); // ptr
258 }
259 }
260 break;
261 }
262 }
263 }
264 break;
265 }
266 }
267
268 return ids;
269}
270
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600271layer_data::optional<VkPrimitiveTopology> SHADER_MODULE_STATE::GetTopology(const spirv_inst_iter &entrypoint) const {
272 layer_data::optional<VkPrimitiveTopology> result;
273
sfricke-samsung962cad92021-04-13 00:46:29 -0700274 auto entrypoint_id = entrypoint.word(2);
275 bool is_point_mode = false;
276
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600277 auto it = static_data_.execution_mode_inst.find(entrypoint_id);
278 if (it != static_data_.execution_mode_inst.end()) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700279 for (auto insn : it->second) {
280 switch (insn.word(2)) {
281 case spv::ExecutionModePointMode:
282 // In tessellation shaders, PointMode is separate and trumps the tessellation topology.
283 is_point_mode = true;
284 break;
285
286 case spv::ExecutionModeOutputPoints:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600287 result.emplace(VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
sfricke-samsung962cad92021-04-13 00:46:29 -0700288 break;
289
290 case spv::ExecutionModeIsolines:
291 case spv::ExecutionModeOutputLineStrip:
Ricardo Garcia122f8f02021-09-28 16:47:19 +0200292 case spv::ExecutionModeOutputLinesNV:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600293 result.emplace(VK_PRIMITIVE_TOPOLOGY_LINE_STRIP);
sfricke-samsung962cad92021-04-13 00:46:29 -0700294 break;
295
296 case spv::ExecutionModeTriangles:
297 case spv::ExecutionModeQuads:
298 case spv::ExecutionModeOutputTriangleStrip:
299 case spv::ExecutionModeOutputTrianglesNV:
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600300 result.emplace(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP);
sfricke-samsung962cad92021-04-13 00:46:29 -0700301 break;
302 }
303 }
304 }
305
Jeremy Gebben84b838b2021-08-23 08:41:39 -0600306 if (is_point_mode) {
307 result.emplace(VK_PRIMITIVE_TOPOLOGY_POINT_LIST);
308 }
309
310 return result;
sfricke-samsung962cad92021-04-13 00:46:29 -0700311}
312
sfricke-samsungef15e482022-01-26 11:32:49 -0800313SHADER_MODULE_STATE::SpirvStaticData::SpirvStaticData(const SHADER_MODULE_STATE &module_state) {
314 for (auto insn : module_state) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700315 switch (insn.opcode()) {
316 // Types
317 case spv::OpTypeVoid:
318 case spv::OpTypeBool:
319 case spv::OpTypeInt:
320 case spv::OpTypeFloat:
321 case spv::OpTypeVector:
322 case spv::OpTypeMatrix:
323 case spv::OpTypeImage:
324 case spv::OpTypeSampler:
325 case spv::OpTypeSampledImage:
326 case spv::OpTypeArray:
327 case spv::OpTypeRuntimeArray:
328 case spv::OpTypeStruct:
329 case spv::OpTypeOpaque:
330 case spv::OpTypePointer:
331 case spv::OpTypeFunction:
332 case spv::OpTypeEvent:
333 case spv::OpTypeDeviceEvent:
334 case spv::OpTypeReserveId:
335 case spv::OpTypeQueue:
336 case spv::OpTypePipe:
337 case spv::OpTypeAccelerationStructureNV:
338 case spv::OpTypeCooperativeMatrixNV:
339 def_index[insn.word(1)] = insn.offset();
340 break;
341
342 // Fixed constants
343 case spv::OpConstantTrue:
344 case spv::OpConstantFalse:
345 case spv::OpConstant:
346 case spv::OpConstantComposite:
347 case spv::OpConstantSampler:
348 case spv::OpConstantNull:
349 def_index[insn.word(2)] = insn.offset();
350 break;
351
352 // Specialization constants
353 case spv::OpSpecConstantTrue:
354 case spv::OpSpecConstantFalse:
355 case spv::OpSpecConstant:
356 case spv::OpSpecConstantComposite:
357 case spv::OpSpecConstantOp:
358 def_index[insn.word(2)] = insn.offset();
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600359 has_specialization_constants = true;
sfricke-samsung962cad92021-04-13 00:46:29 -0700360 break;
361
sfricke-samsung58b84352021-07-31 21:41:04 -0700362 // Have a result that can be a pointer
sfricke-samsung962cad92021-04-13 00:46:29 -0700363 case spv::OpVariable:
sfricke-samsung58b84352021-07-31 21:41:04 -0700364 case spv::OpAccessChain:
365 case spv::OpInBoundsAccessChain:
366 case spv::OpFunctionParameter:
367 case spv::OpImageTexelPointer:
sfricke-samsung962cad92021-04-13 00:46:29 -0700368 def_index[insn.word(2)] = insn.offset();
369 break;
370
sfricke-samsungdb3f3f82022-01-18 06:41:15 -0800371 // Will need to extract loads for SAMPLED_IMAGE and SAMPLER
372 case spv::OpSampledImage:
373 def_index[insn.word(2)] = insn.offset();
374 break;
375
sfricke-samsung962cad92021-04-13 00:46:29 -0700376 // Functions
377 case spv::OpFunction:
378 def_index[insn.word(2)] = insn.offset();
sfricke-samsung962cad92021-04-13 00:46:29 -0700379 break;
380
381 // Decorations
382 case spv::OpDecorate: {
383 auto target_id = insn.word(1);
384 decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
385 decoration_inst.push_back(insn);
386 if (insn.word(2) == spv::DecorationBuiltIn) {
387 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
Nathaniel Cesariocf69bda2021-06-22 13:23:42 -0600388 } else if (insn.word(2) == spv::DecorationSpecId) {
389 spec_const_map[insn.word(3)] = target_id;
sfricke-samsung962cad92021-04-13 00:46:29 -0700390 }
391
392 } break;
393 case spv::OpGroupDecorate: {
394 auto const &src = decorations[insn.word(1)];
395 for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600396 has_group_decoration = true;
397 } break;
398 case spv::OpDecorationGroup:
399 case spv::OpGroupMemberDecorate: {
400 has_group_decoration = true;
sfricke-samsung962cad92021-04-13 00:46:29 -0700401 } break;
402 case spv::OpMemberDecorate: {
403 member_decoration_inst.push_back(insn);
404 if (insn.word(3) == spv::DecorationBuiltIn) {
405 builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
406 }
407 } break;
408
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600409 // Copy operations
410 case spv::OpCopyLogical:
411 case spv::OpCopyObject: {
412 def_index[insn.word(2)] = insn.offset();
413 break;
414 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700415
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600416 // Execution Mode
417 case spv::OpExecutionMode: {
418 execution_mode_inst[insn.word(1)].push_back(insn);
419 } break;
420
421 case spv::OpLoad: {
422 def_index[insn.word(2)] = insn.offset();
423 } break;
424
425 default:
426 if (AtomicOperation(insn.opcode()) == true) {
427 // All atomics have a pointer referenced
428 spirv_inst_iter access;
429 if (insn.opcode() == spv::OpAtomicStore) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800430 access = module_state.get_def(insn.word(1));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600431 } else {
sfricke-samsungef15e482022-01-26 11:32:49 -0800432 access = module_state.get_def(insn.word(3));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600433 def_index[insn.word(2)] = insn.offset();
434 }
435
436 atomic_instruction atomic;
437
sfricke-samsungef15e482022-01-26 11:32:49 -0800438 auto pointer = module_state.get_def(access.word(1));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600439 // spirv-val should catch if not pointer
440 assert(pointer.opcode() == spv::OpTypePointer);
441 atomic.storage_class = pointer.word(2);
442
sfricke-samsungef15e482022-01-26 11:32:49 -0800443 auto data_type = module_state.get_def(pointer.word(3));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600444 atomic.type = data_type.opcode();
445
446 // TODO - Should have a proper GetBitWidth like spirv-val does
447 assert(data_type.opcode() == spv::OpTypeFloat || data_type.opcode() == spv::OpTypeInt);
448 atomic.bit_width = data_type.word(2);
449
450 atomic_inst[insn.offset()] = atomic;
451 }
452 // We don't care about any other defs for now.
453 break;
454 }
455 }
456
sfricke-samsungef15e482022-01-26 11:32:49 -0800457 entry_points = SHADER_MODULE_STATE::ProcessEntryPoints(module_state);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600458 multiple_entry_points = entry_points.size() > 1;
459}
460
461// static
462std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> SHADER_MODULE_STATE::ProcessEntryPoints(
sfricke-samsungef15e482022-01-26 11:32:49 -0800463 const SHADER_MODULE_STATE &module_state) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600464 std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> entry_points;
465 function_set func_set = {};
466 EntryPoint *entry_point = nullptr;
467
sfricke-samsungef15e482022-01-26 11:32:49 -0800468 for (auto insn : module_state) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600469 // offset is not 0, it means it's updated and the offset is in a Function.
470 if (func_set.offset) {
471 func_set.op_lists.emplace(insn.opcode(), insn.offset());
472 } else if (entry_point) {
473 entry_point->decorate_list.emplace(insn.opcode(), insn.offset());
474 }
475
476 switch (insn.opcode()) {
477 // Functions
478 case spv::OpFunction:
479 func_set.id = insn.word(2);
480 func_set.offset = insn.offset();
481 func_set.op_lists.clear();
482 break;
483
484 // Entry points ... add to the entrypoint table
485 case spv::OpEntryPoint: {
sfricke-samsung962cad92021-04-13 00:46:29 -0700486 // Entry points do not have an id (the id is the function id) and thus need their own table
487 auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
488 auto execution_model = insn.word(1);
489 auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
490 entry_points.emplace(entrypoint_name,
491 EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
492
493 auto range = entry_points.equal_range(entrypoint_name);
494 for (auto it = range.first; it != range.second; ++it) {
495 if (it->second.offset == insn.offset()) {
496 entry_point = &(it->second);
497 break;
498 }
499 }
500 assert(entry_point != nullptr);
501 break;
502 }
503 case spv::OpFunctionEnd: {
504 assert(entry_point != nullptr);
505 func_set.length = insn.offset() - func_set.offset;
506 entry_point->function_set_list.emplace_back(func_set);
507 break;
508 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700509 }
510 }
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600511
sfricke-samsungef15e482022-01-26 11:32:49 -0800512 SHADER_MODULE_STATE::SetPushConstantUsedInShader(module_state, entry_points);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600513 return entry_points;
sfricke-samsung962cad92021-04-13 00:46:29 -0700514}
515
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600516void SHADER_MODULE_STATE::PreprocessShaderBinary(const spv_target_env env) {
517 if (static_data_.has_group_decoration) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700518 spvtools::Optimizer optimizer(env);
519 optimizer.RegisterPass(spvtools::CreateFlattenDecorationPass());
520 std::vector<uint32_t> optimized_binary;
521 // Run optimizer to flatten decorations only, set skip_validation so as to not re-run validator
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600522 auto result = optimizer.Run(words.data(), words.size(), &optimized_binary, spvtools::ValidatorOptions(), true);
523
sfricke-samsung962cad92021-04-13 00:46:29 -0700524 if (result) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600525 // NOTE: We need to update words with the result from the spirv-tools optimizer.
526 // **THIS ONLY HAPPENS ON INITIALIZATION**. words should remain const for the lifetime
527 // of the SHADER_MODULE_STATE instance.
528 *const_cast<std::vector<uint32_t> *>(&words) = std::move(optimized_binary);
sfricke-samsung962cad92021-04-13 00:46:29 -0700529 }
530 }
sfricke-samsung962cad92021-04-13 00:46:29 -0700531}
532
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800533char const *StorageClassName(uint32_t sc) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700534 switch (sc) {
535 case spv::StorageClassInput:
536 return "input";
537 case spv::StorageClassOutput:
538 return "output";
539 case spv::StorageClassUniformConstant:
540 return "const uniform";
541 case spv::StorageClassUniform:
542 return "uniform";
543 case spv::StorageClassWorkgroup:
544 return "workgroup local";
545 case spv::StorageClassCrossWorkgroup:
546 return "workgroup global";
547 case spv::StorageClassPrivate:
548 return "private global";
549 case spv::StorageClassFunction:
550 return "function";
551 case spv::StorageClassGeneric:
552 return "generic";
553 case spv::StorageClassAtomicCounter:
554 return "atomic counter";
555 case spv::StorageClassImage:
556 return "image";
557 case spv::StorageClassPushConstant:
558 return "push constant";
559 case spv::StorageClassStorageBuffer:
560 return "storage buffer";
561 default:
562 return "unknown";
563 }
564}
565
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800566void SHADER_MODULE_STATE::DescribeTypeInner(std::ostringstream &ss, uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700567 auto insn = get_def(type);
568 assert(insn != end());
569
570 switch (insn.opcode()) {
571 case spv::OpTypeBool:
572 ss << "bool";
573 break;
574 case spv::OpTypeInt:
575 ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
576 break;
577 case spv::OpTypeFloat:
578 ss << "float" << insn.word(2);
579 break;
580 case spv::OpTypeVector:
581 ss << "vec" << insn.word(3) << " of ";
582 DescribeTypeInner(ss, insn.word(2));
583 break;
584 case spv::OpTypeMatrix:
585 ss << "mat" << insn.word(3) << " of ";
586 DescribeTypeInner(ss, insn.word(2));
587 break;
588 case spv::OpTypeArray:
589 ss << "arr[" << GetConstantValueById(insn.word(3)) << "] of ";
590 DescribeTypeInner(ss, insn.word(2));
591 break;
592 case spv::OpTypeRuntimeArray:
593 ss << "runtime arr[] of ";
594 DescribeTypeInner(ss, insn.word(2));
595 break;
596 case spv::OpTypePointer:
597 ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
598 DescribeTypeInner(ss, insn.word(3));
599 break;
600 case spv::OpTypeStruct: {
601 ss << "struct of (";
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800602 for (uint32_t i = 2; i < insn.len(); i++) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700603 DescribeTypeInner(ss, insn.word(i));
604 if (i == insn.len() - 1) {
605 ss << ")";
606 } else {
607 ss << ", ";
608 }
609 }
610 break;
611 }
612 case spv::OpTypeSampler:
613 ss << "sampler";
614 break;
615 case spv::OpTypeSampledImage:
616 ss << "sampler+";
617 DescribeTypeInner(ss, insn.word(2));
618 break;
619 case spv::OpTypeImage:
620 ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
621 break;
622 case spv::OpTypeAccelerationStructureNV:
623 ss << "accelerationStruture";
624 break;
625 default:
626 ss << "oddtype";
627 break;
628 }
629}
630
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800631std::string SHADER_MODULE_STATE::DescribeType(uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700632 std::ostringstream ss;
633 DescribeTypeInner(ss, type);
634 return ss.str();
635}
636
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800637std::string SHADER_MODULE_STATE::DescribeInstruction(const spirv_inst_iter &insn) const {
638 std::ostringstream ss;
639 const uint32_t opcode = insn.opcode();
640 uint32_t operand_offset = 1; // where to start printing operands
641 // common disassembled for SPIR-V is
642 // %result = Opcode %result_type %operands
643 if (OpcodeHasResult(opcode)) {
644 operand_offset++;
645 ss << "%" << (OpcodeHasType(opcode) ? insn.word(2) : insn.word(1)) << " = ";
646 }
647
648 ss << string_SpvOpcode(opcode);
649
650 if (OpcodeHasType(opcode)) {
651 operand_offset++;
652 ss << " %" << insn.word(1);
653 }
654
sfricke-samsunged00aa42022-01-27 19:03:01 -0800655 // TODO - For now don't list the '%' for any operands since they are only for reference IDs. Without generating a table of each
656 // instructions operand types and covering the many edge cases (such as optional, paired, or variable operands) this is the
657 // simplest way to print the instruction and give the developer something to look into when an error occurs.
658 //
659 // For now this safely should be able to assume it will never come across a LiteralString such as in OpExtInstImport or
660 // OpEntryPoint
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800661 for (uint32_t i = operand_offset; i < insn.len(); i++) {
sfricke-samsunged00aa42022-01-27 19:03:01 -0800662 ss << " " << insn.word(i);
sfricke-samsung7a9bdca2022-01-24 14:38:03 -0800663 }
664 return ss.str();
665}
666
sfricke-samsung962cad92021-04-13 00:46:29 -0700667const SHADER_MODULE_STATE::EntryPoint *SHADER_MODULE_STATE::FindEntrypointStruct(char const *name,
668 VkShaderStageFlagBits stageBits) const {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600669 auto range = static_data_.entry_points.equal_range(name);
sfricke-samsung962cad92021-04-13 00:46:29 -0700670 for (auto it = range.first; it != range.second; ++it) {
671 if (it->second.stage == stageBits) {
672 return &(it->second);
673 }
674 }
675 return nullptr;
676}
677
678spirv_inst_iter SHADER_MODULE_STATE::FindEntrypoint(char const *name, VkShaderStageFlagBits stageBits) const {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600679 auto range = static_data_.entry_points.equal_range(name);
sfricke-samsung962cad92021-04-13 00:46:29 -0700680 for (auto it = range.first; it != range.second; ++it) {
681 if (it->second.stage == stageBits) {
682 return at(it->second.offset);
683 }
684 }
685 return end();
686}
687
688// Because the following is legal, need the entry point
689// OpEntryPoint GLCompute %main "name_a"
690// OpEntryPoint GLCompute %main "name_b"
691bool SHADER_MODULE_STATE::FindLocalSize(const spirv_inst_iter &entrypoint, uint32_t &local_size_x, uint32_t &local_size_y,
692 uint32_t &local_size_z) const {
693 auto entrypoint_id = entrypoint.word(2);
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -0600694 auto it = static_data_.execution_mode_inst.find(entrypoint_id);
695 if (it != static_data_.execution_mode_inst.end()) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700696 for (auto insn : it->second) {
697 // Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
698 // In the future if something like LocalSizeId is supported, the <id> will need to be checked also
699 assert(insn.opcode() == spv::OpExecutionMode);
700 if (insn.word(2) == spv::ExecutionModeLocalSize) {
701 local_size_x = insn.word(3);
702 local_size_y = insn.word(4);
703 local_size_z = insn.word(5);
704 return true;
705 }
706 }
707 }
708 return false;
709}
710
711// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
712// Otherwise, returns src->end().
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800713spirv_inst_iter SHADER_MODULE_STATE::GetConstantDef(uint32_t id) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700714 auto value = get_def(id);
715
716 // If id is a copy, see where it was copied from
717 if ((end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
718 id = value.word(3);
719 value = get_def(id);
720 }
721
722 if ((end() != value) && (value.opcode() == spv::OpConstant)) {
723 return value;
724 }
725 return end();
726}
727
728// Either returns the constant value described by the instruction at id, or 1
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800729uint32_t SHADER_MODULE_STATE::GetConstantValueById(uint32_t id) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700730 auto value = GetConstantDef(id);
731
732 if (end() == value) {
733 // TODO: Either ensure that the specialization transform is already performed on a module we're
734 // considering here, OR -- specialize on the fly now.
735 return 1;
736 }
737 return GetConstantValue(value);
738}
739
740// Returns an int32_t corresponding to the spv::Dim of the given resource, when positive, and corresponding to an unknown type, when
741// negative.
742int32_t SHADER_MODULE_STATE::GetShaderResourceDimensionality(const interface_var &resource) const {
743 auto type = get_def(resource.type_id);
744 while (true) {
745 switch (type.opcode()) {
746 case spv::OpTypeSampledImage:
747 type = get_def(type.word(2));
748 break;
749 case spv::OpTypePointer:
750 type = get_def(type.word(3));
751 break;
752 case spv::OpTypeImage:
753 return type.word(3);
754 default:
755 return -1;
756 }
757 }
758}
759
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800760uint32_t SHADER_MODULE_STATE::GetLocationsConsumedByType(uint32_t type, bool strip_array_level) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700761 auto insn = get_def(type);
762 assert(insn != end());
763
764 switch (insn.opcode()) {
765 case spv::OpTypePointer:
766 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
767 // pointers around.
768 return GetLocationsConsumedByType(insn.word(3), strip_array_level);
769 case spv::OpTypeArray:
770 if (strip_array_level) {
771 return GetLocationsConsumedByType(insn.word(2), false);
772 } else {
773 return GetConstantValueById(insn.word(3)) * GetLocationsConsumedByType(insn.word(2), false);
774 }
775 case spv::OpTypeMatrix:
776 // Num locations is the dimension * element size
777 return insn.word(3) * GetLocationsConsumedByType(insn.word(2), false);
778 case spv::OpTypeVector: {
779 auto scalar_type = get_def(insn.word(2));
780 auto bit_width =
781 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
782
783 // Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
784 return (bit_width * insn.word(3) + 127) / 128;
785 }
786 default:
787 // Everything else is just 1.
788 return 1;
789
790 // TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
791 }
792}
793
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800794uint32_t SHADER_MODULE_STATE::GetComponentsConsumedByType(uint32_t type, bool strip_array_level) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700795 auto insn = get_def(type);
796 assert(insn != end());
797
798 switch (insn.opcode()) {
799 case spv::OpTypePointer:
800 // See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
801 // pointers around.
802 return GetComponentsConsumedByType(insn.word(3), strip_array_level);
803 case spv::OpTypeStruct: {
804 uint32_t sum = 0;
805 for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
806 sum += GetComponentsConsumedByType(insn.word(i), false);
807 }
808 return sum;
809 }
810 case spv::OpTypeArray:
811 if (strip_array_level) {
812 return GetComponentsConsumedByType(insn.word(2), false);
813 } else {
814 return GetConstantValueById(insn.word(3)) * GetComponentsConsumedByType(insn.word(2), false);
815 }
816 case spv::OpTypeMatrix:
817 // Num locations is the dimension * element size
818 return insn.word(3) * GetComponentsConsumedByType(insn.word(2), false);
819 case spv::OpTypeVector: {
820 auto scalar_type = get_def(insn.word(2));
821 auto bit_width =
822 (scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
823 // One component is 32-bit
824 return (bit_width * insn.word(3) + 31) / 32;
825 }
826 case spv::OpTypeFloat: {
827 auto bit_width = insn.word(2);
828 return (bit_width + 31) / 32;
829 }
830 case spv::OpTypeInt: {
831 auto bit_width = insn.word(2);
832 return (bit_width + 31) / 32;
833 }
834 case spv::OpConstant:
835 return GetComponentsConsumedByType(insn.word(1), false);
836 default:
837 return 0;
838 }
839}
840
841// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
842// also used for input attachments, as we statically know their format.
sfricke-samsung7fac88a2022-01-26 11:44:22 -0800843uint32_t SHADER_MODULE_STATE::GetFundamentalType(uint32_t type) const {
sfricke-samsung962cad92021-04-13 00:46:29 -0700844 auto insn = get_def(type);
845 assert(insn != end());
846
847 switch (insn.opcode()) {
848 case spv::OpTypeInt:
849 return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
850 case spv::OpTypeFloat:
851 return FORMAT_TYPE_FLOAT;
852 case spv::OpTypeVector:
853 case spv::OpTypeMatrix:
854 case spv::OpTypeArray:
855 case spv::OpTypeRuntimeArray:
856 case spv::OpTypeImage:
857 return GetFundamentalType(insn.word(2));
858 case spv::OpTypePointer:
859 return GetFundamentalType(insn.word(3));
860
861 default:
862 return 0;
863 }
864}
865
866spirv_inst_iter SHADER_MODULE_STATE::GetStructType(spirv_inst_iter def, bool is_array_of_verts) const {
867 while (true) {
868 if (def.opcode() == spv::OpTypePointer) {
869 def = get_def(def.word(3));
870 } else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
871 def = get_def(def.word(2));
872 is_array_of_verts = false;
873 } else if (def.opcode() == spv::OpTypeStruct) {
874 return def;
875 } else {
876 return end();
877 }
878 }
879}
880
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800881void SHADER_MODULE_STATE::DefineStructMember(const spirv_inst_iter &it, const std::vector<uint32_t> &member_decorate_offsets,
sfricke-samsung962cad92021-04-13 00:46:29 -0700882 shader_struct_member &data) const {
883 const auto struct_it = GetStructType(it, false);
884 assert(struct_it != end());
885 data.size = 0;
886
887 shader_struct_member data1;
888 uint32_t i = 2;
889 uint32_t local_offset = 0;
890 std::vector<uint32_t> offsets;
891 offsets.resize(struct_it.len() - i);
892
893 // The members of struct in SPRIV_R aren't always sort, so we need to know their order.
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800894 for (const auto offset : member_decorate_offsets) {
sfricke-samsung962cad92021-04-13 00:46:29 -0700895 const auto member_decorate = at(offset);
896 if (member_decorate.word(1) != struct_it.word(1)) {
897 continue;
898 }
899
900 offsets[member_decorate.word(2)] = member_decorate.word(4);
901 }
902
903 for (const auto offset : offsets) {
904 local_offset = offset;
905 data1 = {};
906 data1.root = data.root;
907 data1.offset = local_offset;
908 auto def_member = get_def(struct_it.word(i));
909
910 // Array could be multi-dimensional
911 while (def_member.opcode() == spv::OpTypeArray) {
912 const auto len_id = def_member.word(3);
913 const auto def_len = get_def(len_id);
914 data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
915 def_member = get_def(def_member.word(2));
916 }
917
918 if (def_member.opcode() == spv::OpTypeStruct) {
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800919 DefineStructMember(def_member, member_decorate_offsets, data1);
sfricke-samsung962cad92021-04-13 00:46:29 -0700920 } else if (def_member.opcode() == spv::OpTypePointer) {
921 if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
922 // If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
923 // that "points to something."
924 data1.size = 8;
925 } else {
926 // If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
sfricke-samsungad55ccc2022-01-19 20:06:17 -0800927 DefineStructMember(def_member, member_decorate_offsets, data1);
sfricke-samsung962cad92021-04-13 00:46:29 -0700928 }
929 } else {
930 if (def_member.opcode() == spv::OpTypeMatrix) {
931 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
932 def_member = get_def(def_member.word(2));
933 }
934
935 if (def_member.opcode() == spv::OpTypeVector) {
936 data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
937 def_member = get_def(def_member.word(2));
938 }
939
940 // Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
941 data1.size = (def_member.word(2) / 8);
942 }
943 const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
944 if (array_length_hierarchy_szie > 0) {
945 data1.array_block_size.resize(array_length_hierarchy_szie, 1);
946
947 for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
948 data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
949 }
950 }
951 data.struct_members.emplace_back(data1);
952 ++i;
953 }
954 uint32_t total_array_length = 1;
955 for (const auto length : data1.array_length_hierarchy) {
956 total_array_length *= length;
957 }
958 data.size = local_offset + data1.size * total_array_length;
959}
960
961static uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
962 int array_indices_size = static_cast<int>(array_indices.size());
963 if (array_indices_size) {
964 uint32_t array_index = 0;
965 uint32_t i = 0;
966 for (const auto index : array_indices) {
967 array_index += (data.array_block_size[i] * index);
968 ++i;
969 }
970 offset += (array_index * data.size);
971 }
972 return offset;
973}
974
975static void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
976 int array_indices_size = static_cast<int>(array_indices.size());
977 uint32_t block_memory_size = data.size;
978 for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
979 block_memory_size *= data.array_length_hierarchy[i];
980 }
981
982 offset = UpdateOffset(offset, array_indices, data);
983
984 uint32_t end = offset + block_memory_size;
985 auto used_bytes = data.GetUsedbytes();
986 if (used_bytes->size() < end) {
987 used_bytes->resize(end, 0);
988 }
989 std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
990}
991
992void SHADER_MODULE_STATE::RunUsedArray(uint32_t offset, std::vector<uint32_t> array_indices, uint32_t access_chain_word_index,
993 spirv_inst_iter &access_chain_it, const shader_struct_member &data) const {
994 if (access_chain_word_index < access_chain_it.len()) {
995 if (data.array_length_hierarchy.size() > array_indices.size()) {
996 auto def_it = get_def(access_chain_it.word(access_chain_word_index));
997 ++access_chain_word_index;
998
999 if (def_it != end() && def_it.opcode() == spv::OpConstant) {
1000 array_indices.emplace_back(def_it.word(3));
1001 RunUsedArray(offset, array_indices, access_chain_word_index, access_chain_it, data);
1002 } else {
1003 // If it is a variable, set the all array is used.
1004 if (access_chain_word_index < access_chain_it.len()) {
1005 uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
1006 for (uint32_t i = 0; i < array_length; ++i) {
1007 auto array_indices2 = array_indices;
1008 array_indices2.emplace_back(i);
1009 RunUsedArray(offset, array_indices2, access_chain_word_index, access_chain_it, data);
1010 }
1011 } else {
1012 SetUsedBytes(offset, array_indices, data);
1013 }
1014 }
1015 } else {
1016 offset = UpdateOffset(offset, array_indices, data);
1017 RunUsedStruct(offset, access_chain_word_index, access_chain_it, data);
1018 }
1019 } else {
1020 SetUsedBytes(offset, array_indices, data);
1021 }
1022}
1023
1024void SHADER_MODULE_STATE::RunUsedStruct(uint32_t offset, uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it,
1025 const shader_struct_member &data) const {
1026 std::vector<uint32_t> array_indices_emptry;
1027
1028 if (access_chain_word_index < access_chain_it.len()) {
1029 auto strcut_member_index = GetConstantValueById(access_chain_it.word(access_chain_word_index));
1030 ++access_chain_word_index;
1031
1032 auto data1 = data.struct_members[strcut_member_index];
1033 RunUsedArray(offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
1034 }
1035}
1036
1037void SHADER_MODULE_STATE::SetUsedStructMember(const uint32_t variable_id, const std::vector<function_set> &function_set_list,
1038 const shader_struct_member &data) const {
1039 for (const auto &func_set : function_set_list) {
1040 auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
1041 for (auto it = range.first; it != range.second; ++it) {
1042 auto access_chain = at(it->second);
1043 if (access_chain.word(3) == variable_id) {
1044 RunUsedStruct(0, 4, access_chain, data);
1045 }
1046 }
1047 }
1048}
1049
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001050// static
1051void SHADER_MODULE_STATE::SetPushConstantUsedInShader(
sfricke-samsungef15e482022-01-26 11:32:49 -08001052 const SHADER_MODULE_STATE &module_state, std::unordered_multimap<std::string, SHADER_MODULE_STATE::EntryPoint> &entry_points) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001053 for (auto &entrypoint : entry_points) {
1054 auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
1055 for (auto it = range.first; it != range.second; ++it) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001056 const auto def_insn = module_state.at(it->second);
sfricke-samsung962cad92021-04-13 00:46:29 -07001057
1058 if (def_insn.word(3) == spv::StorageClassPushConstant) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001059 spirv_inst_iter type = module_state.get_def(def_insn.word(1));
sfricke-samsung962cad92021-04-13 00:46:29 -07001060 const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
1061 std::vector<uint32_t> offsets;
1062
1063 for (auto it2 = range2.first; it2 != range2.second; ++it2) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001064 auto member_decorate = module_state.at(it2->second);
sfricke-samsung962cad92021-04-13 00:46:29 -07001065 if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
1066 offsets.emplace_back(member_decorate.offset());
1067 }
1068 }
1069 entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
sfricke-samsungef15e482022-01-26 11:32:49 -08001070 module_state.DefineStructMember(type, offsets, entrypoint.second.push_constant_used_in_shader);
1071 module_state.SetUsedStructMember(def_insn.word(2), entrypoint.second.function_set_list,
1072 entrypoint.second.push_constant_used_in_shader);
sfricke-samsung962cad92021-04-13 00:46:29 -07001073 }
1074 }
1075 }
1076}
1077
1078uint32_t SHADER_MODULE_STATE::DescriptorTypeToReqs(uint32_t type_id) const {
1079 auto type = get_def(type_id);
1080
1081 while (true) {
1082 switch (type.opcode()) {
1083 case spv::OpTypeArray:
1084 case spv::OpTypeRuntimeArray:
1085 case spv::OpTypeSampledImage:
1086 type = get_def(type.word(2));
1087 break;
1088 case spv::OpTypePointer:
1089 type = get_def(type.word(3));
1090 break;
1091 case spv::OpTypeImage: {
1092 auto dim = type.word(3);
1093 auto arrayed = type.word(5);
1094 auto msaa = type.word(6);
1095
1096 uint32_t bits = 0;
1097 switch (GetFundamentalType(type.word(2))) {
1098 case FORMAT_TYPE_FLOAT:
1099 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
1100 break;
1101 case FORMAT_TYPE_UINT:
1102 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
1103 break;
1104 case FORMAT_TYPE_SINT:
1105 bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
1106 break;
1107 default:
1108 break;
1109 }
1110
1111 switch (dim) {
1112 case spv::Dim1D:
1113 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
1114 return bits;
1115 case spv::Dim2D:
1116 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1117 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
1118 return bits;
1119 case spv::Dim3D:
1120 bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
1121 return bits;
1122 case spv::DimCube:
1123 bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
1124 return bits;
1125 case spv::DimSubpassData:
1126 bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
1127 return bits;
1128 default: // buffer, etc.
1129 return bits;
1130 }
1131 }
1132 default:
1133 return 0;
1134 }
1135 }
1136}
1137
1138// For some built-in analysis we need to know if the variable decorated with as the built-in was actually written to.
1139// This function examines instructions in the static call tree for a write to this variable.
1140bool SHADER_MODULE_STATE::IsBuiltInWritten(spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) const {
1141 auto type = builtin_instr.opcode();
1142 uint32_t target_id = builtin_instr.word(1);
1143 bool init_complete = false;
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001144 uint32_t target_member_offset = 0;
sfricke-samsung962cad92021-04-13 00:46:29 -07001145
1146 if (type == spv::OpMemberDecorate) {
1147 // Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
1148 auto insn = entrypoint;
1149 while (!init_complete && (insn.opcode() != spv::OpFunction)) {
1150 switch (insn.opcode()) {
1151 case spv::OpTypePointer:
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001152 if (insn.word(2) == spv::StorageClassOutput) {
1153 const auto type_id = insn.word(3);
1154 if (type_id == target_id) {
1155 target_id = insn.word(1);
1156 } else {
1157 // If the output is an array, check if the element type is what we're looking for
1158 const auto type_insn = get_def(type_id);
1159 if ((type_insn.opcode() == spv::OpTypeArray) && (type_insn.word(2) == target_id)) {
1160 target_id = insn.word(1);
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001161 target_member_offset = 1;
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001162 }
1163 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001164 }
1165 break;
1166 case spv::OpVariable:
1167 if (insn.word(1) == target_id) {
1168 target_id = insn.word(2);
1169 init_complete = true;
1170 }
1171 break;
1172 }
1173 insn++;
1174 }
1175 }
1176
1177 if (!init_complete && (type == spv::OpMemberDecorate)) return false;
1178
1179 bool found_write = false;
1180 layer_data::unordered_set<uint32_t> worklist;
1181 worklist.insert(entrypoint.word(2));
1182
1183 // Follow instructions in call graph looking for writes to target
1184 while (!worklist.empty() && !found_write) {
1185 auto id_iter = worklist.begin();
1186 auto id = *id_iter;
1187 worklist.erase(id_iter);
1188
1189 auto insn = get_def(id);
1190 if (insn == end()) {
1191 continue;
1192 }
1193
1194 if (insn.opcode() == spv::OpFunction) {
1195 // Scan body of function looking for other function calls or items in our ID chain
Nathaniel Cesario58fc2282021-08-18 12:20:40 -06001196 while (++insn, (insn.opcode() != spv::OpFunctionEnd) && !found_write) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001197 switch (insn.opcode()) {
1198 case spv::OpAccessChain:
1199 if (insn.word(3) == target_id) {
1200 if (type == spv::OpMemberDecorate) {
Nathaniel Cesario80c0e0f2021-10-14 13:25:54 -06001201 // Get the target member of the struct
1202 // NOTE: this will only work for structs and arrays of structs. Deeper levels of nesting (e.g.,
1203 // arrays of structs of structs) is not currently supported.
1204 const auto value_itr = GetConstantDef(insn.word(4 + target_member_offset));
1205 if (value_itr != end()) {
1206 auto value = GetConstantValue(value_itr);
1207 if (value == builtin_instr.word(2)) {
1208 target_id = insn.word(2);
1209 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001210 }
1211 } else {
1212 target_id = insn.word(2);
1213 }
1214 }
1215 break;
1216 case spv::OpStore:
1217 if (insn.word(1) == target_id) {
1218 found_write = true;
1219 }
1220 break;
1221 case spv::OpFunctionCall:
1222 worklist.insert(insn.word(3));
1223 break;
1224 }
1225 }
1226 }
1227 }
1228 return found_write;
1229}
1230
1231// Used by the collection functions to help aid in state tracking
1232struct shader_module_used_operators {
1233 bool updated;
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001234 std::vector<uint32_t> image_read_members;
1235 std::vector<uint32_t> image_write_members;
1236 std::vector<uint32_t> atomic_members;
1237 std::vector<uint32_t> store_members;
1238 std::vector<uint32_t> atomic_store_members;
1239 std::vector<uint32_t> sampler_implicitLod_dref_proj_members; // sampler Load id
1240 std::vector<uint32_t> sampler_bias_offset_members; // sampler Load id
1241 std::vector<uint32_t> image_dref_members;
1242 std::vector<std::pair<uint32_t, uint32_t>> sampled_image_members; // <image,sampler> Load id
1243 layer_data::unordered_map<uint32_t, uint32_t> load_members;
1244 layer_data::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> accesschain_members;
1245 layer_data::unordered_map<uint32_t, uint32_t> image_texel_pointer_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001246
1247 shader_module_used_operators() : updated(false) {}
1248
1249 bool CheckImageOperandsBiasOffset(uint32_t type) {
1250 return type & (spv::ImageOperandsBiasMask | spv::ImageOperandsConstOffsetMask | spv::ImageOperandsOffsetMask |
1251 spv::ImageOperandsConstOffsetsMask)
1252 ? true
1253 : false;
1254 }
1255
sfricke-samsungef15e482022-01-26 11:32:49 -08001256 void update(SHADER_MODULE_STATE const *module_state) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001257 if (updated) return;
1258 updated = true;
1259
sfricke-samsungef15e482022-01-26 11:32:49 -08001260 for (auto insn : *module_state) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001261 switch (insn.opcode()) {
1262 case spv::OpImageSampleImplicitLod:
1263 case spv::OpImageSampleProjImplicitLod:
1264 case spv::OpImageSampleProjExplicitLod:
1265 case spv::OpImageSparseSampleImplicitLod:
1266 case spv::OpImageSparseSampleProjImplicitLod:
1267 case spv::OpImageSparseSampleProjExplicitLod: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001268 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001269 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001270 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1271 sampler_implicitLod_dref_proj_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001272 // ImageOperands in index: 5
1273 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001274 sampler_bias_offset_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001275 }
1276 break;
1277 }
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001278 case spv::OpImageDrefGather:
1279 case spv::OpImageSparseDrefGather: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001280 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001281 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001282 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(3) : insn.word(3);
1283 image_dref_members.emplace_back(load_id);
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001284 break;
1285 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001286 case spv::OpImageSampleDrefImplicitLod:
1287 case spv::OpImageSampleDrefExplicitLod:
1288 case spv::OpImageSampleProjDrefImplicitLod:
1289 case spv::OpImageSampleProjDrefExplicitLod:
1290 case spv::OpImageSparseSampleDrefImplicitLod:
1291 case spv::OpImageSparseSampleDrefExplicitLod:
1292 case spv::OpImageSparseSampleProjDrefImplicitLod:
1293 case spv::OpImageSparseSampleProjDrefExplicitLod: {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001294 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001295 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001296 auto sampler_load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1297 auto image_load_id = (id.opcode() == spv::OpSampledImage) ? id.word(3) : insn.word(3);
1298
1299 image_dref_members.emplace_back(image_load_id);
1300 sampler_implicitLod_dref_proj_members.emplace_back(sampler_load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001301 // ImageOperands in index: 6
1302 if (insn.len() > 6 && CheckImageOperandsBiasOffset(insn.word(6))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001303 sampler_bias_offset_members.emplace_back(sampler_load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001304 }
1305 break;
1306 }
1307 case spv::OpImageSampleExplicitLod:
1308 case spv::OpImageSparseSampleExplicitLod: {
1309 // ImageOperands in index: 5
1310 if (insn.len() > 5 && CheckImageOperandsBiasOffset(insn.word(5))) {
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001311 // combined image samples are just OpLoad, but also can be separate image and sampler
sfricke-samsungef15e482022-01-26 11:32:49 -08001312 auto id = module_state->get_def(insn.word(3)); // <id> Sampled Image
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001313 auto load_id = (id.opcode() == spv::OpSampledImage) ? id.word(4) : insn.word(3);
1314 sampler_bias_offset_members.emplace_back(load_id);
sfricke-samsung962cad92021-04-13 00:46:29 -07001315 }
1316 break;
1317 }
1318 case spv::OpStore: {
1319 store_members.emplace_back(insn.word(1)); // object id or AccessChain id
1320 break;
1321 }
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001322 case spv::OpImageRead:
1323 case spv::OpImageSparseRead: {
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001324 image_read_members.emplace_back(insn.word(3)); // Load id
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001325 break;
1326 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001327 case spv::OpImageWrite: {
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001328 image_write_members.emplace_back(insn.word(1)); // Load id
sfricke-samsung962cad92021-04-13 00:46:29 -07001329 break;
1330 }
1331 case spv::OpSampledImage: {
1332 // 3: image load id, 4: sampler load id
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001333 sampled_image_members.emplace_back(std::pair<uint32_t, uint32_t>(insn.word(3), insn.word(4)));
sfricke-samsung962cad92021-04-13 00:46:29 -07001334 break;
1335 }
1336 case spv::OpLoad: {
1337 // 2: Load id, 3: object id or AccessChain id
1338 load_members.emplace(insn.word(2), insn.word(3));
1339 break;
1340 }
1341 case spv::OpAccessChain: {
1342 if (insn.len() == 4) {
1343 // If it is for struct, the length is only 4.
1344 // 2: AccessChain id, 3: object id
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001345 accesschain_members.emplace(insn.word(2), std::pair<uint32_t, uint32_t>(insn.word(3), 0));
sfricke-samsung962cad92021-04-13 00:46:29 -07001346 } else {
1347 // 2: AccessChain id, 3: object id, 4: object id of array index
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001348 accesschain_members.emplace(insn.word(2), std::pair<uint32_t, uint32_t>(insn.word(3), insn.word(4)));
sfricke-samsung962cad92021-04-13 00:46:29 -07001349 }
1350 break;
1351 }
1352 case spv::OpImageTexelPointer: {
1353 // 2: ImageTexelPointer id, 3: object id
1354 image_texel_pointer_members.emplace(insn.word(2), insn.word(3));
1355 break;
1356 }
1357 default: {
1358 if (AtomicOperation(insn.opcode())) {
1359 if (insn.opcode() == spv::OpAtomicStore) {
1360 atomic_store_members.emplace_back(insn.word(1)); // ImageTexelPointer id
1361 } else {
1362 atomic_members.emplace_back(insn.word(3)); // ImageTexelPointer id
1363 }
1364 }
1365 break;
1366 }
1367 }
1368 }
1369 }
1370};
1371
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001372static bool CheckObjectIDFromOpLoad(uint32_t object_id, const std::vector<uint32_t> &operator_members,
1373 const layer_data::unordered_map<uint32_t, uint32_t> &load_members,
1374 const layer_data::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> &accesschain_members) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001375 for (auto load_id : operator_members) {
1376 if (object_id == load_id) return true;
1377 auto load_it = load_members.find(load_id);
1378 if (load_it == load_members.end()) {
1379 continue;
1380 }
1381 if (load_it->second == object_id) {
1382 return true;
1383 }
1384
1385 auto accesschain_it = accesschain_members.find(load_it->second);
1386 if (accesschain_it == accesschain_members.end()) {
1387 continue;
1388 }
1389 if (accesschain_it->second.first == object_id) {
1390 return true;
1391 }
1392 }
1393 return false;
1394}
1395
1396// Takes a OpVariable and looks at the the descriptor type it uses. This will find things such as if the variable is writable, image
1397// atomic operation, matching images to samplers, etc
1398void SHADER_MODULE_STATE::IsSpecificDescriptorType(const spirv_inst_iter &id_it, bool is_storage_buffer, bool is_check_writable,
1399 interface_var &out_interface_var,
1400 shader_module_used_operators &used_operators) const {
1401 uint32_t type_id = id_it.word(1);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001402 uint32_t id = id_it.word(2);
sfricke-samsung962cad92021-04-13 00:46:29 -07001403
1404 auto type = get_def(type_id);
1405
1406 // Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
1407 while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray ||
1408 type.opcode() == spv::OpTypeSampledImage) {
1409 if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray ||
1410 type.opcode() == spv::OpTypeSampledImage) {
1411 type = get_def(type.word(2)); // Element type
1412 } else {
1413 type = get_def(type.word(3)); // Pointer type
1414 }
1415 }
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001416
sfricke-samsung962cad92021-04-13 00:46:29 -07001417 switch (type.opcode()) {
1418 case spv::OpTypeImage: {
1419 auto dim = type.word(3);
1420 if (dim != spv::DimSubpassData) {
1421 used_operators.update(this);
1422
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001423 // Sampled == 2 indicates used without a sampler (a storage image)
1424 bool is_image_without_format = false;
1425 if (type.word(7) == 2) is_image_without_format = type.word(8) == spv::ImageFormatUnknown;
1426
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001427 if (CheckObjectIDFromOpLoad(id, used_operators.image_write_members, used_operators.load_members,
sfricke-samsung962cad92021-04-13 00:46:29 -07001428 used_operators.accesschain_members)) {
1429 out_interface_var.is_writable = true;
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001430 if (is_image_without_format) out_interface_var.is_write_without_format = true;
1431 }
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001432 if (CheckObjectIDFromOpLoad(id, used_operators.image_read_members, used_operators.load_members,
Lionel Landwerlinbc7401b2021-12-07 15:43:05 +02001433 used_operators.accesschain_members)) {
1434 out_interface_var.is_readable = true;
1435 if (is_image_without_format) out_interface_var.is_read_without_format = true;
sfricke-samsung962cad92021-04-13 00:46:29 -07001436 }
1437 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_implicitLod_dref_proj_members, used_operators.load_members,
1438 used_operators.accesschain_members)) {
1439 out_interface_var.is_sampler_implicitLod_dref_proj = true;
1440 }
1441 if (CheckObjectIDFromOpLoad(id, used_operators.sampler_bias_offset_members, used_operators.load_members,
1442 used_operators.accesschain_members)) {
1443 out_interface_var.is_sampler_bias_offset = true;
1444 }
1445 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_members, used_operators.image_texel_pointer_members,
1446 used_operators.accesschain_members) ||
1447 CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1448 used_operators.accesschain_members)) {
1449 out_interface_var.is_atomic_operation = true;
1450 }
Lionel Landwerlincdbe8682021-12-08 15:10:37 +02001451 if (CheckObjectIDFromOpLoad(id, used_operators.image_dref_members, used_operators.load_members,
1452 used_operators.accesschain_members)) {
1453 out_interface_var.is_dref_operation = true;
1454 }
sfricke-samsung962cad92021-04-13 00:46:29 -07001455
sfricke-samsungad55ccc2022-01-19 20:06:17 -08001456 for (auto &itp_id : used_operators.sampled_image_members) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001457 // Find if image id match.
1458 uint32_t image_index = 0;
1459 auto load_it = used_operators.load_members.find(itp_id.first);
1460 if (load_it == used_operators.load_members.end()) {
1461 continue;
1462 } else {
1463 if (load_it->second != id) {
1464 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1465 if (accesschain_it == used_operators.accesschain_members.end()) {
1466 continue;
1467 } else {
1468 if (accesschain_it->second.first != id) {
1469 continue;
1470 }
1471
1472 const auto const_itr = GetConstantDef(accesschain_it->second.second);
1473 if (const_itr == end()) {
1474 // access chain index not a constant, skip.
1475 break;
1476 }
1477 image_index = GetConstantValue(const_itr);
1478 }
1479 }
1480 }
1481 // Find sampler's set binding.
1482 load_it = used_operators.load_members.find(itp_id.second);
1483 if (load_it == used_operators.load_members.end()) {
1484 continue;
1485 } else {
1486 uint32_t sampler_id = load_it->second;
1487 uint32_t sampler_index = 0;
1488 auto accesschain_it = used_operators.accesschain_members.find(load_it->second);
1489
1490 if (accesschain_it != used_operators.accesschain_members.end()) {
1491 const auto const_itr = GetConstantDef(accesschain_it->second.second);
1492 if (const_itr == end()) {
1493 // access chain index representing sampler index is not a constant, skip.
1494 break;
1495 }
1496 sampler_id = const_itr.offset();
1497 sampler_index = GetConstantValue(const_itr);
1498 }
1499 auto sampler_dec = get_decorations(sampler_id);
1500 if (image_index >= out_interface_var.samplers_used_by_image.size()) {
1501 out_interface_var.samplers_used_by_image.resize(image_index + 1);
1502 }
sfricke-samsungdb3f3f82022-01-18 06:41:15 -08001503
1504 // Need to check again for these properties in case not using a combined image sampler
1505 if (CheckObjectIDFromOpLoad(sampler_id, used_operators.sampler_implicitLod_dref_proj_members,
1506 used_operators.load_members, used_operators.accesschain_members)) {
1507 out_interface_var.is_sampler_implicitLod_dref_proj = true;
1508 }
1509 if (CheckObjectIDFromOpLoad(sampler_id, used_operators.sampler_bias_offset_members,
1510 used_operators.load_members, used_operators.accesschain_members)) {
1511 out_interface_var.is_sampler_bias_offset = true;
1512 }
1513
sfricke-samsung962cad92021-04-13 00:46:29 -07001514 out_interface_var.samplers_used_by_image[image_index].emplace(
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001515 SamplerUsedByImage{DescriptorSlot{sampler_dec.descriptor_set, sampler_dec.binding}, sampler_index});
sfricke-samsung962cad92021-04-13 00:46:29 -07001516 }
1517 }
1518 }
1519 return;
1520 }
1521
1522 case spv::OpTypeStruct: {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001523 layer_data::unordered_set<uint32_t> nonwritable_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001524 if (get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001525 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001526 if (insn.word(1) == type.word(1) && insn.word(3) == spv::DecorationNonWritable) {
1527 nonwritable_members.insert(insn.word(2));
1528 }
1529 }
1530
1531 // A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
1532 // as nonwritable.
1533 if (is_storage_buffer && nonwritable_members.size() != type.len() - 2) {
1534 used_operators.update(this);
1535
1536 for (auto oid : used_operators.store_members) {
1537 if (id == oid) {
1538 out_interface_var.is_writable = true;
1539 return;
1540 }
1541 auto accesschain_it = used_operators.accesschain_members.find(oid);
1542 if (accesschain_it == used_operators.accesschain_members.end()) {
1543 continue;
1544 }
1545 if (accesschain_it->second.first == id) {
1546 out_interface_var.is_writable = true;
1547 return;
1548 }
1549 }
1550 if (CheckObjectIDFromOpLoad(id, used_operators.atomic_store_members, used_operators.image_texel_pointer_members,
1551 used_operators.accesschain_members)) {
1552 out_interface_var.is_writable = true;
1553 return;
1554 }
1555 }
1556 }
1557 }
1558}
1559
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001560std::vector<std::pair<DescriptorSlot, interface_var>> SHADER_MODULE_STATE::CollectInterfaceByDescriptorSlot(
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001561 layer_data::unordered_set<uint32_t> const &accessible_ids) const {
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001562 std::vector<std::pair<DescriptorSlot, interface_var>> out;
sfricke-samsung962cad92021-04-13 00:46:29 -07001563 shader_module_used_operators operators;
1564
1565 for (auto id : accessible_ids) {
1566 auto insn = get_def(id);
1567 assert(insn != end());
1568
1569 if (insn.opcode() == spv::OpVariable &&
Lionel Landwerlin6a9f89c2021-12-07 15:46:46 +02001570 (insn.word(3) == spv::StorageClassUniform ||
1571 insn.word(3) == spv::StorageClassUniformConstant ||
sfricke-samsung962cad92021-04-13 00:46:29 -07001572 insn.word(3) == spv::StorageClassStorageBuffer)) {
1573 auto d = get_decorations(insn.word(2));
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001574 uint32_t set = d.descriptor_set;
1575 uint32_t binding = d.binding;
sfricke-samsung962cad92021-04-13 00:46:29 -07001576
1577 interface_var v = {};
1578 v.id = insn.word(2);
1579 v.type_id = insn.word(1);
1580
1581 IsSpecificDescriptorType(insn, insn.word(3) == spv::StorageClassStorageBuffer,
1582 !(d.flags & decoration_set::nonwritable_bit), v, operators);
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001583 out.emplace_back(DescriptorSlot{set, binding}, v);
sfricke-samsung962cad92021-04-13 00:46:29 -07001584 }
1585 }
1586
1587 return out;
1588}
1589
1590layer_data::unordered_set<uint32_t> SHADER_MODULE_STATE::CollectWritableOutputLocationinFS(
Jeremy Gebben84b838b2021-08-23 08:41:39 -06001591 const spirv_inst_iter &entrypoint) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001592 layer_data::unordered_set<uint32_t> location_list;
sfricke-samsung962cad92021-04-13 00:46:29 -07001593 const auto outputs = CollectInterfaceByLocation(entrypoint, spv::StorageClassOutput, false);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001594 layer_data::unordered_set<uint32_t> store_members;
1595 layer_data::unordered_map<uint32_t, uint32_t> accesschain_members;
sfricke-samsung962cad92021-04-13 00:46:29 -07001596
1597 for (auto insn : *this) {
1598 switch (insn.opcode()) {
1599 case spv::OpStore:
1600 case spv::OpAtomicStore: {
1601 store_members.insert(insn.word(1)); // object id or AccessChain id
1602 break;
1603 }
1604 case spv::OpAccessChain: {
1605 // 2: AccessChain id, 3: object id
1606 if (insn.word(3)) accesschain_members.emplace(insn.word(2), insn.word(3));
1607 break;
1608 }
1609 default:
1610 break;
1611 }
1612 }
1613 if (store_members.empty()) {
1614 return location_list;
1615 }
1616 for (auto output : outputs) {
1617 auto store_it = store_members.find(output.second.id);
1618 if (store_it != store_members.end()) {
1619 location_list.insert(output.first.first);
1620 store_members.erase(store_it);
1621 continue;
1622 }
1623 store_it = store_members.begin();
1624 while (store_it != store_members.end()) {
1625 auto accesschain_it = accesschain_members.find(*store_it);
1626 if (accesschain_it == accesschain_members.end()) {
1627 ++store_it;
1628 continue;
1629 }
1630 if (accesschain_it->second == output.second.id) {
1631 location_list.insert(output.first.first);
1632 store_members.erase(store_it);
1633 accesschain_members.erase(accesschain_it);
1634 break;
1635 }
1636 ++store_it;
1637 }
1638 }
1639 return location_list;
1640}
1641
1642bool SHADER_MODULE_STATE::CollectInterfaceBlockMembers(std::map<location_t, interface_var> *out, bool is_array_of_verts,
ziga-lunarg9e94e112021-09-27 00:21:10 +02001643 uint32_t id, uint32_t type_id, bool is_patch,
1644 uint32_t /*first_location*/) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001645 // Walk down the type_id presented, trying to determine whether it's actually an interface block.
1646 auto type = GetStructType(get_def(type_id), is_array_of_verts && !is_patch);
1647 if (type == end() || !(get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
1648 // This isn't an interface block.
1649 return false;
1650 }
1651
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001652 layer_data::unordered_map<uint32_t, uint32_t> member_components;
1653 layer_data::unordered_map<uint32_t, uint32_t> member_relaxed_precision;
1654 layer_data::unordered_map<uint32_t, uint32_t> member_patch;
sfricke-samsung962cad92021-04-13 00:46:29 -07001655
1656 // Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001657 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001658 if (insn.word(1) == type.word(1)) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001659 uint32_t member_index = insn.word(2);
sfricke-samsung962cad92021-04-13 00:46:29 -07001660
1661 if (insn.word(3) == spv::DecorationComponent) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001662 uint32_t component = insn.word(4);
sfricke-samsung962cad92021-04-13 00:46:29 -07001663 member_components[member_index] = component;
1664 }
1665
1666 if (insn.word(3) == spv::DecorationRelaxedPrecision) {
1667 member_relaxed_precision[member_index] = 1;
1668 }
1669
1670 if (insn.word(3) == spv::DecorationPatch) {
1671 member_patch[member_index] = 1;
1672 }
1673 }
1674 }
1675
1676 // TODO: correctly handle location assignment from outside
1677
1678 // Second pass -- produce the output, from Location decorations
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001679 for (auto insn : static_data_.member_decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001680 if (insn.word(1) == type.word(1)) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001681 uint32_t member_index = insn.word(2);
1682 uint32_t member_type_id = type.word(2 + member_index);
sfricke-samsung962cad92021-04-13 00:46:29 -07001683
1684 if (insn.word(3) == spv::DecorationLocation) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001685 uint32_t location = insn.word(4);
1686 uint32_t num_locations = GetLocationsConsumedByType(member_type_id, false);
sfricke-samsung962cad92021-04-13 00:46:29 -07001687 auto component_it = member_components.find(member_index);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001688 uint32_t component = component_it == member_components.end() ? 0 : component_it->second;
sfricke-samsung962cad92021-04-13 00:46:29 -07001689 bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
1690 bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
1691
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001692 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001693 interface_var v = {};
1694 v.id = id;
1695 // TODO: member index in interface_var too?
1696 v.type_id = member_type_id;
1697 v.offset = offset;
1698 v.is_patch = member_is_patch;
1699 v.is_block_member = true;
1700 v.is_relaxed_precision = is_relaxed_precision;
1701 (*out)[std::make_pair(location + offset, component)] = v;
1702 }
1703 }
1704 }
1705 }
1706
1707 return true;
1708}
1709
1710std::map<location_t, interface_var> SHADER_MODULE_STATE::CollectInterfaceByLocation(spirv_inst_iter entrypoint,
1711 spv::StorageClass sinterface,
1712 bool is_array_of_verts) const {
1713 // TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
1714
1715 std::map<location_t, interface_var> out;
1716
1717 for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
1718 auto insn = get_def(iid);
1719 assert(insn != end());
1720 assert(insn.opcode() == spv::OpVariable);
1721
ziga-lunarg9e94e112021-09-27 00:21:10 +02001722 const auto d = get_decorations(iid);
1723 bool passthrough = sinterface == spv::StorageClassOutput && insn.word(3) == spv::StorageClassInput &&
1724 (d.flags & decoration_set::passthrough_bit) != 0;
1725 if (insn.word(3) == static_cast<uint32_t>(sinterface) || passthrough) {
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001726 uint32_t id = insn.word(2);
1727 uint32_t type = insn.word(1);
sfricke-samsung962cad92021-04-13 00:46:29 -07001728
ziga-lunarg9e94e112021-09-27 00:21:10 +02001729 auto location = d.location;
sfricke-samsung962cad92021-04-13 00:46:29 -07001730 int builtin = d.builtin;
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001731 uint32_t component = d.component;
sfricke-samsung962cad92021-04-13 00:46:29 -07001732 bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
1733 bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
ziga-lunarg9e94e112021-09-27 00:21:10 +02001734 bool is_per_vertex = (d.flags & decoration_set::per_vertex_bit) != 0;
sfricke-samsung962cad92021-04-13 00:46:29 -07001735
1736 if (builtin != -1) {
1737 continue;
ziga-lunarg9e94e112021-09-27 00:21:10 +02001738 } else if (!CollectInterfaceBlockMembers(&out, is_array_of_verts, id, type, is_patch, location) ||
1739 location != decoration_set::kInvalidValue) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001740 // A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
1741 // one result for each.
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001742 uint32_t num_locations = GetLocationsConsumedByType(type, (is_array_of_verts && !is_patch) || is_per_vertex);
1743 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001744 interface_var v = {};
1745 v.id = id;
1746 v.type_id = type;
1747 v.offset = offset;
1748 v.is_patch = is_patch;
1749 v.is_relaxed_precision = is_relaxed_precision;
1750 out[std::make_pair(location + offset, component)] = v;
1751 }
1752 }
1753 }
1754 }
1755
1756 return out;
1757}
1758
1759std::vector<uint32_t> SHADER_MODULE_STATE::CollectBuiltinBlockMembers(spirv_inst_iter entrypoint, uint32_t storageClass) const {
sfricke-samsung962cad92021-04-13 00:46:29 -07001760 // Find all interface variables belonging to the entrypoint and matching the storage class
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001761 std::vector<uint32_t> variables;
sfricke-samsung962cad92021-04-13 00:46:29 -07001762 for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
1763 auto def = get_def(id);
1764 assert(def != end());
1765 assert(def.opcode() == spv::OpVariable);
1766
1767 if (def.word(3) == storageClass) variables.push_back(def.word(1));
1768 }
1769
1770 // Find all members belonging to the builtin block selected
1771 std::vector<uint32_t> builtin_block_members;
1772 for (auto &var : variables) {
1773 auto def = get_def(get_def(var).word(3));
1774
1775 // It could be an array of IO blocks. The element type should be the struct defining the block contents
1776 if (def.opcode() == spv::OpTypeArray) def = get_def(def.word(2));
1777
1778 // Now find all members belonging to the struct defining the IO block
1779 if (def.opcode() == spv::OpTypeStruct) {
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001780 for (auto set : static_data_.builtin_decoration_list) {
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001781 auto insn = at(set.offset);
1782 if ((insn.opcode() == spv::OpMemberDecorate) && (def.word(1) == insn.word(1))) {
1783 // Start with undefined builtin for each struct member.
1784 // But only when confirmed the struct is the built-in inteface block (can only be one per shader)
1785 if (builtin_block_members.size() == 0) {
1786 builtin_block_members.resize(def.len() - 2, spv::BuiltInMax);
sfricke-samsung962cad92021-04-13 00:46:29 -07001787 }
sfricke-samsung0df5ee72021-07-24 23:27:16 -07001788 auto struct_index = insn.word(2);
1789 assert(struct_index < builtin_block_members.size());
1790 builtin_block_members[struct_index] = insn.word(4);
sfricke-samsung962cad92021-04-13 00:46:29 -07001791 }
1792 }
1793 }
1794 }
1795
1796 return builtin_block_members;
1797}
1798
1799std::vector<std::pair<uint32_t, interface_var>> SHADER_MODULE_STATE::CollectInterfaceByInputAttachmentIndex(
1800 layer_data::unordered_set<uint32_t> const &accessible_ids) const {
1801 std::vector<std::pair<uint32_t, interface_var>> out;
1802
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001803 for (auto insn : static_data_.decoration_inst) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001804 if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
1805 auto attachment_index = insn.word(3);
1806 auto id = insn.word(1);
1807
1808 if (accessible_ids.count(id)) {
1809 auto def = get_def(id);
1810 assert(def != end());
1811 if (def.opcode() == spv::OpVariable && def.word(3) == spv::StorageClassUniformConstant) {
1812 auto num_locations = GetLocationsConsumedByType(def.word(1), false);
sfricke-samsung7fac88a2022-01-26 11:44:22 -08001813 for (uint32_t offset = 0; offset < num_locations; offset++) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001814 interface_var v = {};
1815 v.id = id;
1816 v.type_id = def.word(1);
1817 v.offset = offset;
1818 out.emplace_back(attachment_index + offset, v);
1819 }
1820 }
1821 }
1822 }
1823 }
1824
1825 return out;
1826}
1827
ziga-lunarg8346fe82021-08-22 17:30:50 +02001828uint32_t SHADER_MODULE_STATE::GetNumComponentsInBaseType(const spirv_inst_iter &iter) const {
1829 const uint32_t opcode = iter.opcode();
1830 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt) {
1831 return 1;
1832 } else if (opcode == spv::OpTypeVector) {
1833 const uint32_t component_count = iter.word(3);
1834 return component_count;
1835 } else if (opcode == spv::OpTypeMatrix) {
1836 const auto column_type = get_def(iter.word(2));
1837 const uint32_t vector_length = GetNumComponentsInBaseType(column_type);
1838 const uint32_t column_count = iter.word(3);
1839 return vector_length * column_count;
1840 } else if (opcode == spv::OpTypeArray) {
1841 const auto element_type = get_def(iter.word(2));
1842 const uint32_t element_length = GetNumComponentsInBaseType(element_type);
1843 return element_length;
1844 } else if (opcode == spv::OpTypeStruct) {
1845 uint32_t total_size = 0;
1846 for (uint32_t i = 2; i < iter.len(); ++i) {
1847 total_size += GetNumComponentsInBaseType(get_def(iter.word(i)));
1848 }
1849 return total_size;
1850 } else if (opcode == spv::OpTypePointer) {
1851 const auto type = get_def(iter.word(3));
1852 return GetNumComponentsInBaseType(type);
1853 }
1854 return 0;
1855}
1856
ziga-lunarg2818f492021-08-12 14:30:51 +02001857std::array<uint32_t, 3> SHADER_MODULE_STATE::GetWorkgroupSize(
1858 VkPipelineShaderStageCreateInfo const *pStage, const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map) const {
1859 std::array<uint32_t, 3> work_group_size = {1, 1, 1};
1860
1861 uint32_t work_group_size_id = std::numeric_limits<uint32_t>::max();
1862
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001863 for (const auto &builtin : static_data_.builtin_decoration_list) {
ziga-lunarg2818f492021-08-12 14:30:51 +02001864 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1865 work_group_size_id = at(builtin.offset).word(1);
1866 break;
1867 }
1868 }
1869 for (auto insn : *this) {
1870 uint32_t opcode = insn.opcode();
1871 if (opcode == spv::OpSpecConstantComposite) { // WorkGroupSize must be a composite
1872 uint32_t result_id = insn.word(2);
1873 if (result_id == work_group_size_id) {
1874 uint32_t result_type_id = insn.word(1);
1875 auto result_type = get_def(result_type_id);
1876 if (result_type.opcode() == spv::OpTypeVector) {
1877 uint32_t component_count = result_type.word(3);
1878 for (uint32_t i = 0; i < component_count; ++i) {
1879 auto constituent = get_def(insn.word(3 + i));
Nathaniel Cesario77cd59b2021-10-11 23:52:24 -06001880 for (const auto &sc : static_data_.spec_const_map) {
ziga-lunarg2818f492021-08-12 14:30:51 +02001881 if (sc.second == constituent.word(2)) {
1882 const auto iter = id_value_map.find(sc.first);
1883 if (iter != id_value_map.cend()) {
1884 work_group_size[i] = *iter->second.begin();
1885 }
1886 break;
1887 }
1888 }
1889 }
1890 }
1891 }
1892 }
1893 }
1894
1895 return work_group_size;
1896}
1897
ziga-lunarga26b3602021-08-08 15:53:00 +02001898uint32_t SHADER_MODULE_STATE::GetTypeBitsSize(const spirv_inst_iter &iter) const {
1899 const uint32_t opcode = iter.opcode();
1900 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt) {
1901 return iter.word(2);
1902 } else if (opcode == spv::OpTypeVector) {
1903 const auto component_type = get_def(iter.word(2));
1904 uint32_t scalar_width = GetTypeBitsSize(component_type);
1905 uint32_t component_count = iter.word(3);
1906 return scalar_width * component_count;
1907 } else if (opcode == spv::OpTypeMatrix) {
1908 const auto column_type = get_def(iter.word(2));
1909 uint32_t vector_width = GetTypeBitsSize(column_type);
1910 uint32_t column_count = iter.word(3);
1911 return vector_width * column_count;
1912 } else if (opcode == spv::OpTypeArray) {
1913 const auto element_type = get_def(iter.word(2));
1914 uint32_t element_width = GetTypeBitsSize(element_type);
1915 const auto length_type = get_def(iter.word(3));
1916 uint32_t length = GetConstantValue(length_type);
1917 return element_width * length;
1918 } else if (opcode == spv::OpTypeStruct) {
1919 uint32_t total_size = 0;
1920 for (uint32_t i = 2; i < iter.len(); ++i) {
1921 total_size += GetTypeBitsSize(get_def(iter.word(i)));
1922 }
1923 return total_size;
ziga-lunarg8346fe82021-08-22 17:30:50 +02001924 } else if (opcode == spv::OpTypePointer) {
1925 const auto type = get_def(iter.word(3));
1926 return GetTypeBitsSize(type);
ziga-lunargef2c3172021-11-07 10:35:29 +01001927 } else if (opcode == spv::OpVariable) {
1928 const auto type = get_def(iter.word(1));
1929 return GetTypeBitsSize(type);
ziga-lunarga26b3602021-08-08 15:53:00 +02001930 }
1931 return 0;
1932}
1933
1934uint32_t SHADER_MODULE_STATE::GetTypeBytesSize(const spirv_inst_iter &iter) const { return GetTypeBitsSize(iter) / 8; }
1935
ziga-lunarg19fc6ae2021-09-09 00:05:19 +02001936// Returns the base type (float, int or unsigned int) or struct (can have multiple different base types inside)
ziga-lunarg8346fe82021-08-22 17:30:50 +02001937uint32_t SHADER_MODULE_STATE::GetBaseType(const spirv_inst_iter &iter) const {
1938 const uint32_t opcode = iter.opcode();
1939 if (opcode == spv::OpTypeFloat || opcode == spv::OpTypeInt || opcode == spv::OpTypeStruct) {
1940 return iter.word(1);
1941 } else if (opcode == spv::OpTypeVector) {
1942 const auto& component_type = get_def(iter.word(2));
1943 return GetBaseType(component_type);
1944 } else if (opcode == spv::OpTypeMatrix) {
1945 const auto& column_type = get_def(iter.word(2));
1946 return GetBaseType(column_type);
1947 } else if (opcode == spv::OpTypeArray) {
1948 const auto& element_type = get_def(iter.word(2));
1949 return GetBaseType(element_type);
1950 } else if (opcode == spv::OpTypePointer) {
1951 const auto& type = get_def(iter.word(3));
1952 return GetBaseType(type);
1953 }
1954 return 0;
1955}
1956
sfricke-samsunga6c1ddc2022-01-23 14:15:40 -08001957// Returns type_id if id has type or zero otherwise
1958uint32_t SHADER_MODULE_STATE::GetTypeId(uint32_t id) const {
1959 const auto type = get_def(id);
1960 return OpcodeHasType(type.opcode()) ? type.word(1) : 0;
1961}
1962
ziga-lunarga26b3602021-08-08 15:53:00 +02001963uint32_t SHADER_MODULE_STATE::CalcComputeSharedMemory(VkShaderStageFlagBits stage,
1964 const spirv_inst_iter &insn) const {
1965 if (stage == VK_SHADER_STAGE_COMPUTE_BIT && insn.opcode() == spv::OpVariable) {
1966 uint32_t storage_class = insn.word(3);
1967 if (storage_class == spv::StorageClassWorkgroup) { // StorageClass Workgroup is shared memory
1968 uint32_t result_type_id = insn.word(1);
1969 auto result_type = get_def(result_type_id);
1970 auto type = get_def(result_type.word(3));
1971 return GetTypeBytesSize(type);
1972 }
1973 }
1974
1975 return 0;
1976}
1977
sfricke-samsung962cad92021-04-13 00:46:29 -07001978// Assumes itr points to an OpConstant instruction
1979uint32_t GetConstantValue(const spirv_inst_iter &itr) { return itr.word(3); }
1980
1981std::vector<uint32_t> FindEntrypointInterfaces(const spirv_inst_iter &entrypoint) {
1982 assert(entrypoint.opcode() == spv::OpEntryPoint);
1983
1984 std::vector<uint32_t> interfaces;
1985 // Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
1986 // rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
1987 uint32_t word = 3;
1988 while (entrypoint.word(word) & 0xff000000u) {
1989 ++word;
1990 }
1991 ++word;
1992
1993 for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
1994
1995 return interfaces;
1996}