-
Notifications
You must be signed in to change notification settings - Fork 873
Expand file tree
/
Copy pathDxilCondenseResources.cpp
More file actions
3375 lines (3050 loc) · 118 KB
/
DxilCondenseResources.cpp
File metadata and controls
3375 lines (3050 loc) · 118 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
///////////////////////////////////////////////////////////////////////////////
// //
// DxilCondenseResources.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. //
// //
// Provides a pass to make resource IDs zero-based and dense. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/DXIL/DxilInstructions.h"
#include "dxc/DXIL/DxilMetadataHelper.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilResourceBinding.h"
#include "dxc/DXIL/DxilSignatureElement.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/DxcBindingTable/DxcBindingTable.h"
#include "dxc/HLSL/DxilGenerationPass.h"
#include "dxc/HLSL/DxilSpanAllocator.h"
#include "dxc/HLSL/HLMatrixType.h"
#include "dxc/HLSL/HLModule.h"
#include "dxc/Support/Global.h"
#include "llvm/Analysis/DxilValueCache.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Utils/Local.h"
#include <memory>
#include <unordered_set>
using namespace llvm;
using namespace hlsl;
// Resource rangeID remap.
namespace {
struct ResourceID {
DXIL::ResourceClass Class; // Resource class.
unsigned ID; // Resource ID, as specified on entry.
bool operator<(const ResourceID &other) const {
if (Class < other.Class)
return true;
if (Class > other.Class)
return false;
if (ID < other.ID)
return true;
return false;
}
};
struct RemapEntry {
ResourceID ResID; // Resource identity, as specified on entry.
DxilResourceBase *Resource; // In-memory resource representation.
unsigned Index; // Index in resource vector - new ID for the resource.
};
typedef std::map<ResourceID, RemapEntry> RemapEntryCollection;
template <typename TResource>
void BuildRewrites(const std::vector<std::unique_ptr<TResource>> &Rs,
RemapEntryCollection &C) {
const unsigned s = (unsigned)Rs.size();
for (unsigned i = 0; i < s; ++i) {
const std::unique_ptr<TResource> &R = Rs[i];
if (R->GetID() != i) {
ResourceID RId = {R->GetClass(), R->GetID()};
RemapEntry RE = {RId, R.get(), i};
C[RId] = RE;
}
}
}
// Build m_rewrites, returns 'true' if any rewrites are needed.
bool BuildRewriteMap(RemapEntryCollection &rewrites, DxilModule &DM) {
BuildRewrites(DM.GetCBuffers(), rewrites);
BuildRewrites(DM.GetSRVs(), rewrites);
BuildRewrites(DM.GetUAVs(), rewrites);
BuildRewrites(DM.GetSamplers(), rewrites);
return !rewrites.empty();
}
} // namespace
class DxilResourceRegisterAllocator {
private:
SpacesAllocator<unsigned, hlsl::DxilCBuffer> m_reservedCBufferRegisters;
SpacesAllocator<unsigned, hlsl::DxilSampler> m_reservedSamplerRegisters;
SpacesAllocator<unsigned, hlsl::DxilResource> m_reservedUAVRegisters;
SpacesAllocator<unsigned, hlsl::DxilResource> m_reservedSRVRegisters;
template <typename T>
static void
GatherReservedRegisters(const std::vector<std::unique_ptr<T>> &ResourceList,
SpacesAllocator<unsigned, T> &SAlloc) {
for (auto &res : ResourceList) {
if (res->IsAllocated()) {
typename SpacesAllocator<unsigned, T>::Allocator &Alloc =
SAlloc.Get(res->GetSpaceID());
Alloc.ForceInsertAndClobber(res.get(), res->GetLowerBound(),
res->GetUpperBound());
if (res->IsUnbounded())
Alloc.SetUnbounded(res.get());
}
}
}
template <typename T>
static bool
AllocateRegisters(LLVMContext &Ctx,
const std::vector<std::unique_ptr<T>> &resourceList,
SpacesAllocator<unsigned, T> &ReservedRegisters,
unsigned AutoBindingSpace) {
bool bChanged = false;
SpacesAllocator<unsigned, T> SAlloc;
// Reserve explicitly allocated resources
for (auto &res : resourceList) {
const unsigned space = res->GetSpaceID();
typename SpacesAllocator<unsigned, T>::Allocator &alloc =
SAlloc.Get(space);
typename SpacesAllocator<unsigned, T>::Allocator &reservedAlloc =
ReservedRegisters.Get(space);
if (res->IsAllocated()) {
const unsigned reg = res->GetLowerBound();
const T *conflict = nullptr;
if (res->IsUnbounded()) {
const T *unbounded = alloc.GetUnbounded();
if (unbounded) {
dxilutil::EmitErrorOnGlobalVariable(
Ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
Twine("more than one unbounded resource (") +
unbounded->GetGlobalName() + (" and ") +
res->GetGlobalName() + (") in space ") + Twine(space));
} else {
conflict = alloc.Insert(res.get(), reg, res->GetUpperBound());
if (!conflict) {
alloc.SetUnbounded(res.get());
reservedAlloc.SetUnbounded(res.get());
}
}
} else {
conflict = alloc.Insert(res.get(), reg, res->GetUpperBound());
}
if (conflict) {
dxilutil::EmitErrorOnGlobalVariable(
Ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
((res->IsUnbounded()) ? Twine("unbounded ") : Twine("")) +
Twine("resource ") + res->GetGlobalName() +
Twine(" at register ") + Twine(reg) +
Twine(" overlaps with resource ") +
conflict->GetGlobalName() + Twine(" at register ") +
Twine(conflict->GetLowerBound()) + Twine(", space ") +
Twine(space));
} else {
// Also add this to the reserved (unallocatable) range, if it wasn't
// already there.
reservedAlloc.ForceInsertAndClobber(res.get(), res->GetLowerBound(),
res->GetUpperBound());
}
}
}
// Allocate unallocated resources
for (auto &res : resourceList) {
if (res->IsAllocated())
continue;
unsigned space = res->GetSpaceID();
if (space == UINT_MAX)
space = AutoBindingSpace;
typename SpacesAllocator<unsigned, T>::Allocator &alloc =
SAlloc.Get(space);
typename SpacesAllocator<unsigned, T>::Allocator &reservedAlloc =
ReservedRegisters.Get(space);
unsigned reg = 0;
unsigned end = 0;
bool allocateSpaceFound = false;
if (res->IsUnbounded()) {
if (alloc.GetUnbounded() != nullptr) {
const T *unbounded = alloc.GetUnbounded();
dxilutil::EmitErrorOnGlobalVariable(
Ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
Twine("more than one unbounded resource (") +
unbounded->GetGlobalName() + Twine(" and ") +
res->GetGlobalName() + Twine(") in space ") + Twine(space));
continue;
}
if (reservedAlloc.FindForUnbounded(reg)) {
end = UINT_MAX;
allocateSpaceFound = true;
}
} else if (reservedAlloc.Find(res->GetRangeSize(), reg)) {
end = reg + res->GetRangeSize() - 1;
allocateSpaceFound = true;
}
if (allocateSpaceFound) {
bool success = reservedAlloc.Insert(res.get(), reg, end) == nullptr;
DXASSERT_NOMSG(success);
success = alloc.Insert(res.get(), reg, end) == nullptr;
DXASSERT_NOMSG(success);
if (res->IsUnbounded()) {
alloc.SetUnbounded(res.get());
reservedAlloc.SetUnbounded(res.get());
}
res->SetLowerBound(reg);
res->SetSpaceID(space);
bChanged = true;
} else {
dxilutil::EmitErrorOnGlobalVariable(
Ctx, dyn_cast<GlobalVariable>(res->GetGlobalSymbol()),
((res->IsUnbounded()) ? Twine("unbounded ") : Twine("")) +
Twine("resource ") + res->GetGlobalName() +
Twine(" could not be allocated"));
}
}
return bChanged;
}
public:
void GatherReservedRegisters(DxilModule &DM) {
// For backcompat with FXC, shader models 5.0 and below will not
// auto-allocate resources at a register explicitely assigned to even an
// unused resource.
if (DM.GetLegacyResourceReservation()) {
GatherReservedRegisters(DM.GetCBuffers(), m_reservedCBufferRegisters);
GatherReservedRegisters(DM.GetSamplers(), m_reservedSamplerRegisters);
GatherReservedRegisters(DM.GetUAVs(), m_reservedUAVRegisters);
GatherReservedRegisters(DM.GetSRVs(), m_reservedSRVRegisters);
}
}
bool AllocateRegisters(DxilModule &DM) {
uint32_t AutoBindingSpace = DM.GetAutoBindingSpace();
if (AutoBindingSpace == UINT_MAX) {
// For libraries, we don't allocate unless AutoBindingSpace is set.
if (DM.GetShaderModel()->IsLib())
return false;
// For shaders, we allocate in space 0 by default.
AutoBindingSpace = 0;
}
bool bChanged = false;
bChanged |= AllocateRegisters(DM.GetCtx(), DM.GetCBuffers(),
m_reservedCBufferRegisters, AutoBindingSpace);
bChanged |= AllocateRegisters(DM.GetCtx(), DM.GetSamplers(),
m_reservedSamplerRegisters, AutoBindingSpace);
bChanged |= AllocateRegisters(DM.GetCtx(), DM.GetUAVs(),
m_reservedUAVRegisters, AutoBindingSpace);
bChanged |= AllocateRegisters(DM.GetCtx(), DM.GetSRVs(),
m_reservedSRVRegisters, AutoBindingSpace);
return bChanged;
}
};
bool llvm::AreDxilResourcesDense(llvm::Module *M,
hlsl::DxilResourceBase **ppNonDense) {
DxilModule &DM = M->GetOrCreateDxilModule();
RemapEntryCollection rewrites;
if (BuildRewriteMap(rewrites, DM)) {
*ppNonDense = rewrites.begin()->second.Resource;
return false;
} else {
*ppNonDense = nullptr;
return true;
}
}
static bool GetConstantLegalGepForSplitAlloca(GetElementPtrInst *gep,
DxilValueCache *DVC,
int64_t *ret) {
if (gep->getNumIndices() != 2) {
return false;
}
if (ConstantInt *Index0 = dyn_cast<ConstantInt>(gep->getOperand(1))) {
if (Index0->getLimitedValue() != 0) {
return false;
}
} else {
return false;
}
if (ConstantInt *C = DVC->GetConstInt(gep->getOperand(2))) {
int64_t index = C->getSExtValue();
*ret = index;
return true;
}
return false;
}
static bool LegalizeResourceArrays(Module &M, DxilValueCache *DVC) {
SmallVector<AllocaInst *, 16> Allocas;
bool Changed = false;
// Find all allocas
for (Function &F : M) {
if (F.empty())
continue;
BasicBlock &BB = F.getEntryBlock();
for (Instruction &I : BB) {
if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Type *ty = AI->getAllocatedType();
// Only handle single dimentional array. Since this pass runs after
// MultiDimArrayToOneDimArray, it should handle all arrays.
if (ty->isArrayTy() &&
hlsl::dxilutil::IsHLSLResourceType(ty->getArrayElementType()))
Allocas.push_back(AI);
}
}
}
SmallVector<AllocaInst *, 16> ScalarAllocas;
std::unordered_map<GetElementPtrInst *, int64_t> ConstIndices;
for (AllocaInst *AI : Allocas) {
Type *ty = AI->getAllocatedType();
Type *resType = ty->getArrayElementType();
ScalarAllocas.clear();
ConstIndices.clear();
bool SplitAlloca = true;
for (User *U : AI->users()) {
if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(U)) {
int64_t index = 0;
if (!GetConstantLegalGepForSplitAlloca(gep, DVC, &index)) {
SplitAlloca = false;
break;
}
// Out of bounds. Out of bounds GEP's will trigger and error later.
if (index < 0 || index >= (int64_t)ty->getArrayNumElements()) {
SplitAlloca = false;
Changed = true;
dxilutil::EmitErrorOnInstruction(
gep, "Accessing resource array with out-out-bounds index.");
}
ConstIndices[gep] = index;
} else {
SplitAlloca = false;
break;
}
}
if (SplitAlloca) {
IRBuilder<> B(AI);
ScalarAllocas.resize(ty->getArrayNumElements());
for (auto it = AI->user_begin(), end = AI->user_end(); it != end;) {
GetElementPtrInst *gep = cast<GetElementPtrInst>(*(it++));
assert(ConstIndices.count(gep));
int64_t idx = ConstIndices[gep];
AllocaInst *ScalarAI = ScalarAllocas[idx];
if (!ScalarAI) {
ScalarAI = B.CreateAlloca(resType);
ScalarAllocas[idx] = ScalarAI;
}
gep->replaceAllUsesWith(ScalarAI);
gep->eraseFromParent();
}
AI->eraseFromParent();
Changed = true;
}
}
return Changed;
}
typedef std::unordered_map<std::string, DxilResourceBase *> ResourceMap;
template <typename T>
static inline void GatherResources(const std::vector<std::unique_ptr<T>> &List,
ResourceMap *Map) {
for (const std::unique_ptr<T> &ptr : List) {
(*Map)[ptr->GetGlobalName()] = ptr.get();
}
}
static bool LegalizeResources(Module &M, DxilValueCache *DVC) {
bool Changed = false;
Changed |= LegalizeResourceArrays(M, DVC);
// Simple pass to collect resource PHI's
SmallVector<PHINode *, 8> PHIs;
for (Function &F : M) {
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (PHINode *PN = dyn_cast<PHINode>(&I)) {
if (hlsl::dxilutil::IsHLSLResourceType(PN->getType())) {
PHIs.push_back(PN);
}
} else {
break;
}
}
}
}
SmallVector<Instruction *, 8> DCEWorklist;
// Try to simplify those PHI's with DVC and collect them in DCEWorklist
for (unsigned Attempt = 0, MaxAttempt = PHIs.size(); Attempt < MaxAttempt;
Attempt++) {
bool LocalChanged = false;
for (unsigned i = 0; i < PHIs.size(); i++) {
PHINode *PN = PHIs[i];
if (Value *V = DVC->GetValue(PN)) {
PN->replaceAllUsesWith(V);
LocalChanged = true;
DCEWorklist.push_back(PN);
PHIs.erase(PHIs.begin() + i);
} else {
i++;
}
}
Changed |= LocalChanged;
if (!LocalChanged)
break;
}
// Collect Resource GV loads
for (GlobalVariable &GV : M.globals()) {
Type *Ty = GV.getType()->getPointerElementType();
while (Ty->isArrayTy())
Ty = Ty->getArrayElementType();
if (!hlsl::dxilutil::IsHLSLResourceType(Ty))
continue;
SmallVector<User *, 4> WorkList(GV.user_begin(), GV.user_end());
while (WorkList.size()) {
User *U = WorkList.pop_back_val();
if (LoadInst *Load = dyn_cast<LoadInst>(U)) {
DCEWorklist.push_back(Load);
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
for (User *GepU : GEP->users())
WorkList.push_back(GepU);
}
}
}
// Simple DCE
while (DCEWorklist.size()) {
Instruction *I = DCEWorklist.back();
DCEWorklist.pop_back();
if (llvm::isInstructionTriviallyDead(I)) {
for (Use &Op : I->operands())
if (Instruction *OpI = dyn_cast<Instruction>(Op.get()))
DCEWorklist.push_back(OpI);
I->eraseFromParent();
// Remove the instruction from the worklist if it still exists in it.
DCEWorklist.erase(std::remove(DCEWorklist.begin(), DCEWorklist.end(), I),
DCEWorklist.end());
Changed = true;
}
}
return Changed;
}
namespace {
class DxilLowerCreateHandleForLib : public ModulePass {
private:
RemapEntryCollection m_rewrites;
DxilModule *m_DM;
bool m_HasDbgInfo;
bool m_bIsLib;
bool m_bLegalizationFailed;
public:
static char ID; // Pass identification, replacement for typeid
explicit DxilLowerCreateHandleForLib() : ModulePass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DxilValueCache>();
}
StringRef getPassName() const override {
return "DXIL Lower createHandleForLib";
}
bool runOnModule(Module &M) override {
DxilModule &DM = M.GetOrCreateDxilModule();
m_DM = &DM;
// Clear llvm used to remove unused resource.
m_DM->ClearLLVMUsed();
m_bIsLib = DM.GetShaderModel()->IsLib();
m_bLegalizationFailed = false;
FailOnPoisonResources();
bool bChanged = false;
if (DM.GetShaderModel()->IsSM66Plus()) {
bChanged = PatchDynamicTBuffers(DM);
SetNonUniformIndexForDynamicResource(DM);
}
unsigned numResources = DM.GetCBuffers().size() + DM.GetUAVs().size() +
DM.GetSRVs().size() + DM.GetSamplers().size();
if (!numResources) {
// Remove createHandleFromHandle when not a lib
if (!m_bIsLib)
RemoveCreateHandleFromHandle(DM);
return false;
}
// Switch tbuffers to SRVs, as they have been treated as cbuffers up to this
// point.
if (DM.GetCBuffers().size())
bChanged |= PatchTBuffers(DM);
// Assign resource binding overrides.
hlsl::ApplyBindingTableFromMetadata(DM);
// Gather reserved resource registers while we still have
// unused resources that might have explicit register assignments.
DxilResourceRegisterAllocator ResourceRegisterAllocator;
ResourceRegisterAllocator.GatherReservedRegisters(DM);
// Remove unused resources.
if (DM.GetUnusedResourceBinding() == UnusedResourceBinding::Strip)
bChanged |= DM.RemoveResourcesWithUnusedSymbols();
unsigned newResources = DM.GetCBuffers().size() + DM.GetUAVs().size() +
DM.GetSRVs().size() + DM.GetSamplers().size();
if (0 == newResources)
return bChanged;
{
DxilValueCache *DVC = &getAnalysis<DxilValueCache>();
bool bLocalChanged = LegalizeResources(M, DVC);
if (bLocalChanged &&
DM.GetUnusedResourceBinding() == UnusedResourceBinding::Strip) {
// Remove unused resources.
bChanged |= DM.RemoveResourcesWithUnusedSymbols();
}
bChanged |= bLocalChanged;
}
bChanged |= ResourceRegisterAllocator.AllocateRegisters(DM);
if (DM.GetUnusedResourceBinding() == UnusedResourceBinding::ReserveAll)
bChanged |= DM.RemoveResourcesWithUnusedSymbols();
// Fill in top-level CBuffer variable usage bit
UpdateCBufferUsage();
if (m_bIsLib &&
DM.GetShaderModel()->GetMinor() == ShaderModel::kOfflineMinor)
return bChanged;
// Make sure no select on resource.
bChanged |= RemovePhiOnResource();
if (m_bLegalizationFailed)
return bChanged;
if (m_bIsLib) {
if (DM.GetOP()->UseMinPrecision())
bChanged |= UpdateStructTypeForLegacyLayout();
return bChanged;
}
bChanged = true;
// Load up debug information, to cross-reference values and the instructions
// used to load them.
m_HasDbgInfo = llvm::getDebugMetadataVersionFromModule(M) != 0;
GenerateDxilResourceHandles();
if (DM.GetOP()->UseMinPrecision())
UpdateStructTypeForLegacyLayout();
// Change resource symbol into undef.
UpdateResourceSymbols();
// Remove createHandleFromHandle when not a lib.
RemoveCreateHandleFromHandle(DM);
// Remove unused createHandleForLib functions.
dxilutil::RemoveUnusedFunctions(M, DM.GetEntryFunction(),
DM.GetPatchConstantFunction(), m_bIsLib);
// Erase type annotations for structures no longer used
DM.GetTypeSystem().EraseUnusedStructAnnotations();
return bChanged;
}
private:
void FailOnPoisonResources();
bool RemovePhiOnResource();
void UpdateResourceSymbols();
void ReplaceResourceUserWithHandle(DxilResource &res, LoadInst *load,
Instruction *handle);
void TranslateDxilResourceUses(DxilResourceBase &res);
void GenerateDxilResourceHandles();
bool UpdateStructTypeForLegacyLayout();
// Switch CBuffer for SRV for TBuffers.
bool PatchDynamicTBuffers(DxilModule &DM);
bool PatchTBuffers(DxilModule &DM);
void PatchTBufferUse(Value *V, DxilModule &DM, DenseSet<Value *> &patchedSet);
void UpdateCBufferUsage();
void SetNonUniformIndexForDynamicResource(DxilModule &DM);
void RemoveCreateHandleFromHandle(DxilModule &DM);
};
} // namespace
// Phi on resource.
namespace {
typedef std::unordered_map<Value *, Value *> ValueToValueMap;
typedef llvm::SetVector<Value *> ValueSetVector;
typedef llvm::SmallVector<Value *, 4> IndexVector;
typedef std::unordered_map<Value *, IndexVector> ValueToIdxMap;
//#define SUPPORT_SELECT_ON_ALLOCA
// Errors:
class ResourceUseErrors {
bool m_bErrorsReported;
public:
ResourceUseErrors() : m_bErrorsReported(false) {}
enum ErrorCode : unsigned int {
// Collision between use of one resource GV and another.
// All uses must be guaranteed to resolve to only one GV.
// Additionally, when writing resource to alloca, all uses
// of that alloca are considered resolving to a single GV.
GVConflicts,
// static global resources are disallowed for libraries at this time.
// for non-library targets, they should have been eliminated already.
StaticGVUsed,
// user function calls with resource params or return type are
// are currently disallowed for libraries.
UserCallsWithResources,
// When searching up from store pointer looking for alloca,
// we encountered an unexpted value type
UnexpectedValuesFromStorePointer,
// Without SUPPORT_SELECT_ON_ALLOCA, phi/select on alloca based
// pointer is disallowed, since this scenario is still untested.
// This error also covers any other unknown alloca pointer uses.
// Supported:
// alloca (-> gep)? -> load -> ...
// alloca (-> gep)? -> store.
// Unsupported without SUPPORT_SELECT_ON_ALLOCA:
// alloca (-> gep)? -> phi/select -> ...
AllocaUserDisallowed,
MismatchHandleAnnotation,
MixDynamicResourceWithBindingResource,
MismatchIsSampler,
#ifdef SUPPORT_SELECT_ON_ALLOCA
// Conflict in select/phi between GV pointer and alloca pointer. This
// algorithm can't handle this case.
AllocaSelectConflict,
#endif
ErrorCodeCount
};
const StringRef ErrorText[ErrorCodeCount] = {
"local resource not guaranteed to map to unique global resource.",
"static global resource use is disallowed for library functions.",
"exported library functions cannot have resource parameters or return "
"value.",
"internal error: unexpected instruction type when looking for alloca "
"from store.",
"phi/select disallowed on pointers to local resources.",
"mismatch handle annotation",
"possible mixing dynamic resource and binding resource",
"merging sampler handle and resource handle",
#ifdef SUPPORT_SELECT_ON_ALLOCA
,
"unable to resolve merge of global and local resource pointers."
#endif
};
ValueSetVector ErrorSets[ErrorCodeCount];
// Ulitimately, the goal of ErrorUsers is to mark all create handles
// so we don't try to report errors on them again later.
std::unordered_set<Value *> ErrorUsers; // users of error values
bool AddErrorUsers(Value *V) {
auto it = ErrorUsers.insert(V);
if (!it.second)
return false; // already there
if (isa<GEPOperator>(V) || isa<LoadInst>(V) || isa<PHINode>(V) ||
isa<SelectInst>(V) || isa<AllocaInst>(V)) {
for (auto U : V->users()) {
AddErrorUsers(U);
}
} else if (isa<StoreInst>(V)) {
AddErrorUsers(cast<StoreInst>(V)->getPointerOperand());
}
// create handle will be marked, but users not followed
return true;
}
void ReportError(ErrorCode ec, Value *V) {
DXASSERT_NOMSG(ec < ErrorCodeCount);
if (!ErrorSets[ec].insert(V))
return; // Error already reported
AddErrorUsers(V);
m_bErrorsReported = true;
if (Instruction *I = dyn_cast<Instruction>(V)) {
dxilutil::EmitErrorOnInstruction(I, ErrorText[ec]);
} else {
StringRef Name = V->getName();
std::string escName;
if (isa<Function>(V)) {
llvm::raw_string_ostream os(escName);
dxilutil::PrintEscapedString(Name, os);
os.flush();
Name = escName;
}
V->getContext().emitError(Twine(ErrorText[ec]) + " Value: " + Name);
}
}
bool ErrorsReported() { return m_bErrorsReported; }
};
unsigned CountArrayDimensions(Type *Ty,
// Optionally collect dimensions
SmallVector<unsigned, 4> *dims = nullptr) {
if (Ty->isPointerTy())
Ty = Ty->getPointerElementType();
unsigned dim = 0;
if (dims)
dims->clear();
while (Ty->isArrayTy()) {
if (dims)
dims->push_back(Ty->getArrayNumElements());
dim++;
Ty = Ty->getArrayElementType();
}
return dim;
}
// Delete unused CleanupInsts, restarting when changed
// Return true if something was deleted
bool CleanupUnusedValues(std::unordered_set<Instruction *> &CleanupInsts) {
// - delete unused CleanupInsts, restarting when changed
bool bAnyChanges = false;
bool bChanged = false;
do {
bChanged = false;
for (auto it = CleanupInsts.begin(); it != CleanupInsts.end();) {
Instruction *I = *(it++);
if (I->user_empty()) {
// Add instructions operands CleanupInsts
for (unsigned iOp = 0; iOp < I->getNumOperands(); iOp++) {
if (Instruction *opI = dyn_cast<Instruction>(I->getOperand(iOp)))
CleanupInsts.insert(opI);
}
I->eraseFromParent();
CleanupInsts.erase(I);
bChanged = true;
}
}
if (bChanged)
bAnyChanges = true;
} while (bChanged);
return bAnyChanges;
}
// Helper class for legalizing resource use
// Convert select/phi on resources to select/phi on index to GEP on GV.
// Convert resource alloca to index alloca.
// Assumes createHandleForLib has no select/phi
class LegalizeResourceUseHelper {
// Change:
// gep1 = GEP gRes, i1
// res1 = load gep1
// gep2 = GEP gRes, i2
// gep3 = GEP gRes, i3
// gep4 = phi gep2, gep3 <-- handle select/phi on GEP
// res4 = load gep4
// res5 = phi res1, res4
// res6 = load GEP gRes, 23 <-- handle constant GepExpression
// res = select cnd2, res5, res6
// handle = createHandleForLib(res)
// To:
// i4 = phi i2, i3
// i5 = phi i1, i4
// i6 = select cnd, i5, 23
// gep = GEP gRes, i6
// res = load gep
// handle = createHandleForLib(res)
// Also handles alloca
// resArray = alloca [2 x Resource]
// gep1 = GEP gRes, i1
// res1 = load gep1
// gep2 = GEP gRes, i2
// gep3 = GEP gRes, i3
// phi4 = phi gep2, gep3
// res4 = load phi4
// gep5 = GEP resArray, 0
// gep6 = GEP resArray, 1
// store gep5, res1
// store gep6, res4
// gep7 = GEP resArray, i7 <-- dynamically index array
// res = load gep7
// handle = createHandleForLib(res)
// Desired result:
// idxArray = alloca [2 x i32]
// phi4 = phi i2, i3
// gep5 = GEP idxArray, 0
// gep6 = GEP idxArray, 1
// store gep5, i1
// store gep6, phi4
// gep7 = GEP idxArray, i7
// gep8 = GEP gRes, gep7
// res = load gep8
// handle = createHandleForLib(res)
// Also handles multi-dim resource index and multi-dim resource array allocas
// Basic algorithm:
// - recursively mark each GV user with GV (ValueToResourceGV)
// - verify only one GV used for any given value
// - handle allocas by searching up from store for alloca
// - then recursively mark alloca users
// - ResToIdxReplacement keeps track of vector of indices that
// will be used to replace a given resource value or pointer
// - Next, create selects/phis for indices corresponding to
// selects/phis on resource pointers or values.
// - leave incoming index values undef for now
// - Create index allocas to replace resource allocas
// - Create GEPs on index allocas to replace GEPs on resource allocas
// - Create index loads on index allocas to replace loads on resource alloca
// GEP
// - Fill in replacements for GEPs on resource GVs
// - copy replacement index vectors to corresponding loads
// - Create index stores to replace resource stores to alloca/GEPs
// - Update selects/phis incoming index values
// - SimplifyMerges: replace index phis/selects on same value with that value
// - RemappedValues[phi/select] set to replacement value
// - use LookupValue from now on when reading from ResToIdxReplacement
// - Update handles by replacing load/GEP chains that go through select/phi
// with direct GV GEP + load, with select/phi on GEP indices instead.
public:
ResourceUseErrors m_Errors;
ValueToValueMap ValueToResourceGV;
ValueToIdxMap ResToIdxReplacement;
// Value sets we can use to iterate
ValueSetVector Selects, GEPs, Stores, Handles;
ValueSetVector Allocas, AllocaGEPs, AllocaLoads;
#ifdef SUPPORT_SELECT_ON_ALLOCA
ValueSetVector AllocaSelects;
#endif
std::unordered_set<Value *> NonUniformSet;
// New index selects created by pass, so we can try simplifying later
ValueSetVector NewSelects;
// Values that have been replaced with other values need remapping
ValueToValueMap RemappedValues;
// Things to clean up if no users:
std::unordered_set<Instruction *> CleanupInsts;
GlobalVariable *LookupResourceGV(Value *V) {
auto itGV = ValueToResourceGV.find(V);
if (itGV == ValueToResourceGV.end())
return nullptr;
return cast<GlobalVariable>(itGV->second);
}
// Follow RemappedValues, return input if not remapped
Value *LookupValue(Value *V) {
auto it = RemappedValues.find(V);
SmallPtrSet<Value *, 4> visited;
while (it != RemappedValues.end()) {
// Cycles should not happen, but are bad if they do.
if (visited.count(it->second)) {
// When remapping values to be replaced, we add them to RemappedValues
// so we don't use dead values stored in other sets/maps. Circular
// remaps that should not happen
DXASSERT(false, "otherwise, circular remapping");
llvm_unreachable("cycles detected in value remapping");
break;
}
V = it->second;
it = RemappedValues.find(V);
if (it != RemappedValues.end())
visited.insert(V);
}
return V;
}
bool AreLoadUsersTrivial(LoadInst *LI) {
for (auto U : LI->users()) {
if (CallInst *CI = dyn_cast<CallInst>(U)) {
Function *F = CI->getCalledFunction();
DxilModule &DM = F->getParent()->GetDxilModule();
hlsl::OP *hlslOP = DM.GetOP();
if (hlslOP->IsDxilOpFunc(F)) {
hlsl::OP::OpCodeClass opClass;
if (hlslOP->GetOpCodeClass(F, opClass) &&
opClass == DXIL::OpCodeClass::CreateHandleForLib) {
continue;
}
}
}
return false;
}
return true;
}
// This is used to quickly skip the common case where no work is needed
bool AreGEPUsersTrivial(GEPOperator *GEP) {
if (GlobalVariable *GV = LookupResourceGV(GEP)) {
if (GEP->getPointerOperand() != LookupResourceGV(GEP))
return false;
}
for (auto U : GEP->users()) {
if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
if (AreLoadUsersTrivial(LI))
continue;
}
return false;
}
return true;
}
// AssignResourceGVFromStore is used on pointer being stored to.
// Follow GEP/Phi/Select up to Alloca, then CollectResourceGVUsers on Alloca
void AssignResourceGVFromStore(GlobalVariable *GV, Value *V,
SmallPtrSet<Value *, 4> &visited,
bool bNonUniform) {
// Prevent cycles as we search up
if (visited.count(V) != 0)
return;
// Verify and skip if already processed
auto it = ValueToResourceGV.find(V);
if (it != ValueToResourceGV.end()) {
if (it->second != GV) {
m_Errors.ReportError(ResourceUseErrors::GVConflicts, V);
}
return;
}
if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
CollectResourceGVUsers(GV, AI, /*bAlloca*/ true, bNonUniform);
return;
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
// follow the pointer up
AssignResourceGVFromStore(GV, GEP->getPointerOperand(), visited,
bNonUniform);
return;
} else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
#ifdef SUPPORT_SELECT_ON_ALLOCA
// follow all incoming values
for (auto it : Phi->operand_values())
AssignResourceGVFromStore(GV, it, visited, bNonUniform);
#else