forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCGHLSLMS.cpp
More file actions
5900 lines (5296 loc) · 217 KB
/
CGHLSLMS.cpp
File metadata and controls
5900 lines (5296 loc) · 217 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
//===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
///////////////////////////////////////////////////////////////////////////////
// //
// CGHLSLMS.cpp //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// This provides a class for HLSL code generation. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "CGHLSLRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "CGRecordLayout.h"
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/HLSL/HLMatrixLowerHelper.h"
#include "dxc/HLSL/HLModule.h"
#include "dxc/HLSL/HLOperations.h"
#include "dxc/HLSL/DxilOperations.h"
#include "dxc/HLSL/DxilTypeSystem.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/HlslTypes.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/Lex/HLSLMacroExpander.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include "dxc/HLSL/DxilRootSignature.h"
#include "dxc/HLSL/DxilCBuffer.h"
#include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
#include "dxc/Support/WinIncludes.h" // stream support
#include "dxc/dxcapi.h" // stream support
#include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
using namespace clang;
using namespace CodeGen;
using namespace hlsl;
using namespace llvm;
using std::unique_ptr;
static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
namespace {
/// Use this class to represent HLSL cbuffer in high-level DXIL.
class HLCBuffer : public DxilCBuffer {
public:
HLCBuffer() = default;
virtual ~HLCBuffer() = default;
void AddConst(std::unique_ptr<DxilResourceBase> &pItem);
std::vector<std::unique_ptr<DxilResourceBase>> &GetConstants();
private:
std::vector<std::unique_ptr<DxilResourceBase>> constants; // constants inside const buffer
};
//------------------------------------------------------------------------------
//
// HLCBuffer methods.
//
void HLCBuffer::AddConst(std::unique_ptr<DxilResourceBase> &pItem) {
pItem->SetID(constants.size());
constants.push_back(std::move(pItem));
}
std::vector<std::unique_ptr<DxilResourceBase>> &HLCBuffer::GetConstants() {
return constants;
}
class CGMSHLSLRuntime : public CGHLSLRuntime {
private:
/// Convenience reference to LLVM Context
llvm::LLVMContext &Context;
/// Convenience reference to the current module
llvm::Module &TheModule;
HLModule *m_pHLModule;
llvm::Type *CBufferType;
uint32_t globalCBIndex;
// TODO: make sure how minprec works
llvm::DataLayout legacyLayout;
// decl map to constant id for program
llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
// Map for resource type to resource metadata value.
std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
bool m_bDebugInfo;
bool m_bIsLib;
HLCBuffer &GetGlobalCBuffer() {
return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
}
void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
uint32_t AddSampler(VarDecl *samplerDecl);
uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
DxilResource *hlslRes, const RecordDecl *RD);
uint32_t AddCBuffer(HLSLBufferDecl *D);
hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
// Save the entryFunc so don't need to find it with original name.
llvm::Function *EntryFunc;
// Map to save patch constant functions
StringMap<Function *> patchConstantFunctionMap;
std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
patchConstantFunctionPropsMap;
bool IsPatchConstantFunction(const Function *F);
// Map to save entry functions.
StringMap<Function *> entryFunctionMap;
// List for functions with clip plane.
std::vector<Function *> clipPlaneFuncList;
std::unordered_map<Value *, DebugLoc> debugInfoMap;
DxilRootSignatureVersion rootSigVer;
Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
QualType Ty);
// Flatten the val into scalar val and push into elts and eltTys.
void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
SmallVector<QualType, 4> &eltTys, QualType Ty,
Value *val);
// Push every value on InitListExpr into EltValList and EltTyList.
void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
SmallVector<Value *, 4> &EltValList,
SmallVector<QualType, 4> &EltTyList);
void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
SmallVector<Value *, 4> &idxList,
clang::QualType Type, llvm::Type *Ty,
SmallVector<Value *, 4> &GepList,
SmallVector<QualType, 4> &EltTyList);
void LoadFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
ArrayRef<QualType> EltTyList,
SmallVector<Value *, 4> &EltList);
void StoreFlattenedGepList(CodeGenFunction &CGF, ArrayRef<Value *> GepList,
ArrayRef<QualType> GepTyList,
ArrayRef<Value *> EltValList,
ArrayRef<QualType> SrcTyList);
void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
llvm::Value *DestPtr,
SmallVector<Value *, 4> &idxList,
clang::QualType SrcType,
clang::QualType DestType,
llvm::Type *Ty);
void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *SrcVal,
llvm::Value *DestPtr,
SmallVector<Value *, 4> &idxList,
QualType Type, QualType SrcType,
llvm::Type *Ty);
void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
llvm::Function *Fn);
void CheckParameterAnnotation(SourceLocation SLoc,
const DxilParameterAnnotation ¶mInfo,
bool isPatchConstantFunction);
void CheckParameterAnnotation(SourceLocation SLoc,
DxilParamInputQual paramQual,
llvm::StringRef semFullName,
bool isPatchConstantFunction);
void SetEntryFunction();
SourceLocation SetSemantic(const NamedDecl *decl,
DxilParameterAnnotation ¶mInfo);
hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
bool bKeepUndefined);
hlsl::CompType GetCompType(const BuiltinType *BT);
// save intrinsic opcode
std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
// Type annotation related.
unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
const RecordDecl *RD,
DxilTypeSystem &dxilTypeSys);
unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
unsigned &arrayEltSize);
std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
public:
CGMSHLSLRuntime(CodeGenModule &CGM);
bool IsHlslObjectType(llvm::Type * Ty) override;
/// Add resouce to the program
void addResource(Decl *D) override;
void FinishCodeGen() override;
bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
const CallExpr *E,
ReturnValueSlot ReturnValue) override;
void EmitHLSLOutParamConversionInit(
CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
llvm::SmallVector<LValue, 8> &castArgList,
llvm::SmallVector<const Stmt *, 8> &argList,
const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
override;
void EmitHLSLOutParamConversionCopyBack(
CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
llvm::Type *RetType,
ArrayRef<Value *> paramList) override;
void EmitHLSLDiscard(CodeGenFunction &CGF) override;
Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
Value *Ptr, Value *Idx, QualType Ty) override;
Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
ArrayRef<Value *> paramList,
QualType Ty) override;
Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
QualType Ty) override;
void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
QualType Ty) override;
void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
llvm::Value *DestPtr,
clang::QualType Ty) override;
void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
llvm::Value *DestPtr,
clang::QualType Ty) override;
void EmitHLSLFlatConversionToAggregate(CodeGenFunction &CGF, Value *Val,
Value *DestPtr,
QualType Ty,
QualType SrcTy) override;
Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
QualType DstType) override;
void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
clang::QualType SrcTy,
llvm::Value *DestPtr,
clang::QualType DestTy) override;
void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
llvm::TerminatorInst *TI,
ArrayRef<const Attr *> Attrs) override;
void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
/// Get or add constant to the program
HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
};
}
void clang::CompileRootSignature(
StringRef rootSigStr, DiagnosticsEngine &Diags, SourceLocation SLoc,
hlsl::DxilRootSignatureVersion rootSigVer,
hlsl::RootSignatureHandle *pRootSigHandle) {
std::string OSStr;
llvm::raw_string_ostream OS(OSStr);
hlsl::DxilVersionedRootSignatureDesc *D = nullptr;
if (ParseHLSLRootSignature(rootSigStr.data(), rootSigStr.size(), rootSigVer,
&D, SLoc, Diags)) {
CComPtr<IDxcBlob> pSignature;
CComPtr<IDxcBlobEncoding> pErrors;
hlsl::SerializeRootSignature(D, &pSignature, &pErrors, false);
if (pSignature == nullptr) {
assert(pErrors != nullptr && "else serialize failed with no msg");
ReportHLSLRootSigError(Diags, SLoc, (char *)pErrors->GetBufferPointer(),
pErrors->GetBufferSize());
hlsl::DeleteRootSignature(D);
} else {
pRootSigHandle->Assign(D, pSignature);
}
}
}
//------------------------------------------------------------------------------
//
// CGMSHLSLRuntime methods.
//
CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
: CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()), EntryFunc(nullptr),
TheModule(CGM.getModule()), legacyLayout(HLModule::GetLegacyDataLayoutDesc()),
CBufferType(
llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")) {
const hlsl::ShaderModel *SM =
hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
// Only accept valid, 6.0 shader model.
if (!SM->IsValid() || SM->GetMajor() != 6) {
DiagnosticsEngine &Diags = CGM.getDiags();
unsigned DiagID =
Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
return;
}
m_bIsLib = SM->IsLib();
// TODO: add AllResourceBound.
if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
if (SM->IsSM51Plus()) {
DiagnosticsEngine &Diags = CGM.getDiags();
unsigned DiagID =
Diags.getCustomDiagID(DiagnosticsEngine::Error,
"Gfa option cannot be used in SM_5_1+ unless "
"all_resources_bound flag is specified");
Diags.Report(DiagID);
}
}
// Create HLModule.
const bool skipInit = true;
m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
// Set Option.
HLOptions opts;
opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
m_pHLModule->SetHLOptions(opts);
m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
// set profile
m_pHLModule->SetShaderModel(SM);
// set entry name
m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
// set root signature version.
if (CGM.getLangOpts().RootSigMinor == 0) {
rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
}
else {
DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
"else CGMSHLSLRuntime Constructor needs to be updated");
rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
}
DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
"else CGMSHLSLRuntime Constructor needs to be updated");
// add globalCB
unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
std::string globalCBName = "$Globals";
CB->SetGlobalSymbol(nullptr);
CB->SetGlobalName(globalCBName);
globalCBIndex = m_pHLModule->GetCBuffers().size();
CB->SetID(globalCBIndex);
CB->SetRangeSize(1);
CB->SetLowerBound(UINT_MAX);
DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
}
bool CGMSHLSLRuntime::IsHlslObjectType(llvm::Type *Ty) {
return HLModule::IsHLSLObjectType(Ty);
}
void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
unsigned opcode) {
m_IntrinsicMap.emplace_back(F,opcode);
}
void CGMSHLSLRuntime::CheckParameterAnnotation(
SourceLocation SLoc, const DxilParameterAnnotation ¶mInfo,
bool isPatchConstantFunction) {
if (!paramInfo.HasSemanticString()) {
return;
}
llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
if (paramQual == DxilParamInputQual::Inout) {
CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
return;
}
CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
}
void CGMSHLSLRuntime::CheckParameterAnnotation(
SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
bool isPatchConstantFunction) {
const ShaderModel *SM = m_pHLModule->GetShaderModel();
DXIL::SigPointKind sigPoint = SigPointFromInputQual(
paramQual, SM->GetKind(), isPatchConstantFunction);
llvm::StringRef semName;
unsigned semIndex;
Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
const Semantic *pSemantic =
Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
if (pSemantic->IsInvalid()) {
DiagnosticsEngine &Diags = CGM.getDiags();
const ShaderModel *shader = m_pHLModule->GetShaderModel();
unsigned DiagID =
Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
Diags.Report(SLoc, DiagID) << semName << shader->GetKindName() << shader->GetMajor() << shader->GetMinor();
}
}
SourceLocation
CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
DxilParameterAnnotation ¶mInfo) {
for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
switch (it->getKind()) {
case hlsl::UnusualAnnotation::UA_SemanticDecl: {
const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
paramInfo.SetSemanticString(sd->SemanticName);
return it->Loc;
}
}
}
return SourceLocation();
}
static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
if (domain == "isoline")
return DXIL::TessellatorDomain::IsoLine;
if (domain == "tri")
return DXIL::TessellatorDomain::Tri;
if (domain == "quad")
return DXIL::TessellatorDomain::Quad;
return DXIL::TessellatorDomain::Undefined;
}
static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
if (partition == "integer")
return DXIL::TessellatorPartitioning::Integer;
if (partition == "pow2")
return DXIL::TessellatorPartitioning::Pow2;
if (partition == "fractional_even")
return DXIL::TessellatorPartitioning::FractionalEven;
if (partition == "fractional_odd")
return DXIL::TessellatorPartitioning::FractionalOdd;
return DXIL::TessellatorPartitioning::Undefined;
}
static DXIL::TessellatorOutputPrimitive
StringToTessOutputPrimitive(StringRef primitive) {
if (primitive == "point")
return DXIL::TessellatorOutputPrimitive::Point;
if (primitive == "line")
return DXIL::TessellatorOutputPrimitive::Line;
if (primitive == "triangle_cw")
return DXIL::TessellatorOutputPrimitive::TriangleCW;
if (primitive == "triangle_ccw")
return DXIL::TessellatorOutputPrimitive::TriangleCCW;
return DXIL::TessellatorOutputPrimitive::Undefined;
}
static unsigned AlignTo8Bytes(unsigned offset, bool b8BytesAlign) {
DXASSERT((offset & 0x3) == 0, "offset should be divisible by 4");
if (!b8BytesAlign)
return offset;
else if ((offset & 0x7) == 0)
return offset;
else
return offset + 4;
}
static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size,
QualType Ty, bool bDefaultRowMajor) {
bool b8BytesAlign = false;
if (Ty->isBuiltinType()) {
const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
if (BT->getKind() == clang::BuiltinType::Kind::Double ||
BT->getKind() == clang::BuiltinType::Kind::LongLong)
b8BytesAlign = true;
}
if (unsigned remainder = (baseOffset & 0xf)) {
// Align to 4 x 4 bytes.
unsigned aligned = baseOffset - remainder + 16;
// If cannot fit in the remainder, need align.
bool bNeedAlign = (remainder + size) > 16;
// Array always start aligned.
bNeedAlign |= Ty->isArrayType();
if (IsHLSLMatType(Ty)) {
bool bColMajor = !bDefaultRowMajor;
if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
switch (AT->getAttrKind()) {
case AttributedType::Kind::attr_hlsl_column_major:
bColMajor = true;
break;
case AttributedType::Kind::attr_hlsl_row_major:
bColMajor = false;
break;
default:
// Do nothing
break;
}
}
unsigned row, col;
hlsl::GetHLSLMatRowColCount(Ty, row, col);
bNeedAlign |= bColMajor && col > 1;
bNeedAlign |= !bColMajor && row > 1;
}
if (bNeedAlign)
return AlignTo8Bytes(aligned, b8BytesAlign);
else
return AlignTo8Bytes(baseOffset, b8BytesAlign);
} else
return baseOffset;
}
static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
bool bDefaultRowMajor,
CodeGen::CodeGenModule &CGM,
llvm::DataLayout &layout) {
QualType paramTy = Ty.getCanonicalType();
if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
paramTy = RefType->getPointeeType();
// Get size.
llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
unsigned size = layout.getTypeAllocSize(Type);
return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
}
static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
bool b64Bit) {
bool bColMajor = !defaultRowMajor;
if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
switch (AT->getAttrKind()) {
case AttributedType::Kind::attr_hlsl_column_major:
bColMajor = true;
break;
case AttributedType::Kind::attr_hlsl_row_major:
bColMajor = false;
break;
default:
// Do nothing
break;
}
}
unsigned row, col;
hlsl::GetHLSLMatRowColCount(Ty, row, col);
unsigned EltSize = b64Bit ? 8 : 4;
// Align to 4 * 4bytes.
unsigned alignment = 4 * 4;
if (bColMajor) {
unsigned rowSize = EltSize * row;
// 3x64bit or 4x64bit align to 32 bytes.
if (rowSize > alignment)
alignment <<= 1;
return alignment * (col - 1) + row * EltSize;
} else {
unsigned rowSize = EltSize * col;
// 3x64bit or 4x64bit align to 32 bytes.
if (rowSize > alignment)
alignment <<= 1;
return alignment * (row - 1) + col * EltSize;
}
}
static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
bool bUNorm) {
CompType::Kind kind = CompType::Kind::Invalid;
switch (BTy->getKind()) {
case BuiltinType::UInt:
kind = CompType::Kind::U32;
break;
case BuiltinType::UShort:
kind = CompType::Kind::U16;
break;
case BuiltinType::ULongLong:
kind = CompType::Kind::U64;
break;
case BuiltinType::Int:
kind = CompType::Kind::I32;
break;
case BuiltinType::Min12Int:
case BuiltinType::Short:
kind = CompType::Kind::I16;
break;
case BuiltinType::LongLong:
kind = CompType::Kind::I64;
break;
case BuiltinType::Min10Float:
case BuiltinType::Half:
if (bSNorm)
kind = CompType::Kind::SNormF16;
else if (bUNorm)
kind = CompType::Kind::UNormF16;
else
kind = CompType::Kind::F16;
break;
case BuiltinType::Float:
if (bSNorm)
kind = CompType::Kind::SNormF32;
else if (bUNorm)
kind = CompType::Kind::UNormF32;
else
kind = CompType::Kind::F32;
break;
case BuiltinType::Double:
if (bSNorm)
kind = CompType::Kind::SNormF64;
else if (bUNorm)
kind = CompType::Kind::UNormF64;
else
kind = CompType::Kind::F64;
break;
case BuiltinType::Bool:
kind = CompType::Kind::I1;
break;
}
return kind;
}
static void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation, QualType fieldTy, bool bDefaultRowMajor) {
QualType Ty = fieldTy;
if (Ty->isReferenceType())
Ty = Ty.getNonReferenceType();
// Get element type.
if (Ty->isArrayType()) {
while (isa<clang::ArrayType>(Ty)) {
const clang::ArrayType *ATy = dyn_cast<clang::ArrayType>(Ty);
Ty = ATy->getElementType();
}
}
QualType EltTy = Ty;
if (hlsl::IsHLSLMatType(Ty)) {
DxilMatrixAnnotation Matrix;
Matrix.Orientation = bDefaultRowMajor ? MatrixOrientation::RowMajor
: MatrixOrientation::ColumnMajor;
if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
switch (AT->getAttrKind()) {
case AttributedType::Kind::attr_hlsl_column_major:
Matrix.Orientation = MatrixOrientation::ColumnMajor;
break;
case AttributedType::Kind::attr_hlsl_row_major:
Matrix.Orientation = MatrixOrientation::RowMajor;
break;
default:
// Do nothing
break;
}
}
unsigned row, col;
hlsl::GetHLSLMatRowColCount(Ty, row, col);
Matrix.Cols = col;
Matrix.Rows = row;
fieldAnnotation.SetMatrixAnnotation(Matrix);
EltTy = hlsl::GetHLSLMatElementType(Ty);
}
if (hlsl::IsHLSLVecType(Ty))
EltTy = hlsl::GetHLSLVecElementType(Ty);
bool bSNorm = false;
bool bUNorm = false;
if (const AttributedType *AT = dyn_cast<AttributedType>(Ty)) {
switch (AT->getAttrKind()) {
case AttributedType::Kind::attr_hlsl_snorm:
bSNorm = true;
break;
case AttributedType::Kind::attr_hlsl_unorm:
bUNorm = true;
break;
default:
// Do nothing
break;
}
}
if (EltTy->isBuiltinType()) {
const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
fieldAnnotation.SetCompType(kind);
}
else
DXASSERT(!bSNorm && !bUNorm, "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
}
static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
FieldDecl *fieldDecl) {
// Keep undefined for interpMode here.
InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
fieldDecl->hasAttr<HLSLLinearAttr>(),
fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
fieldDecl->hasAttr<HLSLCentroidAttr>(),
fieldDecl->hasAttr<HLSLSampleAttr>()};
if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
fieldAnnotation.SetInterpolationMode(InterpMode);
}
unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
const RecordDecl *RD,
DxilTypeSystem &dxilTypeSys) {
unsigned fieldIdx = 0;
unsigned offset = 0;
bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
if (CXXRD->getNumBases()) {
// Add base as field.
for (const auto &I : CXXRD->bases()) {
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
std::string fieldSemName = "";
QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
// Align offset.
offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
legacyLayout);
unsigned CBufferOffset = offset;
unsigned arrayEltSize = 0;
// Process field to make sure the size of field is ready.
unsigned size =
AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
// Update offset.
offset += size;
if (size > 0) {
DxilFieldAnnotation &fieldAnnotation =
annotation->GetFieldAnnotation(fieldIdx++);
fieldAnnotation.SetCBufferOffset(CBufferOffset);
fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
}
}
}
}
for (auto fieldDecl : RD->fields()) {
std::string fieldSemName = "";
QualType fieldTy = fieldDecl->getType();
// Align offset.
offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, legacyLayout);
unsigned CBufferOffset = offset;
bool userOffset = false;
// Try to get info from fieldDecl.
for (const hlsl::UnusualAnnotation *it :
fieldDecl->getUnusualAnnotations()) {
switch (it->getKind()) {
case hlsl::UnusualAnnotation::UA_SemanticDecl: {
const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
fieldSemName = sd->SemanticName;
} break;
case hlsl::UnusualAnnotation::UA_ConstantPacking: {
const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
CBufferOffset = cp->Subcomponent << 2;
CBufferOffset += cp->ComponentOffset;
// Change to byte.
CBufferOffset <<= 2;
userOffset = true;
} break;
case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
// register assignment only works on global constant.
DiagnosticsEngine &Diags = CGM.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"location semantics cannot be specified on members.");
Diags.Report(it->Loc, DiagID);
return 0;
} break;
default:
llvm_unreachable("only semantic for input/output");
break;
}
}
unsigned arrayEltSize = 0;
// Process field to make sure the size of field is ready.
unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
// Update offset.
offset += size;
DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
if (fieldDecl->hasAttr<HLSLPreciseAttr>())
fieldAnnotation.SetPrecise();
fieldAnnotation.SetCBufferOffset(CBufferOffset);
fieldAnnotation.SetFieldName(fieldDecl->getName());
if (!fieldSemName.empty())
fieldAnnotation.SetSemanticString(fieldSemName);
}
annotation->SetCBufferSize(offset);
if (offset == 0) {
annotation->MarkEmptyStruct();
}
return offset;
}
static bool IsElementInputOutputType(QualType Ty) {
return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty);
}
// Return the size for constant buffer of each decl.
unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
DxilTypeSystem &dxilTypeSys,
unsigned &arrayEltSize) {
QualType paramTy = Ty.getCanonicalType();
if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
paramTy = RefType->getPointeeType();
// Get size.
llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
unsigned size = legacyLayout.getTypeAllocSize(Type);
if (IsHLSLMatType(Ty)) {
unsigned col, row;
llvm::Type *EltTy = HLMatrixLower::GetMatrixInfo(Type, col, row);
bool b64Bit = legacyLayout.getTypeAllocSize(EltTy) == 8;
size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
b64Bit);
}
// Skip element types.
if (IsElementInputOutputType(paramTy))
return size;
else if (IsHLSLStreamOutputType(Ty)) {
return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
arrayEltSize);
} else if (IsHLSLInputPatchType(Ty))
return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
arrayEltSize);
else if (IsHLSLOutputPatchType(Ty))
return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
arrayEltSize);
else if (const RecordType *RT = paramTy->getAsStructureType()) {
RecordDecl *RD = RT->getDecl();
llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
// Skip if already created.
if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
unsigned structSize = annotation->GetCBufferSize();
return structSize;
}
DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
} else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
// For this pointer.
RecordDecl *RD = RT->getDecl();
llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
// Skip if already created.
if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
unsigned structSize = annotation->GetCBufferSize();
return structSize;
}
DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
} else if (IsHLSLResouceType(Ty)) {
// Save result type info.
AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
// Resource don't count for cbuffer size.
return 0;
} else {
unsigned arraySize = 0;
QualType arrayElementTy = Ty;
if (Ty->isConstantArrayType()) {
const ConstantArrayType *arrayTy =
CGM.getContext().getAsConstantArrayType(Ty);
DXASSERT(arrayTy != nullptr, "Must array type here");
arraySize = arrayTy->getSize().getLimitedValue();
arrayElementTy = arrayTy->getElementType();
}
else if (Ty->isIncompleteArrayType()) {
const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
arrayElementTy = arrayTy->getElementType();
} else
DXASSERT(0, "Must array type here");
unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
// Only set arrayEltSize once.
if (arrayEltSize == 0)
arrayEltSize = elementSize;
// Align to 4 * 4bytes.
unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
return alignedSize * (arraySize - 1) + elementSize;
}
}
static DxilResource::Kind KeywordToKind(StringRef keyword) {
// TODO: refactor for faster search (switch by 1/2/3 first letters, then
// compare)
if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
return DxilResource::Kind::Texture1D;
if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
return DxilResource::Kind::Texture2D;
if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
return DxilResource::Kind::Texture2DMS;
if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
return DxilResource::Kind::Texture3D;
if (keyword == "TextureCube" || keyword == "RWTextureCube")
return DxilResource::Kind::TextureCube;
if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
return DxilResource::Kind::Texture1DArray;
if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
return DxilResource::Kind::Texture2DArray;
if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
return DxilResource::Kind::Texture2DMSArray;
if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
return DxilResource::Kind::TextureCubeArray;
if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
return DxilResource::Kind::RawBuffer;
if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
return DxilResource::Kind::StructuredBuffer;
if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
return DxilResource::Kind::StructuredBuffer;
// TODO: this is not efficient.
bool isBuffer = keyword == "Buffer";
isBuffer |= keyword == "RWBuffer";
isBuffer |= keyword == "RasterizerOrderedBuffer";
if (isBuffer)
return DxilResource::Kind::TypedBuffer;
return DxilResource::Kind::Invalid;
}
static DxilSampler::SamplerKind KeywordToSamplerKind(const std::string &keyword) {
// TODO: refactor for faster search (switch by 1/2/3 first letters, then
// compare)
if (keyword == "SamplerState")
return DxilSampler::SamplerKind::Default;
if (keyword == "SamplerComparisonState")
return DxilSampler::SamplerKind::Comparison;
return DxilSampler::SamplerKind::Invalid;
}
void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
// Add hlsl intrinsic attr
unsigned intrinsicOpcode;
StringRef intrinsicGroup;
if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
// Save resource type annotation.
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
const CXXRecordDecl *RD = MD->getParent();
// For nested case like sample_slice_type.
if (const CXXRecordDecl *PRD =
dyn_cast<CXXRecordDecl>(RD->getDeclContext())) {
RD = PRD;
}
QualType recordTy = MD->getASTContext().getRecordType(RD);
hlsl::DxilResourceBase::Class resClass = TypeToClass(recordTy);
llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
llvm::FunctionType *FT = F->getFunctionType();