-
Notifications
You must be signed in to change notification settings - Fork 673
/
SpirvEmitter.cpp
12007 lines (10778 loc) · 479 KB
/
SpirvEmitter.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
//===------- SpirvEmitter.cpp - SPIR-V Binary Code Emitter ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//===----------------------------------------------------------------------===//
//
// This file implements a SPIR-V emitter class that takes in HLSL AST and emits
// SPIR-V binary words.
//
//===----------------------------------------------------------------------===//
#include "SpirvEmitter.h"
#include "AlignmentSizeCalculator.h"
#include "RawBufferMethods.h"
#include "dxc/HlslIntrinsicOp.h"
#include "spirv-tools/optimizer.hpp"
#include "clang/SPIRV/AstTypeProbe.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/StringExtras.h"
#include "InitListHandler.h"
#include "dxc/DXIL/DxilConstants.h"
#ifdef SUPPORT_QUERY_GIT_COMMIT_INFO
#include "clang/Basic/Version.h"
#else
namespace clang {
uint32_t getGitCommitCount() { return 0; }
const char *getGitCommitHash() { return "<unknown-hash>"; }
} // namespace clang
#endif // SUPPORT_QUERY_GIT_COMMIT_INFO
namespace clang {
namespace spirv {
namespace {
// Returns true if the given decl has the given semantic.
bool hasSemantic(const DeclaratorDecl *decl,
hlsl::DXIL::SemanticKind semanticKind) {
using namespace hlsl;
for (auto *annotation : decl->getUnusualAnnotations()) {
if (auto *semanticDecl = dyn_cast<SemanticDecl>(annotation)) {
llvm::StringRef semanticName;
uint32_t semanticIndex = 0;
Semantic::DecomposeNameAndIndex(semanticDecl->SemanticName, &semanticName,
&semanticIndex);
const auto *semantic = Semantic::GetByName(semanticName);
if (semantic->GetKind() == semanticKind)
return true;
}
}
return false;
}
const ParmVarDecl *patchConstFuncTakesHullOutputPatch(FunctionDecl *pcf) {
for (const auto *param : pcf->parameters())
if (hlsl::IsHLSLOutputPatchType(param->getType()))
return param;
return nullptr;
}
inline bool isSpirvMatrixOp(spv::Op opcode) {
return opcode == spv::Op::OpMatrixTimesMatrix ||
opcode == spv::Op::OpMatrixTimesVector ||
opcode == spv::Op::OpMatrixTimesScalar;
}
/// If expr is a (RW)StructuredBuffer.Load(), returns the object and writes
/// index. Otherwiser, returns false.
// TODO: The following doesn't handle Load(int, int) yet. And it is basically a
// duplicate of doCXXMemberCallExpr.
const Expr *isStructuredBufferLoad(const Expr *expr, const Expr **index) {
using namespace hlsl;
if (const auto *indexing = dyn_cast<CXXMemberCallExpr>(expr)) {
const auto *callee = indexing->getDirectCallee();
uint32_t opcode = static_cast<uint32_t>(IntrinsicOp::Num_Intrinsics);
llvm::StringRef group;
if (GetIntrinsicOp(callee, opcode, group)) {
if (static_cast<IntrinsicOp>(opcode) == IntrinsicOp::MOP_Load) {
const auto *object = indexing->getImplicitObjectArgument();
if (isStructuredBuffer(object->getType())) {
*index = indexing->getArg(0);
return indexing->getImplicitObjectArgument();
}
}
}
}
return nullptr;
}
/// Returns true if the given VarDecl will be translated into a SPIR-V variable
/// not in the Private or Function storage class.
inline bool isExternalVar(const VarDecl *var) {
// Class static variables should be put in the Private storage class.
// groupshared variables are allowed to be declared as "static". But we still
// need to put them in the Workgroup storage class. That is, when seeing
// "static groupshared", ignore "static".
return var->hasExternalFormalLinkage()
? !var->isStaticDataMember()
: (var->getAttr<HLSLGroupSharedAttr>() != nullptr);
}
/// Returns the referenced variable's DeclContext if the given expr is
/// a DeclRefExpr referencing a ConstantBuffer/TextureBuffer. Otherwise,
/// returns nullptr.
const DeclContext *isConstantTextureBufferDeclRef(const Expr *expr) {
if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr->IgnoreParenCasts()))
if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
if (isConstantTextureBuffer(varDecl->getType()))
return hlsl::GetHLSLResourceResultType(varDecl->getType())
->getAs<RecordType>()
->getDecl();
return nullptr;
}
/// Returns true if
/// * the given expr is an DeclRefExpr referencing a kind of structured or byte
/// buffer and it is non-alias one, or
/// * the given expr is an CallExpr returning a kind of structured or byte
/// buffer.
/// * the given expr is an ArraySubscriptExpr referencing a kind of structured
/// or byte buffer.
///
/// Note: legalization specific code
bool isReferencingNonAliasStructuredOrByteBuffer(const Expr *expr) {
expr = expr->IgnoreParenCasts();
if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
if (const auto *varDecl = dyn_cast<VarDecl>(declRefExpr->getFoundDecl()))
if (isAKindOfStructuredOrByteBuffer(varDecl->getType()))
return isExternalVar(varDecl);
} else if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
if (isAKindOfStructuredOrByteBuffer(callExpr->getType()))
return true;
} else if (const auto *arrSubExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
return isReferencingNonAliasStructuredOrByteBuffer(arrSubExpr->getBase());
}
return false;
}
/// Translates atomic HLSL opcodes into the equivalent SPIR-V opcode.
spv::Op translateAtomicHlslOpcodeToSpirvOpcode(hlsl::IntrinsicOp opcode) {
using namespace hlsl;
using namespace spv;
switch (opcode) {
case IntrinsicOp::IOP_InterlockedAdd:
case IntrinsicOp::MOP_InterlockedAdd:
return Op::OpAtomicIAdd;
case IntrinsicOp::IOP_InterlockedAnd:
case IntrinsicOp::MOP_InterlockedAnd:
return Op::OpAtomicAnd;
case IntrinsicOp::IOP_InterlockedOr:
case IntrinsicOp::MOP_InterlockedOr:
return Op::OpAtomicOr;
case IntrinsicOp::IOP_InterlockedXor:
case IntrinsicOp::MOP_InterlockedXor:
return Op::OpAtomicXor;
case IntrinsicOp::IOP_InterlockedUMax:
case IntrinsicOp::MOP_InterlockedUMax:
return Op::OpAtomicUMax;
case IntrinsicOp::IOP_InterlockedUMin:
case IntrinsicOp::MOP_InterlockedUMin:
return Op::OpAtomicUMin;
case IntrinsicOp::IOP_InterlockedMax:
case IntrinsicOp::MOP_InterlockedMax:
return Op::OpAtomicSMax;
case IntrinsicOp::IOP_InterlockedMin:
case IntrinsicOp::MOP_InterlockedMin:
return Op::OpAtomicSMin;
case IntrinsicOp::IOP_InterlockedExchange:
case IntrinsicOp::MOP_InterlockedExchange:
return Op::OpAtomicExchange;
default:
// Only atomic opcodes are relevant.
break;
}
assert(false && "unimplemented hlsl intrinsic opcode");
return Op::Max;
}
// Returns true if the given opcode is an accepted binary opcode in
// OpSpecConstantOp.
bool isAcceptedSpecConstantBinaryOp(spv::Op op) {
switch (op) {
case spv::Op::OpIAdd:
case spv::Op::OpISub:
case spv::Op::OpIMul:
case spv::Op::OpUDiv:
case spv::Op::OpSDiv:
case spv::Op::OpUMod:
case spv::Op::OpSRem:
case spv::Op::OpSMod:
case spv::Op::OpShiftRightLogical:
case spv::Op::OpShiftRightArithmetic:
case spv::Op::OpShiftLeftLogical:
case spv::Op::OpBitwiseOr:
case spv::Op::OpBitwiseXor:
case spv::Op::OpBitwiseAnd:
case spv::Op::OpVectorShuffle:
case spv::Op::OpCompositeExtract:
case spv::Op::OpCompositeInsert:
case spv::Op::OpLogicalOr:
case spv::Op::OpLogicalAnd:
case spv::Op::OpLogicalNot:
case spv::Op::OpLogicalEqual:
case spv::Op::OpLogicalNotEqual:
case spv::Op::OpIEqual:
case spv::Op::OpINotEqual:
case spv::Op::OpULessThan:
case spv::Op::OpSLessThan:
case spv::Op::OpUGreaterThan:
case spv::Op::OpSGreaterThan:
case spv::Op::OpULessThanEqual:
case spv::Op::OpSLessThanEqual:
case spv::Op::OpUGreaterThanEqual:
case spv::Op::OpSGreaterThanEqual:
return true;
default:
// Accepted binary opcodes return true. Anything else is false.
return false;
}
return false;
}
/// Returns true if the given expression is an accepted initializer for a spec
/// constant.
bool isAcceptedSpecConstantInit(const Expr *init) {
// Allow numeric casts
init = init->IgnoreParenCasts();
if (isa<CXXBoolLiteralExpr>(init) || isa<IntegerLiteral>(init) ||
isa<FloatingLiteral>(init))
return true;
// Allow the minus operator which is used to specify negative values
if (const auto *unaryOp = dyn_cast<UnaryOperator>(init))
return unaryOp->getOpcode() == UO_Minus &&
isAcceptedSpecConstantInit(unaryOp->getSubExpr());
return false;
}
/// Returns true if the given function parameter can act as shader stage
/// input parameter.
inline bool canActAsInParmVar(const ParmVarDecl *param) {
// If the parameter has no in/out/inout attribute, it is defaulted to
// an in parameter.
return !param->hasAttr<HLSLOutAttr>() &&
// GS output streams are marked as inout, but it should not be
// used as in parameter.
!hlsl::IsHLSLStreamOutputType(param->getType());
}
/// Returns true if the given function parameter can act as shader stage
/// output parameter.
inline bool canActAsOutParmVar(const ParmVarDecl *param) {
return param->hasAttr<HLSLOutAttr>() || param->hasAttr<HLSLInOutAttr>() ||
hlsl::IsHLSLRayQueryType(param->getType());
}
/// Returns true if the given expression is of builtin type and can be evaluated
/// to a constant zero. Returns false otherwise.
inline bool evaluatesToConstZero(const Expr *expr, ASTContext &astContext) {
const auto type = expr->getType();
if (!type->isBuiltinType())
return false;
Expr::EvalResult evalResult;
if (expr->EvaluateAsRValue(evalResult, astContext) &&
!evalResult.HasSideEffects) {
const auto &val = evalResult.Val;
return ((type->isBooleanType() && !val.getInt().getBoolValue()) ||
(type->isIntegerType() && !val.getInt().getBoolValue()) ||
(type->isFloatingType() && val.getFloat().isZero()));
}
return false;
}
/// Returns the real definition of the callee of the given CallExpr.
///
/// If we are calling a forward-declared function, callee will be the
/// FunctionDecl for the foward-declared function, not the actual
/// definition. The foward-delcaration and defintion are two completely
/// different AST nodes.
inline const FunctionDecl *getCalleeDefinition(const CallExpr *expr) {
const auto *callee = expr->getDirectCallee();
if (callee->isThisDeclarationADefinition())
return callee;
// We need to update callee to the actual definition here
if (!callee->isDefined(callee))
return nullptr;
return callee;
}
/// Returns the referenced definition. The given expr is expected to be a
/// DeclRefExpr or CallExpr after ignoring casts. Returns nullptr otherwise.
const DeclaratorDecl *getReferencedDef(const Expr *expr) {
if (!expr)
return nullptr;
expr = expr->IgnoreParenCasts();
if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
return dyn_cast_or_null<DeclaratorDecl>(declRefExpr->getDecl());
}
if (const auto *callExpr = dyn_cast<CallExpr>(expr)) {
return getCalleeDefinition(callExpr);
}
return nullptr;
}
/// 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;
}
/// Gets the index sequence of casting a derived object to a base object by
/// following the cast chain.
void getBaseClassIndices(const CastExpr *expr,
llvm::SmallVectorImpl<uint32_t> *indices) {
assert(expr->getCastKind() == CK_UncheckedDerivedToBase ||
expr->getCastKind() == CK_HLSLDerivedToBase);
indices->clear();
QualType derivedType = expr->getSubExpr()->getType();
const auto *derivedDecl = derivedType->getAsCXXRecordDecl();
// Go through the base cast chain: for each of the derived to base cast, find
// the index of the base in question in the derived's bases.
for (auto pathIt = expr->path_begin(), pathIe = expr->path_end();
pathIt != pathIe; ++pathIt) {
// The type of the base in question
const auto baseType = (*pathIt)->getType();
uint32_t index = 0;
for (auto baseIt = derivedDecl->bases_begin(),
baseIe = derivedDecl->bases_end();
baseIt != baseIe; ++baseIt, ++index)
if (baseIt->getType() == baseType) {
indices->push_back(index);
break;
}
assert(index < derivedDecl->getNumBases());
// Continue to proceed the next base in the chain
derivedType = baseType;
derivedDecl = derivedType->getAsCXXRecordDecl();
}
}
std::string getNamespacePrefix(const Decl *decl) {
std::string nsPrefix = "";
const DeclContext *dc = decl->getDeclContext();
while (dc && !dc->isTranslationUnit()) {
if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(dc)) {
if (!ns->isAnonymousNamespace()) {
nsPrefix = ns->getName().str() + "::" + nsPrefix;
}
}
dc = dc->getParent();
}
return nsPrefix;
}
std::string getFnName(const FunctionDecl *fn) {
// Prefix the function name with the struct name if necessary
std::string classOrStructName = "";
if (const auto *memberFn = dyn_cast<CXXMethodDecl>(fn))
if (const auto *st = dyn_cast<CXXRecordDecl>(memberFn->getDeclContext()))
classOrStructName = st->getName().str() + ".";
return getNamespacePrefix(fn) + classOrStructName + fn->getName().str();
}
} // namespace
SpirvEmitter::SpirvEmitter(CompilerInstance &ci)
: theCompilerInstance(ci), astContext(ci.getASTContext()),
diags(ci.getDiagnostics()),
spirvOptions(ci.getCodeGenOpts().SpirvOptions),
entryFunctionName(ci.getCodeGenOpts().HLSLEntryFunction), spvContext(),
featureManager(diags, spirvOptions),
spvBuilder(astContext, spvContext, spirvOptions),
declIdMapper(astContext, spvContext, spvBuilder, *this, featureManager,
spirvOptions),
entryFunction(nullptr), curFunction(nullptr), curThis(nullptr),
seenPushConstantAt(), isSpecConstantMode(false), needsLegalization(false),
beforeHlslLegalization(false), mainSourceFile(nullptr) {
// Get ShaderModel from command line hlsl profile option.
const hlsl::ShaderModel *shaderModel =
hlsl::ShaderModel::GetByName(ci.getCodeGenOpts().HLSLProfile.c_str());
if (shaderModel->GetKind() == hlsl::ShaderModel::Kind::Invalid)
emitError("unknown shader module: %0", {}) << shaderModel->GetName();
if (spirvOptions.invertY && !shaderModel->IsVS() && !shaderModel->IsDS() &&
!shaderModel->IsGS())
emitError("-fvk-invert-y can only be used in VS/DS/GS", {});
if (spirvOptions.useGlLayout && spirvOptions.useDxLayout)
emitError("cannot specify both -fvk-use-dx-layout and -fvk-use-gl-layout",
{});
// Set shader model kind and hlsl major/minor version.
spvContext.setCurrentShaderModelKind(shaderModel->GetKind());
spvContext.setMajorVersion(shaderModel->GetMajor());
spvContext.setMinorVersion(shaderModel->GetMinor());
if (spirvOptions.useDxLayout) {
spirvOptions.cBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
spirvOptions.tBufferLayoutRule = SpirvLayoutRule::FxcCTBuffer;
spirvOptions.sBufferLayoutRule = SpirvLayoutRule::FxcSBuffer;
spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::FxcSBuffer;
} else if (spirvOptions.useGlLayout) {
spirvOptions.cBufferLayoutRule = SpirvLayoutRule::GLSLStd140;
spirvOptions.tBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
spirvOptions.sBufferLayoutRule = SpirvLayoutRule::GLSLStd430;
spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::GLSLStd430;
} else if (spirvOptions.useScalarLayout) {
spirvOptions.cBufferLayoutRule = SpirvLayoutRule::Scalar;
spirvOptions.tBufferLayoutRule = SpirvLayoutRule::Scalar;
spirvOptions.sBufferLayoutRule = SpirvLayoutRule::Scalar;
spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::Scalar;
} else {
spirvOptions.cBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd140;
spirvOptions.tBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
spirvOptions.sBufferLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
spirvOptions.ampPayloadLayoutRule = SpirvLayoutRule::RelaxedGLSLStd430;
}
// Set shader module version, source file name, and source file content (if
// needed).
llvm::StringRef source;
std::vector<llvm::StringRef> fileNames;
const auto &inputFiles = ci.getFrontendOpts().Inputs;
// File name
if (spirvOptions.debugInfoFile && !inputFiles.empty()) {
for (const auto &inputFile : inputFiles) {
fileNames.push_back(inputFile.getFile());
}
}
// Source code
if (spirvOptions.debugInfoSource) {
const auto &sm = ci.getSourceManager();
const llvm::MemoryBuffer *mainFile =
sm.getBuffer(sm.getMainFileID(), SourceLocation());
source = StringRef(mainFile->getBufferStart(), mainFile->getBufferSize());
}
mainSourceFile = spvBuilder.setDebugSource(spvContext.getMajorVersion(),
spvContext.getMinorVersion(),
fileNames, source);
// OpenCL.DebugInfo.100 DebugSource
if (spirvOptions.debugInfoRich) {
auto *dbgSrc = spvBuilder.createDebugSource(mainSourceFile->getString());
// spvContext.getDebugInfo().insert() inserts {string key, RichDebugInfo}
// pair and returns {{string key, RichDebugInfo}, true /*Success*/}.
// spvContext.getDebugInfo().insert().first->second is a RichDebugInfo.
auto *richDebugInfo =
&spvContext.getDebugInfo()
.insert(
{mainSourceFile->getString(),
RichDebugInfo(dbgSrc,
spvBuilder.createDebugCompilationUnit(dbgSrc))})
.first->second;
spvContext.pushDebugLexicalScope(richDebugInfo,
richDebugInfo->scopeStack.back());
}
if (spirvOptions.debugInfoTool &&
spirvOptions.targetEnv.compare("vulkan1.1") >= 0) {
// Emit OpModuleProcessed to indicate the commit information.
std::string commitHash =
std::string("dxc-commit-hash: ") + clang::getGitCommitHash();
spvBuilder.addModuleProcessed(commitHash);
// Emit OpModuleProcessed to indicate the command line options that were
// used to generate this module.
if (!spirvOptions.clOptions.empty()) {
// Using this format: "dxc-cl-option: XXXXXX"
std::string clOptionStr = "dxc-cl-option:" + spirvOptions.clOptions;
spvBuilder.addModuleProcessed(clOptionStr);
}
}
}
void SpirvEmitter::HandleTranslationUnit(ASTContext &context) {
// Stop translating if there are errors in previous compilation stages.
if (context.getDiagnostics().hasErrorOccurred())
return;
TranslationUnitDecl *tu = context.getTranslationUnitDecl();
uint32_t numEntryPoints = 0;
// The entry function is the seed of the queue.
for (auto *decl : tu->decls()) {
if (auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
if (spvContext.isLib()) {
if (const auto *shaderAttr = funcDecl->getAttr<HLSLShaderAttr>()) {
// If we are compiling as a library then add everything that has a
// ShaderAttr.
addFunctionToWorkQueue(getShaderModelKind(shaderAttr->getStage()),
funcDecl, /*isEntryFunction*/ true);
numEntryPoints++;
}
} else {
if (funcDecl->getName() == entryFunctionName) {
addFunctionToWorkQueue(spvContext.getCurrentShaderModelKind(),
funcDecl, /*isEntryFunction*/ true);
numEntryPoints++;
}
}
} else {
doDecl(decl);
}
if (context.getDiagnostics().hasErrorOccurred())
return;
}
// Translate all functions reachable from the entry function.
// The queue can grow in the meanwhile; so need to keep evaluating
// workQueue.size().
for (uint32_t i = 0; i < workQueue.size(); ++i) {
const FunctionInfo *curEntryOrCallee = workQueue[i];
spvContext.setCurrentShaderModelKind(curEntryOrCallee->shaderModelKind);
doDecl(curEntryOrCallee->funcDecl);
if (context.getDiagnostics().hasErrorOccurred())
return;
}
const spv_target_env targetEnv = featureManager.getTargetEnv();
// Addressing and memory model are required in a valid SPIR-V module.
spvBuilder.setMemoryModel(spv::AddressingModel::Logical,
spv::MemoryModel::GLSL450);
// Even though the 'workQueue' grows due to the above loop, the first
// 'numEntryPoints' entries in the 'workQueue' are the ones with the HLSL
// 'shader' attribute, and must therefore be entry functions.
assert(numEntryPoints <= workQueue.size());
for (uint32_t i = 0; i < numEntryPoints; ++i) {
// TODO: assign specific StageVars w.r.t. to entry point
const FunctionInfo *entryInfo = workQueue[i];
assert(entryInfo->isEntryFunction);
spvBuilder.addEntryPoint(
getSpirvShaderStage(entryInfo->shaderModelKind),
entryInfo->entryFunction, entryInfo->funcDecl->getName(),
targetEnv == SPV_ENV_VULKAN_1_2
? spvBuilder.getModule()->getVariables()
: llvm::ArrayRef<SpirvVariable *>(declIdMapper.collectStageVars()));
}
// Add Location decorations to stage input/output variables.
if (!declIdMapper.decorateStageIOLocations())
return;
// Add descriptor set and binding decorations to resource variables.
if (!declIdMapper.decorateResourceBindings())
return;
// Add Coherent docrations to resource variables.
if (!declIdMapper.decorateResourceCoherent())
return;
// Output the constructed module.
std::vector<uint32_t> m = spvBuilder.takeModule();
if (!spirvOptions.codeGenHighLevel) {
// In order to flatten composite resources, we must also unroll loops.
// Therefore we should run legalization before optimization.
needsLegalization = needsLegalization ||
declIdMapper.requiresLegalization() ||
spirvOptions.flattenResourceArrays ||
declIdMapper.requiresFlatteningCompositeResources();
// Run legalization passes
if (needsLegalization) {
std::string messages;
if (!spirvToolsLegalize(&m, &messages)) {
emitFatalError("failed to legalize SPIR-V: %0", {}) << messages;
emitNote("please file a bug report on "
"https://github.com/Microsoft/DirectXShaderCompiler/issues "
"with source code if possible",
{});
return;
} else if (!messages.empty()) {
emitWarning("SPIR-V legalization: %0", {}) << messages;
}
}
// Run optimization passes
if (theCompilerInstance.getCodeGenOpts().OptimizationLevel > 0) {
std::string messages;
if (!spirvToolsOptimize(&m, &messages)) {
emitFatalError("failed to optimize SPIR-V: %0", {}) << messages;
emitNote("please file a bug report on "
"https://github.com/Microsoft/DirectXShaderCompiler/issues "
"with source code if possible",
{});
return;
}
}
}
// Validate the generated SPIR-V code
if (!spirvOptions.disableValidation) {
std::string messages;
if (!spirvToolsValidate(&m, &messages)) {
emitFatalError("generated SPIR-V is invalid: %0", {}) << messages;
emitNote("please file a bug report on "
"https://github.com/Microsoft/DirectXShaderCompiler/issues "
"with source code if possible",
{});
return;
}
}
theCompilerInstance.getOutStream()->write(
reinterpret_cast<const char *>(m.data()), m.size() * 4);
}
void SpirvEmitter::doDecl(const Decl *decl) {
if (isa<EmptyDecl>(decl) || isa<TypedefDecl>(decl))
return;
// Implicit decls are lazily created when needed.
if (decl->isImplicit()) {
return;
}
if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
doVarDecl(varDecl);
} else if (const auto *namespaceDecl = dyn_cast<NamespaceDecl>(decl)) {
for (auto *subDecl : namespaceDecl->decls())
// Note: We only emit functions as they are discovered through the call
// graph starting from the entry-point. We should not emit unused
// functions inside namespaces.
if (!isa<FunctionDecl>(subDecl))
doDecl(subDecl);
} else if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
doFunctionDecl(funcDecl);
} else if (const auto *bufferDecl = dyn_cast<HLSLBufferDecl>(decl)) {
doHLSLBufferDecl(bufferDecl);
} else if (const auto *recordDecl = dyn_cast<RecordDecl>(decl)) {
doRecordDecl(recordDecl);
} else if (const auto *enumDecl = dyn_cast<EnumDecl>(decl)) {
doEnumDecl(enumDecl);
} else {
emitError("decl type %0 unimplemented", decl->getLocation())
<< decl->getDeclKindName();
}
}
RichDebugInfo *
SpirvEmitter::getOrCreateRichDebugInfo(const SourceLocation &loc) {
const StringRef file =
astContext.getSourceManager().getPresumedLoc(loc).getFilename();
auto &debugInfo = spvContext.getDebugInfo();
auto it = debugInfo.find(file);
if (it != debugInfo.end())
return &it->second;
auto *dbgSrc = spvBuilder.createDebugSource(file);
// debugInfo.insert() inserts {string key, RichDebugInfo} pair and
// returns {{string key, RichDebugInfo}, true /*Success*/}.
// debugInfo.insert().first->second is a RichDebugInfo.
return &debugInfo
.insert({file, RichDebugInfo(
dbgSrc, spvBuilder.createDebugCompilationUnit(
dbgSrc))})
.first->second;
}
void SpirvEmitter::doStmt(const Stmt *stmt,
llvm::ArrayRef<const Attr *> attrs) {
if (const auto *compoundStmt = dyn_cast<CompoundStmt>(stmt)) {
if (spirvOptions.debugInfoRich) {
// Any opening of curly braces ('{') starts a CompoundStmt in the AST
// tree. It also means we have a new lexical block!
const auto loc = stmt->getLocStart();
const auto &sm = astContext.getSourceManager();
const uint32_t line = sm.getPresumedLineNumber(loc);
const uint32_t column = sm.getPresumedColumnNumber(loc);
RichDebugInfo *info = getOrCreateRichDebugInfo(loc);
auto *debugLexicalBlock = spvBuilder.createDebugLexicalBlock(
info->source, line, column, info->scopeStack.back());
// Add this lexical block to the stack of lexical scopes.
spvContext.pushDebugLexicalScope(info, debugLexicalBlock);
// Update or add DebugScope.
if (spvBuilder.getInsertPoint()->empty()) {
spvBuilder.getInsertPoint()->updateDebugScope(
new (spvContext) SpirvDebugScope(debugLexicalBlock));
} else if (!spvBuilder.isCurrentBasicBlockTerminated()) {
spvBuilder.createDebugScope(debugLexicalBlock);
}
// Iterate over sub-statements
for (auto *st : compoundStmt->body())
doStmt(st);
// We are done with processing this compound statement. Remove its lexical
// block from the stack of lexical scopes.
spvContext.popDebugLexicalScope(info);
if (!spvBuilder.isCurrentBasicBlockTerminated()) {
spvBuilder.createDebugScope(spvContext.getCurrentLexicalScope());
}
} else {
// Iterate over sub-statements
for (auto *st : compoundStmt->body())
doStmt(st);
}
} else if (const auto *retStmt = dyn_cast<ReturnStmt>(stmt)) {
doReturnStmt(retStmt);
} else if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) {
doDeclStmt(declStmt);
} else if (const auto *ifStmt = dyn_cast<IfStmt>(stmt)) {
doIfStmt(ifStmt, attrs);
} else if (const auto *switchStmt = dyn_cast<SwitchStmt>(stmt)) {
doSwitchStmt(switchStmt, attrs);
} else if (dyn_cast<CaseStmt>(stmt)) {
processCaseStmtOrDefaultStmt(stmt);
} else if (dyn_cast<DefaultStmt>(stmt)) {
processCaseStmtOrDefaultStmt(stmt);
} else if (const auto *breakStmt = dyn_cast<BreakStmt>(stmt)) {
doBreakStmt(breakStmt);
} else if (const auto *theDoStmt = dyn_cast<DoStmt>(stmt)) {
doDoStmt(theDoStmt, attrs);
} else if (const auto *discardStmt = dyn_cast<DiscardStmt>(stmt)) {
doDiscardStmt(discardStmt);
} else if (const auto *continueStmt = dyn_cast<ContinueStmt>(stmt)) {
doContinueStmt(continueStmt);
} else if (const auto *whileStmt = dyn_cast<WhileStmt>(stmt)) {
doWhileStmt(whileStmt, attrs);
} else if (const auto *forStmt = dyn_cast<ForStmt>(stmt)) {
doForStmt(forStmt, attrs);
} else if (dyn_cast<NullStmt>(stmt)) {
// For the null statement ";". We don't need to do anything.
} else if (const auto *expr = dyn_cast<Expr>(stmt)) {
// All cases for expressions used as statements
doExpr(expr);
} else if (const auto *attrStmt = dyn_cast<AttributedStmt>(stmt)) {
doStmt(attrStmt->getSubStmt(), attrStmt->getAttrs());
} else {
emitError("statement class '%0' unimplemented", stmt->getLocStart())
<< stmt->getStmtClassName() << stmt->getSourceRange();
}
}
SpirvInstruction *SpirvEmitter::doExpr(const Expr *expr) {
SpirvInstruction *result = nullptr;
expr = expr->IgnoreParens();
if (const auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
result = declIdMapper.getDeclEvalInfo(declRefExpr->getDecl(),
expr->getLocStart());
} else if (const auto *memberExpr = dyn_cast<MemberExpr>(expr)) {
result = doMemberExpr(memberExpr);
} else if (const auto *castExpr = dyn_cast<CastExpr>(expr)) {
result = doCastExpr(castExpr);
} else if (const auto *initListExpr = dyn_cast<InitListExpr>(expr)) {
result = doInitListExpr(initListExpr);
} else if (const auto *boolLiteral = dyn_cast<CXXBoolLiteralExpr>(expr)) {
result =
spvBuilder.getConstantBool(boolLiteral->getValue(), isSpecConstantMode);
result->setRValue();
} else if (const auto *intLiteral = dyn_cast<IntegerLiteral>(expr)) {
result = translateAPInt(intLiteral->getValue(), expr->getType());
result->setRValue();
} else if (const auto *floatLiteral = dyn_cast<FloatingLiteral>(expr)) {
result = translateAPFloat(floatLiteral->getValue(), expr->getType());
result->setRValue();
} else if (const auto *stringLiteral = dyn_cast<StringLiteral>(expr)) {
result = spvBuilder.getString(stringLiteral->getString());
} else if (const auto *compoundAssignOp =
dyn_cast<CompoundAssignOperator>(expr)) {
// CompoundAssignOperator is a subclass of BinaryOperator. It should be
// checked before BinaryOperator.
result = doCompoundAssignOperator(compoundAssignOp);
} else if (const auto *binOp = dyn_cast<BinaryOperator>(expr)) {
result = doBinaryOperator(binOp);
} else if (const auto *unaryOp = dyn_cast<UnaryOperator>(expr)) {
result = doUnaryOperator(unaryOp);
} else if (const auto *vecElemExpr = dyn_cast<HLSLVectorElementExpr>(expr)) {
result = doHLSLVectorElementExpr(vecElemExpr);
} else if (const auto *matElemExpr = dyn_cast<ExtMatrixElementExpr>(expr)) {
result = doExtMatrixElementExpr(matElemExpr);
} else if (const auto *funcCall = dyn_cast<CallExpr>(expr)) {
result = doCallExpr(funcCall);
} else if (const auto *subscriptExpr = dyn_cast<ArraySubscriptExpr>(expr)) {
result = doArraySubscriptExpr(subscriptExpr);
} else if (const auto *condExpr = dyn_cast<ConditionalOperator>(expr)) {
result = doConditionalOperator(condExpr);
} else if (const auto *defaultArgExpr = dyn_cast<CXXDefaultArgExpr>(expr)) {
result = doExpr(defaultArgExpr->getParam()->getDefaultArg());
} else if (isa<CXXThisExpr>(expr)) {
assert(curThis);
result = curThis;
} else if (isa<CXXConstructExpr>(expr)) {
result = curThis;
} else if (const auto *unaryExpr = dyn_cast<UnaryExprOrTypeTraitExpr>(expr)) {
result = doUnaryExprOrTypeTraitExpr(unaryExpr);
} else {
emitError("expression class '%0' unimplemented", expr->getExprLoc())
<< expr->getStmtClassName() << expr->getSourceRange();
}
return result;
}
SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr) {
// We are trying to load the value here, which is what an LValueToRValue
// implicit cast is intended to do. We can ignore the cast if exists.
expr = expr->IgnoreParenLValueCasts();
return loadIfGLValue(expr, doExpr(expr));
}
SpirvInstruction *SpirvEmitter::loadIfGLValue(const Expr *expr,
SpirvInstruction *info) {
const auto exprType = expr->getType();
// Do nothing if this is already rvalue
if (!info || info->isRValue())
return info;
// Check whether we are trying to load an array of opaque objects as a whole.
// If true, we are likely to copy it as a whole. To assist per-element
// copying, avoid the load here and return the pointer directly.
// TODO: consider moving this hack into SPIRV-Tools as a transformation.
if (isOpaqueArrayType(exprType))
return info;
// Check whether we are trying to load an externally visible structured/byte
// buffer as a whole. If true, it means we are creating alias for it. Avoid
// the load and write the pointer directly to the alias variable then.
//
// Also for the case of alias function returns. If we are trying to load an
// alias function return as a whole, it means we are assigning it to another
// alias variable. Avoid the load and write the pointer directly.
//
// Note: legalization specific code
if (isReferencingNonAliasStructuredOrByteBuffer(expr)) {
return info;
}
if (loadIfAliasVarRef(expr, &info)) {
// We are loading an alias variable as a whole here. This is likely for
// wholesale assignments or function returns. Need to load the pointer.
//
// Note: legalization specific code
return info;
}
SpirvInstruction *loadedInstr = nullptr;
// TODO: Ouch. Very hacky. We need special path to get the value type if
// we are loading a whole ConstantBuffer/TextureBuffer since the normal
// type translation path won't work.
if (const auto *declContext = isConstantTextureBufferDeclRef(expr)) {
loadedInstr = spvBuilder.createLoad(
declIdMapper.getCTBufferPushConstantType(declContext), info,
expr->getExprLoc());
} else {
loadedInstr = spvBuilder.createLoad(exprType, info, expr->getExprLoc());
}
assert(loadedInstr);
// Special-case: According to the SPIR-V Spec: There is no physical size or
// bit pattern defined for boolean type. Therefore an unsigned integer is used
// to represent booleans when layout is required. In such cases, after loading
// the uint, we should perform a comparison.
{
uint32_t vecSize = 1, numRows = 0, numCols = 0;
if (info->getLayoutRule() != SpirvLayoutRule::Void &&
isBoolOrVecMatOfBoolType(exprType)) {
QualType uintType = astContext.UnsignedIntTy;
if (isScalarType(exprType) || isVectorType(exprType, nullptr, &vecSize)) {
const auto fromType =
vecSize == 1 ? uintType
: astContext.getExtVectorType(uintType, vecSize);
loadedInstr =
castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
} else {
const bool isMat = isMxNMatrix(exprType, nullptr, &numRows, &numCols);
assert(isMat);
(void)isMat;
const clang::Type *type = exprType.getCanonicalType().getTypePtr();
const RecordType *RT = cast<RecordType>(type);
const ClassTemplateSpecializationDecl *templateSpecDecl =
cast<ClassTemplateSpecializationDecl>(RT->getDecl());
ClassTemplateDecl *templateDecl =
templateSpecDecl->getSpecializedTemplate();
const auto fromType = getHLSLMatrixType(
astContext, theCompilerInstance.getSema(), templateDecl,
astContext.UnsignedIntTy, numRows, numCols);
loadedInstr =
castToBool(loadedInstr, fromType, exprType, expr->getLocStart());
}
// Now that it is converted to Bool, it has no layout rule.
// This result-id should be evaluated as bool from here on out.
loadedInstr->setLayoutRule(SpirvLayoutRule::Void);
}
}
loadedInstr->setRValue();
return loadedInstr;
}
SpirvInstruction *SpirvEmitter::loadIfAliasVarRef(const Expr *expr) {
auto *instr = doExpr(expr);
loadIfAliasVarRef(expr, &instr);
return instr;
}
bool SpirvEmitter::loadIfAliasVarRef(const Expr *varExpr,
SpirvInstruction **instr) {
assert(instr);
if ((*instr) && (*instr)->containsAliasComponent() &&
isAKindOfStructuredOrByteBuffer(varExpr->getType())) {
// Load the pointer of the aliased-to-variable if the expression has a
// pointer to pointer type.
if (varExpr->isGLValue()) {
*instr = spvBuilder.createLoad(varExpr->getType(), *instr,
varExpr->getExprLoc());
}
return true;
}
return false;
}
SpirvInstruction *SpirvEmitter::castToType(SpirvInstruction *value,
QualType fromType, QualType toType,
SourceLocation srcLoc) {
if (isFloatOrVecMatOfFloatType(toType))
return castToFloat(value, fromType, toType, srcLoc);
// Order matters here. Bool (vector) values will also be considered as uint
// (vector) values. So given a bool (vector) argument, isUintOrVecOfUintType()
// will also return true. We need to check bool before uint. The opposite is
// not true.
if (isBoolOrVecMatOfBoolType(toType))
return castToBool(value, fromType, toType, srcLoc);
if (isSintOrVecMatOfSintType(toType) || isUintOrVecMatOfUintType(toType))
return castToInt(value, fromType, toType, srcLoc);
emitError("casting to type %0 unimplemented", {}) << toType;
return nullptr;
}
void SpirvEmitter::doFunctionDecl(const FunctionDecl *decl) {
assert(decl->isThisDeclarationADefinition());
// A RAII class for maintaining the current function under traversal.
class FnEnvRAII {
public:
// Creates a new instance which sets fnEnv to the newFn on creation,
// and resets fnEnv to its original value on destruction.
FnEnvRAII(const FunctionDecl **fnEnv, const FunctionDecl *newFn)
: oldFn(*fnEnv), fnSlot(fnEnv) {
*fnEnv = newFn;
}
~FnEnvRAII() { *fnSlot = oldFn; }
private:
const FunctionDecl *oldFn;
const FunctionDecl **fnSlot;
};
FnEnvRAII fnEnvRAII(&curFunction, decl);
// We are about to start translation for a new function. Clear the break stack
// and the continue stack.
breakStack = std::stack<SpirvBasicBlock *>();
continueStack = std::stack<SpirvBasicBlock *>();
// This will allow the entry-point name to be something like
// myNamespace::myEntrypointFunc.