-
Notifications
You must be signed in to change notification settings - Fork 669
Expand file tree
/
Copy pathvalidate_memory.cpp
More file actions
3589 lines (3292 loc) · 148 KB
/
validate_memory.cpp
File metadata and controls
3589 lines (3292 loc) · 148 KB
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) 2018 Google LLC.
// Modifications Copyright (C) 2020-2024 Advanced Micro Devices, Inc. All
// rights reserved.
//
// 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.
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include "source/opcode.h"
#include "source/spirv_target_env.h"
#include "source/table2.h"
#include "source/val/instruction.h"
#include "source/val/validate.h"
#include "source/val/validate_scopes.h"
#include "source/val/validation_state.h"
namespace spvtools {
namespace val {
namespace {
bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
const Instruction*);
bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
const Instruction*);
bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
const Instruction*);
bool HasConflictingMemberOffsets(const std::set<Decoration>&,
const std::set<Decoration>&);
bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction& type,
std::initializer_list<spv::Op> allowed) {
if (std::find(allowed.begin(), allowed.end(), type.opcode()) !=
allowed.end()) {
return true;
}
if (type.opcode() == spv::Op::OpTypeArray ||
type.opcode() == spv::Op::OpTypeRuntimeArray) {
auto elem_type = _.FindDef(type.word(2));
return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
allowed.end();
}
return false;
}
// Returns true if the two instructions represent structs that, as far as the
// validator can tell, have the exact same data layout.
bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
const Instruction* type2) {
if (type1->opcode() != spv::Op::OpTypeStruct) {
return false;
}
if (type2->opcode() != spv::Op::OpTypeStruct) {
return false;
}
if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
return HaveSameLayoutDecorations(_, type1, type2);
}
// Returns true if the operands to the OpTypeStruct instruction defining the
// types are the same or are layout compatible types. |type1| and |type2| must
// be OpTypeStruct instructions.
bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
const Instruction* type2) {
assert(type1->opcode() == spv::Op::OpTypeStruct &&
"type1 must be an OpTypeStruct instruction.");
assert(type2->opcode() == spv::Op::OpTypeStruct &&
"type2 must be an OpTypeStruct instruction.");
const auto& type1_operands = type1->operands();
const auto& type2_operands = type2->operands();
if (type1_operands.size() != type2_operands.size()) {
return false;
}
for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
if (type1->word(operand) != type2->word(operand)) {
auto def1 = _.FindDef(type1->word(operand));
auto def2 = _.FindDef(type2->word(operand));
if (!AreLayoutCompatibleStructs(_, def1, def2)) {
return false;
}
}
}
return true;
}
// Returns true if all decorations that affect the data layout of the struct
// (like Offset), are the same for the two types. |type1| and |type2| must be
// OpTypeStruct instructions.
bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
const Instruction* type2) {
assert(type1->opcode() == spv::Op::OpTypeStruct &&
"type1 must be an OpTypeStruct instruction.");
assert(type2->opcode() == spv::Op::OpTypeStruct &&
"type2 must be an OpTypeStruct instruction.");
const std::set<Decoration>& type1_decorations = _.id_decorations(type1->id());
const std::set<Decoration>& type2_decorations = _.id_decorations(type2->id());
// TODO: Will have to add other check for arrays an matricies if we want to
// handle them.
if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
return false;
}
return true;
}
bool HasConflictingMemberOffsets(
const std::set<Decoration>& type1_decorations,
const std::set<Decoration>& type2_decorations) {
{
// We are interested in conflicting decoration. If a decoration is in one
// list but not the other, then we will assume the code is correct. We are
// looking for things we know to be wrong.
//
// We do not have to traverse type2_decoration because, after traversing
// type1_decorations, anything new will not be found in
// type1_decoration. Therefore, it cannot lead to a conflict.
for (const Decoration& decoration : type1_decorations) {
switch (decoration.dec_type()) {
case spv::Decoration::Offset: {
// Since these affect the layout of the struct, they must be present
// in both structs.
auto compare = [&decoration](const Decoration& rhs) {
if (rhs.dec_type() != spv::Decoration::Offset) return false;
return decoration.struct_member_index() ==
rhs.struct_member_index();
};
auto i = std::find_if(type2_decorations.begin(),
type2_decorations.end(), compare);
if (i != type2_decorations.end() &&
decoration.params().front() != i->params().front()) {
return true;
}
} break;
default:
// This decoration does not affect the layout of the structure, so
// just moving on.
break;
}
}
}
return false;
}
// If |skip_builtin| is true, returns true if |storage| contains bool within
// it and no storage that contains the bool is builtin.
// If |skip_builtin| is false, returns true if |storage| contains bool within
// it.
bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
bool skip_builtin) {
if (skip_builtin) {
for (const Decoration& decoration : _.id_decorations(storage->id())) {
if (decoration.dec_type() == spv::Decoration::BuiltIn) return false;
}
}
const size_t elem_type_index = 1;
uint32_t elem_type_id;
Instruction* elem_type;
switch (storage->opcode()) {
case spv::Op::OpTypeBool:
return true;
case spv::Op::OpTypeVector:
case spv::Op::OpTypeMatrix:
case spv::Op::OpTypeArray:
case spv::Op::OpTypeRuntimeArray:
elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
elem_type = _.FindDef(elem_type_id);
return ContainsInvalidBool(_, elem_type, skip_builtin);
case spv::Op::OpTypeStruct:
for (size_t member_type_index = 1;
member_type_index < storage->operands().size();
++member_type_index) {
auto member_type_id =
storage->GetOperandAs<uint32_t>(member_type_index);
auto member_type = _.FindDef(member_type_id);
if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
}
default:
break;
}
return false;
}
std::pair<Instruction*, Instruction*> GetPointerTypes(ValidationState_t& _,
const Instruction* inst) {
Instruction* dst_pointer_type = nullptr;
Instruction* src_pointer_type = nullptr;
switch (inst->opcode()) {
case spv::Op::OpCooperativeMatrixLoadNV:
case spv::Op::OpCooperativeMatrixLoadTensorNV:
case spv::Op::OpCooperativeMatrixLoadKHR:
case spv::Op::OpCooperativeVectorLoadNV:
case spv::Op::OpLoad: {
auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
dst_pointer_type = _.FindDef(load_pointer->type_id());
break;
}
case spv::Op::OpCooperativeMatrixStoreNV:
case spv::Op::OpCooperativeMatrixStoreTensorNV:
case spv::Op::OpCooperativeMatrixStoreKHR:
case spv::Op::OpCooperativeVectorStoreNV:
case spv::Op::OpStore: {
auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
dst_pointer_type = _.FindDef(store_pointer->type_id());
break;
}
// Spec: "Matching Storage Class is not required"
case spv::Op::OpCopyMemory:
case spv::Op::OpCopyMemorySized: {
auto dst_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
dst_pointer_type = _.FindDef(dst_pointer->type_id());
auto src_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(1));
src_pointer_type = _.FindDef(src_pointer->type_id());
break;
}
default:
break;
}
return std::make_pair(dst_pointer_type, src_pointer_type);
}
// Returns the number of instruction words taken up by a memory access
// argument and its implied operands.
int MemoryAccessNumWords(uint32_t mask) {
int result = 1; // Count the mask
if (mask & uint32_t(spv::MemoryAccessMask::Aligned)) ++result;
if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) ++result;
if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) ++result;
return result;
}
// Returns the scope ID operand for MakeAvailable memory access with mask
// at the given operand index.
// This function is only called for OpLoad, OpStore, OpCopyMemory and
// OpCopyMemorySized, OpCooperativeMatrixLoadNV,
// OpCooperativeMatrixStoreNV, OpCooperativeVectorLoadNV,
// OpCooperativeVectorStoreNV.
uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
uint32_t mask_index) {
assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR));
uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR);
uint32_t index =
mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
return inst->GetOperandAs<uint32_t>(index);
}
// This function is only called for OpLoad, OpStore, OpCopyMemory,
// OpCopyMemorySized, OpCooperativeMatrixLoadNV,
// OpCooperativeMatrixStoreNV, OpCooperativeVectorLoadNV,
// OpCooperativeVectorStoreNV.
uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
uint32_t mask_index) {
assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR));
uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR);
uint32_t index =
mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
return inst->GetOperandAs<uint32_t>(index);
}
bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
for (size_t member_index = 1; member_index < inst->operands().size();
++member_index) {
const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
const auto member_type = _.FindDef(member_id);
if (member_type->opcode() == spv::Op::OpTypeRuntimeArray) return true;
}
return false;
}
spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
uint32_t index) {
Instruction* dst_pointer_type = nullptr;
Instruction* src_pointer_type = nullptr; // only used for OpCopyMemory
std::tie(dst_pointer_type, src_pointer_type) = GetPointerTypes(_, inst);
const spv::StorageClass dst_sc =
dst_pointer_type ? dst_pointer_type->GetOperandAs<spv::StorageClass>(1)
: spv::StorageClass::Max;
const spv::StorageClass src_sc =
src_pointer_type ? src_pointer_type->GetOperandAs<spv::StorageClass>(1)
: spv::StorageClass::Max;
if (inst->operands().size() <= index) {
// Cases where lack of some operand is invalid
if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4708)
<< "Memory accesses with PhysicalStorageBuffer must use Aligned.";
}
return SPV_SUCCESS;
}
const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) {
if (inst->opcode() == spv::Op::OpLoad ||
inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV ||
inst->opcode() == spv::Op::OpCooperativeMatrixLoadTensorNV ||
inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR ||
inst->opcode() == spv::Op::OpCooperativeVectorLoadNV) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "MakePointerAvailableKHR cannot be used with OpLoad.";
}
if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "NonPrivatePointerKHR must be specified if "
"MakePointerAvailableKHR is specified.";
}
// Check the associated scope for MakeAvailableKHR.
const auto available_scope = GetMakeAvailableScope(inst, mask, index);
if (auto error = ValidateMemoryScope(_, inst, available_scope))
return error;
}
if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) {
if (inst->opcode() == spv::Op::OpStore ||
inst->opcode() == spv::Op::OpCooperativeMatrixStoreNV ||
inst->opcode() == spv::Op::OpCooperativeMatrixStoreKHR ||
inst->opcode() == spv::Op::OpCooperativeMatrixStoreTensorNV ||
inst->opcode() == spv::Op::OpCooperativeVectorStoreNV) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "MakePointerVisibleKHR cannot be used with OpStore.";
}
if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "NonPrivatePointerKHR must be specified if "
<< "MakePointerVisibleKHR is specified.";
}
// Check the associated scope for MakeVisibleKHR.
const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
}
if (mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR)) {
if (dst_sc != spv::StorageClass::Uniform &&
dst_sc != spv::StorageClass::Workgroup &&
dst_sc != spv::StorageClass::CrossWorkgroup &&
dst_sc != spv::StorageClass::Generic &&
dst_sc != spv::StorageClass::Image &&
dst_sc != spv::StorageClass::StorageBuffer &&
dst_sc != spv::StorageClass::PhysicalStorageBuffer) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "NonPrivatePointerKHR requires a pointer in Uniform, "
<< "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
<< "storage classes.";
}
if (src_sc != spv::StorageClass::Max &&
src_sc != spv::StorageClass::Uniform &&
src_sc != spv::StorageClass::Workgroup &&
src_sc != spv::StorageClass::CrossWorkgroup &&
src_sc != spv::StorageClass::Generic &&
src_sc != spv::StorageClass::Image &&
src_sc != spv::StorageClass::StorageBuffer &&
src_sc != spv::StorageClass::PhysicalStorageBuffer) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "NonPrivatePointerKHR requires a pointer in Uniform, "
<< "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
<< "storage classes.";
}
}
if (!(mask & uint32_t(spv::MemoryAccessMask::Aligned))) {
if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4708)
<< "Memory accesses with PhysicalStorageBuffer must use Aligned.";
}
} else {
// even if there are other masks, the Aligned operand will be next
const uint32_t aligned_value = inst->GetOperandAs<uint32_t>(index + 1);
const bool is_power_of_two =
aligned_value && !(aligned_value & (aligned_value - 1));
if (!is_power_of_two) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Memory accesses Aligned operand value " << aligned_value
<< " is not a power of two.";
}
uint32_t largest_scalar = 0;
if (dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
if (dst_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR) {
largest_scalar =
_.GetLargestScalarType(dst_pointer_type->GetOperandAs<uint32_t>(2));
} else if (inst->type_id() != 0) {
largest_scalar = _.GetLargestScalarType(inst->type_id());
} else {
// TODO need to handle cases like OpStore and OpCopyMemorySized which
// don't have a result type
}
}
// TODO - Handle Untyped in OpCopyMemory
if (src_sc == spv::StorageClass::PhysicalStorageBuffer &&
src_pointer_type->opcode() != spv::Op::OpTypeUntypedPointerKHR) {
largest_scalar = std::max(
largest_scalar,
_.GetLargestScalarType(src_pointer_type->GetOperandAs<uint32_t>(2)));
}
if (aligned_value < largest_scalar) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(6314) << "Memory accesses Aligned operand value "
<< aligned_value << " is too small, the largest scalar type is "
<< largest_scalar << " bytes.";
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableInitializer(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
uint32_t value_id) {
const bool untyped_pointer = inst->opcode() == spv::Op::OpUntypedVariableKHR;
const uint32_t initializer_index = untyped_pointer ? 4u : 3u;
if (initializer_index < inst->operands().size()) {
const uint32_t initializer_id =
inst->GetOperandAs<uint32_t>(initializer_index);
const Instruction* initializer = _.FindDef(initializer_id);
const uint32_t storage_class_index = 2u;
const bool is_module_scope_var =
initializer &&
(initializer->opcode() == spv::Op::OpVariable ||
initializer->opcode() == spv::Op::OpUntypedVariableKHR) &&
(initializer->GetOperandAs<spv::StorageClass>(storage_class_index) !=
spv::StorageClass::Function);
const bool is_constant =
initializer && spvOpcodeIsConstant(initializer->opcode());
if (!initializer || !(is_constant || is_module_scope_var)) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Variable Initializer <id> " << _.getIdName(initializer_id)
<< " is not a constant or module-scope variable.";
}
if (initializer->type_id() != value_id) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Initializer type must match the data type";
}
}
// Vulkan Appendix A: Check that if contains initializer, then
// storage class is Output, Private, or Function.
if (inst->operands().size() > initializer_index &&
storage_class != spv::StorageClass::Output &&
storage_class != spv::StorageClass::Private &&
storage_class != spv::StorageClass::Function) {
if (spvIsVulkanEnv(_.context()->target_env)) {
if (storage_class == spv::StorageClass::Workgroup) {
auto init_id = inst->GetOperandAs<uint32_t>(initializer_index);
auto init = _.FindDef(init_id);
if (init->opcode() != spv::Op::OpConstantNull) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4734) << "OpVariable, <id> "
<< _.getIdName(inst->id())
<< ", initializers are limited to OpConstantNull in "
"Workgroup "
"storage class";
}
} else if (storage_class != spv::StorageClass::Output &&
storage_class != spv::StorageClass::Private &&
storage_class != spv::StorageClass::Function) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4651) << "OpVariable, <id> "
<< _.getIdName(inst->id())
<< ", has a disallowed initializer & storage class "
<< "combination.\n"
<< "From " << spvLogStringForEnv(_.context()->target_env)
<< " spec:\n"
<< "Variable declarations that include initializers must have "
<< "one of the following storage classes: Output, Private, "
<< "Function or Workgroup";
}
}
}
if (initializer_index < inst->operands().size()) {
if (storage_class == spv::StorageClass::TaskPayloadWorkgroupEXT) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpVariable, <id> " << _.getIdName(inst->id())
<< ", initializer are not allowed for TaskPayloadWorkgroupEXT";
}
if (storage_class == spv::StorageClass::Input) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpVariable, <id> " << _.getIdName(inst->id())
<< ", initializer are not allowed for Input";
}
if (storage_class == spv::StorageClass::HitObjectAttributeNV) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpVariable, <id> " << _.getIdName(inst->id())
<< ", initializer are not allowed for HitObjectAttributeNV";
}
if (storage_class == spv::StorageClass::HitObjectAttributeEXT) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpVariable, <id> " << _.getIdName(inst->id())
<< ", initializer are not allowed for HitObjectAttributeEXT";
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableStorageClass(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction* value_type) {
if (storage_class != spv::StorageClass::Workgroup &&
storage_class != spv::StorageClass::CrossWorkgroup &&
storage_class != spv::StorageClass::Private &&
storage_class != spv::StorageClass::Function &&
storage_class != spv::StorageClass::UniformConstant &&
storage_class != spv::StorageClass::RayPayloadKHR &&
storage_class != spv::StorageClass::IncomingRayPayloadKHR &&
storage_class != spv::StorageClass::HitAttributeKHR &&
storage_class != spv::StorageClass::CallableDataKHR &&
storage_class != spv::StorageClass::IncomingCallableDataKHR &&
storage_class != spv::StorageClass::TaskPayloadWorkgroupEXT &&
storage_class != spv::StorageClass::HitObjectAttributeNV &&
storage_class != spv::StorageClass::HitObjectAttributeEXT &&
storage_class != spv::StorageClass::NodePayloadAMDX) {
bool storage_input_or_output = storage_class == spv::StorageClass::Input ||
storage_class == spv::StorageClass::Output;
bool builtin = false;
if (storage_input_or_output) {
for (const Decoration& decoration : _.id_decorations(inst->id())) {
if (decoration.dec_type() == spv::Decoration::BuiltIn) {
builtin = true;
break;
}
}
}
if (!builtin && value_type &&
ContainsInvalidBool(_, value_type, storage_input_or_output)) {
if (storage_input_or_output) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(7290)
<< "If OpTypeBool is stored in conjunction with OpVariable "
"using Input or Output Storage Classes it requires a BuiltIn "
"decoration";
} else {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "If OpTypeBool is stored in conjunction with OpVariable, it "
"can only be used with non-externally visible shader Storage "
"Classes: Workgroup, CrossWorkgroup, Private, Function, "
"Input, Output, RayPayloadKHR, IncomingRayPayloadKHR, "
"HitAttributeKHR, CallableDataKHR, "
"IncomingCallableDataKHR, NodePayloadAMDX, or "
"UniformConstant";
}
}
}
if (!_.IsValidStorageClass(storage_class)) {
return _.diag(SPV_ERROR_INVALID_BINARY, inst)
<< _.VkErrorID(4643)
<< "Invalid storage class for target environment";
}
if (storage_class == spv::StorageClass::Generic) {
return _.diag(SPV_ERROR_INVALID_BINARY, inst)
<< "Variable storage class cannot be Generic";
}
if (inst->function() && storage_class != spv::StorageClass::Function) {
return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
<< "Variables must have a function[7] storage class inside"
" of a function";
}
if (!inst->function() && storage_class == spv::StorageClass::Function) {
return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
<< "Variables can not have a function[7] storage class "
"outside of a function";
}
// SPIR-V 3.32.8: Check that pointer type and variable type have the same
// storage class.
auto result_type = _.FindDef(inst->type_id());
const auto result_storage_class_index = 1;
const auto result_storage_class =
result_type->GetOperandAs<spv::StorageClass>(result_storage_class_index);
if (storage_class != result_storage_class) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Storage class must match result type storage class";
}
if (storage_class == spv::StorageClass::PhysicalStorageBuffer) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "PhysicalStorageBuffer must not be used with OpVariable.";
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariablePointer(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction& pointee) {
if ((_.addressing_model() == spv::AddressingModel::Logical ||
_.addressing_model() == spv::AddressingModel::PhysicalStorageBuffer64) &&
!_.options()->relax_logical_pointer) {
spv_result_t error = SPV_SUCCESS;
bool contains_logical_pointer = _.ContainsType(
pointee.id(),
[&_, inst, &error](const Instruction* type) {
if (type->opcode() == spv::Op::OpTypePointer ||
type->opcode() == spv::Op::OpTypeUntypedPointerKHR) {
const auto sc = type->GetOperandAs<spv::StorageClass>(1u);
if (sc != spv::StorageClass::PhysicalStorageBuffer) {
if (sc != spv::StorageClass::StorageBuffer &&
sc != spv::StorageClass::Workgroup) {
error =
_.diag(SPV_ERROR_INVALID_ID, inst)
<< "In Logical addressing, variables can only allocate a "
"pointer to the StorageBuffer or Workgroup storage "
"classes";
} else if (!_.HasCapability(
spv::Capability::VariablePointersStorageBuffer) &&
sc == spv::StorageClass::StorageBuffer) {
error =
_.diag(SPV_ERROR_INVALID_ID, inst)
<< "In Logical addressing, variables can only allocate a "
"storage buffer pointer if the "
"VariablePointersStorageBuffer capability is declared";
} else if (!_.HasCapability(spv::Capability::VariablePointers) &&
sc == spv::StorageClass::Workgroup) {
error =
_.diag(SPV_ERROR_INVALID_ID, inst)
<< "In Logical addressing, variables can only allocate a "
"workgroup pointer if the VariablePointers capability "
"is "
"declared";
}
return true;
}
}
return false;
},
/* traverse_all_types = */ false);
if (error != SPV_SUCCESS) return error;
if (contains_logical_pointer) {
if (storage_class != spv::StorageClass::Function &&
storage_class != spv::StorageClass::Private) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "In Logical addressing with variable pointers, variables "
<< "that allocate pointers must be in Function or Private "
<< "storage classes";
}
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableVulkanDescriptor(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction& pointee) {
// Vulkan Push Constant Interface section: Check type of PushConstant
// variables.
if (storage_class == spv::StorageClass::PushConstant) {
if (pointee.opcode() != spv::Op::OpTypeStruct) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(6808) << "PushConstant OpVariable <id> "
<< _.getIdName(inst->id()) << " has illegal type.\n"
<< "From Vulkan spec, Push Constant Interface section:\n"
<< "Such variables must be typed as OpTypeStruct";
}
}
// Vulkan Descriptor Set Interface: Check type of UniformConstant and
// Uniform variables.
if (storage_class == spv::StorageClass::UniformConstant) {
if (!IsAllowedTypeOrArrayOfSame(
_, pointee,
{spv::Op::OpTypeImage, spv::Op::OpTypeSampler,
spv::Op::OpTypeSampledImage, spv::Op::OpTypeTensorARM,
spv::Op::OpTypeAccelerationStructureKHR})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4655) << "UniformConstant OpVariable <id> "
<< _.getIdName(inst->id()) << " has illegal type.\n"
<< "Variables identified with the UniformConstant storage class "
<< "are used only as handles to refer to opaque resources. Such "
<< "variables must be typed as OpTypeImage, OpTypeSampler, "
<< "OpTypeSampledImage, OpTypeAccelerationStructureKHR, "
<< "or an array of one of these types.";
}
}
if (storage_class == spv::StorageClass::Uniform) {
if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(6807) << "Uniform OpVariable <id> "
<< _.getIdName(inst->id()) << " has illegal type.\n"
<< "From Vulkan spec:\n"
<< "Variables identified with the Uniform storage class are "
<< "used to access transparent buffer backed resources. Such "
<< "variables must be typed as OpTypeStruct, or an array of "
<< "this type";
}
}
if (storage_class == spv::StorageClass::StorageBuffer) {
if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(6807) << "StorageBuffer OpVariable <id> "
<< _.getIdName(inst->id()) << " has illegal type.\n"
<< "From Vulkan spec:\n"
<< "Variables identified with the StorageBuffer storage class "
"are used to access transparent buffer backed resources. "
"Such variables must be typed as OpTypeStruct, or an array "
"of this type";
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableVulkanInterface(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction* value_type,
uint32_t value_id) {
// Check for invalid use of Invariant
if (storage_class != spv::StorageClass::Input &&
storage_class != spv::StorageClass::Output) {
if (_.HasDecoration(inst->id(), spv::Decoration::Invariant)) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4677)
<< "Variable decorated with Invariant must only be identified "
"with the Input or Output storage class in Vulkan "
"environment.";
}
// Need to check if only the members in a struct are decorated
if (value_type && value_type->opcode() == spv::Op::OpTypeStruct) {
if (_.HasDecoration(value_id, spv::Decoration::Invariant)) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4677)
<< "Variable struct member decorated with Invariant must only "
"be identified with the Input or Output storage class in "
"Vulkan environment.";
}
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableCoopMat(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction& pointee) {
// Cooperative matrix types can only be allocated in Function or Private
if ((storage_class != spv::StorageClass::Function &&
storage_class != spv::StorageClass::Private) &&
_.ContainsType(pointee.id(), [](const Instruction* type_inst) {
auto opcode = type_inst->opcode();
return opcode == spv::Op::OpTypeCooperativeMatrixNV ||
opcode == spv::Op::OpTypeCooperativeMatrixKHR;
})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Cooperative matrix types (or types containing them) can only be "
"allocated "
<< "in Function or Private storage classes or as function "
"parameters";
}
return SPV_SUCCESS;
}
// Vulkan specific validation rules for OpTypeRuntimeArray
spv_result_t ValidateVariableVulkanArray(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction& value_type,
uint32_t value_id) {
// OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
// so should never appear as a bare variable.
// Unless the module has the RuntimeDescriptorArray capability.
if (value_type.opcode() == spv::Op::OpTypeRuntimeArray) {
if (!_.HasCapability(spv::Capability::RuntimeDescriptorArray)) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4680) << "OpVariable, <id> "
<< _.getIdName(inst->id())
<< ", is attempting to create memory for an illegal type, "
<< "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
<< "appear as the final member of an OpTypeStruct, thus cannot "
<< "be instantiated via OpVariable, unless the "
"RuntimeDescriptorArray Capability is declared";
} else {
// A bare variable OpTypeRuntimeArray is allowed in this context, but
// still need to check the storage class.
if (storage_class != spv::StorageClass::StorageBuffer &&
storage_class != spv::StorageClass::Uniform &&
storage_class != spv::StorageClass::UniformConstant) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4680)
<< "For Vulkan with RuntimeDescriptorArray, a variable "
<< "containing OpTypeRuntimeArray must have storage class of "
<< "StorageBuffer, Uniform, or UniformConstant.";
}
}
}
// If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
// must either have the storage class StorageBuffer and be decorated
// with Block, or it must be in the Uniform storage class
if (value_type.opcode() == spv::Op::OpTypeStruct) {
if (DoesStructContainRTA(_, &value_type)) {
if (storage_class == spv::StorageClass::StorageBuffer ||
storage_class == spv::StorageClass::PhysicalStorageBuffer) {
if (!_.HasDecoration(value_id, spv::Decoration::Block)) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4680)
<< "For Vulkan, an OpTypeStruct variable containing an "
<< "OpTypeRuntimeArray must be decorated with Block if it "
<< "has storage class StorageBuffer or "
"PhysicalStorageBuffer.";
}
} else if (storage_class == spv::StorageClass::Uniform) {
// BufferBlock Uniform were always allowed.
//
// Block Uniform use to be invalid, but Vulkan added
// VK_EXT_shader_uniform_buffer_unsized_array and now this is
// validated at runtime
//
// The uniform must have either the Block or BufferBlock decoration
// (see VUID-StandaloneSpirv-Uniform-06676)
} else {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(4680)
<< "For Vulkan, OpTypeStruct variables containing "
<< "OpTypeRuntimeArray must have storage class of "
<< "StorageBuffer, PhysicalStorageBuffer, or Uniform.";
}
}
}
return SPV_SUCCESS;
}
// Vulkan-specific validation for long vectors
spv_result_t ValidateVariableVulkanLongVector(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction& pointee) {
if (_.HasCapability(spv::Capability::LongVectorEXT)) {
if ((storage_class != spv::StorageClass::Function &&
storage_class != spv::StorageClass::Private &&
storage_class != spv::StorageClass::StorageBuffer &&
storage_class != spv::StorageClass::PhysicalStorageBuffer &&
storage_class != spv::StorageClass::Workgroup &&
storage_class != spv::StorageClass::Uniform &&
storage_class != spv::StorageClass::PushConstant &&
storage_class != spv::StorageClass::ShaderRecordBufferKHR) &&
_.ContainsType(pointee.id(), [&](const Instruction* type_inst) {
auto opcode = type_inst->opcode();
if (opcode == spv::Op::OpTypeVector ||
opcode == spv::Op::OpTypeVectorIdEXT) {
uint32_t dim = _.GetDimension(type_inst->id());
return dim > 4;
}
return false;
})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(12297)
<< "Long vector types with more than 4 components (or types "
"containing them) not supported in storage class "
<< StorageClassToString(storage_class);
}
if ((storage_class == spv::StorageClass::StorageBuffer ||
storage_class == spv::StorageClass::PhysicalStorageBuffer ||
storage_class == spv::StorageClass::Uniform ||
storage_class == spv::StorageClass::PushConstant ||
storage_class == spv::StorageClass::ShaderRecordBufferKHR ||
(storage_class == spv::StorageClass::Workgroup &&
_.HasDecoration(pointee.id(), spv::Decoration::Block))) &&
_.ContainsType(pointee.id(), [&](const Instruction* type_inst) {
auto opcode = type_inst->opcode();
if (opcode == spv::Op::OpTypeVectorIdEXT) {
auto component_count =
_.FindDef(type_inst->GetOperandAs<uint32_t>(2u));
return (bool)spvOpcodeIsSpecConstant(component_count->opcode());
}
return false;
})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< _.VkErrorID(12294)
<< "Long vector types with spec constant component count "
"not supported in storage class with explicit layout "
<< StorageClassToString(storage_class);
}
} else {
if ((storage_class != spv::StorageClass::Function &&
storage_class != spv::StorageClass::Private) &&
_.ContainsType(pointee.id(), [](const Instruction* type_inst) {
auto opcode = type_inst->opcode();
return opcode == spv::Op::OpTypeVectorIdEXT;
})) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Cooperative vector types (or types containing them) can "
"only be "
"allocated "
<< "in Function or Private storage classes or as function "
"parameters";
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateVariableShader(ValidationState_t& _,
const Instruction* inst,
spv::StorageClass storage_class,
const Instruction* value_type,
uint32_t value_id) {
// Don't allow variables containing 16-bit elements without the appropriate
// capabilities.
if ((!_.HasCapability(spv::Capability::Int16) &&
_.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeInt, 16)) ||
(!_.HasCapability(spv::Capability::Float16) &&
_.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeFloat, 16))) {
auto underlying_type = value_type;
while (underlying_type &&
underlying_type->opcode() == spv::Op::OpTypePointer) {
storage_class = underlying_type->GetOperandAs<spv::StorageClass>(1u);
underlying_type = _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
}
bool storage_class_ok = true;
std::string sc_name = _.grammar().lookupOperandName(
SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(storage_class));
switch (storage_class) {
case spv::StorageClass::StorageBuffer:
case spv::StorageClass::PhysicalStorageBuffer:
if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess)) {
storage_class_ok = false;
}
break;
case spv::StorageClass::Uniform:
if (underlying_type &&
!_.HasCapability(
spv::Capability::UniformAndStorageBuffer16BitAccess)) {
if (underlying_type->opcode() == spv::Op::OpTypeArray ||
underlying_type->opcode() == spv::Op::OpTypeRuntimeArray) {
underlying_type =
_.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
}
if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess) ||
!_.HasDecoration(underlying_type->id(),
spv::Decoration::BufferBlock)) {
storage_class_ok = false;
}
}
break;
case spv::StorageClass::PushConstant:
if (!_.HasCapability(spv::Capability::StoragePushConstant16)) {
storage_class_ok = false;
}
break;
case spv::StorageClass::Input:
case spv::StorageClass::Output:
if (!_.HasCapability(spv::Capability::StorageInputOutput16)) {
storage_class_ok = false;
}
break;
case spv::StorageClass::Workgroup:
if (!_.HasCapability(
spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR)) {
storage_class_ok = false;
}
break;
default:
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "Cannot allocate a variable containing a 16-bit type in "
<< sc_name << " storage class";
}
if (!storage_class_ok) {
return _.diag(SPV_ERROR_INVALID_ID, inst)