forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHLMatrixLowerPass.cpp
More file actions
1785 lines (1531 loc) · 71.2 KB
/
Copy pathHLMatrixLowerPass.cpp
File metadata and controls
1785 lines (1531 loc) · 71.2 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
///////////////////////////////////////////////////////////////////////////////
// //
// HLMatrixLowerPass.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. //
// //
// HLMatrixLowerPass implementation. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "dxc/HLSL/HLMatrixLowerPass.h"
#include "HLMatrixSubscriptUseReplacer.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/HLSL/HLMatrixLowerHelper.h"
#include "dxc/HLSL/HLMatrixType.h"
#include "dxc/HLSL/HLModule.h"
#include "dxc/HLSL/HLOperations.h"
#include "dxc/HlslIntrinsicOp.h"
#include "dxc/Support/Global.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#include <unordered_set>
#include <vector>
using namespace llvm;
using namespace hlsl;
using namespace hlsl::HLMatrixLower;
namespace hlsl {
namespace HLMatrixLower {
Value *BuildVector(Type *EltTy, ArrayRef<llvm::Value *> elts,
IRBuilder<> &Builder) {
Value *Vec = UndefValue::get(
VectorType::get(EltTy, static_cast<unsigned>(elts.size())));
for (unsigned i = 0; i < elts.size(); i++)
Vec = Builder.CreateInsertElement(Vec, elts[i], i);
return Vec;
}
} // namespace HLMatrixLower
} // namespace hlsl
namespace {
// Creates and manages a set of temporary overloaded functions keyed on the
// function type, and which should be destroyed when the pool gets out of scope.
class TempOverloadPool {
public:
TempOverloadPool(llvm::Module &Module, const char *BaseName)
: Module(Module), BaseName(BaseName) {}
~TempOverloadPool() { clear(); }
Function *get(FunctionType *Ty);
bool contains(FunctionType *Ty) const { return Funcs.count(Ty) != 0; }
bool contains(Function *Func) const;
void clear();
private:
llvm::Module &Module;
const char *BaseName;
llvm::DenseMap<FunctionType *, Function *> Funcs;
};
Function *TempOverloadPool::get(FunctionType *Ty) {
auto It = Funcs.find(Ty);
if (It != Funcs.end())
return It->second;
std::string MangledName;
raw_string_ostream MangledNameStream(MangledName);
MangledNameStream << BaseName;
MangledNameStream << '.';
Ty->print(MangledNameStream);
MangledNameStream.flush();
Function *Func = cast<Function>(Module.getOrInsertFunction(MangledName, Ty));
Funcs.insert(std::make_pair(Ty, Func));
return Func;
}
bool TempOverloadPool::contains(Function *Func) const {
auto It = Funcs.find(Func->getFunctionType());
return It != Funcs.end() && It->second == Func;
}
void TempOverloadPool::clear() {
for (auto Entry : Funcs) {
DXASSERT(Entry.second->use_empty(),
"Temporary function still used during pool destruction.");
Entry.second->eraseFromParent();
}
Funcs.clear();
}
// High-level matrix lowering pass.
//
// This pass converts matrices to their lowered vector representations,
// including global variables, local variables and operations,
// but not function signatures (arguments and return types) - left to
// HLSignatureLower and HLMatrixBitcastLower, nor matrices obtained from
// resources or constant - left to HLOperationLower.
//
// Algorithm overview:
// 1. Find all matrix and matrix array global variables and lower them to
// vectors.
// Walk any GEPs and insert vec-to-mat translation stubs so that consuming
// instructions keep dealing with matrix types for the moment.
// 2. For each function
// 2a. Lower all matrix and matrix array allocas, just like global variables.
// 2b. Lower all other instructions producing or consuming matrices
//
// Conversion stubs are used to allow converting instructions in isolation,
// and in an order-independent manner:
//
// Initial: MatInst1(MatInst2(MatInst3))
// After lowering MatInst2: MatInst1(VecToMat(VecInst2(MatToVec(MatInst3))))
// After lowering MatInst1: VecInst1(VecInst2(MatToVec(MatInst3)))
// After lowering MatInst3: VecInst1(VecInst2(VecInst3))
class HLMatrixLowerPass : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
explicit HLMatrixLowerPass() : ModulePass(ID) {}
StringRef getPassName() const override { return "HL matrix lower"; }
bool runOnModule(Module &M) override;
private:
void runOnFunction(Function &Func);
void addToDeadInsts(Instruction *Inst) { m_deadInsts.emplace_back(Inst); }
void deleteDeadInsts();
void getMatrixAllocasAndOtherInsts(Function &Func,
std::vector<AllocaInst *> &MatAllocas,
std::vector<Instruction *> &MatInsts);
Value *getLoweredByValOperand(Value *Val, IRBuilder<> &Builder,
bool DiscardStub = false);
Value *tryGetLoweredPtrOperand(Value *Ptr, IRBuilder<> &Builder,
bool DiscardStub = false);
Value *bitCastValue(Value *SrcVal, Type *DstTy, bool DstTyAlloca,
IRBuilder<> &Builder);
void replaceAllUsesByLoweredValue(Instruction *MatInst, Value *VecVal);
void replaceAllVariableUses(Value *MatPtr, Value *LoweredPtr);
void replaceAllVariableUses(SmallVectorImpl<Value *> &GEPIdxStack,
Value *StackTopPtr, Value *LoweredPtr);
Value *translateScalarMatMul(Value *scalar, Value *mat, IRBuilder<> &Builder,
bool isLhsScalar = true);
void lowerGlobal(GlobalVariable *Global);
Constant *lowerConstInitVal(Constant *Val);
AllocaInst *lowerAlloca(AllocaInst *MatAlloca);
void lowerInstruction(Instruction *Inst);
void lowerReturn(ReturnInst *Return);
Value *lowerCall(CallInst *Call);
Value *lowerNonHLCall(CallInst *Call);
void lowerPreciseCall(CallInst *Call, IRBuilder<> Builder);
Value *lowerHLOperation(CallInst *Call, HLOpcodeGroup OpcodeGroup);
Value *lowerHLIntrinsic(CallInst *Call, IntrinsicOp Opcode);
Value *lowerHLMulIntrinsic(Value *Lhs, Value *Rhs, bool Unsigned,
IRBuilder<> &Builder);
Value *lowerHLTransposeIntrinsic(Value *MatVal, IRBuilder<> &Builder);
Value *lowerHLDeterminantIntrinsic(Value *MatVal, IRBuilder<> &Builder);
Value *lowerHLUnaryOperation(Value *MatVal, HLUnaryOpcode Opcode,
IRBuilder<> &Builder);
Value *lowerHLBinaryOperation(Value *Lhs, Value *Rhs, HLBinaryOpcode Opcode,
IRBuilder<> &Builder);
Value *lowerHLLoadStore(CallInst *Call, HLMatLoadStoreOpcode Opcode);
Value *lowerHLLoad(CallInst *Call, Value *MatPtr, bool RowMajor,
IRBuilder<> &Builder);
Value *lowerHLStore(CallInst *Call, Value *MatVal, Value *MatPtr,
bool RowMajor, bool Return, IRBuilder<> &Builder);
Value *lowerHLCast(CallInst *Call, Value *Src, Type *DstTy,
HLCastOpcode Opcode, IRBuilder<> &Builder);
Value *lowerHLSubscript(CallInst *Call, HLSubscriptOpcode Opcode);
Value *lowerHLMatElementSubscript(CallInst *Call, bool RowMajor);
Value *lowerHLMatSubscript(CallInst *Call, bool RowMajor);
void lowerHLMatSubscript(CallInst *Call, Value *MatPtr,
SmallVectorImpl<Value *> &ElemIndices);
Value *lowerHLInit(CallInst *Call);
Value *lowerHLSelect(CallInst *Call);
private:
Module *m_pModule;
HLModule *m_pHLModule;
bool m_HasDbgInfo;
// Pools for the translation stubs
TempOverloadPool *m_matToVecStubs = nullptr;
TempOverloadPool *m_vecToMatStubs = nullptr;
std::vector<Instruction *> m_deadInsts;
};
} // namespace
char HLMatrixLowerPass::ID = 0;
ModulePass *llvm::createHLMatrixLowerPass() { return new HLMatrixLowerPass(); }
INITIALIZE_PASS(HLMatrixLowerPass, "hlmatrixlower",
"HLSL High-Level Matrix Lower", false, false)
bool HLMatrixLowerPass::runOnModule(Module &M) {
TempOverloadPool matToVecStubs(M, "hlmatrixlower.mat2vec");
TempOverloadPool vecToMatStubs(M, "hlmatrixlower.vec2mat");
m_pModule = &M;
m_pHLModule = &m_pModule->GetOrCreateHLModule();
// Load up debug information, to cross-reference values and the instructions
// used to load them.
m_HasDbgInfo = hasDebugInfo(M);
m_matToVecStubs = &matToVecStubs;
m_vecToMatStubs = &vecToMatStubs;
// First, lower static global variables.
// We need to accumulate them locally because we'll be creating new ones as we
// lower them.
std::vector<GlobalVariable *> Globals;
for (GlobalVariable &Global : M.globals()) {
if ((dxilutil::IsStaticGlobal(&Global) ||
dxilutil::IsSharedMemoryGlobal(&Global)) &&
HLMatrixType::isMatrixPtrOrArrayPtr(Global.getType())) {
Globals.emplace_back(&Global);
}
}
for (GlobalVariable *Global : Globals)
lowerGlobal(Global);
for (Function &F : M.functions()) {
if (F.isDeclaration())
continue;
runOnFunction(F);
}
m_pModule = nullptr;
m_pHLModule = nullptr;
m_matToVecStubs = nullptr;
m_vecToMatStubs = nullptr;
// If you hit an assert during TempOverloadPool destruction,
// it means that either a matrix producer was lowered,
// causing a translation stub to be created,
// but the consumer of that matrix was never (properly) lowered.
// Or the opposite: a matrix consumer was lowered and not its producer.
return true;
}
void HLMatrixLowerPass::runOnFunction(Function &Func) {
// Skip hl function definition (like createhandle)
if (hlsl::GetHLOpcodeGroupByName(&Func) != HLOpcodeGroup::NotHL)
return;
// Save the matrix instructions first since the translation process
// will temporarily create other instructions consuming/producing matrix
// types.
std::vector<AllocaInst *> MatAllocas;
std::vector<Instruction *> MatInsts;
getMatrixAllocasAndOtherInsts(Func, MatAllocas, MatInsts);
// First lower all allocas and take care of their GEP chains
for (AllocaInst *MatAlloca : MatAllocas) {
AllocaInst *LoweredAlloca = lowerAlloca(MatAlloca);
replaceAllVariableUses(MatAlloca, LoweredAlloca);
addToDeadInsts(MatAlloca);
}
// Now lower all other matrix instructions
for (Instruction *MatInst : MatInsts)
lowerInstruction(MatInst);
deleteDeadInsts();
}
void HLMatrixLowerPass::deleteDeadInsts() {
while (!m_deadInsts.empty()) {
Instruction *Inst = m_deadInsts.back();
m_deadInsts.pop_back();
DXASSERT_NOMSG(Inst->use_empty());
for (Value *Operand : Inst->operand_values()) {
Instruction *OperandInst = dyn_cast<Instruction>(Operand);
if (OperandInst &&
++OperandInst->user_begin() == OperandInst->user_end()) {
// We were its only user, erase recursively.
// This will get rid of translation stubs:
// Original: MatConsumer(MatProducer)
// Producer lowered: MatConsumer(VecToMat(VecProducer)), MatProducer
// dead Consumer lowered: VecConsumer(VecProducer)),
// MatConsumer(VecToMat) dead Only by recursing on MatConsumer's operand
// do we delete the VecToMat stub.
DXASSERT_NOMSG(*OperandInst->user_begin() == Inst);
m_deadInsts.emplace_back(OperandInst);
}
}
Inst->eraseFromParent();
}
}
// Find all instructions consuming or producing matrices,
// directly or through pointers/arrays.
void HLMatrixLowerPass::getMatrixAllocasAndOtherInsts(
Function &Func, std::vector<AllocaInst *> &MatAllocas,
std::vector<Instruction *> &MatInsts) {
for (BasicBlock &BasicBlock : Func) {
for (Instruction &Inst : BasicBlock) {
// Don't lower GEPs directly, we'll handle them as we lower the root
// pointer, typically a global variable or alloca.
if (isa<GetElementPtrInst>(&Inst))
continue;
// Don't lower lifetime intrinsics here, we'll handle them as we lower the
// alloca.
IntrinsicInst *Intrin = dyn_cast<IntrinsicInst>(&Inst);
if (Intrin && Intrin->getIntrinsicID() == Intrinsic::lifetime_start)
continue;
if (Intrin && Intrin->getIntrinsicID() == Intrinsic::lifetime_end)
continue;
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst)) {
if (HLMatrixType::isMatrixOrPtrOrArrayPtr(Alloca->getType())) {
MatAllocas.emplace_back(Alloca);
}
continue;
}
if (CallInst *Call = dyn_cast<CallInst>(&Inst)) {
// Lowering of global variables will have introduced
// vec-to-mat translation stubs, which we deal with indirectly,
// as we lower the instructions consuming them.
if (m_vecToMatStubs->contains(Call->getCalledFunction()))
continue;
// Mat-to-vec stubs should only be introduced during instruction
// lowering. Globals lowering won't introduce any because their only
// operand is their initializer, which we can fully lower without
// stubbing since it is constant.
DXASSERT(!m_matToVecStubs->contains(Call->getCalledFunction()),
"Unexpected mat-to-vec stubbing before function instruction "
"lowering.");
// Match matrix producers
if (HLMatrixType::isMatrixOrPtrOrArrayPtr(Inst.getType())) {
MatInsts.emplace_back(Call);
continue;
}
// Match matrix consumers
for (Value *Operand : Inst.operand_values()) {
if (HLMatrixType::isMatrixOrPtrOrArrayPtr(Operand->getType())) {
MatInsts.emplace_back(Call);
break;
}
}
continue;
}
if (ReturnInst *Return = dyn_cast<ReturnInst>(&Inst)) {
Value *ReturnValue = Return->getReturnValue();
if (ReturnValue != nullptr &&
HLMatrixType::isMatrixOrPtrOrArrayPtr(ReturnValue->getType()))
MatInsts.emplace_back(Return);
continue;
}
// Nothing else should produce or consume matrices
}
}
}
// Gets the matrix-lowered representation of a value, potentially adding a
// translation stub. DiscardStub causes any vec-to-mat translation stubs to be
// deleted, it should be true only if the original instruction will be modified
// and kept alive. If a new instruction is created and the original marked as
// dead, then the remove dead instructions pass will take care of removing the
// stub.
Value *HLMatrixLowerPass::getLoweredByValOperand(Value *Val,
IRBuilder<> &Builder,
bool DiscardStub) {
Type *Ty = Val->getType();
// We're only lowering byval matrices.
// Since structs and arrays are always accessed by pointer,
// we do not need to worry about a matrix being hidden inside a more complex
// type.
DXASSERT(!Ty->isPointerTy(), "Value cannot be a pointer.");
HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty);
if (!MatTy)
return Val;
Type *LoweredTy = MatTy.getLoweredVectorTypeForReg();
// Check if the value is already a vec-to-mat translation stub
if (CallInst *Call = dyn_cast<CallInst>(Val)) {
if (m_vecToMatStubs->contains(Call->getCalledFunction())) {
if (DiscardStub && Call->getNumUses() == 1) {
Call->use_begin()->set(UndefValue::get(Call->getType()));
addToDeadInsts(Call);
}
Value *LoweredVal = Call->getArgOperand(0);
DXASSERT(LoweredVal->getType() == LoweredTy,
"Unexpected already-lowered value type.");
return LoweredVal;
}
}
// Lower mat 0 to vec 0.
if (isa<ConstantAggregateZero>(Val))
return ConstantAggregateZero::get(LoweredTy);
// Lower undef mat as undef vec
if (isa<UndefValue>(Val))
return UndefValue::get(LoweredTy);
// Return a mat-to-vec translation stub
FunctionType *TranslationStubTy =
FunctionType::get(LoweredTy, {Ty}, /* isVarArg */ false);
Function *TranslationStub = m_matToVecStubs->get(TranslationStubTy);
return Builder.CreateCall(TranslationStub, {Val});
}
// Attempts to retrieve the lowered vector pointer equivalent to a matrix
// pointer. Returns nullptr if the pointed-to matrix lives in memory that cannot
// be lowered at this time, for example a buffer or shader inputs/outputs, which
// are lowered during signature lowering.
Value *HLMatrixLowerPass::tryGetLoweredPtrOperand(Value *Ptr,
IRBuilder<> &Builder,
bool DiscardStub) {
if (!HLMatrixType::isMatrixPtrOrArrayPtr(Ptr->getType()))
return nullptr;
// Matrix pointers can only be derived from Allocas, GlobalVariables or
// resource accesses. The first two cases are what this pass must be able to
// lower, and we should already have replaced their uses by vector to matrix
// pointer translation stubs.
if (CallInst *Call = dyn_cast<CallInst>(Ptr)) {
if (m_vecToMatStubs->contains(Call->getCalledFunction())) {
if (DiscardStub && Call->getNumUses() == 1) {
Call->use_begin()->set(UndefValue::get(Call->getType()));
addToDeadInsts(Call);
}
return Call->getArgOperand(0);
}
}
// There's one more case to handle.
// When compiling shader libraries, signatures won't have been lowered yet.
// So we can have a matrix in a struct as an argument,
// or an alloca'd struct holding the return value of a call and containing a
// matrix.
Value *RootPtr = Ptr;
while (GEPOperator *GEP = dyn_cast<GEPOperator>(RootPtr))
RootPtr = GEP->getPointerOperand();
Argument *Arg = dyn_cast<Argument>(RootPtr);
bool IsNonShaderArg =
Arg != nullptr &&
!m_pHLModule->IsEntryThatUsesSignatures(Arg->getParent());
if (IsNonShaderArg || isa<AllocaInst>(RootPtr)) {
// Bitcast the matrix pointer to its lowered equivalent.
// The HLMatrixBitcast pass will take care of this later.
return Builder.CreateBitCast(Ptr,
HLMatrixType::getLoweredType(Ptr->getType()));
}
// The pointer must be derived from a resource, we don't handle it in this
// pass.
return nullptr;
}
// Bitcasts a value from matrix to vector or vice-versa.
// This is used to convert to/from arguments/return values since we don't
// lower signatures in this pass. The later HLMatrixBitcastLower pass fixes
// this.
Value *HLMatrixLowerPass::bitCastValue(Value *SrcVal, Type *DstTy,
bool DstTyAlloca, IRBuilder<> &Builder) {
Type *SrcTy = SrcVal->getType();
DXASSERT_NOMSG(!SrcTy->isPointerTy());
// We store and load from a temporary alloca, bitcasting either on the store
// pointer or on the load pointer.
IRBuilder<> AllocaBuilder(
dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
Value *Alloca = AllocaBuilder.CreateAlloca(DstTyAlloca ? DstTy : SrcTy);
Value *BitCastedAlloca = Builder.CreateBitCast(
Alloca, (DstTyAlloca ? SrcTy : DstTy)->getPointerTo());
Builder.CreateStore(SrcVal, DstTyAlloca ? BitCastedAlloca : Alloca);
return Builder.CreateLoad(DstTyAlloca ? Alloca : BitCastedAlloca);
}
// Replaces all uses of a matrix value by its lowered vector form,
// inserting translation stubs for users which still expect a matrix value.
void HLMatrixLowerPass::replaceAllUsesByLoweredValue(Instruction *MatInst,
Value *VecVal) {
if (VecVal == nullptr || VecVal == MatInst)
return;
DXASSERT(HLMatrixType::getLoweredType(MatInst->getType()) ==
VecVal->getType(),
"Unexpected lowered value type.");
Instruction *VecToMatStub = nullptr;
while (!MatInst->use_empty()) {
Use &ValUse = *MatInst->use_begin();
// Handle non-matrix cases, just point to the new value.
if (MatInst->getType() == VecVal->getType()) {
ValUse.set(VecVal);
continue;
}
// If the user is already a matrix-to-vector translation stub,
// we can now replace it by the proper vector value.
if (CallInst *Call = dyn_cast<CallInst>(ValUse.getUser())) {
if (m_matToVecStubs->contains(Call->getCalledFunction())) {
Call->replaceAllUsesWith(VecVal);
ValUse.set(UndefValue::get(MatInst->getType()));
addToDeadInsts(Call);
continue;
}
}
// Otherwise, the user should point to a vector-to-matrix translation
// stub of the new vector value.
if (VecToMatStub == nullptr) {
FunctionType *TranslationStubTy = FunctionType::get(
MatInst->getType(), {VecVal->getType()}, /* isVarArg */ false);
Function *TranslationStub = m_vecToMatStubs->get(TranslationStubTy);
Instruction *PrevInst = dyn_cast<Instruction>(VecVal);
if (PrevInst == nullptr)
PrevInst = MatInst;
IRBuilder<> Builder(PrevInst->getNextNode());
VecToMatStub = Builder.CreateCall(TranslationStub, {VecVal});
}
ValUse.set(VecToMatStub);
}
}
// Replaces all uses of a matrix or matrix array alloca or global variable by
// its lowered equivalent. This doesn't lower the users, but will insert a
// translation stub from the lowered value pointer back to the matrix value
// pointer, and recreate any GEPs around the new pointer. Before:
// User(GEP(MatrixArrayAlloca)) After:
// User(VecToMatPtrStub(GEP'(VectorArrayAlloca)))
void HLMatrixLowerPass::replaceAllVariableUses(Value *MatPtr,
Value *LoweredPtr) {
DXASSERT_NOMSG(HLMatrixType::isMatrixPtrOrArrayPtr(MatPtr->getType()));
DXASSERT_NOMSG(LoweredPtr->getType() ==
HLMatrixType::getLoweredType(MatPtr->getType()));
SmallVector<Value *, 4> GEPIdxStack;
GEPIdxStack.emplace_back(
ConstantInt::get(Type::getInt32Ty(MatPtr->getContext()), 0));
replaceAllVariableUses(GEPIdxStack, MatPtr, LoweredPtr);
}
void HLMatrixLowerPass::replaceAllVariableUses(
SmallVectorImpl<Value *> &GEPIdxStack, Value *StackTopPtr,
Value *LoweredPtr) {
while (!StackTopPtr->use_empty()) {
llvm::Use &Use = *StackTopPtr->use_begin();
if (GEPOperator *GEP = dyn_cast<GEPOperator>(Use.getUser())) {
DXASSERT(GEP->getNumIndices() >= 1, "Unexpected degenerate GEP.");
DXASSERT(cast<ConstantInt>(*GEP->idx_begin())->isZero(),
"Unexpected non-zero first GEP index.");
// Recurse in GEP to find actual users
for (auto It = GEP->idx_begin() + 1; It != GEP->idx_end(); ++It)
GEPIdxStack.emplace_back(*It);
replaceAllVariableUses(GEPIdxStack, GEP, LoweredPtr);
GEPIdxStack.erase(GEPIdxStack.end() - (GEP->getNumIndices() - 1),
GEPIdxStack.end());
// Discard the GEP
DXASSERT_NOMSG(GEP->use_empty());
if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(GEP)) {
Use.set(UndefValue::get(Use->getType()));
addToDeadInsts(GEPInst);
} else {
// constant GEP
cast<Constant>(GEP)->destroyConstant();
}
continue;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Use.getUser())) {
DXASSERT(CE->getOpcode() == Instruction::AddrSpaceCast || CE->use_empty(),
"Unexpected constant user");
replaceAllVariableUses(GEPIdxStack, CE, LoweredPtr);
DXASSERT_NOMSG(CE->use_empty());
CE->destroyConstant();
continue;
}
if (AddrSpaceCastInst *CI = dyn_cast<AddrSpaceCastInst>(Use.getUser())) {
replaceAllVariableUses(GEPIdxStack, CI, LoweredPtr);
Use.set(UndefValue::get(Use->getType()));
addToDeadInsts(CI);
continue;
}
if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.getUser())) {
// Replace bitcasts to i8* for lifetime intrinsics.
if (BCI->getType()->isPointerTy() &&
BCI->getType()->getPointerElementType()->isIntegerTy(8)) {
DXASSERT(onlyUsedByLifetimeMarkers(BCI),
"bitcast to i8* must only be used by lifetime intrinsics");
Value *NewBCI =
IRBuilder<>(BCI).CreateBitCast(LoweredPtr, BCI->getType());
// Replace all uses of the use.
BCI->replaceAllUsesWith(NewBCI);
// Remove the current use to end iteration.
Use.set(UndefValue::get(Use->getType()));
addToDeadInsts(BCI);
continue;
}
}
// Recreate the same GEP sequence, if any, on the lowered pointer
IRBuilder<> Builder(cast<Instruction>(Use.getUser()));
Value *LoweredStackTopPtr =
GEPIdxStack.size() == 1 ? LoweredPtr
: Builder.CreateGEP(LoweredPtr, GEPIdxStack);
// Generate a stub translating the vector pointer back to a matrix pointer,
// such that consuming instructions are unaffected.
FunctionType *TranslationStubTy = FunctionType::get(
StackTopPtr->getType(), {LoweredStackTopPtr->getType()},
/* isVarArg */ false);
Function *TranslationStub = m_vecToMatStubs->get(TranslationStubTy);
Use.set(Builder.CreateCall(TranslationStub, {LoweredStackTopPtr}));
}
}
void HLMatrixLowerPass::lowerGlobal(GlobalVariable *Global) {
if (Global->user_empty())
return;
PointerType *LoweredPtrTy =
cast<PointerType>(HLMatrixType::getLoweredType(Global->getType()));
DXASSERT_NOMSG(LoweredPtrTy != Global->getType());
Constant *LoweredInitVal = Global->hasInitializer()
? lowerConstInitVal(Global->getInitializer())
: nullptr;
GlobalVariable *LoweredGlobal = new GlobalVariable(
*m_pModule, LoweredPtrTy->getElementType(), Global->isConstant(),
Global->getLinkage(), LoweredInitVal, Global->getName() + ".v",
/*InsertBefore*/ nullptr, Global->getThreadLocalMode(),
Global->getType()->getAddressSpace());
// Calculate preferred alignment for the new global
const llvm::DataLayout &DL = m_pModule->getDataLayout();
LoweredGlobal->setAlignment(DL.getPreferredAlignment(LoweredGlobal));
// Add debug info.
if (m_HasDbgInfo) {
DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
HLModule::UpdateGlobalVariableDebugInfo(Global, Finder, LoweredGlobal);
}
replaceAllVariableUses(Global, LoweredGlobal);
Global->removeDeadConstantUsers();
Global->eraseFromParent();
}
Constant *HLMatrixLowerPass::lowerConstInitVal(Constant *Val) {
Type *Ty = Val->getType();
// If it's an array of matrices, recurse for each element or nested array
if (ArrayType *ArrayTy = dyn_cast<ArrayType>(Ty)) {
SmallVector<Constant *, 4> LoweredElems;
unsigned NumElems = ArrayTy->getNumElements();
LoweredElems.reserve(NumElems);
for (unsigned ElemIdx = 0; ElemIdx < NumElems; ++ElemIdx) {
Constant *ArrayElem = Val->getAggregateElement(ElemIdx);
LoweredElems.emplace_back(lowerConstInitVal(ArrayElem));
}
Type *LoweredElemTy = HLMatrixType::getLoweredType(
ArrayTy->getElementType(), /*MemRepr*/ true);
ArrayType *LoweredArrayTy = ArrayType::get(LoweredElemTy, NumElems);
return ConstantArray::get(LoweredArrayTy, LoweredElems);
}
// Otherwise it's a matrix, lower it to a vector
HLMatrixType MatTy = HLMatrixType::cast(Ty);
DXASSERT_NOMSG(isa<StructType>(Ty));
Constant *RowArrayVal = Val->getAggregateElement((unsigned)0);
// Original initializer should have been produced in row/column-major order
// depending on the qualifiers of the target variable, so preserve the order.
SmallVector<Constant *, 16> MatElems;
for (unsigned RowIdx = 0; RowIdx < MatTy.getNumRows(); ++RowIdx) {
Constant *RowVal = RowArrayVal->getAggregateElement(RowIdx);
for (unsigned ColIdx = 0; ColIdx < MatTy.getNumColumns(); ++ColIdx) {
MatElems.emplace_back(RowVal->getAggregateElement(ColIdx));
}
}
Constant *Vec = ConstantVector::get(MatElems);
// Matrix elements are always in register representation,
// but the lowered global variable is of vector type in
// its memory representation, so we must convert here.
// This will produce a constant so we can use an IRBuilder without a valid
// insertion point.
IRBuilder<> DummyBuilder(Val->getContext());
return cast<Constant>(MatTy.emitLoweredRegToMem(Vec, DummyBuilder));
}
AllocaInst *HLMatrixLowerPass::lowerAlloca(AllocaInst *MatAlloca) {
PointerType *LoweredAllocaTy =
cast<PointerType>(HLMatrixType::getLoweredType(MatAlloca->getType()));
IRBuilder<> Builder(MatAlloca);
AllocaInst *LoweredAlloca = Builder.CreateAlloca(
LoweredAllocaTy->getElementType(), nullptr, MatAlloca->getName());
// Update debug info.
if (DbgDeclareInst *DbgDeclare = llvm::FindAllocaDbgDeclare(MatAlloca)) {
DILocalVariable *DbgDeclareVar = DbgDeclare->getVariable();
DIExpression *DbgDeclareExpr = DbgDeclare->getExpression();
DIBuilder DIB(*MatAlloca->getModule());
DIB.insertDeclare(LoweredAlloca, DbgDeclareVar, DbgDeclareExpr,
DbgDeclare->getDebugLoc(), DbgDeclare);
}
if (HLModule::HasPreciseAttributeWithMetadata(MatAlloca))
HLModule::MarkPreciseAttributeWithMetadata(LoweredAlloca);
replaceAllVariableUses(MatAlloca, LoweredAlloca);
return LoweredAlloca;
}
void HLMatrixLowerPass::lowerInstruction(Instruction *Inst) {
if (CallInst *Call = dyn_cast<CallInst>(Inst)) {
Value *LoweredValue = lowerCall(Call);
// lowerCall returns the lowered value iff we should discard
// the original matrix instruction and replace all of its uses
// by the lowered value. It returns nullptr to opt-out of this.
if (LoweredValue != nullptr) {
replaceAllUsesByLoweredValue(Call, LoweredValue);
addToDeadInsts(Inst);
}
} else if (ReturnInst *Return = dyn_cast<ReturnInst>(Inst)) {
lowerReturn(Return);
} else
llvm_unreachable("Unexpected matrix instruction type.");
}
void HLMatrixLowerPass::lowerReturn(ReturnInst *Return) {
Value *RetVal = Return->getReturnValue();
Type *RetTy = RetVal->getType();
DXASSERT_LOCALVAR(RetTy, !RetTy->isPointerTy(),
"Unexpected matrix returned by pointer.");
IRBuilder<> Builder(Return);
Value *LoweredRetVal =
getLoweredByValOperand(RetVal, Builder, /* DiscardStub */ true);
// Since we're not lowering the signature, we can't return the lowered value
// directly, so insert a bitcast, which HLMatrixBitcastLower knows how to
// eliminate.
Value *BitCastedRetVal = bitCastValue(LoweredRetVal, RetVal->getType(),
/* DstTyAlloca */ false, Builder);
Return->setOperand(0, BitCastedRetVal);
}
Value *HLMatrixLowerPass::lowerCall(CallInst *Call) {
HLOpcodeGroup OpcodeGroup = GetHLOpcodeGroupByName(Call->getCalledFunction());
return OpcodeGroup == HLOpcodeGroup::NotHL
? lowerNonHLCall(Call)
: lowerHLOperation(Call, OpcodeGroup);
}
// Special function to lower precise call applied to a matrix
// The matrix should be lowered and the call regenerated with vector arg
void HLMatrixLowerPass::lowerPreciseCall(CallInst *Call, IRBuilder<> Builder) {
DXASSERT(Call->getNumArgOperands() == 1,
"Only one arg expected for precise matrix call");
Value *Arg = Call->getArgOperand(0);
Value *LoweredArg = getLoweredByValOperand(Arg, Builder);
HLModule::MarkPreciseAttributeOnValWithFunctionCall(LoweredArg, Builder,
*m_pModule);
addToDeadInsts(Call);
}
Value *HLMatrixLowerPass::lowerNonHLCall(CallInst *Call) {
// First, handle any operand of matrix-derived type
// We don't lower the callee's signature in this pass,
// so, for any matrix-typed parameter, we create a bitcast from the
// lowered vector back to the matrix type, which the later
// HLMatrixBitcastLower pass knows how to eliminate.
IRBuilder<> PreCallBuilder(Call);
unsigned NumArgs = Call->getNumArgOperands();
Function *Func = Call->getCalledFunction();
if (Func && HLModule::HasPreciseAttribute(Func)) {
lowerPreciseCall(Call, PreCallBuilder);
return nullptr;
}
for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Use &ArgUse = Call->getArgOperandUse(ArgIdx);
if (ArgUse->getType()->isPointerTy()) {
// Byref arg
Value *LoweredArg = tryGetLoweredPtrOperand(ArgUse.get(), PreCallBuilder,
/* DiscardStub */ true);
if (LoweredArg != nullptr) {
// Pointer to a matrix we've lowered, insert a bitcast back to matrix
// pointer type.
Value *BitCastedArg =
PreCallBuilder.CreateBitCast(LoweredArg, ArgUse->getType());
ArgUse.set(BitCastedArg);
}
} else {
// Byvalue arg
Value *LoweredArg = getLoweredByValOperand(ArgUse.get(), PreCallBuilder,
/* DiscardStub */ true);
if (LoweredArg == ArgUse.get())
continue;
Value *BitCastedArg =
bitCastValue(LoweredArg, ArgUse->getType(), /* DstTyAlloca */ false,
PreCallBuilder);
ArgUse.set(BitCastedArg);
}
}
// Now check the return type
HLMatrixType RetMatTy = HLMatrixType::dyn_cast(Call->getType());
if (!RetMatTy) {
DXASSERT(!HLMatrixType::isMatrixPtrOrArrayPtr(Call->getType()),
"Unexpected user call returning a matrix by pointer.");
// Nothing to replace, other instructions can consume a non-matrix return
// type.
return nullptr;
}
// The callee returns a matrix, and we don't lower signatures in this pass.
// We perform a sketchy bitcast to the lowered register-representation type,
// which the later HLMatrixBitcastLower pass knows how to eliminate.
IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Call));
Value *LoweredAlloca =
AllocaBuilder.CreateAlloca(RetMatTy.getLoweredVectorTypeForReg());
IRBuilder<> PostCallBuilder(Call->getNextNode());
Value *BitCastedAlloca = PostCallBuilder.CreateBitCast(
LoweredAlloca, Call->getType()->getPointerTo());
// This is slightly tricky
// We want to replace all uses of the matrix-returning call by the bitcasted
// value, but the store to the bitcasted pointer itself is a use of that
// matrix, so we need to create the load, replace the uses, and then insert
// the store.
LoadInst *LoweredVal = PostCallBuilder.CreateLoad(LoweredAlloca);
replaceAllUsesByLoweredValue(Call, LoweredVal);
// Now we can insert the store. Make sure to do so before the load.
PostCallBuilder.SetInsertPoint(LoweredVal);
PostCallBuilder.CreateStore(Call, BitCastedAlloca);
// Return nullptr since we did our own uses replacement and we don't want
// the matrix instruction to be marked as dead since we're still using it.
return nullptr;
}
Value *HLMatrixLowerPass::lowerHLOperation(CallInst *Call,
HLOpcodeGroup OpcodeGroup) {
IRBuilder<> Builder(Call);
switch (OpcodeGroup) {
case HLOpcodeGroup::HLIntrinsic:
return lowerHLIntrinsic(Call, static_cast<IntrinsicOp>(GetHLOpcode(Call)));
case HLOpcodeGroup::HLBinOp:
return lowerHLBinaryOperation(
Call->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx),
Call->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx),
static_cast<HLBinaryOpcode>(GetHLOpcode(Call)), Builder);
case HLOpcodeGroup::HLUnOp:
return lowerHLUnaryOperation(
Call->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx),
static_cast<HLUnaryOpcode>(GetHLOpcode(Call)), Builder);
case HLOpcodeGroup::HLMatLoadStore:
return lowerHLLoadStore(
Call, static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(Call)));
case HLOpcodeGroup::HLCast:
return lowerHLCast(
Call, Call->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx),
Call->getType(), static_cast<HLCastOpcode>(GetHLOpcode(Call)), Builder);
case HLOpcodeGroup::HLSubscript:
return lowerHLSubscript(Call,
static_cast<HLSubscriptOpcode>(GetHLOpcode(Call)));
case HLOpcodeGroup::HLInit:
return lowerHLInit(Call);
case HLOpcodeGroup::HLSelect:
return lowerHLSelect(Call);
default:
llvm_unreachable("Unexpected matrix opcode");
}
}
Value *HLMatrixLowerPass::lowerHLIntrinsic(CallInst *Call, IntrinsicOp Opcode) {
IRBuilder<> Builder(Call);
// See if this is a matrix-specific intrinsic which we should expand here
switch (Opcode) {
case IntrinsicOp::IOP_umul:
case IntrinsicOp::IOP_mul:
return lowerHLMulIntrinsic(
Call->getArgOperand(HLOperandIndex::kBinaryOpSrc0Idx),
Call->getArgOperand(HLOperandIndex::kBinaryOpSrc1Idx),
/* Unsigned */ Opcode == IntrinsicOp::IOP_umul, Builder);
case IntrinsicOp::IOP_transpose:
return lowerHLTransposeIntrinsic(
Call->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx), Builder);
case IntrinsicOp::IOP_determinant:
return lowerHLDeterminantIntrinsic(
Call->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx), Builder);
}
// Delegate to a lowered intrinsic call
SmallVector<Value *, 4> LoweredArgs;
LoweredArgs.reserve(Call->getNumArgOperands());
for (Value *Arg : Call->arg_operands()) {
if (Arg->getType()->isPointerTy()) {
// ByRef parameter (for example, frexp's second parameter)
// If the argument points to a lowered matrix variable, replace it here,
// otherwise preserve the matrix type and let further passes handle the
// lowering.
Value *LoweredArg = tryGetLoweredPtrOperand(Arg, Builder);
if (LoweredArg == nullptr)
LoweredArg = Arg;
LoweredArgs.emplace_back(LoweredArg);
} else {
LoweredArgs.emplace_back(getLoweredByValOperand(Arg, Builder));
}
}
Type *LoweredRetTy = HLMatrixType::getLoweredType(Call->getType());
return callHLFunction(
*m_pModule, HLOpcodeGroup::HLIntrinsic, static_cast<unsigned>(Opcode),
LoweredRetTy, LoweredArgs,
Call->getCalledFunction()->getAttributes().getFnAttributes(), Builder);
}
// Handles multiplcation of a scalar with a matrix
Value *HLMatrixLowerPass::translateScalarMatMul(Value *Lhs, Value *Rhs,
IRBuilder<> &Builder,
bool isLhsScalar) {
Value *Mat = isLhsScalar ? Rhs : Lhs;
Value *Scalar = isLhsScalar ? Lhs : Rhs;
Value *LoweredMat = getLoweredByValOperand(Mat, Builder);
Type *ScalarTy = Scalar->getType();
FixedVectorType *VT = dyn_cast<FixedVectorType>(LoweredMat->getType());
// Perform the scalar-matrix multiplication!
Type *ElemTy = VT->getElementType();
bool isIntMulOp = ScalarTy->isIntegerTy() && ElemTy->isIntegerTy();
bool isFloatMulOp =
ScalarTy->isFloatingPointTy() && ElemTy->isFloatingPointTy();
DXASSERT(ScalarTy == ElemTy,
"Scalar type must match the matrix component type.");
Value *Result = Builder.CreateVectorSplat(VT->getNumElements(), Scalar);
if (isFloatMulOp) {
// Preserve the order of operation for floats
Result = isLhsScalar ? Builder.CreateFMul(Result, LoweredMat)
: Builder.CreateFMul(LoweredMat, Result);
} else if (isIntMulOp) {
// Doesn't matter for integers but still preserve the order of operation
Result = isLhsScalar ? Builder.CreateMul(Result, LoweredMat)
: Builder.CreateMul(LoweredMat, Result);
} else {