forked from KhronosGroup/SPIRV-LLVM-Translator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPIRVReader.cpp
4568 lines (4132 loc) · 172 KB
/
SPIRVReader.cpp
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
//===- SPIRVReader.cpp - Converts SPIR-V to LLVM ----------------*- C++ -*-===//
//
// The LLVM/SPIR-V Translator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the documentation
// and/or other materials provided with the distribution.
// Neither the names of Advanced Micro Devices, Inc., nor the names of its
// contributors may be used to endorse or promote products derived from this
// Software without specific prior written permission.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
// THE SOFTWARE.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements conversion of SPIR-V binary to LLVM IR.
///
//===----------------------------------------------------------------------===//
#include "SPIRVReader.h"
#include "OCLUtil.h"
#include "SPIRVAsm.h"
#include "SPIRVBasicBlock.h"
#include "SPIRVExtInst.h"
#include "SPIRVFunction.h"
#include "SPIRVInstruction.h"
#include "SPIRVInternal.h"
#include "SPIRVMDBuilder.h"
#include "SPIRVMemAliasingINTEL.h"
#include "SPIRVModule.h"
#include "SPIRVToLLVMDbgTran.h"
#include "SPIRVToOCL.h"
#include "SPIRVType.h"
#include "SPIRVUtil.h"
#include "SPIRVValue.h"
#include "VectorComputeUtil.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <string>
#define DEBUG_TYPE "spirv"
using namespace std;
using namespace llvm;
using namespace SPIRV;
using namespace OCLUtil;
namespace SPIRV {
cl::opt<bool> SPIRVEnableStepExpansion(
"spirv-expand-step", cl::init(true),
cl::desc("Enable expansion of OpenCL step and smoothstep function"));
// Prefix for placeholder global variable name.
const char *KPlaceholderPrefix = "placeholder.";
// Save the translated LLVM before validation for debugging purpose.
static bool DbgSaveTmpLLVM = false;
static const char *DbgTmpLLVMFileName = "_tmp_llvmbil.ll";
namespace kOCLTypeQualifierName {
const static char *Volatile = "volatile";
const static char *Restrict = "restrict";
const static char *Pipe = "pipe";
} // namespace kOCLTypeQualifierName
static bool isKernel(SPIRVFunction *BF) {
return BF->getModule()->isEntryPoint(ExecutionModelKernel, BF->getId());
}
static void dumpLLVM(Module *M, const std::string &FName) {
std::error_code EC;
raw_fd_ostream FS(FName, EC, sys::fs::OF_None);
if (!EC) {
FS << *M;
FS.close();
}
}
static MDNode *getMDNodeStringIntVec(LLVMContext *Context,
const std::vector<SPIRVWord> &IntVals) {
std::vector<Metadata *> ValueVec;
for (auto &I : IntVals)
ValueVec.push_back(ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), I)));
return MDNode::get(*Context, ValueVec);
}
static MDNode *getMDTwoInt(LLVMContext *Context, unsigned Int1, unsigned Int2) {
std::vector<Metadata *> ValueVec;
ValueVec.push_back(ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), Int1)));
ValueVec.push_back(ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), Int2)));
return MDNode::get(*Context, ValueVec);
}
static void addOCLVersionMetadata(LLVMContext *Context, Module *M,
const std::string &MDName, unsigned Major,
unsigned Minor) {
NamedMDNode *NamedMD = M->getOrInsertNamedMetadata(MDName);
NamedMD->addOperand(getMDTwoInt(Context, Major, Minor));
}
static void addNamedMetadataStringSet(LLVMContext *Context, Module *M,
const std::string &MDName,
const std::set<std::string> &StrSet) {
NamedMDNode *NamedMD = M->getOrInsertNamedMetadata(MDName);
std::vector<Metadata *> ValueVec;
for (auto &&Str : StrSet) {
ValueVec.push_back(MDString::get(*Context, Str));
}
NamedMD->addOperand(MDNode::get(*Context, ValueVec));
}
static void addKernelArgumentMetadata(
LLVMContext *Context, const std::string &MDName, SPIRVFunction *BF,
llvm::Function *Fn,
std::function<Metadata *(SPIRVFunctionParameter *)> ForeachFnArg) {
std::vector<Metadata *> ValueVec;
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
ValueVec.push_back(ForeachFnArg(Arg));
});
Fn->setMetadata(MDName, MDNode::get(*Context, ValueVec));
}
static void addBufferLocationMetadata(
LLVMContext *Context, SPIRVFunction *BF, llvm::Function *Fn,
std::function<Metadata *(SPIRVFunctionParameter *)> ForeachFnArg) {
std::vector<Metadata *> ValueVec;
bool DecorationFound = false;
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
if (Arg->getType()->isTypePointer() &&
Arg->hasDecorate(DecorationBufferLocationINTEL)) {
DecorationFound = true;
ValueVec.push_back(ForeachFnArg(Arg));
} else {
llvm::Metadata *DefaultNode = ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), -1));
ValueVec.push_back(DefaultNode);
}
});
if (DecorationFound)
Fn->setMetadata("kernel_arg_buffer_location",
MDNode::get(*Context, ValueVec));
}
static void addRuntimeAlignedMetadata(
LLVMContext *Context, SPIRVFunction *BF, llvm::Function *Fn,
std::function<Metadata *(SPIRVFunctionParameter *)> ForeachFnArg) {
std::vector<Metadata *> ValueVec;
bool DecorationFound = false;
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
if (Arg->getType()->isTypePointer() &&
Arg->hasDecorate(internal::DecorationRuntimeAlignedINTEL)) {
DecorationFound = true;
ValueVec.push_back(ForeachFnArg(Arg));
} else {
llvm::Metadata *DefaultNode = ConstantAsMetadata::get(
ConstantInt::get(Type::getInt1Ty(*Context), 0));
ValueVec.push_back(DefaultNode);
}
});
if (DecorationFound)
Fn->setMetadata("kernel_arg_runtime_aligned",
MDNode::get(*Context, ValueVec));
}
Value *SPIRVToLLVM::getTranslatedValue(SPIRVValue *BV) {
auto Loc = ValueMap.find(BV);
if (Loc != ValueMap.end())
return Loc->second;
return nullptr;
}
static llvm::Optional<llvm::Attribute>
translateSEVMetadata(SPIRVValue *BV, llvm::LLVMContext &Context) {
llvm::Optional<llvm::Attribute> RetAttr;
if (!BV->hasDecorate(DecorationSingleElementVectorINTEL))
return RetAttr;
auto VecDecorateSEV = BV->getDecorations(DecorationSingleElementVectorINTEL);
assert(VecDecorateSEV.size() == 1 &&
"Entry must have no more than one SingleElementVectorINTEL "
"decoration");
auto *DecorateSEV = VecDecorateSEV.back();
auto LiteralCount = DecorateSEV->getLiteralCount();
assert(LiteralCount <= 1 && "SingleElementVectorINTEL decoration must "
"have no more than one literal");
SPIRVWord IndirectLevelsOnElement =
(LiteralCount == 1) ? DecorateSEV->getLiteral(0) : 0;
RetAttr = Attribute::get(Context, kVCMetadata::VCSingleElementVector,
std::to_string(IndirectLevelsOnElement));
return RetAttr;
}
IntrinsicInst *SPIRVToLLVM::getLifetimeStartIntrinsic(Instruction *I) {
auto II = dyn_cast<IntrinsicInst>(I);
if (II && II->getIntrinsicID() == Intrinsic::lifetime_start)
return II;
// Bitcast might be inserted during translation of OpLifetimeStart
auto BC = dyn_cast<BitCastInst>(I);
if (BC) {
for (const auto &U : BC->users()) {
II = dyn_cast<IntrinsicInst>(U);
if (II && II->getIntrinsicID() == Intrinsic::lifetime_start)
return II;
;
}
}
return nullptr;
}
SPIRVErrorLog &SPIRVToLLVM::getErrorLog() { return BM->getErrorLog(); }
void SPIRVToLLVM::setCallingConv(CallInst *Call) {
Function *F = Call->getCalledFunction();
assert(F && "Function pointers are not allowed in SPIRV");
Call->setCallingConv(F->getCallingConv());
}
// For integer types shorter than 32 bit, unsigned/signedness can be inferred
// from zext/sext attribute.
MDString *SPIRVToLLVM::transOCLKernelArgTypeName(SPIRVFunctionParameter *Arg) {
auto Ty =
Arg->isByVal() ? Arg->getType()->getPointerElementType() : Arg->getType();
return MDString::get(*Context, transTypeToOCLTypeName(Ty, !Arg->isZext()));
}
Value *SPIRVToLLVM::mapFunction(SPIRVFunction *BF, Function *F) {
SPIRVDBG(spvdbgs() << "[mapFunction] " << *BF << " -> ";
dbgs() << *F << '\n';)
FuncMap[BF] = F;
return F;
}
Type *SPIRVToLLVM::transFPType(SPIRVType *T) {
switch (T->getFloatBitWidth()) {
case 16:
return Type::getHalfTy(*Context);
case 32:
return Type::getFloatTy(*Context);
case 64:
return Type::getDoubleTy(*Context);
default:
llvm_unreachable("Invalid type");
return nullptr;
}
}
std::string SPIRVToLLVM::transOCLImageTypeName(SPIRV::SPIRVTypeImage *ST) {
return getSPIRVTypeName(
kSPIRVTypeName::Image,
getSPIRVImageTypePostfixes(
getSPIRVImageSampledTypeName(ST->getSampledType()),
ST->getDescriptor(),
ST->hasAccessQualifier() ? ST->getAccessQualifier()
: AccessQualifierReadOnly));
}
std::string
SPIRVToLLVM::transOCLSampledImageTypeName(SPIRV::SPIRVTypeSampledImage *ST) {
return getSPIRVTypeName(
kSPIRVTypeName::SampledImg,
getSPIRVImageTypePostfixes(
getSPIRVImageSampledTypeName(ST->getImageType()->getSampledType()),
ST->getImageType()->getDescriptor(),
ST->getImageType()->hasAccessQualifier()
? ST->getImageType()->getAccessQualifier()
: AccessQualifierReadOnly));
}
std::string
SPIRVToLLVM::transVMEImageTypeName(SPIRV::SPIRVTypeVmeImageINTEL *VT) {
return getSPIRVTypeName(
kSPIRVTypeName::VmeImageINTEL,
getSPIRVImageTypePostfixes(
getSPIRVImageSampledTypeName(VT->getImageType()->getSampledType()),
VT->getImageType()->getDescriptor(),
VT->getImageType()->hasAccessQualifier()
? VT->getImageType()->getAccessQualifier()
: AccessQualifierReadOnly));
}
std::string SPIRVToLLVM::transPipeTypeName(SPIRV::SPIRVTypePipe *PT) {
SPIRVAccessQualifierKind PipeAccess = PT->getAccessQualifier();
assert((PipeAccess == AccessQualifierReadOnly ||
PipeAccess == AccessQualifierWriteOnly) &&
"Invalid access qualifier");
return std::string(kSPIRVTypeName::PrefixAndDelim) + kSPIRVTypeName::Pipe +
kSPIRVTypeName::Delimiter + kSPIRVTypeName::PostfixDelim + PipeAccess;
}
std::string
SPIRVToLLVM::transOCLPipeStorageTypeName(SPIRV::SPIRVTypePipeStorage *PST) {
return std::string(kSPIRVTypeName::PrefixAndDelim) +
kSPIRVTypeName::PipeStorage;
}
std::string SPIRVToLLVM::transVCTypeName(SPIRVTypeBufferSurfaceINTEL *PST) {
if (PST->hasAccessQualifier())
return VectorComputeUtil::getVCBufferSurfaceName(PST->getAccessQualifier());
return VectorComputeUtil::getVCBufferSurfaceName();
}
Type *SPIRVToLLVM::transType(SPIRVType *T, bool IsClassMember) {
auto Loc = TypeMap.find(T);
if (Loc != TypeMap.end())
return Loc->second;
SPIRVDBG(spvdbgs() << "[transType] " << *T << " -> ";)
T->validate();
switch (static_cast<SPIRVWord>(T->getOpCode())) {
case OpTypeVoid:
return mapType(T, Type::getVoidTy(*Context));
case OpTypeBool:
return mapType(T, Type::getInt1Ty(*Context));
case OpTypeInt:
return mapType(T, Type::getIntNTy(*Context, T->getIntegerBitWidth()));
case OpTypeFloat:
return mapType(T, transFPType(T));
case OpTypeArray: {
// The length might be an OpSpecConstantOp, that needs to be specialized
// and evaluated before the LLVM ArrayType can be constructed.
auto *LenExpr = static_cast<const SPIRVTypeArray *>(T)->getLength();
auto *LenValue = cast<ConstantInt>(transValue(LenExpr, nullptr, nullptr));
return mapType(T, ArrayType::get(transType(T->getArrayElementType()),
LenValue->getZExtValue()));
}
case internal::OpTypeTokenINTEL:
return mapType(T, Type::getTokenTy(*Context));
case OpTypePointer:
return mapType(
T, PointerType::get(
transType(T->getPointerElementType(), IsClassMember),
SPIRSPIRVAddrSpaceMap::rmap(T->getPointerStorageClass())));
case OpTypeVector:
return mapType(T,
FixedVectorType::get(transType(T->getVectorComponentType()),
T->getVectorComponentCount()));
case OpTypeMatrix:
return mapType(T, ArrayType::get(transType(T->getMatrixColumnType()),
T->getMatrixColumnCount()));
case OpTypeOpaque:
return mapType(T, StructType::create(*Context, T->getName()));
case OpTypeFunction: {
auto FT = static_cast<SPIRVTypeFunction *>(T);
auto RT = transType(FT->getReturnType());
std::vector<Type *> PT;
for (size_t I = 0, E = FT->getNumParameters(); I != E; ++I)
PT.push_back(transType(FT->getParameterType(I)));
return mapType(T, FunctionType::get(RT, PT, false));
}
case OpTypeImage: {
auto ST = static_cast<SPIRVTypeImage *>(T);
if (ST->isOCLImage())
return mapType(T, getOrCreateOpaquePtrType(M, transOCLImageTypeName(ST)));
else
llvm_unreachable("Unsupported image type");
return nullptr;
}
case OpTypeSampledImage: {
auto ST = static_cast<SPIRVTypeSampledImage *>(T);
return mapType(
T, getOrCreateOpaquePtrType(M, transOCLSampledImageTypeName(ST)));
}
case OpTypeStruct: {
auto ST = static_cast<SPIRVTypeStruct *>(T);
auto Name = ST->getName();
if (!Name.empty()) {
if (auto OldST = StructType::getTypeByName(*Context, Name))
OldST->setName("");
} else {
Name = "structtype";
}
auto *StructTy = StructType::create(*Context, Name);
mapType(ST, StructTy);
SmallVector<Type *, 4> MT;
for (size_t I = 0, E = ST->getMemberCount(); I != E; ++I)
MT.push_back(transType(ST->getMemberType(I), true));
for (auto &CI : ST->getContinuedInstructions())
for (size_t I = 0, E = CI->getNumElements(); I != E; ++I)
MT.push_back(transType(CI->getMemberType(I), true));
StructTy->setBody(MT, ST->isPacked());
return StructTy;
}
case OpTypePipe: {
auto PT = static_cast<SPIRVTypePipe *>(T);
return mapType(
T, getOrCreateOpaquePtrType(M, transPipeTypeName(PT),
getOCLOpaqueTypeAddrSpace(T->getOpCode())));
}
case OpTypePipeStorage: {
auto PST = static_cast<SPIRVTypePipeStorage *>(T);
return mapType(
T, getOrCreateOpaquePtrType(M, transOCLPipeStorageTypeName(PST),
getOCLOpaqueTypeAddrSpace(T->getOpCode())));
}
case OpTypeVmeImageINTEL: {
auto *VT = static_cast<SPIRVTypeVmeImageINTEL *>(T);
return mapType(T, getOrCreateOpaquePtrType(M, transVMEImageTypeName(VT)));
}
case OpTypeBufferSurfaceINTEL: {
auto PST = static_cast<SPIRVTypeBufferSurfaceINTEL *>(T);
return mapType(T,
getOrCreateOpaquePtrType(M, transVCTypeName(PST),
SPIRAddressSpace::SPIRAS_Global));
}
case internal::OpTypeJointMatrixINTEL: {
auto *MT = static_cast<SPIRVTypeJointMatrixINTEL *>(T);
auto R = static_cast<SPIRVConstant *>(MT->getRows())->getZExtIntValue();
auto C = static_cast<SPIRVConstant *>(MT->getColumns())->getZExtIntValue();
std::stringstream SS;
SS << kSPIRVTypeName::PostfixDelim;
SS << transTypeToOCLTypeName(MT->getCompType());
auto L = static_cast<SPIRVConstant *>(MT->getLayout())->getZExtIntValue();
auto S = static_cast<SPIRVConstant *>(MT->getScope())->getZExtIntValue();
SS << kSPIRVTypeName::PostfixDelim << R << kSPIRVTypeName::PostfixDelim << C
<< kSPIRVTypeName::PostfixDelim << L << kSPIRVTypeName::PostfixDelim
<< S;
if (auto *Use = MT->getUse())
SS << kSPIRVTypeName::PostfixDelim
<< static_cast<SPIRVConstant *>(Use)->getZExtIntValue();
std::string Name =
getSPIRVTypeName(kSPIRVTypeName::JointMatrixINTEL, SS.str());
return mapType(T, getOrCreateOpaquePtrType(M, Name));
}
case OpTypeForwardPointer: {
SPIRVTypeForwardPointer *FP =
static_cast<SPIRVTypeForwardPointer *>(static_cast<SPIRVEntry *>(T));
return mapType(T, transType(static_cast<SPIRVType *>(
BM->getEntry(FP->getPointerId()))));
}
default: {
auto OC = T->getOpCode();
if (isOpaqueGenericTypeOpCode(OC) || isSubgroupAvcINTELTypeOpCode(OC))
return mapType(T, getSPIRVOpaquePtrType(M, OC));
llvm_unreachable("Not implemented!");
}
}
return 0;
}
std::string SPIRVToLLVM::transTypeToOCLTypeName(SPIRVType *T, bool IsSigned) {
switch (T->getOpCode()) {
case OpTypeVoid:
return "void";
case OpTypeBool:
return "bool";
case OpTypeInt: {
std::string Prefix = IsSigned ? "" : "u";
switch (T->getIntegerBitWidth()) {
case 8:
return Prefix + "char";
case 16:
return Prefix + "short";
case 32:
return Prefix + "int";
case 64:
return Prefix + "long";
default:
// Arbitrary precision integer
return Prefix + std::string("int") + T->getIntegerBitWidth() + "_t";
}
} break;
case OpTypeFloat:
switch (T->getFloatBitWidth()) {
case 16:
return "half";
case 32:
return "float";
case 64:
return "double";
default:
llvm_unreachable("invalid floating pointer bitwidth");
return std::string("float") + T->getFloatBitWidth() + "_t";
}
break;
case OpTypeArray:
return "array";
case OpTypePointer: {
SPIRVType *ET = T->getPointerElementType();
if (isa<OpTypeFunction>(ET)) {
SPIRVTypeFunction *TF = static_cast<SPIRVTypeFunction *>(ET);
std::string name = transTypeToOCLTypeName(TF->getReturnType());
name += " (*)(";
for (unsigned I = 0, E = TF->getNumParameters(); I < E; ++I)
name += transTypeToOCLTypeName(TF->getParameterType(I)) + ',';
name.back() = ')'; // replace the last comma with a closing brace.
return name;
}
return transTypeToOCLTypeName(ET) + "*";
}
case OpTypeVector:
return transTypeToOCLTypeName(T->getVectorComponentType()) +
T->getVectorComponentCount();
case OpTypeMatrix:
return transTypeToOCLTypeName(T->getMatrixColumnType()) +
T->getMatrixColumnCount();
case OpTypeOpaque:
return T->getName();
case OpTypeFunction:
llvm_unreachable("Unsupported");
return "function";
case OpTypeStruct: {
auto Name = T->getName();
if (Name.find("struct.") == 0)
Name[6] = ' ';
else if (Name.find("union.") == 0)
Name[5] = ' ';
return Name;
}
case OpTypePipe:
return "pipe";
case OpTypeSampler:
return "sampler_t";
case OpTypeImage: {
std::string Name;
Name = rmap<std::string>(static_cast<SPIRVTypeImage *>(T)->getDescriptor());
return Name;
}
default:
if (isOpaqueGenericTypeOpCode(T->getOpCode())) {
return OCLOpaqueTypeOpCodeMap::rmap(T->getOpCode());
}
llvm_unreachable("Not implemented");
return "unknown";
}
}
std::vector<Type *>
SPIRVToLLVM::transTypeVector(const std::vector<SPIRVType *> &BT) {
std::vector<Type *> T;
for (auto I : BT)
T.push_back(transType(I));
return T;
}
std::vector<Value *>
SPIRVToLLVM::transValue(const std::vector<SPIRVValue *> &BV, Function *F,
BasicBlock *BB) {
std::vector<Value *> V;
for (auto I : BV)
V.push_back(transValue(I, F, BB));
return V;
}
void SPIRVToLLVM::setName(llvm::Value *V, SPIRVValue *BV) {
auto Name = BV->getName();
if (!Name.empty() && (!V->hasName() || Name != V->getName()))
V->setName(Name);
}
inline llvm::Metadata *SPIRVToLLVM::getMetadataFromName(std::string Name) {
return llvm::MDNode::get(*Context, llvm::MDString::get(*Context, Name));
}
inline std::vector<llvm::Metadata *>
SPIRVToLLVM::getMetadataFromNameAndParameter(std::string Name,
SPIRVWord Parameter) {
return {MDString::get(*Context, Name),
ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), Parameter))};
}
inline llvm::MDNode *
SPIRVToLLVM::getMetadataFromNameAndParameter(std::string Name,
int64_t Parameter) {
std::vector<llvm::Metadata *> Metadata = {
MDString::get(*Context, Name),
ConstantAsMetadata::get(
ConstantInt::get(Type::getInt64Ty(*Context), Parameter))};
return llvm::MDNode::get(*Context, Metadata);
}
template <typename LoopInstType>
void SPIRVToLLVM::setLLVMLoopMetadata(const LoopInstType *LM,
const Loop *LoopObj) {
if (!LM)
return;
auto Temp = MDNode::getTemporary(*Context, None);
auto Self = MDNode::get(*Context, Temp.get());
Self->replaceOperandWith(0, Self);
SPIRVWord LC = LM->getLoopControl();
if (LC == LoopControlMaskNone) {
LoopObj->setLoopID(Self);
return;
}
unsigned NumParam = 0;
std::vector<llvm::Metadata *> Metadata;
std::vector<SPIRVWord> LoopControlParameters = LM->getLoopControlParameters();
Metadata.push_back(llvm::MDNode::get(*Context, Self));
// To correctly decode loop control parameters, order of checks for loop
// control masks must match with the order given in the spec (see 3.23),
// i.e. check smaller-numbered bits first.
// Unroll and UnrollCount loop controls can't be applied simultaneously with
// DontUnroll loop control.
if (LC & LoopControlUnrollMask)
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.enable"));
else if (LC & LoopControlDontUnrollMask)
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.disable"));
if (LC & LoopControlDependencyInfiniteMask)
Metadata.push_back(getMetadataFromName("llvm.loop.ivdep.enable"));
if (LC & LoopControlDependencyLengthMask) {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.ivdep.safelen",
LoopControlParameters[NumParam])));
++NumParam;
// TODO: Fix the increment/assertion logic in all of the conditions
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
// Placeholder for LoopControls added in SPIR-V 1.4 spec (see 3.23)
if (LC & LoopControlMinIterationsMask) {
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlMaxIterationsMask) {
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlIterationMultipleMask) {
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlPeelCountMask) {
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlPartialCountMask && !(LC & LoopControlDontUnrollMask)) {
// If unroll factor is set as '1' - disable loop unrolling
if (1 == LoopControlParameters[NumParam])
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.disable"));
else
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.unroll.count",
LoopControlParameters[NumParam])));
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlInitiationIntervalINTELMask) {
Metadata.push_back(llvm::MDNode::get(
*Context, getMetadataFromNameAndParameter(
"llvm.loop.ii.count", LoopControlParameters[NumParam])));
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlMaxConcurrencyINTELMask) {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.max_concurrency.count",
LoopControlParameters[NumParam])));
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlDependencyArrayINTELMask) {
// Collect pointer variable <-> safelen information
std::map<Value *, unsigned> PointerSflnMap;
unsigned NumOperandPairs = LoopControlParameters[NumParam];
unsigned OperandsEndIndex = NumParam + NumOperandPairs * 2;
assert(OperandsEndIndex <= LoopControlParameters.size() &&
"Missing loop control parameter!");
SPIRVModule *M = LM->getModule();
while (NumParam < OperandsEndIndex) {
SPIRVId ArraySPIRVId = LoopControlParameters[++NumParam];
Value *PointerVar = ValueMap[M->getValue(ArraySPIRVId)];
unsigned Safelen = LoopControlParameters[++NumParam];
PointerSflnMap.emplace(PointerVar, Safelen);
}
// A single run over the loop to retrieve all GetElementPtr instructions
// that access relevant array variables
std::map<Value *, std::vector<GetElementPtrInst *>> ArrayGEPMap;
for (const auto &BB : LoopObj->blocks()) {
for (Instruction &I : *BB) {
auto *GEP = dyn_cast<GetElementPtrInst>(&I);
if (!GEP)
continue;
Value *AccessedPointer = GEP->getPointerOperand();
if (auto *LI = dyn_cast<LoadInst>(AccessedPointer))
AccessedPointer = LI->getPointerOperand();
auto PointerSflnIt = PointerSflnMap.find(AccessedPointer);
if (PointerSflnIt != PointerSflnMap.end()) {
ArrayGEPMap[AccessedPointer].push_back(GEP);
}
}
}
// Create index group metadata nodes - one per each of the array
// variables. Mark each GEP accessing a particular array variable
// into a corresponding index group
std::map<unsigned, SmallSet<MDNode *, 4>> SafelenIdxGroupMap;
// Whenever a kernel closure field access is pointed to instead of
// an array/pointer variable, ensure that all GEPs to that memory
// share the same index group by hashing the newly added index groups.
// "Memory offset info" represents a handle to the whole closure block
// + an integer offset to a particular captured parameter.
using MemoryOffsetInfo = std::pair<Value *, unsigned>;
std::map<MemoryOffsetInfo, MDNode *> OffsetIdxGroupMap;
for (auto &ArrayGEPIt : ArrayGEPMap) {
MDNode *CurrentDepthIdxGroup = nullptr;
if (auto *PrecedingGEP = dyn_cast<GetElementPtrInst>(ArrayGEPIt.first)) {
Value *ClosureFieldPointer = PrecedingGEP->getPointerOperand();
unsigned Offset =
cast<ConstantInt>(PrecedingGEP->getOperand(2))->getZExtValue();
MemoryOffsetInfo Info{ClosureFieldPointer, Offset};
auto OffsetIdxGroupIt = OffsetIdxGroupMap.find(Info);
if (OffsetIdxGroupIt == OffsetIdxGroupMap.end()) {
// This is the first GEP encountered for this closure field.
// Emit a distinct index group that will be referenced from
// llvm.loop.parallel_access_indices metadata; hash the new
// MDNode for future accesses to the same memory.
CurrentDepthIdxGroup = llvm::MDNode::getDistinct(*Context, None);
OffsetIdxGroupMap.emplace(Info, CurrentDepthIdxGroup);
} else {
// Previous accesses to that field have already been indexed,
// just use the already-existing metadata.
CurrentDepthIdxGroup = OffsetIdxGroupIt->second;
}
} else /* Regular kernel-scope array/pointer variable */ {
// Emit a distinct index group that will be referenced from
// llvm.loop.parallel_access_indices metadata
CurrentDepthIdxGroup = llvm::MDNode::getDistinct(*Context, None);
}
unsigned Safelen = PointerSflnMap.find(ArrayGEPIt.first)->second;
SafelenIdxGroupMap[Safelen].insert(CurrentDepthIdxGroup);
for (auto *GEP : ArrayGEPIt.second) {
StringRef IdxGroupMDName("llvm.index.group");
llvm::MDNode *PreviousIdxGroup = GEP->getMetadata(IdxGroupMDName);
if (!PreviousIdxGroup) {
GEP->setMetadata(IdxGroupMDName, CurrentDepthIdxGroup);
continue;
}
// If we're dealing with an embedded loop, it may be the case
// that GEP instructions for some of the arrays were already
// marked by the algorithm when it went over the outer level loops.
// In order to retain the IVDep information for each "loop
// dimension", we will mark such GEP's into a separate joined node
// that will refer to the previous levels' index groups AND to the
// index group specific to the current loop.
std::vector<llvm::Metadata *> CurrentDepthOperands(
PreviousIdxGroup->op_begin(), PreviousIdxGroup->op_end());
if (CurrentDepthOperands.empty())
CurrentDepthOperands.push_back(PreviousIdxGroup);
CurrentDepthOperands.push_back(CurrentDepthIdxGroup);
auto *JointIdxGroup = llvm::MDNode::get(*Context, CurrentDepthOperands);
GEP->setMetadata(IdxGroupMDName, JointIdxGroup);
}
}
for (auto &SflnIdxGroupIt : SafelenIdxGroupMap) {
auto *Name = MDString::get(*Context, "llvm.loop.parallel_access_indices");
unsigned SflnValue = SflnIdxGroupIt.first;
llvm::Metadata *SafelenMDOp =
SflnValue ? ConstantAsMetadata::get(ConstantInt::get(
Type::getInt32Ty(*Context), SflnValue))
: nullptr;
std::vector<llvm::Metadata *> Parameters{Name};
for (auto *Node : SflnIdxGroupIt.second)
Parameters.push_back(Node);
if (SafelenMDOp)
Parameters.push_back(SafelenMDOp);
Metadata.push_back(llvm::MDNode::get(*Context, Parameters));
}
++NumParam;
}
if (LC & LoopControlPipelineEnableINTELMask) {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.intel.pipelining.enable",
LoopControlParameters[NumParam++])));
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlLoopCoalesceINTELMask) {
// If LoopCoalesce has a parameter of '0'
if (!LoopControlParameters[NumParam]) {
Metadata.push_back(llvm::MDNode::get(
*Context, getMetadataFromName("llvm.loop.coalesce.enable")));
} else {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.coalesce.count",
LoopControlParameters[NumParam])));
}
++NumParam;
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlMaxInterleavingINTELMask) {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.max_interleaving.count",
LoopControlParameters[NumParam++])));
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlSpeculatedIterationsINTELMask) {
Metadata.push_back(llvm::MDNode::get(
*Context, getMetadataFromNameAndParameter(
"llvm.loop.intel.speculated.iterations.count",
LoopControlParameters[NumParam++])));
assert(NumParam <= LoopControlParameters.size() &&
"Missing loop control parameter!");
}
if (LC & LoopControlNoFusionINTELMask)
Metadata.push_back(getMetadataFromName("llvm.loop.fusion.disable"));
if (LC & spv::internal::LoopControlLoopCountINTELMask) {
// LoopCountINTELMask parameters are int64 and each parameter is stored
// as 2 SPIRVWords (int32)
assert(NumParam + 6 <= LoopControlParameters.size() &&
"Missing loop control parameter!");
uint64_t LoopCountMin =
static_cast<uint64_t>(LoopControlParameters[NumParam++]);
LoopCountMin |= static_cast<uint64_t>(LoopControlParameters[NumParam++])
<< 32;
if (static_cast<int64_t>(LoopCountMin) >= 0) {
Metadata.push_back(getMetadataFromNameAndParameter(
"llvm.loop.intel.loopcount_min", static_cast<int64_t>(LoopCountMin)));
}
uint64_t LoopCountMax =
static_cast<uint64_t>(LoopControlParameters[NumParam++]);
LoopCountMax |= static_cast<uint64_t>(LoopControlParameters[NumParam++])
<< 32;
if (static_cast<int64_t>(LoopCountMax) >= 0) {
Metadata.push_back(getMetadataFromNameAndParameter(
"llvm.loop.intel.loopcount_max", static_cast<int64_t>(LoopCountMax)));
}
uint64_t LoopCountAvg =
static_cast<uint64_t>(LoopControlParameters[NumParam++]);
LoopCountAvg |= static_cast<uint64_t>(LoopControlParameters[NumParam++])
<< 32;
if (static_cast<int64_t>(LoopCountAvg) >= 0) {
Metadata.push_back(getMetadataFromNameAndParameter(
"llvm.loop.intel.loopcount_avg", static_cast<int64_t>(LoopCountAvg)));
}
}
llvm::MDNode *Node = llvm::MDNode::get(*Context, Metadata);
// Set the first operand to refer itself
Node->replaceOperandWith(0, Node);
LoopObj->setLoopID(Node);
}
void SPIRVToLLVM::transLLVMLoopMetadata(const Function *F) {
assert(F);
if (FuncLoopMetadataMap.empty())
return;
// Function declaration doesn't contain loop metadata.
if (F->isDeclaration())
return;
DominatorTree DomTree(*(const_cast<Function *>(F)));
LoopInfo LI(DomTree);
// In SPIRV loop metadata is linked to a header basic block of a loop
// whilst in LLVM IR it is linked to a latch basic block (the one
// whose back edge goes to a header basic block) of the loop.
// To ensure consistent behaviour, we can rely on the `llvm::Loop`
// class to handle the metadata placement
for (const auto *LoopObj : LI.getLoopsInPreorder()) {
// Check that loop header BB contains loop metadata.
const auto LMDItr = FuncLoopMetadataMap.find(LoopObj->getHeader());
if (LMDItr == FuncLoopMetadataMap.end())
continue;
const auto *LMD = LMDItr->second;
if (LMD->getOpCode() == OpLoopMerge) {
const auto *LM = static_cast<const SPIRVLoopMerge *>(LMD);
setLLVMLoopMetadata<SPIRVLoopMerge>(LM, LoopObj);
} else if (LMD->getOpCode() == OpLoopControlINTEL) {
const auto *LCI = static_cast<const SPIRVLoopControlINTEL *>(LMD);
setLLVMLoopMetadata<SPIRVLoopControlINTEL>(LCI, LoopObj);
}
FuncLoopMetadataMap.erase(LMDItr);
}
}
Value *SPIRVToLLVM::transValue(SPIRVValue *BV, Function *F, BasicBlock *BB,
bool CreatePlaceHolder) {
SPIRVToLLVMValueMap::iterator Loc = ValueMap.find(BV);
if (Loc != ValueMap.end() && (!PlaceholderMap.count(BV) || CreatePlaceHolder))
return Loc->second;
SPIRVDBG(spvdbgs() << "[transValue] " << *BV << " -> ";)
BV->validate();
auto V = transValueWithoutDecoration(BV, F, BB, CreatePlaceHolder);
if (!V) {
SPIRVDBG(dbgs() << " Warning ! nullptr\n";)
return nullptr;
}
setName(V, BV);
if (!transDecoration(BV, V)) {
assert(0 && "trans decoration fail");
return nullptr;
}
SPIRVDBG(dbgs() << *V << '\n';)
return V;
}
Value *SPIRVToLLVM::transConvertInst(SPIRVValue *BV, Function *F,
BasicBlock *BB) {
SPIRVUnary *BC = static_cast<SPIRVUnary *>(BV);
auto Src = transValue(BC->getOperand(0), F, BB, BB ? true : false);
auto Dst = transType(BC->getType());
CastInst::CastOps CO = Instruction::BitCast;
bool IsExt =
Dst->getScalarSizeInBits() > Src->getType()->getScalarSizeInBits();
switch (BC->getOpCode()) {
case OpPtrCastToGeneric:
case OpGenericCastToPtr:
case OpPtrCastToCrossWorkgroupINTEL:
case OpCrossWorkgroupCastToPtrINTEL: {
// If module has pointers with DeviceOnlyINTEL and HostOnlyINTEL storage
// classes there will be a situation, when global_device/global_host
// address space will be lowered to just global address space. If there also
// is an addrspacecast - we need to replace it with source pointer.
if (Src->getType()->getPointerAddressSpace() ==
Dst->getPointerAddressSpace())
return Src;
CO = Instruction::AddrSpaceCast;