forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHLModule.cpp
More file actions
1268 lines (1095 loc) · 42.3 KB
/
HLModule.cpp
File metadata and controls
1268 lines (1095 loc) · 42.3 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
///////////////////////////////////////////////////////////////////////////////
// //
// HLModule.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. //
// //
// HighLevel DX IR module. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/HLSL/HLModule.h"
#include "dxc/DXIL/DxilCBuffer.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/WinAdapter.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using std::string;
using std::unique_ptr;
using std::vector;
namespace hlsl {
// Avoid dependency on HLModule from llvm::Module using this:
void HLModule_RemoveGlobal(llvm::Module *M, llvm::GlobalObject *G) {
if (M && G && M->HasHLModule()) {
if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(G))
M->GetHLModule().RemoveGlobal(GV);
else if (llvm::Function *F = dyn_cast<llvm::Function>(G))
M->GetHLModule().RemoveFunction(F);
}
}
void HLModule_ResetModule(llvm::Module *M) {
if (M && M->HasHLModule())
delete &M->GetHLModule();
M->SetHLModule(nullptr);
}
//------------------------------------------------------------------------------
//
// HLModule methods.
//
HLModule::HLModule(Module *pModule)
: m_Ctx(pModule->getContext()), m_pModule(pModule), m_pEntryFunc(nullptr),
m_EntryName(""),
m_pMDHelper(llvm::make_unique<DxilMDHelper>(
pModule, llvm::make_unique<HLExtraPropertyHelper>(pModule))),
m_pDebugInfoFinder(nullptr), m_pSM(nullptr),
m_DxilMajor(DXIL::kDxilMajor), m_DxilMinor(DXIL::kDxilMinor),
m_ValMajor(0), m_ValMinor(0),
m_Float32DenormMode(DXIL::Float32DenormMode::Any),
m_pOP(llvm::make_unique<OP>(pModule->getContext(), pModule)),
m_AutoBindingSpace(UINT_MAX),
m_DefaultLinkage(DXIL::DefaultLinkage::Default),
m_pTypeSystem(llvm::make_unique<DxilTypeSystem>(pModule)) {
DXASSERT_NOMSG(m_pModule != nullptr);
m_pModule->pfnRemoveGlobal = &HLModule_RemoveGlobal;
m_pModule->pfnResetHLModule = &HLModule_ResetModule;
// Pin LLVM dump methods. TODO: make debug-only.
void (__thiscall Module::*pfnModuleDump)() const = &Module::dump;
void (__thiscall Type::*pfnTypeDump)() const = &Type::dump;
m_pUnused = (char *)&pfnModuleDump - (char *)&pfnTypeDump;
}
HLModule::~HLModule() {
if (m_pModule->pfnRemoveGlobal == &HLModule_RemoveGlobal)
m_pModule->pfnRemoveGlobal = nullptr;
}
LLVMContext &HLModule::GetCtx() const { return m_Ctx; }
Module *HLModule::GetModule() const { return m_pModule; }
OP *HLModule::GetOP() const { return m_pOP.get(); }
void HLModule::SetValidatorVersion(unsigned ValMajor, unsigned ValMinor) {
m_ValMajor = ValMajor;
m_ValMinor = ValMinor;
}
void HLModule::GetValidatorVersion(unsigned &ValMajor,
unsigned &ValMinor) const {
ValMajor = m_ValMajor;
ValMinor = m_ValMinor;
}
void HLModule::SetShaderModel(const ShaderModel *pSM) {
DXASSERT(m_pSM == nullptr, "shader model must not change for the module");
DXASSERT(pSM != nullptr && pSM->IsValidForDxil(),
"shader model must be valid");
m_pSM = pSM;
m_pSM->GetDxilVersion(m_DxilMajor, m_DxilMinor);
m_pMDHelper->SetShaderModel(m_pSM);
m_SerializedRootSignature.clear();
}
const ShaderModel *HLModule::GetShaderModel() const { return m_pSM; }
uint32_t HLOptions::GetHLOptionsRaw() const {
union Cast {
Cast(const HLOptions &options) { hlOptions = options; }
HLOptions hlOptions;
uint32_t rawData;
};
static_assert(sizeof(uint32_t) == sizeof(HLOptions),
"size must match to make sure no undefined bits when cast");
Cast rawCast(*this);
return rawCast.rawData;
}
void HLOptions::SetHLOptionsRaw(uint32_t data) {
union Cast {
Cast(uint32_t data) { rawData = data; }
HLOptions hlOptions;
uint64_t rawData;
};
Cast rawCast(data);
*this = rawCast.hlOptions;
}
void HLModule::SetHLOptions(HLOptions &opts) { m_Options = opts; }
const HLOptions &HLModule::GetHLOptions() const { return m_Options; }
void HLModule::SetAutoBindingSpace(uint32_t Space) {
m_AutoBindingSpace = Space;
}
uint32_t HLModule::GetAutoBindingSpace() const { return m_AutoBindingSpace; }
Function *HLModule::GetEntryFunction() const { return m_pEntryFunc; }
Function *HLModule::GetPatchConstantFunction() {
if (!m_pSM->IsHS())
return nullptr;
if (!m_pEntryFunc)
return nullptr;
DxilFunctionProps &funcProps = GetDxilFunctionProps(m_pEntryFunc);
return funcProps.ShaderProps.HS.patchConstantFunc;
}
void HLModule::SetEntryFunction(Function *pEntryFunc) {
m_pEntryFunc = pEntryFunc;
}
const string &HLModule::GetEntryFunctionName() const { return m_EntryName; }
void HLModule::SetEntryFunctionName(const string &name) { m_EntryName = name; }
template <typename T>
unsigned HLModule::AddResource(vector<unique_ptr<T>> &Vec, unique_ptr<T> pRes) {
DXASSERT_NOMSG((unsigned)Vec.size() < UINT_MAX);
unsigned Id = (unsigned)Vec.size();
Vec.emplace_back(std::move(pRes));
return Id;
}
unsigned HLModule::AddCBuffer(unique_ptr<DxilCBuffer> pCBuffer) {
return AddResource<DxilCBuffer>(m_CBuffers, std::move(pCBuffer));
}
DxilCBuffer &HLModule::GetCBuffer(unsigned idx) { return *m_CBuffers[idx]; }
const DxilCBuffer &HLModule::GetCBuffer(unsigned idx) const {
return *m_CBuffers[idx];
}
const vector<unique_ptr<DxilCBuffer>> &HLModule::GetCBuffers() const {
return m_CBuffers;
}
unsigned HLModule::AddSampler(unique_ptr<DxilSampler> pSampler) {
return AddResource<DxilSampler>(m_Samplers, std::move(pSampler));
}
DxilSampler &HLModule::GetSampler(unsigned idx) { return *m_Samplers[idx]; }
const DxilSampler &HLModule::GetSampler(unsigned idx) const {
return *m_Samplers[idx];
}
const vector<unique_ptr<DxilSampler>> &HLModule::GetSamplers() const {
return m_Samplers;
}
unsigned HLModule::AddSRV(unique_ptr<HLResource> pSRV) {
return AddResource<HLResource>(m_SRVs, std::move(pSRV));
}
HLResource &HLModule::GetSRV(unsigned idx) { return *m_SRVs[idx]; }
const HLResource &HLModule::GetSRV(unsigned idx) const { return *m_SRVs[idx]; }
const vector<unique_ptr<HLResource>> &HLModule::GetSRVs() const {
return m_SRVs;
}
unsigned HLModule::AddUAV(unique_ptr<HLResource> pUAV) {
return AddResource<HLResource>(m_UAVs, std::move(pUAV));
}
HLResource &HLModule::GetUAV(unsigned idx) { return *m_UAVs[idx]; }
const HLResource &HLModule::GetUAV(unsigned idx) const { return *m_UAVs[idx]; }
const vector<unique_ptr<HLResource>> &HLModule::GetUAVs() const {
return m_UAVs;
}
void HLModule::RemoveFunction(llvm::Function *F) {
DXASSERT_NOMSG(F != nullptr);
m_DxilFunctionPropsMap.erase(F);
if (m_pTypeSystem.get()->GetFunctionAnnotation(F))
m_pTypeSystem.get()->EraseFunctionAnnotation(F);
m_pOP->RemoveFunction(F);
}
namespace {
template <typename TResource>
bool RemoveResource(std::vector<std::unique_ptr<TResource>> &vec,
GlobalVariable *pVariable, bool keepAllocated) {
for (auto p = vec.begin(), e = vec.end(); p != e; ++p) {
if ((*p)->GetGlobalSymbol() != pVariable)
continue;
if (keepAllocated && (*p)->IsAllocated()) {
// Keep the resource, but it has no more symbol.
(*p)->SetGlobalSymbol(UndefValue::get(pVariable->getType()));
} else {
// Erase the resource alltogether and update IDs of subsequent ones
p = vec.erase(p);
for (e = vec.end(); p != e; ++p) {
unsigned ID = (*p)->GetID() - 1;
(*p)->SetID(ID);
}
}
return true;
}
return false;
}
} // namespace
void HLModule::RemoveGlobal(llvm::GlobalVariable *GV) {
DXASSERT_NOMSG(GV != nullptr);
// With legacy resource reservation, we must keep unused resources around
// when they have a register allocation because they prevent that
// register range from being allocated to other resources.
bool keepAllocated = GetHLOptions().bLegacyResourceReservation;
// This could be considerably faster - check variable type to see which
// resource type this is rather than scanning all lists, and look for
// usage and removal patterns.
if (RemoveResource(m_CBuffers, GV, keepAllocated))
return;
if (RemoveResource(m_SRVs, GV, keepAllocated))
return;
if (RemoveResource(m_UAVs, GV, keepAllocated))
return;
if (RemoveResource(m_Samplers, GV, keepAllocated))
return;
// TODO: do m_TGSMVariables and m_StreamOutputs need maintenance?
}
HLModule::tgsm_iterator HLModule::tgsm_begin() {
return m_TGSMVariables.begin();
}
HLModule::tgsm_iterator HLModule::tgsm_end() { return m_TGSMVariables.end(); }
void HLModule::AddGroupSharedVariable(GlobalVariable *GV) {
m_TGSMVariables.emplace_back(GV);
}
std::vector<uint8_t> &HLModule::GetSerializedRootSignature() {
return m_SerializedRootSignature;
}
void HLModule::SetSerializedRootSignature(const uint8_t *pData, unsigned size) {
m_SerializedRootSignature.assign(pData, pData + size);
}
DxilTypeSystem &HLModule::GetTypeSystem() { return *m_pTypeSystem; }
DxilTypeSystem *HLModule::ReleaseTypeSystem() {
return m_pTypeSystem.release();
}
hlsl::OP *HLModule::ReleaseOP() { return m_pOP.release(); }
DxilFunctionPropsMap &&HLModule::ReleaseFunctionPropsMap() {
return std::move(m_DxilFunctionPropsMap);
}
void HLModule::EmitLLVMUsed() {
if (m_LLVMUsed.empty())
return;
vector<llvm::Constant *> GVs;
GVs.resize(m_LLVMUsed.size());
for (size_t i = 0, e = m_LLVMUsed.size(); i != e; i++) {
GVs[i] = ConstantExpr::getAddrSpaceCast(
cast<llvm::Constant>(&*m_LLVMUsed[i]), Type::getInt8PtrTy(m_Ctx));
}
ArrayType *pATy = ArrayType::get(Type::getInt8PtrTy(m_Ctx), GVs.size());
GlobalVariable *pGV =
new GlobalVariable(*m_pModule, pATy, false, GlobalValue::AppendingLinkage,
ConstantArray::get(pATy, GVs), "llvm.used");
pGV->setSection("llvm.metadata");
}
vector<GlobalVariable *> &HLModule::GetLLVMUsed() { return m_LLVMUsed; }
bool HLModule::HasDxilFunctionProps(llvm::Function *F) {
return m_DxilFunctionPropsMap.find(F) != m_DxilFunctionPropsMap.end();
}
DxilFunctionProps &HLModule::GetDxilFunctionProps(llvm::Function *F) {
DXASSERT(m_DxilFunctionPropsMap.count(F) != 0, "cannot find F in map");
return *m_DxilFunctionPropsMap[F];
}
void HLModule::AddDxilFunctionProps(llvm::Function *F,
std::unique_ptr<DxilFunctionProps> &info) {
DXASSERT(m_DxilFunctionPropsMap.count(F) == 0,
"F already in map, info will be overwritten");
DXASSERT_NOMSG(info->shaderKind != DXIL::ShaderKind::Invalid);
m_DxilFunctionPropsMap[F] = std::move(info);
}
void HLModule::SetPatchConstantFunctionForHS(
llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc) {
auto propIter = m_DxilFunctionPropsMap.find(hullShaderFunc);
DXASSERT(propIter != m_DxilFunctionPropsMap.end(),
"else Hull Shader missing function props");
DxilFunctionProps &props = *(propIter->second);
DXASSERT(props.IsHS(), "else hullShaderFunc is not a Hull Shader");
if (props.ShaderProps.HS.patchConstantFunc)
m_PatchConstantFunctions.erase(props.ShaderProps.HS.patchConstantFunc);
props.ShaderProps.HS.patchConstantFunc = patchConstantFunc;
if (patchConstantFunc)
m_PatchConstantFunctions.insert(patchConstantFunc);
}
bool HLModule::IsGraphicsShader(llvm::Function *F) {
return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsGraphics();
}
bool HLModule::IsPatchConstantShader(llvm::Function *F) {
return m_PatchConstantFunctions.count(F) != 0;
}
bool HLModule::IsComputeShader(llvm::Function *F) {
return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsCS();
}
bool HLModule::IsNodeShader(llvm::Function *F) {
return HasDxilFunctionProps(F) && GetDxilFunctionProps(F).IsNode();
}
bool HLModule::IsEntryThatUsesSignatures(llvm::Function *F) {
auto propIter = m_DxilFunctionPropsMap.find(F);
if (propIter != m_DxilFunctionPropsMap.end()) {
DxilFunctionProps &props = *(propIter->second);
return props.IsGraphics() || props.IsCS() || props.IsNode();
}
// Otherwise, return true if patch constant function
return IsPatchConstantShader(F);
}
bool HLModule::IsEntry(llvm::Function *F) {
auto propIter = m_DxilFunctionPropsMap.find(F);
if (propIter != m_DxilFunctionPropsMap.end()) {
DXASSERT(propIter->second->shaderKind != DXIL::ShaderKind::Invalid,
"invalid entry props");
return true;
}
// Otherwise, return true if patch constant function
return IsPatchConstantShader(F);
}
DxilFunctionAnnotation *HLModule::GetFunctionAnnotation(llvm::Function *F) {
return m_pTypeSystem->GetFunctionAnnotation(F);
}
DxilFunctionAnnotation *HLModule::AddFunctionAnnotation(llvm::Function *F) {
DXASSERT(m_pTypeSystem->GetFunctionAnnotation(F) == nullptr,
"function annotation already exist");
return m_pTypeSystem->AddFunctionAnnotation(F);
}
DXIL::Float32DenormMode HLModule::GetFloat32DenormMode() const {
return m_Float32DenormMode;
}
void HLModule::SetFloat32DenormMode(const DXIL::Float32DenormMode mode) {
m_Float32DenormMode = mode;
}
DXIL::DefaultLinkage HLModule::GetDefaultLinkage() const {
return m_DefaultLinkage;
}
void HLModule::SetDefaultLinkage(const DXIL::DefaultLinkage linkage) {
m_DefaultLinkage = linkage;
}
static const StringRef kHLDxilFunctionPropertiesMDName = "dx.fnprops";
static const StringRef kHLDxilOptionsMDName = "dx.options";
// DXIL metadata serialization/deserialization.
void HLModule::EmitHLMetadata() {
m_pMDHelper->EmitDxilVersion(m_DxilMajor, m_DxilMinor);
m_pMDHelper->EmitValidatorVersion(m_ValMajor, m_ValMinor);
m_pMDHelper->EmitDxilShaderModel(m_pSM);
MDTuple *pMDResources = EmitHLResources();
MDTuple *pMDProperties = EmitHLShaderProperties();
m_pMDHelper->EmitDxilTypeSystem(GetTypeSystem(), m_LLVMUsed);
EmitLLVMUsed();
MDTuple *const pNullMDSig = nullptr;
MDTuple *pEntry = m_pMDHelper->EmitDxilEntryPointTuple(
GetEntryFunction(), m_EntryName, pNullMDSig, pMDResources, pMDProperties);
vector<MDNode *> Entries;
Entries.emplace_back(pEntry);
m_pMDHelper->EmitDxilEntryPoints(Entries);
{
NamedMDNode *fnProps =
m_pModule->getOrInsertNamedMetadata(kHLDxilFunctionPropertiesMDName);
for (auto &&pair : m_DxilFunctionPropsMap) {
const hlsl::DxilFunctionProps *props = pair.second.get();
MDTuple *pProps = m_pMDHelper->EmitDxilFunctionProps(props, pair.first);
fnProps->addOperand(pProps);
}
NamedMDNode *options =
m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
uint32_t hlOptions = m_Options.GetHLOptionsRaw();
options->addOperand(
MDNode::get(m_Ctx, m_pMDHelper->Uint32ToConstMD(hlOptions)));
options->addOperand(MDNode::get(
m_Ctx, m_pMDHelper->Uint32ToConstMD(GetAutoBindingSpace())));
}
if (!m_SerializedRootSignature.empty()) {
m_pMDHelper->EmitRootSignature(m_SerializedRootSignature);
}
// Save Subobjects
if (GetSubobjects()) {
m_pMDHelper->EmitSubobjects(*GetSubobjects());
}
}
void HLModule::LoadHLMetadata() {
m_pMDHelper->LoadDxilVersion(m_DxilMajor, m_DxilMinor);
m_pMDHelper->LoadValidatorVersion(m_ValMajor, m_ValMinor);
m_pMDHelper->LoadDxilShaderModel(m_pSM);
m_SerializedRootSignature.clear();
const llvm::NamedMDNode *pEntries = m_pMDHelper->GetDxilEntryPoints();
Function *pEntryFunc;
string EntryName;
const llvm::MDOperand *pSignatures, *pResources, *pProperties;
m_pMDHelper->GetDxilEntryPoint(pEntries->getOperand(0), pEntryFunc, EntryName,
pSignatures, pResources, pProperties);
SetEntryFunction(pEntryFunc);
SetEntryFunctionName(EntryName);
LoadHLResources(*pResources);
LoadHLShaderProperties(*pProperties);
m_pMDHelper->LoadDxilTypeSystem(*m_pTypeSystem.get());
{
NamedMDNode *fnProps =
m_pModule->getNamedMetadata(kHLDxilFunctionPropertiesMDName);
size_t propIdx = 0;
while (propIdx < fnProps->getNumOperands()) {
MDTuple *pProps = dyn_cast<MDTuple>(fnProps->getOperand(propIdx++));
std::unique_ptr<hlsl::DxilFunctionProps> props =
llvm::make_unique<hlsl::DxilFunctionProps>();
const Function *F =
m_pMDHelper->LoadDxilFunctionProps(pProps, props.get());
if (props->IsHS() && props->ShaderProps.HS.patchConstantFunc) {
// Add patch constant function to m_PatchConstantFunctions
m_PatchConstantFunctions.insert(
props->ShaderProps.HS.patchConstantFunc);
}
m_DxilFunctionPropsMap[F] = std::move(props);
}
const NamedMDNode *options =
m_pModule->getOrInsertNamedMetadata(kHLDxilOptionsMDName);
const MDNode *MDOptions = options->getOperand(0);
m_Options.SetHLOptionsRaw(
DxilMDHelper::ConstMDToUint32(MDOptions->getOperand(0)));
if (options->getNumOperands() > 1)
SetAutoBindingSpace(
DxilMDHelper::ConstMDToUint32(options->getOperand(1)->getOperand(0)));
}
m_pOP->InitWithMinPrecision(m_Options.bUseMinPrecision);
m_pMDHelper->LoadRootSignature(m_SerializedRootSignature);
// Load Subobjects
std::unique_ptr<DxilSubobjects> pSubobjects(new DxilSubobjects());
m_pMDHelper->LoadSubobjects(*pSubobjects);
if (pSubobjects->GetSubobjects().size()) {
ResetSubobjects(pSubobjects.release());
}
}
void HLModule::ClearHLMetadata(llvm::Module &M) {
Module::named_metadata_iterator b = M.named_metadata_begin(),
e = M.named_metadata_end();
SmallVector<NamedMDNode *, 8> nodes;
for (; b != e; ++b) {
StringRef name = b->getName();
if (name == DxilMDHelper::kDxilVersionMDName ||
name == DxilMDHelper::kDxilShaderModelMDName ||
name == DxilMDHelper::kDxilEntryPointsMDName ||
name == DxilMDHelper::kDxilRootSignatureMDName ||
name == DxilMDHelper::kDxilResourcesMDName ||
name == DxilMDHelper::kDxilTypeSystemMDName ||
name == DxilMDHelper::kDxilValidatorVersionMDName ||
name ==
kHLDxilFunctionPropertiesMDName || // TODO: adjust to proper name
name == kHLDxilOptionsMDName ||
name.startswith(DxilMDHelper::kDxilTypeSystemHelperVariablePrefix)) {
nodes.push_back(b);
}
}
for (size_t i = 0; i < nodes.size(); ++i) {
M.eraseNamedMetadata(nodes[i]);
}
}
MDTuple *HLModule::EmitHLResources() {
// Emit SRV records.
MDTuple *pTupleSRVs = nullptr;
if (!m_SRVs.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_SRVs.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilSRV(*m_SRVs[i]));
}
pTupleSRVs = MDNode::get(m_Ctx, MDVals);
}
// Emit UAV records.
MDTuple *pTupleUAVs = nullptr;
if (!m_UAVs.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_UAVs.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilUAV(*m_UAVs[i]));
}
pTupleUAVs = MDNode::get(m_Ctx, MDVals);
}
// Emit CBuffer records.
MDTuple *pTupleCBuffers = nullptr;
if (!m_CBuffers.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_CBuffers.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilCBuffer(*m_CBuffers[i]));
}
pTupleCBuffers = MDNode::get(m_Ctx, MDVals);
}
// Emit Sampler records.
MDTuple *pTupleSamplers = nullptr;
if (!m_Samplers.empty()) {
vector<Metadata *> MDVals;
for (size_t i = 0; i < m_Samplers.size(); i++) {
MDVals.emplace_back(m_pMDHelper->EmitDxilSampler(*m_Samplers[i]));
}
pTupleSamplers = MDNode::get(m_Ctx, MDVals);
}
if (pTupleSRVs != nullptr || pTupleUAVs != nullptr ||
pTupleCBuffers != nullptr || pTupleSamplers != nullptr) {
return m_pMDHelper->EmitDxilResourceTuple(pTupleSRVs, pTupleUAVs,
pTupleCBuffers, pTupleSamplers);
} else {
return nullptr;
}
}
void HLModule::LoadHLResources(const llvm::MDOperand &MDO) {
const llvm::MDTuple *pSRVs, *pUAVs, *pCBuffers, *pSamplers;
// No resources. Nothing to do.
if (MDO.get() == nullptr)
return;
m_pMDHelper->GetDxilResources(MDO, pSRVs, pUAVs, pCBuffers, pSamplers);
// Load SRV records.
if (pSRVs != nullptr) {
for (unsigned i = 0; i < pSRVs->getNumOperands(); i++) {
unique_ptr<HLResource> pSRV(new HLResource);
m_pMDHelper->LoadDxilSRV(pSRVs->getOperand(i), *pSRV);
AddSRV(std::move(pSRV));
}
}
// Load UAV records.
if (pUAVs != nullptr) {
for (unsigned i = 0; i < pUAVs->getNumOperands(); i++) {
unique_ptr<HLResource> pUAV(new HLResource);
m_pMDHelper->LoadDxilUAV(pUAVs->getOperand(i), *pUAV);
AddUAV(std::move(pUAV));
}
}
// Load CBuffer records.
if (pCBuffers != nullptr) {
for (unsigned i = 0; i < pCBuffers->getNumOperands(); i++) {
unique_ptr<DxilCBuffer> pCB = llvm::make_unique<DxilCBuffer>();
m_pMDHelper->LoadDxilCBuffer(pCBuffers->getOperand(i), *pCB);
AddCBuffer(std::move(pCB));
}
}
// Load Sampler records.
if (pSamplers != nullptr) {
for (unsigned i = 0; i < pSamplers->getNumOperands(); i++) {
unique_ptr<DxilSampler> pSampler(new DxilSampler);
m_pMDHelper->LoadDxilSampler(pSamplers->getOperand(i), *pSampler);
AddSampler(std::move(pSampler));
}
}
}
MDTuple *HLModule::EmitHLShaderProperties() { return nullptr; }
void HLModule::LoadHLShaderProperties(const MDOperand &MDO) { return; }
DxilResourceBase *
HLModule::AddResourceWithGlobalVariableAndProps(llvm::Constant *GV,
DxilResourceProperties &RP) {
DxilResource::Class RC = RP.getResourceClass();
DxilResource::Kind RK = RP.getResourceKind();
unsigned rangeSize = 1;
Type *Ty = GV->getType()->getPointerElementType();
if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
rangeSize = AT->getNumElements();
DxilResourceBase *R = nullptr;
switch (RC) {
case DxilResource::Class::Sampler: {
std::unique_ptr<DxilSampler> S = llvm::make_unique<DxilSampler>();
if (RP.Basic.SamplerCmpOrHasCounter)
S->SetSamplerKind(DxilSampler::SamplerKind::Comparison);
else
S->SetSamplerKind(DxilSampler::SamplerKind::Default);
S->SetKind(RK);
S->SetGlobalSymbol(GV);
S->SetGlobalName(GV->getName());
S->SetRangeSize(rangeSize);
R = S.get();
AddSampler(std::move(S));
} break;
case DxilResource::Class::SRV: {
std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
if (DXIL::IsTyped(RP.getResourceKind())) {
Res->SetCompType(RP.Typed.CompType);
} else if (DXIL::IsStructuredBuffer(RK)) {
Res->SetElementStride(RP.StructStrideInBytes);
}
Res->SetRW(false);
Res->SetKind(RK);
Res->SetGlobalSymbol(GV);
Res->SetGlobalName(GV->getName());
Res->SetRangeSize(rangeSize);
R = Res.get();
AddSRV(std::move(Res));
} break;
case DxilResource::Class::UAV: {
std::unique_ptr<HLResource> Res = llvm::make_unique<HLResource>();
if (DXIL::IsTyped(RK)) {
Res->SetCompType(RP.Typed.CompType);
} else if (DXIL::IsStructuredBuffer(RK)) {
Res->SetElementStride(RP.StructStrideInBytes);
}
Res->SetRW(true);
Res->SetROV(RP.Basic.IsROV);
Res->SetGloballyCoherent(RP.Basic.IsGloballyCoherent);
Res->SetHasCounter(RP.Basic.SamplerCmpOrHasCounter);
Res->SetKind(RK);
Res->SetGlobalSymbol(GV);
Res->SetGlobalName(GV->getName());
Res->SetRangeSize(rangeSize);
R = Res.get();
AddUAV(std::move(Res));
} break;
default:
DXASSERT(0, "Invalid metadata for AddResourceWithGlobalVariableAndMDNode");
}
return R;
}
static uint64_t getRegBindingKey(unsigned CbID, unsigned ConstantIdx) {
return (uint64_t)(CbID) << 32 | ConstantIdx;
}
void HLModule::AddRegBinding(unsigned CbID, unsigned ConstantIdx, unsigned Srv,
unsigned Uav, unsigned Sampler) {
uint64_t Key = getRegBindingKey(CbID, ConstantIdx);
m_SrvBindingInCB[Key] = Srv;
m_UavBindingInCB[Key] = Uav;
m_SamplerBindingInCB[Key] = Sampler;
}
// Helper functions for resource in cbuffer.
namespace {
DXIL::ResourceClass GetRCFromType(StructType *ST, Module &M) {
for (Function &F : M.functions()) {
if (F.user_empty())
continue;
hlsl::HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(&F);
if (group != HLOpcodeGroup::HLAnnotateHandle)
continue;
Type *Ty = F.getFunctionType()->getParamType(
HLOperandIndex::kAnnotateHandleResourceTypeOpIdx);
if (Ty != ST)
continue;
CallInst *CI = cast<CallInst>(F.user_back());
Constant *Props = cast<Constant>(CI->getArgOperand(
HLOperandIndex::kAnnotateHandleResourcePropertiesOpIdx));
DxilResourceProperties RP = resource_helper::loadPropsFromConstant(*Props);
return RP.getResourceClass();
}
return DXIL::ResourceClass::Invalid;
}
unsigned CountResNum(Module &M, Type *Ty, DXIL::ResourceClass RC) {
// Count num of RCs.
unsigned ArraySize = 1;
while (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
ArraySize *= AT->getNumElements();
Ty = AT->getElementType();
}
if (!Ty->isAggregateType())
return 0;
StructType *ST = dyn_cast<StructType>(Ty);
DXIL::ResourceClass TmpRC = GetRCFromType(ST, M);
if (TmpRC == RC)
return ArraySize;
unsigned Size = 0;
for (Type *EltTy : ST->elements()) {
Size += CountResNum(M, EltTy, RC);
}
return Size * ArraySize;
}
// Note: the rule for register binding on struct array is like this:
// struct X {
// Texture2D x;
// SamplerState s ;
// Texture2D y;
// };
// X x[2] : register(t3) : register(s3);
// x[0].x t3
// x[0].s s3
// x[0].y t4
// x[1].x t5
// x[1].s s4
// x[1].y t6
// So x[0].x and x[1].x not in an array.
unsigned CalcRegBinding(gep_type_iterator GEPIt, gep_type_iterator E, Module &M,
DXIL::ResourceClass RC) {
unsigned NumRC = 0;
// Count GEP offset when only count RC size.
for (; GEPIt != E; GEPIt++) {
Type *Ty = *GEPIt;
Value *idx = GEPIt.getOperand();
Constant *constIdx = dyn_cast<Constant>(idx);
unsigned immIdx = constIdx->getUniqueInteger().getLimitedValue();
// Not support dynamic indexing.
// Array should be just 1d res array as global res.
if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
NumRC += immIdx * CountResNum(M, AT->getElementType(), RC);
} else if (StructType *ST = dyn_cast<StructType>(Ty)) {
for (unsigned i = 0; i < immIdx; i++) {
NumRC += CountResNum(M, ST->getElementType(i), RC);
}
}
}
return NumRC;
}
} // namespace
unsigned HLModule::GetBindingForResourceInCB(GetElementPtrInst *CbPtr,
GlobalVariable *CbGV,
DXIL::ResourceClass RC) {
if (!CbPtr->hasAllConstantIndices()) {
// Not support dynmaic indexing resource array inside cb.
string ErrorMsg(
"Index for resource array inside cbuffer must be a literal expression");
dxilutil::EmitErrorOnInstruction(CbPtr, ErrorMsg);
return UINT_MAX;
}
Module &M = *m_pModule;
unsigned RegBinding = UINT_MAX;
for (auto &CB : m_CBuffers) {
if (CbGV != CB->GetGlobalSymbol())
continue;
gep_type_iterator GEPIt = gep_type_begin(CbPtr), E = gep_type_end(CbPtr);
// The pointer index.
GEPIt++;
unsigned ID = CB->GetID();
unsigned idx = cast<ConstantInt>(GEPIt.getOperand())->getLimitedValue();
// The first level index to get current constant.
GEPIt++;
uint64_t Key = getRegBindingKey(ID, idx);
switch (RC) {
default:
break;
case DXIL::ResourceClass::SRV:
if (m_SrvBindingInCB.count(Key))
RegBinding = m_SrvBindingInCB[Key];
break;
case DXIL::ResourceClass::UAV:
if (m_UavBindingInCB.count(Key))
RegBinding = m_UavBindingInCB[Key];
break;
case DXIL::ResourceClass::Sampler:
if (m_SamplerBindingInCB.count(Key))
RegBinding = m_SamplerBindingInCB[Key];
break;
}
if (RegBinding == UINT_MAX)
break;
// Calc RegBinding.
RegBinding += CalcRegBinding(GEPIt, E, M, RC);
break;
}
return RegBinding;
}
// TODO: Don't check names.
bool HLModule::IsStreamOutputType(llvm::Type *Ty) {
if (StructType *ST = dyn_cast<StructType>(Ty)) {
StringRef name = ST->getName();
if (name.startswith("class.PointStream"))
return true;
if (name.startswith("class.LineStream"))
return true;
if (name.startswith("class.TriangleStream"))
return true;
}
return false;
}
bool HLModule::IsStreamOutputPtrType(llvm::Type *Ty) {
if (!Ty->isPointerTy())
return false;
Ty = Ty->getPointerElementType();
return IsStreamOutputType(Ty);
}
void HLModule::GetParameterRowsAndCols(
Type *Ty, unsigned &rows, unsigned &cols,
DxilParameterAnnotation ¶mAnnotation) {
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
// For array input of HS, DS, GS and array output of MS,
// we need to skip the first level which size is based on primitive type.
DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
bool skipOneLevelArray = inputQual == DxilParamInputQual::InputPatch;
skipOneLevelArray |= inputQual == DxilParamInputQual::OutputPatch;
skipOneLevelArray |= inputQual == DxilParamInputQual::InputPrimitive;
skipOneLevelArray |= inputQual == DxilParamInputQual::OutVertices;
skipOneLevelArray |= inputQual == DxilParamInputQual::OutPrimitives;
if (skipOneLevelArray) {
if (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
}
unsigned arraySize = 1;
while (Ty->isArrayTy()) {
arraySize *= Ty->getArrayNumElements();
Ty = Ty->getArrayElementType();
}
rows = 1;
cols = 1;
if (paramAnnotation.HasMatrixAnnotation()) {
const DxilMatrixAnnotation &matrix = paramAnnotation.GetMatrixAnnotation();
if (matrix.Orientation == MatrixOrientation::RowMajor) {
rows = matrix.Rows;
cols = matrix.Cols;
} else {
DXASSERT_NOMSG(matrix.Orientation == MatrixOrientation::ColumnMajor);
cols = matrix.Rows;
rows = matrix.Cols;
}
} else if (FixedVectorType *VT = dyn_cast<FixedVectorType>(Ty))
cols = VT->getNumElements();
rows *= arraySize;
}
llvm::Function *HLModule::GetHLOperationFunction(
HLOpcodeGroup group, unsigned opcode, llvm::Type *RetType,
llvm::ArrayRef<llvm::Value *> paramList, llvm::Module &M) {
SmallVector<llvm::Type *, 4> paramTyList;
// Add the opcode param
llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
paramTyList.emplace_back(opcodeTy);
for (Value *param : paramList) {
paramTyList.emplace_back(param->getType());
}
llvm::FunctionType *funcTy =
llvm::FunctionType::get(RetType, paramTyList, false);
Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
return opFunc;
}
template CallInst *HLModule::EmitHLOperationCall(IRBuilder<> &Builder,
HLOpcodeGroup group,
unsigned opcode, Type *RetType,
ArrayRef<Value *> paramList,
llvm::Module &M);
template <typename BuilderTy>
CallInst *HLModule::EmitHLOperationCall(BuilderTy &Builder, HLOpcodeGroup group,
unsigned opcode, Type *RetType,
ArrayRef<Value *> paramList,
llvm::Module &M) {
// Add the opcode param
llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
Function *opFunc =
GetHLOperationFunction(group, opcode, RetType, paramList, M);
SmallVector<Value *, 4> opcodeParamList;
Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
opcodeParamList.emplace_back(opcodeConst);
opcodeParamList.append(paramList.begin(), paramList.end());
return Builder.CreateCall(opFunc, opcodeParamList);
}
unsigned HLModule::GetNumericCastOp(llvm::Type *SrcTy, bool SrcIsUnsigned,
llvm::Type *DstTy, bool DstIsUnsigned) {
DXASSERT(SrcTy != DstTy, "No-op conversions are not casts and should have "
"been handled by the callee.");
uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
uint32_t DstBitSize = DstTy->getScalarSizeInBits();
bool SrcIsInt = SrcTy->isIntOrIntVectorTy();
bool DstIsInt = DstTy->isIntOrIntVectorTy();
DXASSERT(DstBitSize != 1, "Conversions to bool are not a cast and should "
"have been handled by the callee.");
// Conversions from bools are like unsigned integer widening
if (SrcBitSize == 1)
SrcIsUnsigned = true;
if (SrcIsInt) {
if (DstIsInt) { // int to int
if (SrcBitSize > DstBitSize)
return Instruction::Trunc;
// unsigned to unsigned: zext
// unsigned to signed: zext (fully representable)
// signed to signed: sext
// signed to unsigned: sext (like C++)
return SrcIsUnsigned ? Instruction::ZExt : Instruction::SExt;
} else { // int to float
return SrcIsUnsigned ? Instruction::UIToFP : Instruction::SIToFP;
}