-
Notifications
You must be signed in to change notification settings - Fork 854
Expand file tree
/
Copy pathDeclResultIdMapper.cpp
More file actions
5062 lines (4503 loc) · 194 KB
/
DeclResultIdMapper.cpp
File metadata and controls
5062 lines (4503 loc) · 194 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
//===--- DeclResultIdMapper.cpp - DeclResultIdMapper impl --------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DeclResultIdMapper.h"
#include <algorithm>
#include <optional>
#include <sstream>
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/Support/SPIRVOptions.h"
#include "clang/AST/Expr.h"
#include "clang/AST/HlslTypes.h"
#include "clang/SPIRV/AstTypeProbe.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Casting.h"
#include "AlignmentSizeCalculator.h"
#include "SignaturePackingUtil.h"
#include "SpirvEmitter.h"
namespace clang {
namespace spirv {
namespace {
// Returns true if the image format is compatible with the sampled type. This is
// determined according to the same at
// https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#spirvenv-format-type-matching.
bool areFormatAndTypeCompatible(spv::ImageFormat format, QualType sampledType) {
if (format == spv::ImageFormat::Unknown) {
return true;
}
if (hlsl::IsHLSLVecType(sampledType)) {
// For vectors, we need to check if the element type is compatible. We do
// not check the number of elements because it is possible that the number
// of elements in the sampled type is different. I could not find in the
// spec what should happen in that case.
sampledType = hlsl::GetHLSLVecElementType(sampledType);
}
const Type *desugaredType = sampledType->getUnqualifiedDesugaredType();
const BuiltinType *builtinType = dyn_cast<BuiltinType>(desugaredType);
if (!builtinType) {
return false;
}
switch (format) {
case spv::ImageFormat::Rgba32f:
case spv::ImageFormat::Rg32f:
case spv::ImageFormat::R32f:
case spv::ImageFormat::Rgba16f:
case spv::ImageFormat::Rg16f:
case spv::ImageFormat::R16f:
case spv::ImageFormat::Rgba16:
case spv::ImageFormat::Rg16:
case spv::ImageFormat::R16:
case spv::ImageFormat::Rgba16Snorm:
case spv::ImageFormat::Rg16Snorm:
case spv::ImageFormat::R16Snorm:
case spv::ImageFormat::Rgb10A2:
case spv::ImageFormat::R11fG11fB10f:
case spv::ImageFormat::Rgba8:
case spv::ImageFormat::Rg8:
case spv::ImageFormat::R8:
case spv::ImageFormat::Rgba8Snorm:
case spv::ImageFormat::Rg8Snorm:
case spv::ImageFormat::R8Snorm:
// 32-bit float
return builtinType->getKind() == BuiltinType::Float;
case spv::ImageFormat::Rgba32i:
case spv::ImageFormat::Rg32i:
case spv::ImageFormat::R32i:
case spv::ImageFormat::Rgba16i:
case spv::ImageFormat::Rg16i:
case spv::ImageFormat::R16i:
case spv::ImageFormat::Rgba8i:
case spv::ImageFormat::Rg8i:
case spv::ImageFormat::R8i:
// signed 32-bit int
return builtinType->getKind() == BuiltinType::Int;
case spv::ImageFormat::Rgba32ui:
case spv::ImageFormat::Rg32ui:
case spv::ImageFormat::R32ui:
case spv::ImageFormat::Rgba16ui:
case spv::ImageFormat::Rg16ui:
case spv::ImageFormat::R16ui:
case spv::ImageFormat::Rgb10a2ui:
case spv::ImageFormat::Rgba8ui:
case spv::ImageFormat::Rg8ui:
case spv::ImageFormat::R8ui:
// unsigned 32-bit int
return builtinType->getKind() == BuiltinType::UInt;
case spv::ImageFormat::R64i:
// signed 64-bit int
return builtinType->getKind() == BuiltinType::LongLong;
case spv::ImageFormat::R64ui:
// unsigned 64-bit int
return builtinType->getKind() == BuiltinType::ULongLong;
}
return true;
}
uint32_t getVkBindingAttrSet(const VKBindingAttr *attr, uint32_t defaultSet) {
// If the [[vk::binding(x)]] attribute is provided without the descriptor set,
// we should use the default descriptor set.
if (attr->getSet() == INT_MIN) {
return defaultSet;
}
return attr->getSet();
}
/// Returns the :packoffset() annotation on the given decl. Returns nullptr if
/// the decl does not have one.
hlsl::ConstantPacking *getPackOffset(const clang::NamedDecl *decl) {
for (auto *annotation : decl->getUnusualAnnotations())
if (auto *packing = llvm::dyn_cast<hlsl::ConstantPacking>(annotation))
return packing;
return nullptr;
}
/// Returns the number of binding numbers that are used up by the given type.
/// An array of size N consumes N*M binding numbers where M is the number of
/// binding numbers used by each array element.
/// The number of binding numbers used by a structure is the sum of binding
/// numbers used by its members.
uint32_t getNumBindingsUsedByResourceType(QualType type) {
// For custom-generated types that have SpirvType but no QualType.
if (type.isNull())
return 1;
// For every array dimension, the number of bindings needed should be
// multiplied by the array size. For example: an array of two Textures should
// use 2 binding slots.
uint32_t arrayFactor = 1;
while (auto constArrayType = dyn_cast<ConstantArrayType>(type)) {
arrayFactor *=
static_cast<uint32_t>(constArrayType->getSize().getZExtValue());
type = constArrayType->getElementType();
}
// Once we remove the arrayness, we expect the given type to be either a
// resource OR a structure that only contains resources.
assert(isResourceType(type) || isResourceOnlyStructure(type));
// In the case of a resource, each resource takes 1 binding slot, so in total
// it consumes: 1 * arrayFactor.
if (isResourceType(type))
return arrayFactor;
// In the case of a struct of resources, we need to sum up the number of
// bindings for the struct members. So in total it consumes:
// sum(bindings of struct members) * arrayFactor.
if (isResourceOnlyStructure(type)) {
uint32_t sumOfMemberBindings = 0;
const auto *structDecl = type->getAs<RecordType>()->getDecl();
assert(structDecl);
for (const auto *field : structDecl->fields())
sumOfMemberBindings += getNumBindingsUsedByResourceType(field->getType());
return sumOfMemberBindings * arrayFactor;
}
llvm_unreachable(
"getNumBindingsUsedByResourceType was called with unknown resource type");
}
QualType getUintTypeWithSourceComponents(const ASTContext &astContext,
QualType sourceType) {
if (isScalarType(sourceType)) {
return astContext.UnsignedIntTy;
}
uint32_t elemCount = 0;
if (isVectorType(sourceType, nullptr, &elemCount)) {
return astContext.getExtVectorType(astContext.UnsignedIntTy, elemCount);
}
llvm_unreachable("only scalar and vector types are supported in "
"getUintTypeWithSourceComponents");
}
LocationAndComponent getLocationAndComponentCount(const ASTContext &astContext,
QualType type) {
// See Vulkan spec 14.1.4. Location Assignment for the complete set of rules.
const auto canonicalType = type.getCanonicalType();
if (canonicalType != type)
return getLocationAndComponentCount(astContext, canonicalType);
// Inputs and outputs of the following types consume a single interface
// location:
// * 16-bit scalar and vector types, and
// * 32-bit scalar and vector types, and
// * 64-bit scalar and 2-component vector types.
// 64-bit three- and four- component vectors consume two consecutive
// locations.
// Primitive types
if (isScalarType(type)) {
const auto *builtinType = type->getAs<BuiltinType>();
if (builtinType != nullptr) {
switch (builtinType->getKind()) {
case BuiltinType::Double:
case BuiltinType::LongLong:
case BuiltinType::ULongLong:
return {1, 2, true};
default:
return {1, 1, false};
}
}
return {1, 1, false};
}
// Vector types
{
QualType elemType = {};
uint32_t elemCount = {};
if (isVectorType(type, &elemType, &elemCount)) {
const auto *builtinType = elemType->getAs<BuiltinType>();
switch (builtinType->getKind()) {
case BuiltinType::Double:
case BuiltinType::LongLong:
case BuiltinType::ULongLong: {
if (elemCount >= 3)
return {2, 4, true};
return {1, 2 * elemCount, true};
}
default:
// Filter switch only interested in types occupying 2 locations.
break;
}
return {1, elemCount, false};
}
}
// If the declared input or output is an n * m 16- , 32- or 64- bit matrix,
// it will be assigned multiple locations starting with the location
// specified. The number of locations assigned for each matrix will be the
// same as for an n-element array of m-component vectors.
// Matrix types
{
QualType elemType = {};
uint32_t rowCount = 0, colCount = 0;
if (isMxNMatrix(type, &elemType, &rowCount, &colCount)) {
auto locComponentCount = getLocationAndComponentCount(
astContext, astContext.getExtVectorType(elemType, colCount));
return {locComponentCount.location * rowCount,
locComponentCount.component,
locComponentCount.componentAlignment};
}
}
// Typedefs
if (const auto *typedefType = type->getAs<TypedefType>())
return getLocationAndComponentCount(astContext, typedefType->desugar());
// Reference types
if (const auto *refType = type->getAs<ReferenceType>())
return getLocationAndComponentCount(astContext, refType->getPointeeType());
// Pointer types
if (const auto *ptrType = type->getAs<PointerType>())
return getLocationAndComponentCount(astContext, ptrType->getPointeeType());
// If a declared input or output is an array of size n and each element takes
// m locations, it will be assigned m * n consecutive locations starting with
// the location specified.
// Array types
if (const auto *arrayType = astContext.getAsConstantArrayType(type)) {
auto locComponentCount =
getLocationAndComponentCount(astContext, arrayType->getElementType());
uint32_t arrayLength =
static_cast<uint32_t>(arrayType->getSize().getZExtValue());
return {locComponentCount.location * arrayLength,
locComponentCount.component, locComponentCount.componentAlignment};
}
// Struct type
if (type->getAs<RecordType>()) {
assert(false && "all structs should already be flattened");
return {0, 0, false};
}
llvm_unreachable(
"calculating number of occupied locations for type unimplemented");
return {0, 0, false};
}
bool shouldSkipInStructLayout(const Decl *decl) {
// Ignore implicit generated struct declarations/constructors/destructors
if (decl->isImplicit())
return true;
// Ignore embedded type decls
if (isa<TypeDecl>(decl))
return true;
// Ignore embeded function decls
if (isa<FunctionDecl>(decl))
return true;
// Ignore empty decls
if (isa<EmptyDecl>(decl))
return true;
// For the $Globals cbuffer, we only care about externally-visible
// non-resource-type variables. The rest should be filtered out.
const auto *declContext = decl->getDeclContext();
// $Globals' "struct" is the TranslationUnit, so we should ignore resources
// in the TranslationUnit "struct" and its child namespaces.
if (declContext->isTranslationUnit() || declContext->isNamespace()) {
if (decl->hasAttr<VKConstantIdAttr>()) {
return true;
}
if (decl->hasAttr<VKPushConstantAttr>()) {
return true;
}
// External visibility
if (const auto *declDecl = dyn_cast<DeclaratorDecl>(decl))
if (!declDecl->hasExternalFormalLinkage())
return true;
// cbuffer/tbuffer
if (isa<HLSLBufferDecl>(decl))
return true;
// 'groupshared' variables should not be placed in $Globals cbuffer.
if (decl->hasAttr<HLSLGroupSharedAttr>())
return true;
// Other resource types
if (const auto *valueDecl = dyn_cast<ValueDecl>(decl)) {
const auto declType = valueDecl->getType();
if (isResourceType(declType) || isResourceOnlyStructure(declType))
return true;
}
}
return false;
}
void collectDeclsInField(const Decl *field,
llvm::SmallVector<const Decl *, 4> *decls) {
// Case of nested namespaces.
if (const auto *nsDecl = dyn_cast<NamespaceDecl>(field)) {
for (const auto *decl : nsDecl->decls()) {
collectDeclsInField(decl, decls);
}
}
if (shouldSkipInStructLayout(field))
return;
if (!isa<DeclaratorDecl>(field)) {
return;
}
decls->push_back(field);
}
llvm::SmallVector<const Decl *, 4>
collectDeclsInDeclContext(const DeclContext *declContext) {
llvm::SmallVector<const Decl *, 4> decls;
for (const auto *field : declContext->decls()) {
collectDeclsInField(field, &decls);
}
return decls;
}
/// \brief Returns true if the given decl is a boolean stage I/O variable.
/// Returns false if the type is not boolean, or the decl is a built-in stage
/// variable.
bool isBooleanStageIOVar(const NamedDecl *decl, QualType type,
const hlsl::DXIL::SemanticKind semanticKind,
const hlsl::SigPoint::Kind sigPointKind) {
// [[vk::builtin(...)]] makes the decl a built-in stage variable.
// IsFrontFace (if used as PSIn) is the only known boolean built-in stage
// variable.
bool isBooleanBuiltin = false;
if ((decl->getAttr<VKBuiltInAttr>() != nullptr))
isBooleanBuiltin = true;
else if (semanticKind == hlsl::Semantic::Kind::IsFrontFace &&
sigPointKind == hlsl::SigPoint::Kind::PSIn) {
isBooleanBuiltin = true;
} else if (semanticKind == hlsl::Semantic::Kind::CullPrimitive) {
isBooleanBuiltin = true;
}
// TODO: support boolean matrix stage I/O variable if needed.
QualType elemType = {};
const bool isBooleanType =
((isScalarType(type, &elemType) || isVectorType(type, &elemType)) &&
elemType->isBooleanType());
return isBooleanType && !isBooleanBuiltin;
}
/// \brief Returns the stage variable's register assignment for the given Decl.
const hlsl::RegisterAssignment *getResourceBinding(const NamedDecl *decl) {
for (auto *annotation : decl->getUnusualAnnotations()) {
if (auto *reg = dyn_cast<hlsl::RegisterAssignment>(annotation)) {
return reg;
}
}
return nullptr;
}
/// \brief Returns the stage variable's 'register(c#) assignment for the given
/// Decl. Return nullptr if the given variable does not have such assignment.
const hlsl::RegisterAssignment *getRegisterCAssignment(const NamedDecl *decl) {
const auto *regAssignment = getResourceBinding(decl);
if (regAssignment)
return regAssignment->RegisterType == 'c' ? regAssignment : nullptr;
return nullptr;
}
/// \brief Returns true if the given declaration has a primitive type qualifier.
/// Returns false otherwise.
inline bool hasGSPrimitiveTypeQualifier(const Decl *decl) {
return decl->hasAttr<HLSLTriangleAttr>() ||
decl->hasAttr<HLSLTriangleAdjAttr>() ||
decl->hasAttr<HLSLPointAttr>() || decl->hasAttr<HLSLLineAttr>() ||
decl->hasAttr<HLSLLineAdjAttr>();
}
/// \brief Deduces the parameter qualifier for the given decl.
hlsl::DxilParamInputQual deduceParamQual(const DeclaratorDecl *decl,
bool asInput) {
const auto type = decl->getType();
if (hlsl::IsHLSLInputPatchType(type))
return hlsl::DxilParamInputQual::InputPatch;
if (hlsl::IsHLSLOutputPatchType(type))
return hlsl::DxilParamInputQual::OutputPatch;
// TODO: Add support for multiple output streams.
if (hlsl::IsHLSLStreamOutputType(type))
return hlsl::DxilParamInputQual::OutStream0;
// The inputs to the geometry shader that have a primitive type qualifier
// must use 'InputPrimitive'.
if (hasGSPrimitiveTypeQualifier(decl))
return hlsl::DxilParamInputQual::InputPrimitive;
if (decl->hasAttr<HLSLIndicesAttr>())
return hlsl::DxilParamInputQual::OutIndices;
if (decl->hasAttr<HLSLVerticesAttr>())
return hlsl::DxilParamInputQual::OutVertices;
if (decl->hasAttr<HLSLPrimitivesAttr>())
return hlsl::DxilParamInputQual::OutPrimitives;
if (decl->hasAttr<HLSLPayloadAttr>())
return hlsl::DxilParamInputQual::InPayload;
if (hlsl::IsHLSLNodeType(type)) {
return hlsl::DxilParamInputQual::NodeIO;
}
return asInput ? hlsl::DxilParamInputQual::In : hlsl::DxilParamInputQual::Out;
}
/// \brief Deduces the HLSL SigPoint for the given decl appearing in the given
/// shader model.
const hlsl::SigPoint *deduceSigPoint(const DeclaratorDecl *decl, bool asInput,
const hlsl::ShaderModel::Kind kind,
bool forPCF) {
if (kind == hlsl::ShaderModel::Kind::Node) {
return hlsl::SigPoint::GetSigPoint(hlsl::SigPoint::Kind::CSIn);
}
return hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
deduceParamQual(decl, asInput), kind, forPCF));
}
/// Returns the type of the given decl. If the given decl is a FunctionDecl,
/// returns its result type.
inline QualType getTypeOrFnRetType(const DeclaratorDecl *decl) {
if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
return funcDecl->getReturnType();
}
return decl->getType();
}
/// Returns the number of base classes if this type is a derived class/struct.
/// Returns zero otherwise.
inline uint32_t getNumBaseClasses(QualType type) {
if (const auto *cxxDecl = type->getAsCXXRecordDecl())
return cxxDecl->getNumBases();
return 0;
}
/// Returns the appropriate storage class for an extern variable of the given
/// type.
spv::StorageClass getStorageClassForExternVar(QualType type,
bool hasGroupsharedAttr) {
// For CS groupshared variables
if (hasGroupsharedAttr)
return spv::StorageClass::Workgroup;
if (isAKindOfStructuredOrByteBuffer(type) || isConstantTextureBuffer(type))
return spv::StorageClass::Uniform;
return spv::StorageClass::UniformConstant;
}
/// Returns the appropriate layout rule for an extern variable of the given
/// type.
SpirvLayoutRule getLayoutRuleForExternVar(QualType type,
const SpirvCodeGenOptions &opts) {
if (isAKindOfStructuredOrByteBuffer(type))
return opts.sBufferLayoutRule;
if (isConstantBuffer(type))
return opts.cBufferLayoutRule;
if (isTextureBuffer(type))
return opts.tBufferLayoutRule;
return SpirvLayoutRule::Void;
}
std::optional<spv::ImageFormat>
getSpvImageFormat(const VKImageFormatAttr *imageFormatAttr) {
if (imageFormatAttr == nullptr)
return std::nullopt;
switch (imageFormatAttr->getImageFormat()) {
case VKImageFormatAttr::unknown:
return spv::ImageFormat::Unknown;
case VKImageFormatAttr::rgba32f:
return spv::ImageFormat::Rgba32f;
case VKImageFormatAttr::rgba16f:
return spv::ImageFormat::Rgba16f;
case VKImageFormatAttr::r32f:
return spv::ImageFormat::R32f;
case VKImageFormatAttr::rgba8:
return spv::ImageFormat::Rgba8;
case VKImageFormatAttr::rgba8snorm:
return spv::ImageFormat::Rgba8Snorm;
case VKImageFormatAttr::rg32f:
return spv::ImageFormat::Rg32f;
case VKImageFormatAttr::rg16f:
return spv::ImageFormat::Rg16f;
case VKImageFormatAttr::r11g11b10f:
return spv::ImageFormat::R11fG11fB10f;
case VKImageFormatAttr::r16f:
return spv::ImageFormat::R16f;
case VKImageFormatAttr::rgba16:
return spv::ImageFormat::Rgba16;
case VKImageFormatAttr::rgb10a2:
return spv::ImageFormat::Rgb10A2;
case VKImageFormatAttr::rg16:
return spv::ImageFormat::Rg16;
case VKImageFormatAttr::rg8:
return spv::ImageFormat::Rg8;
case VKImageFormatAttr::r16:
return spv::ImageFormat::R16;
case VKImageFormatAttr::r8:
return spv::ImageFormat::R8;
case VKImageFormatAttr::rgba16snorm:
return spv::ImageFormat::Rgba16Snorm;
case VKImageFormatAttr::rg16snorm:
return spv::ImageFormat::Rg16Snorm;
case VKImageFormatAttr::rg8snorm:
return spv::ImageFormat::Rg8Snorm;
case VKImageFormatAttr::r16snorm:
return spv::ImageFormat::R16Snorm;
case VKImageFormatAttr::r8snorm:
return spv::ImageFormat::R8Snorm;
case VKImageFormatAttr::rgba32i:
return spv::ImageFormat::Rgba32i;
case VKImageFormatAttr::rgba16i:
return spv::ImageFormat::Rgba16i;
case VKImageFormatAttr::rgba8i:
return spv::ImageFormat::Rgba8i;
case VKImageFormatAttr::r32i:
return spv::ImageFormat::R32i;
case VKImageFormatAttr::rg32i:
return spv::ImageFormat::Rg32i;
case VKImageFormatAttr::rg16i:
return spv::ImageFormat::Rg16i;
case VKImageFormatAttr::rg8i:
return spv::ImageFormat::Rg8i;
case VKImageFormatAttr::r16i:
return spv::ImageFormat::R16i;
case VKImageFormatAttr::r8i:
return spv::ImageFormat::R8i;
case VKImageFormatAttr::rgba32ui:
return spv::ImageFormat::Rgba32ui;
case VKImageFormatAttr::rgba16ui:
return spv::ImageFormat::Rgba16ui;
case VKImageFormatAttr::rgba8ui:
return spv::ImageFormat::Rgba8ui;
case VKImageFormatAttr::r32ui:
return spv::ImageFormat::R32ui;
case VKImageFormatAttr::rgb10a2ui:
return spv::ImageFormat::Rgb10a2ui;
case VKImageFormatAttr::rg32ui:
return spv::ImageFormat::Rg32ui;
case VKImageFormatAttr::rg16ui:
return spv::ImageFormat::Rg16ui;
case VKImageFormatAttr::rg8ui:
return spv::ImageFormat::Rg8ui;
case VKImageFormatAttr::r16ui:
return spv::ImageFormat::R16ui;
case VKImageFormatAttr::r8ui:
return spv::ImageFormat::R8ui;
case VKImageFormatAttr::r64ui:
return spv::ImageFormat::R64ui;
case VKImageFormatAttr::r64i:
return spv::ImageFormat::R64i;
}
return spv::ImageFormat::Unknown;
}
// Inserts seen semantics for entryPoint to seenSemanticsForEntryPoints. Returns
// whether it does not already exist in seenSemanticsForEntryPoints.
bool insertSeenSemanticsForEntryPointIfNotExist(
llvm::SmallDenseMap<SpirvFunction *, llvm::StringSet<>>
*seenSemanticsForEntryPoints,
SpirvFunction *entryPoint, const std::string &semantics) {
auto seenSemanticsForEntryPointsItr =
seenSemanticsForEntryPoints->find(entryPoint);
if (seenSemanticsForEntryPointsItr == seenSemanticsForEntryPoints->end()) {
bool insertResult = false;
std::tie(seenSemanticsForEntryPointsItr, insertResult) =
seenSemanticsForEntryPoints->insert(
std::make_pair(entryPoint, llvm::StringSet<>()));
assert(insertResult);
seenSemanticsForEntryPointsItr->second.insert(semantics);
return true;
}
auto &seenSemantics = seenSemanticsForEntryPointsItr->second;
if (seenSemantics.count(semantics)) {
return false;
}
seenSemantics.insert(semantics);
return true;
}
// Returns whether the type is translated to a 32-bit floating point type,
// depending on whether SPIR-V codegen options are configured to use 16-bit
// types when possible.
bool is32BitFloatingPointType(BuiltinType::Kind kind, bool use16Bit) {
// Always translated into 32-bit floating point types.
if (kind == BuiltinType::Float || kind == BuiltinType::LitFloat)
return true;
// Translated into 32-bit floating point types when run without
// -enable-16bit-types.
if (kind == BuiltinType::Half || kind == BuiltinType::HalfFloat ||
kind == BuiltinType::Min10Float || kind == BuiltinType::Min16Float)
return !use16Bit;
return false;
}
// Returns whether the type is a 4-component 32-bit float or a composite type
// recursively including only such a vector e.g., float4, float4[1], struct S {
// float4 foo[1]; }.
bool containOnlyVecWithFourFloats(QualType type, bool use16Bit) {
if (type->isReferenceType())
type = type->getPointeeType();
if (is1xNMatrix(type, nullptr, nullptr))
return false;
uint32_t elemCount = 0;
if (type->isConstantArrayType()) {
const ConstantArrayType *arrayType =
(const ConstantArrayType *)type->getAsArrayTypeUnsafe();
elemCount = hlsl::GetArraySize(type);
return elemCount == 1 &&
containOnlyVecWithFourFloats(arrayType->getElementType(), use16Bit);
}
if (const auto *structType = type->getAs<RecordType>()) {
uint32_t fieldCount = 0;
for (const auto *field : structType->getDecl()->fields()) {
if (fieldCount != 0)
return false;
if (!containOnlyVecWithFourFloats(field->getType(), use16Bit))
return false;
++fieldCount;
}
return fieldCount == 1;
}
QualType elemType = {};
if (isVectorType(type, &elemType, &elemCount)) {
if (const auto *builtinType = elemType->getAs<BuiltinType>()) {
return elemCount == 4 &&
is32BitFloatingPointType(builtinType->getKind(), use16Bit);
}
return false;
}
return false;
}
} // anonymous namespace
std::string StageVar::getSemanticStr() const {
// A special case for zero index, which is equivalent to no index.
// Use what is in the source code.
// TODO: this looks like a hack to make the current tests happy.
// Should consider remove it and fix all tests.
if (semanticInfo.index == 0)
return semanticInfo.str;
std::ostringstream ss;
ss << semanticInfo.name.str() << semanticInfo.index;
return ss.str();
}
SpirvInstruction *CounterIdAliasPair::getAliasAddress() const {
assert(isAlias);
return counterVar;
}
SpirvInstruction *
CounterIdAliasPair::getCounterVariable(SpirvBuilder &builder,
SpirvContext &spvContext) const {
if (isAlias) {
const auto *counterType = spvContext.getACSBufferCounterType();
const auto *counterVarType =
spvContext.getPointerType(counterType, spv::StorageClass::Uniform);
return builder.createLoad(counterVarType, counterVar,
/* SourceLocation */ {});
}
return counterVar;
}
const CounterIdAliasPair *
CounterVarFields::get(const llvm::SmallVectorImpl<uint32_t> &indices) const {
for (const auto &field : fields)
if (field.indices == indices)
return &field.counterVar;
return nullptr;
}
bool CounterVarFields::assign(const CounterVarFields &srcFields,
SpirvBuilder &builder,
SpirvContext &context) const {
for (const auto &field : fields) {
const auto *srcField = srcFields.get(field.indices);
if (!srcField)
return false;
field.counterVar.assign(srcField->getCounterVariable(builder, context),
builder);
}
return true;
}
bool CounterVarFields::assign(const CounterVarFields &srcFields,
const llvm::SmallVector<uint32_t, 4> &dstPrefix,
const llvm::SmallVector<uint32_t, 4> &srcPrefix,
SpirvBuilder &builder,
SpirvContext &context) const {
if (dstPrefix.empty() && srcPrefix.empty())
return assign(srcFields, builder, context);
llvm::SmallVector<uint32_t, 4> srcIndices = srcPrefix;
// If whole has the given prefix, appends all elements after the prefix in
// whole to srcIndices.
const auto applyDiff =
[&srcIndices](const llvm::SmallVector<uint32_t, 4> &whole,
const llvm::SmallVector<uint32_t, 4> &prefix) -> bool {
uint32_t i = 0;
for (; i < prefix.size(); ++i)
if (whole[i] != prefix[i]) {
break;
}
if (i == prefix.size()) {
for (; i < whole.size(); ++i)
srcIndices.push_back(whole[i]);
return true;
}
return false;
};
for (const auto &field : fields)
if (applyDiff(field.indices, dstPrefix)) {
const auto *srcField = srcFields.get(srcIndices);
if (!srcField)
return false;
field.counterVar.assign(srcField->getCounterVariable(builder, context),
builder);
for (uint32_t i = srcPrefix.size(); i < srcIndices.size(); ++i)
srcIndices.pop_back();
}
return true;
}
SemanticInfo DeclResultIdMapper::getStageVarSemantic(const NamedDecl *decl) {
for (auto *annotation : decl->getUnusualAnnotations()) {
if (auto *sema = dyn_cast<hlsl::SemanticDecl>(annotation)) {
llvm::StringRef semanticStr = sema->SemanticName;
llvm::StringRef semanticName;
uint32_t index = 0;
hlsl::Semantic::DecomposeNameAndIndex(semanticStr, &semanticName, &index);
const auto *semantic = hlsl::Semantic::GetByName(semanticName);
return {semanticStr, semantic, semanticName, index, sema->Loc};
}
}
return {};
}
bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
SpirvInstruction *storedValue,
bool forPCF) {
QualType type = getTypeOrFnRetType(decl);
uint32_t arraySize = 0;
// Output stream types (PointStream, LineStream, TriangleStream) are
// translated as their underlying struct types.
if (hlsl::IsHLSLStreamOutputType(type))
type = hlsl::GetHLSLResourceResultType(type);
if (decl->hasAttr<HLSLIndicesAttr>() || decl->hasAttr<HLSLVerticesAttr>() ||
decl->hasAttr<HLSLPrimitivesAttr>()) {
const auto *typeDecl = astContext.getAsConstantArrayType(type);
type = typeDecl->getElementType();
arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
if (decl->hasAttr<HLSLIndicesAttr>()) {
// create SPIR-V builtin array PrimitiveIndicesNV of type
// "uint [MaxPrimitiveCount * verticesPerPrim]"
uint32_t verticesPerPrim = 1;
if (!isVectorType(type, nullptr, &verticesPerPrim)) {
assert(isScalarType(type));
}
spv::BuiltIn builtinID = spv::BuiltIn::Max;
if (featureManager.isExtensionEnabled(Extension::EXT_mesh_shader)) {
// For EXT_mesh_shader, set builtin type as
// PrimitivePoint/Line/TriangleIndicesEXT based on the vertices per
// primitive
switch (verticesPerPrim) {
case 1:
builtinID = spv::BuiltIn::PrimitivePointIndicesEXT;
break;
case 2:
builtinID = spv::BuiltIn::PrimitiveLineIndicesEXT;
break;
case 3:
builtinID = spv::BuiltIn::PrimitiveTriangleIndicesEXT;
break;
default:
break;
}
QualType arrayType = astContext.getConstantArrayType(
type, llvm::APInt(32, arraySize), clang::ArrayType::Normal, 0);
msOutIndicesBuiltin =
getBuiltinVar(builtinID, arrayType, decl->getLocation());
} else {
// For NV_mesh_shader, the built type is PrimitiveIndicesNV
builtinID = spv::BuiltIn::PrimitiveIndicesNV;
arraySize = arraySize * verticesPerPrim;
QualType arrayType = astContext.getConstantArrayType(
astContext.UnsignedIntTy, llvm::APInt(32, arraySize),
clang::ArrayType::Normal, 0);
msOutIndicesBuiltin =
getBuiltinVar(builtinID, arrayType, decl->getLocation());
}
return true;
}
}
const auto *sigPoint = deduceSigPoint(
decl, /*asInput=*/false, spvContext.getCurrentShaderModelKind(), forPCF);
// HS output variables are created using the other overload. For the rest,
// none of them should be created as arrays.
assert(sigPoint->GetKind() != hlsl::DXIL::SigPointKind::HSCPOut);
SemanticInfo inheritSemantic = {};
// If storedValue is 0, it means this parameter in the original source code is
// not used at all. Avoid writing back.
//
// Write back of stage output variables in GS is manually controlled by
// .Append() intrinsic method, implemented in writeBackOutputStream(). So
// ignoreValue should be set to true for GS.
const bool noWriteBack =
storedValue == nullptr || spvContext.isGS() || spvContext.isMS();
StageVarDataBundle stageVarData = {
decl, &inheritSemantic, false, sigPoint,
type, arraySize, "out.var", llvm::None};
return createStageVars(stageVarData, /*asInput=*/false, &storedValue,
noWriteBack);
}
bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
uint32_t arraySize,
SpirvInstruction *invocationId,
SpirvInstruction *storedValue) {
assert(spvContext.isHS());
QualType type = getTypeOrFnRetType(decl);
const auto *sigPoint =
hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::HSCPOut);
SemanticInfo inheritSemantic = {};
StageVarDataBundle stageVarData = {
decl, &inheritSemantic, false, sigPoint,
type, arraySize, "out.var", invocationId};
return createStageVars(stageVarData, /*asInput=*/false, &storedValue,
/*noWriteBack=*/false);
}
bool DeclResultIdMapper::createStageInputVar(const ParmVarDecl *paramDecl,
SpirvInstruction **loadedValue,
bool forPCF) {
uint32_t arraySize = 0;
QualType type = paramDecl->getType();
// Deprive the outermost arrayness for HS/DS/GS and use arraySize
// to convey that information
if (hlsl::IsHLSLInputPatchType(type)) {
arraySize = hlsl::GetHLSLInputPatchCount(type);
type = hlsl::GetHLSLInputPatchElementType(type);
} else if (hlsl::IsHLSLOutputPatchType(type)) {
arraySize = hlsl::GetHLSLOutputPatchCount(type);
type = hlsl::GetHLSLOutputPatchElementType(type);
}
if (hasGSPrimitiveTypeQualifier(paramDecl)) {
const auto *typeDecl = astContext.getAsConstantArrayType(type);
arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
type = typeDecl->getElementType();
}
const auto *sigPoint =
deduceSigPoint(paramDecl, /*asInput=*/true,
spvContext.getCurrentShaderModelKind(), forPCF);
SemanticInfo inheritSemantic = {};
if (paramDecl->hasAttr<HLSLPayloadAttr>()) {
spv::StorageClass sc =
(featureManager.isExtensionEnabled(Extension::EXT_mesh_shader))
? spv::StorageClass::TaskPayloadWorkgroupEXT
: getStorageClassForSigPoint(sigPoint);
return createPayloadStageVars(sigPoint, sc, paramDecl, /*asInput=*/true,
type, "in.var", loadedValue);
} else {
StageVarDataBundle stageVarData = {
paramDecl,
&inheritSemantic,
paramDecl->hasAttr<HLSLNoInterpolationAttr>(),
sigPoint,
type,
arraySize,
"in.var",
llvm::None};
return createStageVars(stageVarData, /*asInput=*/true, loadedValue,
/*noWriteBack=*/false);
}
}
const DeclResultIdMapper::DeclSpirvInfo *
DeclResultIdMapper::getDeclSpirvInfo(const ValueDecl *decl) const {
auto it = astDecls.find(decl);
if (it != astDecls.end())
return &it->second;
return nullptr;
}
SpirvInstruction *DeclResultIdMapper::getDeclEvalInfo(const ValueDecl *decl,
SourceLocation loc,
SourceRange range) {
if (auto *builtinAttr = decl->getAttr<VKExtBuiltinInputAttr>()) {
return getBuiltinVar(spv::BuiltIn(builtinAttr->getBuiltInID()),
decl->getType(), spv::StorageClass::Input, loc);
} else if (auto *builtinAttr = decl->getAttr<VKExtBuiltinOutputAttr>()) {
return getBuiltinVar(spv::BuiltIn(builtinAttr->getBuiltInID()),
decl->getType(), spv::StorageClass::Output, loc);