forked from KhronosGroup/Vulkan-ValidationLayers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshader_module.cpp
1809 lines (1645 loc) · 74.5 KB
/
shader_module.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2021 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Spencer Fricke <s.fricke@samsung.com>
*/
#include "shader_module.h"
#include <sstream>
#include <string>
#include "vk_layer_data.h"
#include "vk_layer_utils.h"
#include "pipeline_state.h"
#include "descriptor_sets.h"
void decoration_set::merge(decoration_set const &other) {
if (other.flags & location_bit) location = other.location;
if (other.flags & component_bit) component = other.component;
if (other.flags & input_attachment_index_bit) input_attachment_index = other.input_attachment_index;
if (other.flags & descriptor_set_bit) descriptor_set = other.descriptor_set;
if (other.flags & binding_bit) binding = other.binding;
if (other.flags & builtin_bit) builtin = other.builtin;
flags |= other.flags;
}
void decoration_set::add(uint32_t decoration, uint32_t value) {
switch (decoration) {
case spv::DecorationLocation:
flags |= location_bit;
location = value;
break;
case spv::DecorationPatch:
flags |= patch_bit;
break;
case spv::DecorationRelaxedPrecision:
flags |= relaxed_precision_bit;
break;
case spv::DecorationBlock:
flags |= block_bit;
break;
case spv::DecorationBufferBlock:
flags |= buffer_block_bit;
break;
case spv::DecorationComponent:
flags |= component_bit;
component = value;
break;
case spv::DecorationInputAttachmentIndex:
flags |= input_attachment_index_bit;
input_attachment_index = value;
break;
case spv::DecorationDescriptorSet:
flags |= descriptor_set_bit;
descriptor_set = value;
break;
case spv::DecorationBinding:
flags |= binding_bit;
binding = value;
break;
case spv::DecorationNonWritable:
flags |= nonwritable_bit;
break;
case spv::DecorationBuiltIn:
flags |= builtin_bit;
builtin = value;
break;
case spv::DecorationNonReadable:
flags |= nonreadable_bit;
break;
}
}
std::string shader_struct_member::GetLocationDesc(uint32_t index_used_bytes) const {
std::string desc = "";
if (array_length_hierarchy.size() > 0) {
desc += " index:";
for (const auto block_size : array_block_size) {
desc += "[";
desc += std::to_string(index_used_bytes / (block_size * size));
desc += "]";
index_used_bytes = index_used_bytes % (block_size * size);
}
}
const int struct_members_size = static_cast<int>(struct_members.size());
if (struct_members_size > 0) {
desc += " member:";
for (int i = struct_members_size - 1; i >= 0; --i) {
if (index_used_bytes > struct_members[i].offset) {
desc += std::to_string(i);
desc += struct_members[i].GetLocationDesc(index_used_bytes - struct_members[i].offset);
break;
}
}
} else {
desc += " offset:";
desc += std::to_string(index_used_bytes);
}
return desc;
}
static unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
switch (mode) {
case spv::ExecutionModelVertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case spv::ExecutionModelTessellationControl:
return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
case spv::ExecutionModelTessellationEvaluation:
return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
case spv::ExecutionModelGeometry:
return VK_SHADER_STAGE_GEOMETRY_BIT;
case spv::ExecutionModelFragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case spv::ExecutionModelGLCompute:
return VK_SHADER_STAGE_COMPUTE_BIT;
case spv::ExecutionModelRayGenerationNV:
return VK_SHADER_STAGE_RAYGEN_BIT_NV;
case spv::ExecutionModelAnyHitNV:
return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
case spv::ExecutionModelClosestHitNV:
return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
case spv::ExecutionModelMissNV:
return VK_SHADER_STAGE_MISS_BIT_NV;
case spv::ExecutionModelIntersectionNV:
return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
case spv::ExecutionModelCallableNV:
return VK_SHADER_STAGE_CALLABLE_BIT_NV;
case spv::ExecutionModelTaskNV:
return VK_SHADER_STAGE_TASK_BIT_NV;
case spv::ExecutionModelMeshNV:
return VK_SHADER_STAGE_MESH_BIT_NV;
default:
return 0;
}
}
// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
// important for identifying the set of shader resources actually used by an entrypoint, for example.
// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
// - NOT the shader input/output interfaces.
//
// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
// converting parts of this to be generated from the machine-readable spec instead.
layer_data::unordered_set<uint32_t> SHADER_MODULE_STATE::MarkAccessibleIds(spirv_inst_iter entrypoint) const {
layer_data::unordered_set<uint32_t> ids;
layer_data::unordered_set<uint32_t> worklist;
worklist.insert(entrypoint.word(2));
while (!worklist.empty()) {
auto id_iter = worklist.begin();
auto id = *id_iter;
worklist.erase(id_iter);
auto insn = get_def(id);
if (insn == end()) {
// ID is something we didn't collect in BuildDefIndex. that's OK -- we'll stumble across all kinds of things here
// that we may not care about.
continue;
}
// Try to add to the output set
if (!ids.insert(id).second) {
continue; // If we already saw this id, we don't want to walk it again.
}
switch (insn.opcode()) {
case spv::OpFunction:
// Scan whole body of the function, enlisting anything interesting
while (++insn, insn.opcode() != spv::OpFunctionEnd) {
switch (insn.opcode()) {
case spv::OpLoad:
worklist.insert(insn.word(3)); // ptr
break;
case spv::OpStore:
worklist.insert(insn.word(1)); // ptr
break;
case spv::OpAccessChain:
case spv::OpInBoundsAccessChain:
worklist.insert(insn.word(3)); // base ptr
break;
case spv::OpSampledImage:
case spv::OpImageSampleImplicitLod:
case spv::OpImageSampleExplicitLod:
case spv::OpImageSampleDrefImplicitLod:
case spv::OpImageSampleDrefExplicitLod:
case spv::OpImageSampleProjImplicitLod:
case spv::OpImageSampleProjExplicitLod:
case spv::OpImageSampleProjDrefImplicitLod:
case spv::OpImageSampleProjDrefExplicitLod:
case spv::OpImageFetch:
case spv::OpImageGather:
case spv::OpImageDrefGather:
case spv::OpImageRead:
case spv::OpImage:
case spv::OpImageQueryFormat:
case spv::OpImageQueryOrder:
case spv::OpImageQuerySizeLod:
case spv::OpImageQuerySize:
case spv::OpImageQueryLod:
case spv::OpImageQueryLevels:
case spv::OpImageQuerySamples:
case spv::OpImageSparseSampleImplicitLod:
case spv::OpImageSparseSampleExplicitLod:
case spv::OpImageSparseSampleDrefImplicitLod:
case spv::OpImageSparseSampleDrefExplicitLod:
case spv::OpImageSparseSampleProjImplicitLod:
case spv::OpImageSparseSampleProjExplicitLod:
case spv::OpImageSparseSampleProjDrefImplicitLod:
case spv::OpImageSparseSampleProjDrefExplicitLod:
case spv::OpImageSparseFetch:
case spv::OpImageSparseGather:
case spv::OpImageSparseDrefGather:
case spv::OpImageTexelPointer:
worklist.insert(insn.word(3)); // Image or sampled image
break;
case spv::OpImageWrite:
worklist.insert(insn.word(1)); // Image -- different operand order to above
break;
case spv::OpFunctionCall:
for (uint32_t i = 3; i < insn.len(); i++) {
worklist.insert(insn.word(i)); // fn itself, and all args
}
break;
case spv::OpExtInst:
for (uint32_t i = 5; i < insn.len(); i++) {
worklist.insert(insn.word(i)); // Operands to ext inst
}
break;
default: {
if (AtomicOperation(insn.opcode())) {
if (insn.opcode() == spv::OpAtomicStore) {
worklist.insert(insn.word(1)); // ptr
} else {
worklist.insert(insn.word(3)); // ptr
}
}
break;
}
}
}
break;
}
}
return ids;
}
void SHADER_MODULE_STATE::ProcessExecutionModes(const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) const {
auto entrypoint_id = entrypoint.word(2);
bool is_point_mode = false;
auto it = execution_mode_inst.find(entrypoint_id);
if (it != execution_mode_inst.end()) {
for (auto insn : it->second) {
switch (insn.word(2)) {
case spv::ExecutionModePointMode:
// In tessellation shaders, PointMode is separate and trumps the tessellation topology.
is_point_mode = true;
break;
case spv::ExecutionModeOutputPoints:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
break;
case spv::ExecutionModeIsolines:
case spv::ExecutionModeOutputLineStrip:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
break;
case spv::ExecutionModeTriangles:
case spv::ExecutionModeQuads:
case spv::ExecutionModeOutputTriangleStrip:
case spv::ExecutionModeOutputTrianglesNV:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
break;
}
}
}
if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
}
void SHADER_MODULE_STATE::BuildDefIndex() {
function_set func_set = {};
EntryPoint *entry_point = nullptr;
for (auto insn : *this) {
// offset is not 0, it means it's updated and the offset is in a Function.
if (func_set.offset) {
func_set.op_lists.emplace(insn.opcode(), insn.offset());
} else if (entry_point) {
entry_point->decorate_list.emplace(insn.opcode(), insn.offset());
}
switch (insn.opcode()) {
// Types
case spv::OpTypeVoid:
case spv::OpTypeBool:
case spv::OpTypeInt:
case spv::OpTypeFloat:
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeImage:
case spv::OpTypeSampler:
case spv::OpTypeSampledImage:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeStruct:
case spv::OpTypeOpaque:
case spv::OpTypePointer:
case spv::OpTypeFunction:
case spv::OpTypeEvent:
case spv::OpTypeDeviceEvent:
case spv::OpTypeReserveId:
case spv::OpTypeQueue:
case spv::OpTypePipe:
case spv::OpTypeAccelerationStructureNV:
case spv::OpTypeCooperativeMatrixNV:
def_index[insn.word(1)] = insn.offset();
break;
// Fixed constants
case spv::OpConstantTrue:
case spv::OpConstantFalse:
case spv::OpConstant:
case spv::OpConstantComposite:
case spv::OpConstantSampler:
case spv::OpConstantNull:
def_index[insn.word(2)] = insn.offset();
break;
// Specialization constants
case spv::OpSpecConstantTrue:
case spv::OpSpecConstantFalse:
case spv::OpSpecConstant:
case spv::OpSpecConstantComposite:
case spv::OpSpecConstantOp:
def_index[insn.word(2)] = insn.offset();
break;
// Variables
case spv::OpVariable:
def_index[insn.word(2)] = insn.offset();
break;
// Functions
case spv::OpFunction:
def_index[insn.word(2)] = insn.offset();
func_set.id = insn.word(2);
func_set.offset = insn.offset();
func_set.op_lists.clear();
break;
// Decorations
case spv::OpDecorate: {
auto target_id = insn.word(1);
decorations[target_id].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
decoration_inst.push_back(insn);
if (insn.word(2) == spv::DecorationBuiltIn) {
builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(3)));
} else if (insn.word(2) == spv::DecorationSpecId) {
spec_const_map[insn.word(3)] = target_id;
}
} break;
case spv::OpGroupDecorate: {
auto const &src = decorations[insn.word(1)];
for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
} break;
case spv::OpMemberDecorate: {
member_decoration_inst.push_back(insn);
if (insn.word(3) == spv::DecorationBuiltIn) {
builtin_decoration_list.emplace_back(insn.offset(), static_cast<spv::BuiltIn>(insn.word(4)));
}
} break;
// Entry points ... add to the entrypoint table
case spv::OpEntryPoint: {
if (entry_point != nullptr) {
multiple_entry_points = true;
}
// Entry points do not have an id (the id is the function id) and thus need their own table
auto entrypoint_name = reinterpret_cast<char const *>(&insn.word(3));
auto execution_model = insn.word(1);
auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
entry_points.emplace(entrypoint_name,
EntryPoint{insn.offset(), static_cast<VkShaderStageFlagBits>(entrypoint_stage)});
auto range = entry_points.equal_range(entrypoint_name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.offset == insn.offset()) {
entry_point = &(it->second);
break;
}
}
assert(entry_point != nullptr);
break;
}
case spv::OpFunctionEnd: {
assert(entry_point != nullptr);
func_set.length = insn.offset() - func_set.offset;
entry_point->function_set_list.emplace_back(func_set);
break;
}
// Copy operations
case spv::OpCopyLogical:
case spv::OpCopyObject: {
def_index[insn.word(2)] = insn.offset();
break;
}
// Execution Mode
case spv::OpExecutionMode: {
execution_mode_inst[insn.word(1)].push_back(insn);
} break;
case spv::OpLoad: {
def_index[insn.word(2)] = insn.offset();
} break;
default:
// We don't care about any other defs for now.
break;
}
}
}
std::vector<uint32_t> SHADER_MODULE_STATE::PreprocessShaderBinary(uint32_t *src_binary, size_t binary_size, spv_target_env env) {
std::vector<uint32_t> src(src_binary, src_binary + binary_size / sizeof(uint32_t));
// Check if there are any group decoration instructions, and flatten them if found.
bool has_group_decoration = false;
bool done = false;
// Walk through the first part of the SPIR-V module, looking for group decoration and specialization constant instructions.
// Skip the header (5 words).
auto itr = spirv_inst_iter(src.begin(), src.begin() + 5);
auto itrend = spirv_inst_iter(src.begin(), src.end());
while (itr != itrend && !done) {
spv::Op opcode = (spv::Op)itr.opcode();
switch (opcode) {
case spv::OpDecorationGroup:
case spv::OpGroupDecorate:
case spv::OpGroupMemberDecorate:
has_group_decoration = true;
break;
case spv::OpSpecConstantTrue:
case spv::OpSpecConstantFalse:
case spv::OpSpecConstant:
case spv::OpSpecConstantComposite:
case spv::OpSpecConstantOp:
has_specialization_constants = true;
break;
case spv::OpFunction:
// An OpFunction indicates there are no more decorations
done = true;
break;
default:
break;
}
itr++;
}
if (has_group_decoration) {
spvtools::Optimizer optimizer(env);
optimizer.RegisterPass(spvtools::CreateFlattenDecorationPass());
std::vector<uint32_t> optimized_binary;
// Run optimizer to flatten decorations only, set skip_validation so as to not re-run validator
auto result =
optimizer.Run(src_binary, binary_size / sizeof(uint32_t), &optimized_binary, spvtools::ValidatorOptions(), true);
if (result) {
return optimized_binary;
}
}
// Return the original module.
return src;
}
static char const *StorageClassName(unsigned sc) {
switch (sc) {
case spv::StorageClassInput:
return "input";
case spv::StorageClassOutput:
return "output";
case spv::StorageClassUniformConstant:
return "const uniform";
case spv::StorageClassUniform:
return "uniform";
case spv::StorageClassWorkgroup:
return "workgroup local";
case spv::StorageClassCrossWorkgroup:
return "workgroup global";
case spv::StorageClassPrivate:
return "private global";
case spv::StorageClassFunction:
return "function";
case spv::StorageClassGeneric:
return "generic";
case spv::StorageClassAtomicCounter:
return "atomic counter";
case spv::StorageClassImage:
return "image";
case spv::StorageClassPushConstant:
return "push constant";
case spv::StorageClassStorageBuffer:
return "storage buffer";
default:
return "unknown";
}
}
void SHADER_MODULE_STATE::DescribeTypeInner(std::ostringstream &ss, unsigned type) const {
auto insn = get_def(type);
assert(insn != end());
switch (insn.opcode()) {
case spv::OpTypeBool:
ss << "bool";
break;
case spv::OpTypeInt:
ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
break;
case spv::OpTypeFloat:
ss << "float" << insn.word(2);
break;
case spv::OpTypeVector:
ss << "vec" << insn.word(3) << " of ";
DescribeTypeInner(ss, insn.word(2));
break;
case spv::OpTypeMatrix:
ss << "mat" << insn.word(3) << " of ";
DescribeTypeInner(ss, insn.word(2));
break;
case spv::OpTypeArray:
ss << "arr[" << GetConstantValueById(insn.word(3)) << "] of ";
DescribeTypeInner(ss, insn.word(2));
break;
case spv::OpTypeRuntimeArray:
ss << "runtime arr[] of ";
DescribeTypeInner(ss, insn.word(2));
break;
case spv::OpTypePointer:
ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
DescribeTypeInner(ss, insn.word(3));
break;
case spv::OpTypeStruct: {
ss << "struct of (";
for (unsigned i = 2; i < insn.len(); i++) {
DescribeTypeInner(ss, insn.word(i));
if (i == insn.len() - 1) {
ss << ")";
} else {
ss << ", ";
}
}
break;
}
case spv::OpTypeSampler:
ss << "sampler";
break;
case spv::OpTypeSampledImage:
ss << "sampler+";
DescribeTypeInner(ss, insn.word(2));
break;
case spv::OpTypeImage:
ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
break;
case spv::OpTypeAccelerationStructureNV:
ss << "accelerationStruture";
break;
default:
ss << "oddtype";
break;
}
}
std::string SHADER_MODULE_STATE::DescribeType(unsigned type) const {
std::ostringstream ss;
DescribeTypeInner(ss, type);
return ss.str();
}
const SHADER_MODULE_STATE::EntryPoint *SHADER_MODULE_STATE::FindEntrypointStruct(char const *name,
VkShaderStageFlagBits stageBits) const {
auto range = entry_points.equal_range(name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.stage == stageBits) {
return &(it->second);
}
}
return nullptr;
}
spirv_inst_iter SHADER_MODULE_STATE::FindEntrypoint(char const *name, VkShaderStageFlagBits stageBits) const {
auto range = entry_points.equal_range(name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.stage == stageBits) {
return at(it->second.offset);
}
}
return end();
}
// Because the following is legal, need the entry point
// OpEntryPoint GLCompute %main "name_a"
// OpEntryPoint GLCompute %main "name_b"
bool SHADER_MODULE_STATE::FindLocalSize(const spirv_inst_iter &entrypoint, uint32_t &local_size_x, uint32_t &local_size_y,
uint32_t &local_size_z) const {
auto entrypoint_id = entrypoint.word(2);
auto it = execution_mode_inst.find(entrypoint_id);
if (it != execution_mode_inst.end()) {
for (auto insn : it->second) {
// Future Note: For now, Vulkan doesn't have a valid mode that can makes use of OpExecutionModeId
// In the future if something like LocalSizeId is supported, the <id> will need to be checked also
assert(insn.opcode() == spv::OpExecutionMode);
if (insn.word(2) == spv::ExecutionModeLocalSize) {
local_size_x = insn.word(3);
local_size_y = insn.word(4);
local_size_z = insn.word(5);
return true;
}
}
}
return false;
}
// If the instruction at id is a constant or copy of a constant, returns a valid iterator pointing to that instruction.
// Otherwise, returns src->end().
spirv_inst_iter SHADER_MODULE_STATE::GetConstantDef(unsigned id) const {
auto value = get_def(id);
// If id is a copy, see where it was copied from
if ((end() != value) && ((value.opcode() == spv::OpCopyObject) || (value.opcode() == spv::OpCopyLogical))) {
id = value.word(3);
value = get_def(id);
}
if ((end() != value) && (value.opcode() == spv::OpConstant)) {
return value;
}
return end();
}
// Either returns the constant value described by the instruction at id, or 1
uint32_t SHADER_MODULE_STATE::GetConstantValueById(unsigned id) const {
auto value = GetConstantDef(id);
if (end() == value) {
// TODO: Either ensure that the specialization transform is already performed on a module we're
// considering here, OR -- specialize on the fly now.
return 1;
}
return GetConstantValue(value);
}
// Returns an int32_t corresponding to the spv::Dim of the given resource, when positive, and corresponding to an unknown type, when
// negative.
int32_t SHADER_MODULE_STATE::GetShaderResourceDimensionality(const interface_var &resource) const {
auto type = get_def(resource.type_id);
while (true) {
switch (type.opcode()) {
case spv::OpTypeSampledImage:
type = get_def(type.word(2));
break;
case spv::OpTypePointer:
type = get_def(type.word(3));
break;
case spv::OpTypeImage:
return type.word(3);
default:
return -1;
}
}
}
unsigned SHADER_MODULE_STATE::GetLocationsConsumedByType(unsigned type, bool strip_array_level) const {
auto insn = get_def(type);
assert(insn != end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetLocationsConsumedByType(insn.word(3), strip_array_level);
case spv::OpTypeArray:
if (strip_array_level) {
return GetLocationsConsumedByType(insn.word(2), false);
} else {
return GetConstantValueById(insn.word(3)) * GetLocationsConsumedByType(insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetLocationsConsumedByType(insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
return (bit_width * insn.word(3) + 127) / 128;
}
default:
// Everything else is just 1.
return 1;
// TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
}
}
unsigned SHADER_MODULE_STATE::GetComponentsConsumedByType(unsigned type, bool strip_array_level) const {
auto insn = get_def(type);
assert(insn != end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetComponentsConsumedByType(insn.word(3), strip_array_level);
case spv::OpTypeStruct: {
uint32_t sum = 0;
for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
sum += GetComponentsConsumedByType(insn.word(i), false);
}
return sum;
}
case spv::OpTypeArray:
if (strip_array_level) {
return GetComponentsConsumedByType(insn.word(2), false);
} else {
return GetConstantValueById(insn.word(3)) * GetComponentsConsumedByType(insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetComponentsConsumedByType(insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// One component is 32-bit
return (bit_width * insn.word(3) + 31) / 32;
}
case spv::OpTypeFloat: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpTypeInt: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpConstant:
return GetComponentsConsumedByType(insn.word(1), false);
default:
return 0;
}
}
// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
// also used for input attachments, as we statically know their format.
unsigned SHADER_MODULE_STATE::GetFundamentalType(unsigned type) const {
auto insn = get_def(type);
assert(insn != end());
switch (insn.opcode()) {
case spv::OpTypeInt:
return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
case spv::OpTypeFloat:
return FORMAT_TYPE_FLOAT;
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeImage:
return GetFundamentalType(insn.word(2));
case spv::OpTypePointer:
return GetFundamentalType(insn.word(3));
default:
return 0;
}
}
spirv_inst_iter SHADER_MODULE_STATE::GetStructType(spirv_inst_iter def, bool is_array_of_verts) const {
while (true) {
if (def.opcode() == spv::OpTypePointer) {
def = get_def(def.word(3));
} else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
def = get_def(def.word(2));
is_array_of_verts = false;
} else if (def.opcode() == spv::OpTypeStruct) {
return def;
} else {
return end();
}
}
}
void SHADER_MODULE_STATE::DefineStructMember(const spirv_inst_iter &it, const std::vector<uint32_t> &memberDecorate_offsets,
shader_struct_member &data) const {
const auto struct_it = GetStructType(it, false);
assert(struct_it != end());
data.size = 0;
shader_struct_member data1;
uint32_t i = 2;
uint32_t local_offset = 0;
std::vector<uint32_t> offsets;
offsets.resize(struct_it.len() - i);
// The members of struct in SPRIV_R aren't always sort, so we need to know their order.
for (const auto offset : memberDecorate_offsets) {
const auto member_decorate = at(offset);
if (member_decorate.word(1) != struct_it.word(1)) {
continue;
}
offsets[member_decorate.word(2)] = member_decorate.word(4);
}
for (const auto offset : offsets) {
local_offset = offset;
data1 = {};
data1.root = data.root;
data1.offset = local_offset;
auto def_member = get_def(struct_it.word(i));
// Array could be multi-dimensional
while (def_member.opcode() == spv::OpTypeArray) {
const auto len_id = def_member.word(3);
const auto def_len = get_def(len_id);
data1.array_length_hierarchy.emplace_back(def_len.word(3)); // array length
def_member = get_def(def_member.word(2));
}
if (def_member.opcode() == spv::OpTypeStruct) {
DefineStructMember(def_member, memberDecorate_offsets, data1);
} else if (def_member.opcode() == spv::OpTypePointer) {
if (def_member.word(2) == spv::StorageClassPhysicalStorageBuffer) {
// If it's a pointer with PhysicalStorageBuffer class, this member is essentially a uint64_t containing an address
// that "points to something."
data1.size = 8;
} else {
// If it's OpTypePointer. it means the member is a buffer, the type will be TypePointer, and then struct
DefineStructMember(def_member, memberDecorate_offsets, data1);
}
} else {
if (def_member.opcode() == spv::OpTypeMatrix) {
data1.array_length_hierarchy.emplace_back(def_member.word(3)); // matrix's columns. matrix's row is vector.
def_member = get_def(def_member.word(2));
}
if (def_member.opcode() == spv::OpTypeVector) {
data1.array_length_hierarchy.emplace_back(def_member.word(3)); // vector length
def_member = get_def(def_member.word(2));
}
// Get scalar type size. The value in SPRV-R is bit. It needs to translate to byte.
data1.size = (def_member.word(2) / 8);
}
const auto array_length_hierarchy_szie = data1.array_length_hierarchy.size();
if (array_length_hierarchy_szie > 0) {
data1.array_block_size.resize(array_length_hierarchy_szie, 1);
for (int i2 = static_cast<int>(array_length_hierarchy_szie - 1); i2 > 0; --i2) {
data1.array_block_size[i2 - 1] = data1.array_length_hierarchy[i2] * data1.array_block_size[i2];
}
}
data.struct_members.emplace_back(data1);
++i;
}
uint32_t total_array_length = 1;
for (const auto length : data1.array_length_hierarchy) {
total_array_length *= length;
}
data.size = local_offset + data1.size * total_array_length;
}
static uint32_t UpdateOffset(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
int array_indices_size = static_cast<int>(array_indices.size());
if (array_indices_size) {
uint32_t array_index = 0;
uint32_t i = 0;
for (const auto index : array_indices) {
array_index += (data.array_block_size[i] * index);
++i;
}
offset += (array_index * data.size);
}
return offset;
}
static void SetUsedBytes(uint32_t offset, const std::vector<uint32_t> &array_indices, const shader_struct_member &data) {
int array_indices_size = static_cast<int>(array_indices.size());
uint32_t block_memory_size = data.size;
for (uint32_t i = static_cast<int>(array_indices_size); i < data.array_length_hierarchy.size(); ++i) {
block_memory_size *= data.array_length_hierarchy[i];
}
offset = UpdateOffset(offset, array_indices, data);
uint32_t end = offset + block_memory_size;
auto used_bytes = data.GetUsedbytes();
if (used_bytes->size() < end) {
used_bytes->resize(end, 0);
}
std::memset(used_bytes->data() + offset, true, static_cast<std::size_t>(block_memory_size));
}
void SHADER_MODULE_STATE::RunUsedArray(uint32_t offset, std::vector<uint32_t> array_indices, uint32_t access_chain_word_index,
spirv_inst_iter &access_chain_it, const shader_struct_member &data) const {
if (access_chain_word_index < access_chain_it.len()) {
if (data.array_length_hierarchy.size() > array_indices.size()) {
auto def_it = get_def(access_chain_it.word(access_chain_word_index));
++access_chain_word_index;
if (def_it != end() && def_it.opcode() == spv::OpConstant) {
array_indices.emplace_back(def_it.word(3));
RunUsedArray(offset, array_indices, access_chain_word_index, access_chain_it, data);
} else {
// If it is a variable, set the all array is used.
if (access_chain_word_index < access_chain_it.len()) {
uint32_t array_length = data.array_length_hierarchy[array_indices.size()];
for (uint32_t i = 0; i < array_length; ++i) {
auto array_indices2 = array_indices;
array_indices2.emplace_back(i);
RunUsedArray(offset, array_indices2, access_chain_word_index, access_chain_it, data);
}
} else {
SetUsedBytes(offset, array_indices, data);
}
}
} else {
offset = UpdateOffset(offset, array_indices, data);
RunUsedStruct(offset, access_chain_word_index, access_chain_it, data);
}
} else {
SetUsedBytes(offset, array_indices, data);
}
}
void SHADER_MODULE_STATE::RunUsedStruct(uint32_t offset, uint32_t access_chain_word_index, spirv_inst_iter &access_chain_it,
const shader_struct_member &data) const {
std::vector<uint32_t> array_indices_emptry;
if (access_chain_word_index < access_chain_it.len()) {
auto strcut_member_index = GetConstantValueById(access_chain_it.word(access_chain_word_index));
++access_chain_word_index;
auto data1 = data.struct_members[strcut_member_index];
RunUsedArray(offset + data1.offset, array_indices_emptry, access_chain_word_index, access_chain_it, data1);
}
}
void SHADER_MODULE_STATE::SetUsedStructMember(const uint32_t variable_id, const std::vector<function_set> &function_set_list,
const shader_struct_member &data) const {
for (const auto &func_set : function_set_list) {
auto range = func_set.op_lists.equal_range(spv::OpAccessChain);
for (auto it = range.first; it != range.second; ++it) {
auto access_chain = at(it->second);
if (access_chain.word(3) == variable_id) {
RunUsedStruct(0, 4, access_chain, data);
}
}
}
}
void SHADER_MODULE_STATE::SetPushConstantUsedInShader() {
for (auto &entrypoint : entry_points) {
auto range = entrypoint.second.decorate_list.equal_range(spv::OpVariable);
for (auto it = range.first; it != range.second; ++it) {
const auto def_insn = at(it->second);
if (def_insn.word(3) == spv::StorageClassPushConstant) {
spirv_inst_iter type = get_def(def_insn.word(1));
const auto range2 = entrypoint.second.decorate_list.equal_range(spv::OpMemberDecorate);
std::vector<uint32_t> offsets;
for (auto it2 = range2.first; it2 != range2.second; ++it2) {
auto member_decorate = at(it2->second);
if (member_decorate.len() == 5 && member_decorate.word(3) == spv::DecorationOffset) {
offsets.emplace_back(member_decorate.offset());
}
}
entrypoint.second.push_constant_used_in_shader.root = &entrypoint.second.push_constant_used_in_shader;
DefineStructMember(type, offsets, entrypoint.second.push_constant_used_in_shader);
SetUsedStructMember(def_insn.word(2), entrypoint.second.function_set_list,