forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDxilLinker.cpp
More file actions
1615 lines (1394 loc) · 51.8 KB
/
DxilLinker.cpp
File metadata and controls
1615 lines (1394 loc) · 51.8 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
///////////////////////////////////////////////////////////////////////////////
// //
// DxilLinker.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. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/HLSL/DxilLinker.h"
#include "dxc/DXIL/DxilCBuffer.h"
#include "dxc/DXIL/DxilEntryProps.h"
#include "dxc/DXIL/DxilFunctionProps.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResource.h"
#include "dxc/DXIL/DxilSampler.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/Support/Global.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <memory>
#include <vector>
#include "dxc/DxilContainer/DxilContainer.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/LLVMContext.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "dxc/HLSL/ComputeViewIdState.h"
#include "dxc/HLSL/DxilExportMap.h"
using namespace llvm;
using namespace hlsl;
namespace {
void CollectUsedFunctions(Constant *C, llvm::SetVector<Function *> &funcSet) {
for (User *U : C->users()) {
if (Instruction *I = dyn_cast<Instruction>(U)) {
funcSet.insert(I->getParent()->getParent());
} else {
Constant *CU = cast<Constant>(U);
CollectUsedFunctions(CU, funcSet);
}
}
}
template <class T>
void AddResourceMap(
const std::vector<std::unique_ptr<T>> &resTab, DXIL::ResourceClass resClass,
llvm::MapVector<const llvm::Constant *, DxilResourceBase *> &resMap,
DxilModule &DM) {
for (auto &Res : resTab) {
resMap[Res->GetGlobalSymbol()] = Res.get();
}
}
void CloneFunction(Function *F, Function *NewF, ValueToValueMapTy &vmap,
hlsl::DxilTypeSystem *TypeSys = nullptr,
hlsl::DxilTypeSystem *SrcTypeSys = nullptr) {
SmallVector<ReturnInst *, 2> Returns;
// Map params.
auto paramIt = NewF->arg_begin();
for (Argument ¶m : F->args()) {
vmap[¶m] = (paramIt++);
}
llvm::CloneFunctionInto(NewF, F, vmap, /*ModuleLevelChanges*/ true, Returns);
if (TypeSys) {
if (SrcTypeSys == nullptr)
SrcTypeSys = TypeSys;
TypeSys->CopyFunctionAnnotation(NewF, F, *SrcTypeSys);
}
// Remove params from vmap.
for (Argument ¶m : F->args()) {
vmap.erase(¶m);
}
}
} // namespace
namespace {
struct DxilFunctionLinkInfo {
DxilFunctionLinkInfo(llvm::Function *F);
llvm::Function *func;
// SetVectors for deterministic iteration
llvm::SetVector<llvm::Function *> usedFunctions;
llvm::SetVector<llvm::GlobalVariable *> usedGVs;
};
// Library to link.
class DxilLib {
public:
DxilLib(std::unique_ptr<llvm::Module> pModule);
virtual ~DxilLib() {}
bool HasFunction(std::string &name);
llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> &GetFunctionTable() {
return m_functionNameMap;
}
bool IsInitFunc(llvm::Function *F);
bool IsEntry(llvm::Function *F);
bool IsResourceGlobal(const llvm::Constant *GV);
DxilResourceBase *GetResource(const llvm::Constant *GV);
DxilModule &GetDxilModule() { return m_DM; }
void LazyLoadFunction(Function *F);
void BuildGlobalUsage();
void CollectUsedInitFunctions(SetVector<StringRef> &addedFunctionSet,
SmallVector<StringRef, 4> &workList);
void FixIntrinsicOverloads();
private:
std::unique_ptr<llvm::Module> m_pModule;
DxilModule &m_DM;
// Map from name to Link info for extern functions.
llvm::StringMap<std::unique_ptr<DxilFunctionLinkInfo>> m_functionNameMap;
llvm::SmallPtrSet<llvm::Function *, 4> m_entrySet;
// Map from resource link global to resource. MapVector for deterministic
// iteration.
llvm::MapVector<const llvm::Constant *, DxilResourceBase *> m_resourceMap;
// Set of initialize functions for global variable. SetVector for
// deterministic iteration.
llvm::SetVector<llvm::Function *> m_initFuncSet;
};
struct DxilLinkJob;
class DxilLinkerImpl : public hlsl::DxilLinker {
public:
DxilLinkerImpl(LLVMContext &Ctx, unsigned valMajor, unsigned valMinor)
: DxilLinker(Ctx, valMajor, valMinor) {}
virtual ~DxilLinkerImpl() {}
bool HasLibNameRegistered(StringRef name) override;
bool RegisterLib(StringRef name, std::unique_ptr<llvm::Module> pModule,
std::unique_ptr<llvm::Module> pDebugModule) override;
bool AttachLib(StringRef name) override;
bool DetachLib(StringRef name) override;
void DetachAll() override;
std::unique_ptr<llvm::Module> Link(StringRef entry, StringRef profile,
dxilutil::ExportMap &exportMap) override;
private:
bool AttachLib(DxilLib *lib);
bool DetachLib(DxilLib *lib);
bool AddFunctions(SmallVector<StringRef, 4> &workList,
SetVector<DxilLib *> &libSet,
SetVector<StringRef> &addedFunctionSet,
DxilLinkJob &linkJob, bool bLazyLoadDone,
bool bAllowFuncionDecls);
// Attached libs to link.
std::unordered_set<DxilLib *> m_attachedLibs;
// Owner of all DxilLib.
StringMap<std::unique_ptr<DxilLib>> m_LibMap;
llvm::StringMap<std::pair<DxilFunctionLinkInfo *, DxilLib *>>
m_functionNameMap;
};
} // namespace
//------------------------------------------------------------------------------
//
// DxilFunctionLinkInfo methods.
//
DxilFunctionLinkInfo::DxilFunctionLinkInfo(Function *F) : func(F) {
DXASSERT_NOMSG(F);
}
//------------------------------------------------------------------------------
//
// DxilLib methods.
//
DxilLib::DxilLib(std::unique_ptr<llvm::Module> pModule)
: m_pModule(std::move(pModule)), m_DM(m_pModule->GetOrCreateDxilModule()) {
Module &M = *m_pModule;
const std::string MID = (Twine(M.getModuleIdentifier()) + ".").str();
// Collect function defines.
for (Function &F : M.functions()) {
if (F.isDeclaration())
continue;
if (F.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
// Add prefix to internal function.
F.setName(MID + F.getName());
}
m_functionNameMap[F.getName()] =
llvm::make_unique<DxilFunctionLinkInfo>(&F);
if (m_DM.IsEntry(&F))
m_entrySet.insert(&F);
}
// Update internal global name.
for (GlobalVariable &GV : M.globals()) {
if (GV.getLinkage() == GlobalValue::LinkageTypes::InternalLinkage) {
// Add prefix to internal global.
GV.setName(MID + GV.getName());
}
}
}
void DxilLib::FixIntrinsicOverloads() {
// Fix DXIL overload name collisions that may be caused by name
// collisions between dxil ops with different overload types,
// when those types may have had the same name in the original
// modules.
m_DM.GetOP()->FixOverloadNames();
}
void DxilLib::LazyLoadFunction(Function *F) {
DXASSERT(m_functionNameMap.count(F->getName()), "else invalid Function");
DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
std::error_code EC = F->materialize();
DXASSERT_LOCALVAR(EC, !EC, "else fail to materialize");
// Build used functions for F.
for (auto &BB : F->getBasicBlockList()) {
for (auto &I : BB.getInstList()) {
if (CallInst *CI = dyn_cast<CallInst>(&I)) {
linkInfo->usedFunctions.insert(CI->getCalledFunction());
}
}
}
if (m_DM.HasDxilFunctionProps(F)) {
DxilFunctionProps &props = m_DM.GetDxilFunctionProps(F);
if (props.IsHS()) {
// Add patch constant function to usedFunctions of entry.
Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
linkInfo->usedFunctions.insert(patchConstantFunc);
}
}
// Used globals will be build before link.
}
void DxilLib::BuildGlobalUsage() {
Module &M = *m_pModule;
// Collect init functions for static globals.
if (GlobalVariable *Ctors = M.getGlobalVariable("llvm.global_ctors")) {
if (ConstantArray *CA = dyn_cast<ConstantArray>(Ctors->getInitializer())) {
for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
++i) {
if (isa<ConstantAggregateZero>(*i))
continue;
ConstantStruct *CS = cast<ConstantStruct>(*i);
if (isa<ConstantPointerNull>(CS->getOperand(1)))
continue;
// Must have a function or null ptr.
if (!isa<Function>(CS->getOperand(1)))
continue;
Function *Ctor = cast<Function>(CS->getOperand(1));
assert(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0 &&
"function type must be void (void)");
// Add Ctor.
m_initFuncSet.insert(Ctor);
LazyLoadFunction(Ctor);
}
}
}
// Build used globals.
for (GlobalVariable &GV : M.globals()) {
llvm::SetVector<Function *> funcSet;
CollectUsedFunctions(&GV, funcSet);
for (Function *F : funcSet) {
DXASSERT(m_functionNameMap.count(F->getName()), "must exist in table");
DxilFunctionLinkInfo *linkInfo = m_functionNameMap[F->getName()].get();
linkInfo->usedGVs.insert(&GV);
}
}
// Build resource map.
AddResourceMap(m_DM.GetUAVs(), DXIL::ResourceClass::UAV, m_resourceMap, m_DM);
AddResourceMap(m_DM.GetSRVs(), DXIL::ResourceClass::SRV, m_resourceMap, m_DM);
AddResourceMap(m_DM.GetCBuffers(), DXIL::ResourceClass::CBuffer,
m_resourceMap, m_DM);
AddResourceMap(m_DM.GetSamplers(), DXIL::ResourceClass::Sampler,
m_resourceMap, m_DM);
}
void DxilLib::CollectUsedInitFunctions(SetVector<StringRef> &addedFunctionSet,
SmallVector<StringRef, 4> &workList) {
// Add init functions to used functions.
for (Function *Ctor : m_initFuncSet) {
DXASSERT(m_functionNameMap.count(Ctor->getName()),
"must exist in internal table");
DxilFunctionLinkInfo *linkInfo = m_functionNameMap[Ctor->getName()].get();
// If function other than Ctor used GV of Ctor.
// Add Ctor to usedFunctions for it.
for (GlobalVariable *GV : linkInfo->usedGVs) {
llvm::SetVector<Function *> funcSet;
CollectUsedFunctions(GV, funcSet);
bool bAdded = false;
for (Function *F : funcSet) {
if (F == Ctor)
continue;
// If F is added for link, add init func to workList.
if (addedFunctionSet.count(F->getName())) {
workList.emplace_back(Ctor->getName());
bAdded = true;
break;
}
}
if (bAdded)
break;
}
}
}
bool DxilLib::HasFunction(std::string &name) {
return m_functionNameMap.count(name);
}
bool DxilLib::IsEntry(llvm::Function *F) { return m_entrySet.count(F); }
bool DxilLib::IsInitFunc(llvm::Function *F) { return m_initFuncSet.count(F); }
bool DxilLib::IsResourceGlobal(const llvm::Constant *GV) {
return m_resourceMap.count(GV);
}
DxilResourceBase *DxilLib::GetResource(const llvm::Constant *GV) {
if (IsResourceGlobal(GV))
return m_resourceMap[GV];
else
return nullptr;
}
namespace {
// Create module from link defines.
struct DxilLinkJob {
DxilLinkJob(LLVMContext &Ctx, dxilutil::ExportMap &exportMap,
unsigned valMajor, unsigned valMinor)
: m_ctx(Ctx), m_exportMap(exportMap), m_valMajor(valMajor),
m_valMinor(valMinor) {}
std::unique_ptr<llvm::Module>
Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
const ShaderModel *pSM);
std::unique_ptr<llvm::Module> LinkToLib(const ShaderModel *pSM);
void StripDeadDebugInfo(llvm::Module &M);
// Fix issues when link to different shader model.
void FixShaderModelMismatch(llvm::Module &M);
void RunPreparePass(llvm::Module &M);
void AddFunction(std::pair<DxilFunctionLinkInfo *, DxilLib *> &linkPair);
void AddFunction(llvm::Function *F);
private:
void LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap);
void AddFunctionDecls(Module *pM);
bool AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap);
void EmitCtorListForLib(Module *pM);
void CloneFunctions(ValueToValueMapTy &vmap);
void AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap);
bool AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV);
void AddResourceToDM(DxilModule &DM);
llvm::MapVector<DxilFunctionLinkInfo *, DxilLib *> m_functionDefs;
// Function decls, in order added.
llvm::MapVector<llvm::StringRef,
std::pair<llvm::SmallPtrSet<llvm::FunctionType *, 2>,
llvm::SmallVector<llvm::Function *, 2>>>
m_functionDecls;
// New created functions, in order added.
llvm::MapVector<llvm::StringRef, llvm::Function *> m_newFunctions;
// New created globals, in order added.
llvm::MapVector<llvm::StringRef, llvm::GlobalVariable *> m_newGlobals;
// Map for resource, ordered by name.
std::map<llvm::StringRef,
std::pair<DxilResourceBase *, llvm::GlobalVariable *>>
m_resourceMap;
LLVMContext &m_ctx;
dxilutil::ExportMap &m_exportMap;
unsigned m_valMajor, m_valMinor;
};
} // namespace
namespace {
const char kUndefFunction[] = "Cannot find definition of function ";
const char kRedefineFunction[] = "Definition already exists for function ";
const char kRedefineGlobal[] = "Definition already exists for global variable ";
const char kShaderKindMismatch[] =
"Profile mismatch between entry function and target profile:";
const char kNoEntryProps[] =
"Cannot find function property for entry function ";
const char kRedefineResource[] = "Resource already exists as ";
const char kInvalidValidatorVersion[] =
"Validator version does not support target profile ";
const char kExportNameCollision[] =
"Export name collides with another export: ";
const char kExportFunctionMissing[] = "Could not find target for export: ";
const char kNoFunctionsToExport[] = "Library has no functions to export";
} // namespace
//------------------------------------------------------------------------------
//
// DxilLinkJob methods.
//
namespace {
// Helper function to check type match.
bool IsMatchedType(Type *Ty0, Type *Ty);
StringRef RemoveNameSuffix(StringRef Name) {
size_t DotPos = Name.rfind('.');
if (DotPos != StringRef::npos && Name.back() != '.' &&
isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
Name = Name.substr(0, DotPos);
return Name;
}
bool IsMatchedStructType(StructType *ST0, StructType *ST) {
StringRef Name0 = RemoveNameSuffix(ST0->getName());
StringRef Name = RemoveNameSuffix(ST->getName());
if (Name0 != Name)
return false;
if (ST0->getNumElements() != ST->getNumElements())
return false;
if (ST0->isLayoutIdentical(ST))
return true;
for (unsigned i = 0; i < ST->getNumElements(); i++) {
Type *Ty = ST->getElementType(i);
Type *Ty0 = ST0->getElementType(i);
if (!IsMatchedType(Ty, Ty0))
return false;
}
return true;
}
bool IsMatchedArrayType(ArrayType *AT0, ArrayType *AT) {
if (AT0->getNumElements() != AT->getNumElements())
return false;
return IsMatchedType(AT0->getElementType(), AT->getElementType());
}
bool IsMatchedType(Type *Ty0, Type *Ty) {
if (Ty0->isStructTy() && Ty->isStructTy()) {
StructType *ST0 = cast<StructType>(Ty0);
StructType *ST = cast<StructType>(Ty);
return IsMatchedStructType(ST0, ST);
}
if (Ty0->isArrayTy() && Ty->isArrayTy()) {
ArrayType *AT0 = cast<ArrayType>(Ty0);
ArrayType *AT = cast<ArrayType>(Ty);
return IsMatchedArrayType(AT0, AT);
}
if (Ty0->isPointerTy() && Ty->isPointerTy()) {
if (Ty0->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return false;
return IsMatchedType(Ty0->getPointerElementType(),
Ty->getPointerElementType());
}
return Ty0 == Ty;
}
} // namespace
bool DxilLinkJob::AddResource(DxilResourceBase *res, llvm::GlobalVariable *GV) {
if (m_resourceMap.count(res->GetGlobalName())) {
DxilResourceBase *res0 = m_resourceMap[res->GetGlobalName()].first;
Type *Ty0 = res0->GetHLSLType()->getPointerElementType();
Type *Ty = res->GetHLSLType()->getPointerElementType();
// Make sure res0 match res.
bool bMatch = IsMatchedType(Ty0, Ty);
if (!bMatch) {
// Report error.
dxilutil::EmitErrorOnGlobalVariable(
m_ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
Twine(kRedefineResource) + res->GetResClassName() + " for " +
res->GetGlobalName());
return false;
}
} else {
m_resourceMap[res->GetGlobalName()] = std::make_pair(res, GV);
}
return true;
}
void DxilLinkJob::AddResourceToDM(DxilModule &DM) {
for (auto &it : m_resourceMap) {
DxilResourceBase *res = it.second.first;
GlobalVariable *GV = it.second.second;
unsigned ID = 0;
DxilResourceBase *basePtr = nullptr;
switch (res->GetClass()) {
case DXIL::ResourceClass::UAV: {
std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
DxilResource *ptr = pUAV.get();
// Copy the content.
*ptr = *(static_cast<DxilResource *>(res));
ID = DM.AddUAV(std::move(pUAV));
basePtr = &DM.GetUAV(ID);
} break;
case DXIL::ResourceClass::SRV: {
std::unique_ptr<DxilResource> pSRV = llvm::make_unique<DxilResource>();
DxilResource *ptr = pSRV.get();
// Copy the content.
*ptr = *(static_cast<DxilResource *>(res));
ID = DM.AddSRV(std::move(pSRV));
basePtr = &DM.GetSRV(ID);
} break;
case DXIL::ResourceClass::CBuffer: {
std::unique_ptr<DxilCBuffer> pCBuf = llvm::make_unique<DxilCBuffer>();
DxilCBuffer *ptr = pCBuf.get();
// Copy the content.
*ptr = *(static_cast<DxilCBuffer *>(res));
ID = DM.AddCBuffer(std::move(pCBuf));
basePtr = &DM.GetCBuffer(ID);
} break;
case DXIL::ResourceClass::Sampler: {
std::unique_ptr<DxilSampler> pSampler = llvm::make_unique<DxilSampler>();
DxilSampler *ptr = pSampler.get();
// Copy the content.
*ptr = *(static_cast<DxilSampler *>(res));
ID = DM.AddSampler(std::move(pSampler));
basePtr = &DM.GetSampler(ID);
} break;
default:
DXASSERT(false, "Invalid resource class");
break;
}
// Update ID.
basePtr->SetID(ID);
basePtr->SetGlobalSymbol(GV);
DM.GetLLVMUsed().push_back(GV);
}
// Prevent global vars used for resources from being deleted through
// optimizations while we still have hidden uses (pointers in resource
// vectors).
DM.EmitLLVMUsed();
}
void DxilLinkJob::LinkNamedMDNodes(Module *pM, ValueToValueMapTy &vmap) {
SetVector<Module *> moduleSet;
for (auto &it : m_functionDefs) {
DxilLib *pLib = it.second;
moduleSet.insert(pLib->GetDxilModule().GetModule());
}
// Link normal NamedMDNode.
// TODO: skip duplicate operands.
for (Module *pSrcM : moduleSet) {
const NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
for (const NamedMDNode &NMD : pSrcM->named_metadata()) {
// Don't link module flags here. Do them separately.
if (&NMD == pSrcModFlags)
continue;
// Skip dxil metadata which will be regenerated.
if (DxilMDHelper::IsKnownNamedMetaData(NMD))
continue;
NamedMDNode *DestNMD = pM->getOrInsertNamedMetadata(NMD.getName());
// Add Src elements into Dest node.
for (const MDNode *op : NMD.operands())
DestNMD->addOperand(MapMetadata(op, vmap, RF_None, /*TypeMap*/ nullptr,
/*ValMaterializer*/ nullptr));
}
}
// Link mod flags.
SetVector<MDNode *> flagSet;
for (Module *pSrcM : moduleSet) {
NamedMDNode *pSrcModFlags = pSrcM->getModuleFlagsMetadata();
if (pSrcModFlags) {
for (MDNode *flag : pSrcModFlags->operands()) {
flagSet.insert(flag);
}
}
}
// TODO: check conflict in flags.
if (!flagSet.empty()) {
NamedMDNode *ModFlags = pM->getOrInsertModuleFlagsMetadata();
for (MDNode *flag : flagSet) {
ModFlags->addOperand(flag);
}
}
}
void DxilLinkJob::AddFunctionDecls(Module *pM) {
for (auto &it : m_functionDecls) {
for (auto F : it.second.second) {
Function *NewF = pM->getFunction(F->getName());
if (!NewF || F->getFunctionType() != NewF->getFunctionType()) {
NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
F->getName(), pM);
NewF->setAttributes(F->getAttributes());
}
m_newFunctions[F->getName()] = NewF;
}
}
}
bool DxilLinkJob::AddGlobals(DxilModule &DM, ValueToValueMapTy &vmap) {
DxilTypeSystem &typeSys = DM.GetTypeSystem();
Module *pM = DM.GetModule();
bool bSuccess = true;
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
DxilLib *pLib = it.second;
DxilModule &tmpDM = pLib->GetDxilModule();
DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
for (GlobalVariable *GV : linkInfo->usedGVs) {
// Skip added globals.
if (m_newGlobals.count(GV->getName())) {
if (vmap.find(GV) == vmap.end()) {
if (DxilResourceBase *res = pLib->GetResource(GV)) {
// For resource of same name, if class and type match, just map to
// same NewGV.
GlobalVariable *NewGV = m_newGlobals[GV->getName()];
if (AddResource(res, NewGV)) {
vmap[GV] = NewGV;
} else {
bSuccess = false;
}
continue;
}
// Redefine of global.
dxilutil::EmitErrorOnGlobalVariable(
m_ctx, GV, Twine(kRedefineGlobal) + GV->getName());
bSuccess = false;
}
continue;
}
Constant *Initializer = nullptr;
if (GV->hasInitializer())
Initializer = GV->getInitializer();
Type *Ty = GV->getType()->getElementType();
GlobalVariable *NewGV = new GlobalVariable(
*pM, Ty, GV->isConstant(), GV->getLinkage(), Initializer,
GV->getName(),
/*InsertBefore*/ nullptr, GV->getThreadLocalMode(),
GV->getType()->getAddressSpace(), GV->isExternallyInitialized());
m_newGlobals[GV->getName()] = NewGV;
vmap[GV] = NewGV;
typeSys.CopyTypeAnnotation(Ty, tmpTypeSys);
if (DxilResourceBase *res = pLib->GetResource(GV)) {
bSuccess &= AddResource(res, NewGV);
typeSys.CopyTypeAnnotation(res->GetHLSLType(), tmpTypeSys);
}
}
}
return bSuccess;
}
void DxilLinkJob::CloneFunctions(ValueToValueMapTy &vmap) {
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
Function *F = linkInfo->func;
Function *NewF = m_newFunctions[F->getName()];
// Add dxil functions to vmap.
for (Function *UsedF : linkInfo->usedFunctions) {
if (!vmap.count(UsedF)) {
// Extern function need match by name
DXASSERT(m_newFunctions.count(UsedF->getName()),
"Must have new function.");
vmap[UsedF] = m_newFunctions[UsedF->getName()];
}
}
CloneFunction(F, NewF, vmap);
}
}
void DxilLinkJob::AddFunctions(DxilModule &DM, ValueToValueMapTy &vmap) {
DxilTypeSystem &typeSys = DM.GetTypeSystem();
Module *pM = DM.GetModule();
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
DxilLib *pLib = it.second;
DxilModule &tmpDM = pLib->GetDxilModule();
DxilTypeSystem &tmpTypeSys = tmpDM.GetTypeSystem();
Function *F = linkInfo->func;
Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
F->getName(), pM);
NewF->setAttributes(F->getAttributes());
if (!NewF->hasFnAttribute(llvm::Attribute::NoInline))
NewF->addFnAttr(llvm::Attribute::AlwaysInline);
if (DxilFunctionAnnotation *funcAnnotation =
tmpTypeSys.GetFunctionAnnotation(F)) {
// Clone funcAnnotation to typeSys.
typeSys.CopyFunctionAnnotation(NewF, F, tmpTypeSys);
}
// Add to function map.
m_newFunctions[NewF->getName()] = NewF;
vmap[F] = NewF;
}
}
std::unique_ptr<Module>
DxilLinkJob::Link(std::pair<DxilFunctionLinkInfo *, DxilLib *> &entryLinkPair,
const ShaderModel *pSM) {
Function *entryFunc = entryLinkPair.first->func;
DxilModule &entryDM = entryLinkPair.second->GetDxilModule();
if (!entryDM.HasDxilFunctionProps(entryFunc)) {
// Cannot get function props.
dxilutil::EmitErrorOnFunction(m_ctx, entryFunc,
Twine(kNoEntryProps) + entryFunc->getName());
return nullptr;
}
DxilFunctionProps props = entryDM.GetDxilFunctionProps(entryFunc);
if (pSM->GetKind() != props.shaderKind) {
// Shader kind mismatch.
dxilutil::EmitErrorOnFunction(
m_ctx, entryFunc,
Twine(kShaderKindMismatch) + ShaderModel::GetKindName(pSM->GetKind()) +
" and " + ShaderModel::GetKindName(props.shaderKind));
return nullptr;
}
// Create new module.
std::unique_ptr<Module> pM =
llvm::make_unique<Module>(entryFunc->getName(), entryDM.GetCtx());
// Set target.
pM->setTargetTriple(entryDM.GetModule()->getTargetTriple());
// Add dxil operation functions before create DxilModule.
AddFunctionDecls(pM.get());
// Create DxilModule.
const bool bSkipInit = true;
DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
DM.SetShaderModel(pSM, entryDM.GetUseMinPrecision());
// Set Validator version.
DM.SetValidatorVersion(m_valMajor, m_valMinor);
ValueToValueMapTy vmap;
// Add function
AddFunctions(DM, vmap);
// Set Entry
Function *NewEntryFunc = m_newFunctions[entryFunc->getName()];
DM.SetEntryFunction(NewEntryFunc);
DM.SetEntryFunctionName(entryFunc->getName());
DxilEntryPropsMap EntryPropMap;
std::unique_ptr<DxilEntryProps> pProps =
llvm::make_unique<DxilEntryProps>(entryDM.GetDxilEntryProps(entryFunc));
EntryPropMap[NewEntryFunc] = std::move(pProps);
DM.ResetEntryPropsMap(std::move(EntryPropMap));
if (NewEntryFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
NewEntryFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
if (props.IsHS()) {
Function *patchConstantFunc = props.ShaderProps.HS.patchConstantFunc;
Function *newPatchConstantFunc =
m_newFunctions[patchConstantFunc->getName()];
props.ShaderProps.HS.patchConstantFunc = newPatchConstantFunc;
if (newPatchConstantFunc->hasFnAttribute(llvm::Attribute::AlwaysInline))
newPatchConstantFunc->removeFnAttr(llvm::Attribute::AlwaysInline);
}
// Set root sig if exist.
if (!props.serializedRootSignature.empty()) {
DM.ResetSerializedRootSignature(props.serializedRootSignature);
props.serializedRootSignature.clear();
}
// Set EntryProps
DM.SetShaderProperties(&props);
// Add global
bool bSuccess = AddGlobals(DM, vmap);
if (!bSuccess)
return nullptr;
// Clone functions.
CloneFunctions(vmap);
// Call global constrctor.
IRBuilder<> Builder(dxilutil::FindAllocaInsertionPt(DM.GetEntryFunction()));
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
DxilLib *pLib = it.second;
// Skip constructor in entry lib which is already called for entries inside
// entry lib.
if (pLib == entryLinkPair.second)
continue;
Function *F = linkInfo->func;
if (pLib->IsInitFunc(F)) {
Function *NewF = m_newFunctions[F->getName()];
Builder.CreateCall(NewF);
}
}
// Refresh intrinsic cache.
DM.GetOP()->RefreshCache();
// Add resource to DM.
// This should be after functions cloned.
AddResourceToDM(DM);
// Link metadata like debug info.
LinkNamedMDNodes(pM.get(), vmap);
RunPreparePass(*pM);
return pM;
}
// Based on CodeGenModule::EmitCtorList.
void DxilLinkJob::EmitCtorListForLib(Module *pM) {
LLVMContext &Ctx = pM->getContext();
Type *VoidTy = Type::getVoidTy(Ctx);
Type *Int32Ty = Type::getInt32Ty(Ctx);
Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
// Ctor function type is void()*.
llvm::FunctionType *CtorFTy = llvm::FunctionType::get(VoidTy, false);
llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
// Get the type of a ctor entry, { i32, void ()*, i8* }.
llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
// Construct the constructor and destructor arrays.
SmallVector<llvm::Constant *, 8> Ctors;
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
DxilLib *pLib = it.second;
Function *F = linkInfo->func;
if (pLib->IsInitFunc(F)) {
Function *NewF = m_newFunctions[F->getName()];
llvm::Constant *S[] = {llvm::ConstantInt::get(Int32Ty, 65535, false),
llvm::ConstantExpr::getBitCast(NewF, CtorPFTy),
(llvm::Constant::getNullValue(VoidPtrTy))};
Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
}
}
if (!Ctors.empty()) {
const StringRef GlobalName = "llvm.global_ctors";
llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
new llvm::GlobalVariable(*pM, AT, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(AT, Ctors), GlobalName);
}
}
std::unique_ptr<Module> DxilLinkJob::LinkToLib(const ShaderModel *pSM) {
if (m_functionDefs.empty()) {
dxilutil::EmitErrorOnContext(m_ctx, Twine(kNoFunctionsToExport));
return nullptr;
}
DxilLib *pLib = m_functionDefs.begin()->second;
DxilModule &tmpDM = pLib->GetDxilModule();
// Create new module.
std::unique_ptr<Module> pM =
llvm::make_unique<Module>("merged_lib", tmpDM.GetCtx());
// Set target.
pM->setTargetTriple(tmpDM.GetModule()->getTargetTriple());
// Add dxil operation functions and external decls before create DxilModule.
AddFunctionDecls(pM.get());
// Create DxilModule.
const bool bSkipInit = true;
DxilModule &DM = pM->GetOrCreateDxilModule(bSkipInit);
DM.SetShaderModel(pSM, tmpDM.GetUseMinPrecision());
// Set Validator version.
DM.SetValidatorVersion(m_valMajor, m_valMinor);
ValueToValueMapTy vmap;
// Add function
AddFunctions(DM, vmap);
// Set DxilFunctionProps.
DxilEntryPropsMap EntryPropMap;
for (auto &it : m_functionDefs) {
DxilFunctionLinkInfo *linkInfo = it.first;
DxilLib *pLib = it.second;
DxilModule &tmpDM = pLib->GetDxilModule();
Function *F = linkInfo->func;
if (tmpDM.HasDxilEntryProps(F)) {
Function *NewF = m_newFunctions[F->getName()];
DxilEntryProps &props = tmpDM.GetDxilEntryProps(F);
std::unique_ptr<DxilEntryProps> pProps =
llvm::make_unique<DxilEntryProps>(props);
EntryPropMap[NewF] = std::move(pProps);
}
}
DM.ResetEntryPropsMap(std::move(EntryPropMap));
// Add global
bool bSuccess = AddGlobals(DM, vmap);
if (!bSuccess)
return nullptr;
// Clone functions.
CloneFunctions(vmap);
// Refresh intrinsic cache.
DM.GetOP()->RefreshCache();
// Add resource to DM.
// This should be after functions cloned.
AddResourceToDM(DM);
// Link metadata like debug info.
LinkNamedMDNodes(pM.get(), vmap);
// Build global.ctors.
EmitCtorListForLib(pM.get());
RunPreparePass(*pM);
if (!m_exportMap.empty()) {
m_exportMap.BeginProcessing();
DM.ClearDxilMetadata(*pM);
for (auto it = pM->begin(); it != pM->end();) {
Function *F = it++;
if (F->isDeclaration())
continue;
if (!m_exportMap.ProcessFunction(F, true)) {
// Remove Function not in exportMap.
DM.RemoveFunction(F);
// Only erase function if user is empty. The function can still be
// used by @llvm.global_ctors
if (F->user_empty())
F->eraseFromParent();
}
}
if (!m_exportMap.EndProcessing()) {
for (auto &name : m_exportMap.GetNameCollisions()) {
std::string escaped;
llvm::raw_string_ostream os(escaped);
dxilutil::PrintEscapedString(name, os);
dxilutil::EmitErrorOnContext(m_ctx,
Twine(kExportNameCollision) + os.str());
}
for (auto &name : m_exportMap.GetUnusedExports()) {
std::string escaped;
llvm::raw_string_ostream os(escaped);
dxilutil::PrintEscapedString(name, os);
dxilutil::EmitErrorOnContext(m_ctx,
Twine(kExportFunctionMissing) + os.str());
}
return nullptr;
}
// Rename the original, if necessary, then clone the rest
for (auto &it : m_exportMap.GetFunctionRenames()) {
Function *F = it.first;
auto &renames = it.second;
if (renames.empty())
continue;
auto itName = renames.begin();