-
Notifications
You must be signed in to change notification settings - Fork 3
/
SPIRVReader.cpp
2514 lines (2328 loc) · 85.6 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 "libSPIRV/SPIRVUtil.h"
#include "libSPIRV/SPIRVType.h"
#include "libSPIRV/SPIRVValue.h"
#include "libSPIRV/SPIRVModule.h"
#include "libSPIRV/SPIRVFunction.h"
#include "libSPIRV/SPIRVBasicBlock.h"
#include "libSPIRV/SPIRVInstruction.h"
#include "libSPIRV/SPIRVExtInst.h"
#include "SPIRVInternal.h"
#include "libSPIRV/SPIRVMDBuilder.h"
#include "OCLUtil.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <fstream>
#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"));
cl::opt<bool> SPIRVGenKernelArgNameMD("spirv-gen-kernel-arg-name-md",
cl::init(false), cl::desc("Enable generating OpenCL kernel argument name "
"metadata"));
cl::opt<bool> SPIRVGenImgTypeAccQualPostfix("spirv-gen-image-type-acc-postfix",
cl::init(false), cl::desc("Enable generating access qualifier postfix"
" in OpenCL image type names"));
// Prefix for placeholder global variable name.
const char* kPlaceholderPrefix = "placeholder.";
// Save the translated LLVM before validation for debugging purpose.
static bool DbgSaveTmpLLVM = true;
static const char *DbgTmpLLVMFileName = "_tmp_llvmbil.ll";
typedef std::pair < unsigned, AttributeList > AttributeWithIndex;
static bool
isOpenCLKernel(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::F_None);
if (EC) {
FS << *M;
FS.close();
}
}
static MDNode*
getMDNodeStringIntVec(LLVMContext *Context, const std::string& Str,
const std::vector<SPIRVWord>& IntVals) {
std::vector<Metadata*> ValueVec;
ValueVec.push_back(MDString::get(*Context, Str));
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 MDNode*
getMDString(LLVMContext *Context, const std::string& Str) {
std::vector<Metadata*> ValueVec;
if (!Str.empty())
ValueVec.push_back(MDString::get(*Context, Str));
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
addOCLKernelArgumentMetadata(LLVMContext *Context,
std::vector<llvm::Metadata*> &KernelMD, const std::string &MDName,
SPIRVFunction *BF, std::function<Metadata *(SPIRVFunctionParameter *)>Func){
std::vector<Metadata*> ValueVec;
ValueVec.push_back(MDString::get(*Context, MDName));
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
ValueVec.push_back(Func(Arg));
});
KernelMD.push_back(MDNode::get(*Context, ValueVec));
}
class SPIRVToLLVMDbgTran {
public:
SPIRVToLLVMDbgTran(SPIRVModule *TBM, Module *TM)
:BM(TBM), M(TM), SpDbg(BM), Builder(*M){
Enable = BM->hasDebugInfo();
}
void createCompileUnit() {
if (!Enable)
return;
auto File = SpDbg.getEntryPointFileStr(ExecutionModelKernel, 0);
//std::string BaseName;
//std::string Path;
//splitFileName(File, BaseName, Path);
Builder.createCompileUnit(dwarf::DW_LANG_C99,
getDIFile(File), "spirv", false, "", 0, "", DICompileUnit::DebugEmissionKind::LineTablesOnly);
}
void addDbgInfoVersion() {
if (!Enable)
return;
M->addModuleFlag(Module::Warning, "Dwarf Version",
dwarf::DWARF_VERSION);
M->addModuleFlag(Module::Warning, "Debug Info Version",
DEBUG_METADATA_VERSION);
}
DIFile *getDIFile(const std::string &FileName){
return getOrInsert(FileMap, FileName, [=](){
std::string BaseName;
std::string Path;
splitFileName(FileName, BaseName, Path);
if (!BaseName.empty())
return Builder.createFile(BaseName, Path);
else
return (DIFile *)nullptr;
});
}
DISubprogram* getDISubprogram(SPIRVFunction *SF, Function *F){
return getOrInsert(FuncMap, F, [=](){
auto DF = getDIFile(SpDbg.getFunctionFileStr(SF));
auto FN = F->getName();
auto LN = SpDbg.getFunctionLineNo(SF);
Metadata *Args[] = {nullptr};
return Builder.createFunction(DF, FN, FN, DF, LN,
Builder.createSubroutineType(Builder.getOrCreateTypeArray({Args})),
Function::isInternalLinkage(F->getLinkage()),
true, LN);
});
}
void transDbgInfo(SPIRVValue *SV, Value *V) {
if (!Enable || !SV->hasLine())
return;
if (auto I = dyn_cast<Instruction>(V)) {
assert(SV->isInst() && "Invalid instruction");
auto SI = static_cast<SPIRVInstruction *>(SV);
assert(SI->getParent() &&
SI->getParent()->getParent() &&
"Invalid instruction");
auto Line = SV->getLine();
I->setDebugLoc(DebugLoc::get(Line->getLine(), Line->getColumn(),
getDISubprogram(SI->getParent()->getParent(),
I->getParent()->getParent())));
}
}
void finalize() {
if (!Enable)
return;
Builder.finalize();
}
private:
SPIRVModule *BM;
Module *M;
SPIRVDbgInfo SpDbg;
DIBuilder Builder;
bool Enable;
std::unordered_map<std::string, DIFile*> FileMap;
std::unordered_map<Function *, DISubprogram*> FuncMap;
void splitFileName(const std::string &FileName,
std::string &BaseName,
std::string &Path) {
auto Loc = FileName.find_last_of("/\\");
if (Loc != std::string::npos) {
BaseName = FileName.substr(Loc + 1);
Path = FileName.substr(0, Loc);
} else {
BaseName = FileName;
Path = ".";
}
}
};
class SPIRVToLLVM {
public:
SPIRVToLLVM(Module *LLVMModule, SPIRVModule *TheSPIRVModule)
:M(LLVMModule), BM(TheSPIRVModule), DbgTran(BM, M){
assert(M);
Context = &M->getContext();
}
std::string getOCLBuiltinName(SPIRVInstruction* BI);
std::string getOCLConvertBuiltinName(SPIRVInstruction *BI);
std::string getOCLGenericCastToPtrName(SPIRVInstruction *BI);
Type *transType(SPIRVType *BT);
std::string transTypeToOCLTypeName(SPIRVType *BT, bool IsSigned = true);
std::vector<Type *> transTypeVector(const std::vector<SPIRVType *>&);
bool translate();
bool transAddressingModel();
Value *transValue(SPIRVValue *, Function *F, BasicBlock *,
bool CreatePlaceHolder = true);
Value *transValueWithoutDecoration(SPIRVValue *, Function *F, BasicBlock *,
bool CreatePlaceHolder = true);
bool transDecoration(SPIRVValue *, Value *);
bool transAlign(SPIRVValue *, Value *);
Instruction *transOCLBuiltinFromExtInst(SPIRVExtInst *BC, BasicBlock *BB);
std::vector<Value *> transValue(const std::vector<SPIRVValue *>&, Function *F,
BasicBlock *);
Function *transFunction(SPIRVFunction *F);
bool transFPContractMetadata();
bool transKernelMetadata();
bool transSourceLanguage();
bool transSourceExtension();
void transGeneratorMD();
Value *transConvertInst(SPIRVValue* BV, Function* F, BasicBlock* BB);
Instruction *transBuiltinFromInst(const std::string& FuncName,
SPIRVInstruction* BI, BasicBlock* BB);
Instruction *transOCLBuiltinFromInst(SPIRVInstruction *BI, BasicBlock *BB);
Instruction *transSPIRVBuiltinFromInst(SPIRVInstruction *BI, BasicBlock *BB);
Instruction *transOCLBarrierFence(SPIRVInstruction* BI, BasicBlock *BB);
void transOCLVectorLoadStore(std::string& UnmangledName,
std::vector<SPIRVWord> &BArgs);
/// Post-process translated LLVM module for OpenCL.
bool postProcessOCL();
/// \brief Post-process OpenCL builtin functions returning struct type.
///
/// Some OpenCL builtin functions are translated to SPIR-V instructions with
/// struct type result, e.g. NDRange creation functions. Such functions
/// need to be post-processed to return the struct through sret argument.
bool postProcessOCLBuiltinReturnStruct(Function *F);
/// \brief Post-process OpenCL builtin functions having block argument.
///
/// These functions are translated to functions with function pointer type
/// argument first, then post-processed to have block argument.
bool postProcessOCLBuiltinWithFuncPointer(Function *F,
Function::arg_iterator I);
/// \brief Post-process OpenCL builtin functions having array argument.
///
/// These functions are translated to functions with array type argument
/// first, then post-processed to have pointer arguments.
bool postProcessOCLBuiltinWithArrayArguments(Function *F,
const std::string &DemangledName);
/// \brief Post-process OpImageSampleExplicitLod.
/// sampled_image = __spirv_SampledImage__(image, sampler);
/// return __spirv_ImageSampleExplicitLod__(sampled_image, image_operands,
/// ...);
/// =>
/// read_image(image, sampler, ...)
/// \return transformed call instruction.
Instruction *postProcessOCLReadImage(SPIRVInstruction *BI, CallInst *CI,
const std::string &DemangledName);
/// \brief Post-process OpImageWrite.
/// return write_image(image, coord, color, image_operands, ...);
/// =>
/// write_image(image, coord, ..., color)
/// \return transformed call instruction.
CallInst *postProcessOCLWriteImage(SPIRVInstruction *BI, CallInst *CI,
const std::string &DemangledName);
/// \brief Post-process OpBuildNDRange.
/// OpBuildNDRange GlobalWorkSize, LocalWorkSize, GlobalWorkOffset
/// =>
/// call ndrange_XD(GlobalWorkOffset, GlobalWorkSize, LocalWorkSize)
/// \return transformed call instruction.
CallInst *postProcessOCLBuildNDRange(SPIRVInstruction *BI, CallInst *CI,
const std::string &DemangledName);
/// \brief Expand OCL builtin functions with scalar argument, e.g.
/// step, smoothstep.
/// gentype func (fp edge, gentype x)
/// =>
/// gentype func (gentype edge, gentype x)
/// \return transformed call instruction.
CallInst *expandOCLBuiltinWithScalarArg(CallInst* CI,
const std::string &FuncName);
/// \brief Post-process OpGroupAll and OpGroupAny instructions translation.
/// i1 func (<n x i1> arg)
/// =>
/// i32 func (<n x i32> arg)
/// \return transformed call instruction.
Instruction *postProcessGroupAllAny(CallInst *CI,
const std::string &DemangledName);
typedef DenseMap<SPIRVType *, Type *> SPIRVToLLVMTypeMap;
typedef DenseMap<SPIRVValue *, Value *> SPIRVToLLVMValueMap;
typedef DenseMap<SPIRVFunction *, Function *> SPIRVToLLVMFunctionMap;
typedef DenseMap<GlobalVariable *, SPIRVBuiltinVariableKind> BuiltinVarMap;
// A SPIRV value may be translated to a load instruction of a placeholder
// global variable. This map records load instruction of these placeholders
// which are supposed to be replaced by the real values later.
typedef std::map<SPIRVValue *, LoadInst*> SPIRVToLLVMPlaceholderMap;
private:
Module *M;
BuiltinVarMap BuiltinGVMap;
LLVMContext *Context;
SPIRVModule *BM;
SPIRVToLLVMTypeMap TypeMap;
SPIRVToLLVMValueMap ValueMap;
SPIRVToLLVMFunctionMap FuncMap;
SPIRVToLLVMPlaceholderMap PlaceholderMap;
SPIRVToLLVMDbgTran DbgTran;
Type *mapType(SPIRVType *BT, Type *T) {
SPIRVDBG(dbgs() << *T << '\n';)
TypeMap[BT] = T;
return T;
}
// If a value is mapped twice, the existing mapped value is a placeholder,
// which must be a load instruction of a global variable whose name starts
// with kPlaceholderPrefix.
Value *mapValue(SPIRVValue *BV, Value *V) {
auto Loc = ValueMap.find(BV);
if (Loc != ValueMap.end()) {
if (Loc->second == V)
return V;
auto LD = dyn_cast<LoadInst>(Loc->second);
auto Placeholder = dyn_cast<GlobalVariable>(LD->getPointerOperand());
assert (LD && Placeholder &&
Placeholder->getName().startswith(kPlaceholderPrefix) &&
"A value is translated twice");
// Replaces placeholders for PHI nodes
LD->replaceAllUsesWith(V);
LD->dropAllReferences();
LD->removeFromParent();
Placeholder->dropAllReferences();
Placeholder->removeFromParent();
}
ValueMap[BV] = V;
return V;
}
bool isSPIRVBuiltinVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind *Kind = nullptr) {
auto Loc = BuiltinGVMap.find(GV);
if (Loc == BuiltinGVMap.end())
return false;
if (Kind)
*Kind = Loc->second;
return true;
}
// OpenCL function always has NoUnwound attribute.
// Change this if it is no longer true.
bool isFuncNoUnwind() const { return true;}
bool isSPIRVCmpInstTransToLLVMInst(SPIRVInstruction *BI) const;
bool transOCLBuiltinsFromVariables();
bool transOCLBuiltinFromVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind Kind);
MDString *transOCLKernelArgTypeName(SPIRVFunctionParameter *);
Value *mapFunction(SPIRVFunction *BF, Function *F) {
SPIRVDBG(spvdbgs() << "[mapFunction] " << *BF << " -> ";
dbgs() << *F << '\n';)
FuncMap[BF] = F;
return F;
}
Value *getTranslatedValue(SPIRVValue *BV);
Type *getTranslatedType(SPIRVType *BT);
SPIRVErrorLog &getErrorLog() {
return BM->getErrorLog();
}
void setCallingConv(CallInst *Call) {
Function *F = Call->getCalledFunction();
assert(F);
Call->setCallingConv(F->getCallingConv());
}
void setAttrByCalledFunc(CallInst *Call);
Type *transFPType(SPIRVType* T);
BinaryOperator *transShiftLogicalBitwiseInst(SPIRVValue* BV, BasicBlock* BB,
Function* F);
void transFlags(llvm::Value* V);
Instruction *transCmpInst(SPIRVValue* BV, BasicBlock* BB, Function* F);
void transOCLBuiltinFromInstPreproc(SPIRVInstruction* BI, Type *&RetTy,
std::vector<SPIRVValue *> &Args);
Instruction* transOCLBuiltinPostproc(SPIRVInstruction* BI,
CallInst* CI, BasicBlock* BB, const std::string &DemangledName);
std::string transOCLImageTypeName(SPIRV::SPIRVTypeImage* ST);
std::string transOCLSampledImageTypeName(SPIRV::SPIRVTypeSampledImage* ST);
std::string transOCLPipeTypeName(SPIRV::SPIRVTypePipe* ST);
std::string transOCLImageTypeAccessQualifier(SPIRV::SPIRVTypeImage* ST);
std::string transOCLPipeTypeAccessQualifier(SPIRV::SPIRVTypePipe* ST);
Value *oclTransConstantSampler(SPIRV::SPIRVConstantSampler* BCS);
void setName(llvm::Value* V, SPIRVValue* BV);
template<class Source, class Func>
bool foreachFuncCtlMask(Source, Func);
llvm::GlobalValue::LinkageTypes transLinkageType(const SPIRVValue* V);
Instruction *transOCLAllAny(SPIRVInstruction* BI, BasicBlock *BB);
Instruction *transOCLRelational(SPIRVInstruction* BI, BasicBlock *BB);
};
Type *
SPIRVToLLVM::getTranslatedType(SPIRVType *BV){
auto Loc = TypeMap.find(BV);
if (Loc != TypeMap.end())
return Loc->second;
return nullptr;
}
Value *
SPIRVToLLVM::getTranslatedValue(SPIRVValue *BV){
auto Loc = ValueMap.find(BV);
if (Loc != ValueMap.end())
return Loc->second;
return nullptr;
}
void
SPIRVToLLVM::setAttrByCalledFunc(CallInst *Call) {
Function *F = Call->getCalledFunction();
assert(F);
if (F->isIntrinsic()) {
return;
}
Call->setCallingConv(F->getCallingConv());
Call->setAttributes(F->getAttributes());
}
bool
SPIRVToLLVM::transOCLBuiltinsFromVariables(){
std::vector<GlobalVariable *> WorkList;
for (auto I = M->global_begin(), E = M->global_end(); I != E; ++I) {
SPIRVBuiltinVariableKind Kind;
if (!isSPIRVBuiltinVariable(&*I, &Kind))
continue;
if (!transOCLBuiltinFromVariable(&*I, Kind))
return false;
WorkList.push_back(&*I);
}
for (auto &I:WorkList) {
I->dropAllReferences();
I->removeFromParent();
}
return true;
}
// 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()));
}
// Variable like GlobalInvolcationId[x] -> get_global_id(x).
// Variable like WorkDim -> get_work_dim().
bool
SPIRVToLLVM::transOCLBuiltinFromVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind Kind) {
std::string FuncName = SPIRSPIRVBuiltinVariableMap::rmap(Kind);
std::string MangledName;
Type *ReturnTy = GV->getType()->getPointerElementType();
bool IsVec = ReturnTy->isVectorTy();
if (IsVec)
ReturnTy = cast<VectorType>(ReturnTy)->getElementType();
std::vector<Type*> ArgTy;
if (IsVec)
ArgTy.push_back(Type::getInt32Ty(*Context));
MangleOpenCLBuiltin(FuncName, ArgTy, MangledName);
Function *Func = M->getFunction(MangledName);
if (!Func) {
FunctionType *FT = FunctionType::get(ReturnTy, ArgTy, false);
Func = Function::Create(FT, GlobalValue::ExternalLinkage, MangledName, M);
Func->setCallingConv(CallingConv::SPIR_FUNC);
Func->addFnAttr(Attribute::NoUnwind);
Func->addFnAttr(Attribute::ReadNone);
}
std::vector<Instruction *> Deletes;
std::vector<Instruction *> Uses;
for (auto UI = GV->user_begin(), UE = GV->user_end(); UI != UE; ++UI) {
assert (isa<LoadInst>(*UI) && "Unsupported use");
auto LD = dyn_cast<LoadInst>(*UI);
if (!IsVec) {
Uses.push_back(LD);
Deletes.push_back(LD);
continue;
}
for (auto LDUI = LD->user_begin(), LDUE = LD->user_end(); LDUI != LDUE;
++LDUI) {
assert(isa<ExtractElementInst>(*LDUI) && "Unsupported use");
auto EEI = dyn_cast<ExtractElementInst>(*LDUI);
Uses.push_back(EEI);
Deletes.push_back(EEI);
}
Deletes.push_back(LD);
}
for (auto &I:Uses) {
std::vector<Value *> Arg;
if (auto EEI = dyn_cast<ExtractElementInst>(I))
Arg.push_back(EEI->getIndexOperand());
auto Call = CallInst::Create(Func, Arg, "", I);
Call->takeName(I);
setAttrByCalledFunc(Call);
SPIRVDBG(dbgs() << "[transOCLBuiltinFromVariable] " << *I << " -> " <<
*Call << '\n';)
I->replaceAllUsesWith(Call);
}
for (auto &I:Deletes) {
I->dropAllReferences();
I->removeFromParent();
}
return true;
}
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) {
std::string Name = std::string(kSPR2TypeName::OCLPrefix)
+ rmap<std::string>(ST->getDescriptor());
if (SPIRVGenImgTypeAccQualPostfix)
Name = Name + kSPR2TypeName::Delimiter
+ rmap<std::string>(ST->getAccessQualifier());
return Name;
}
std::string
SPIRVToLLVM::transOCLSampledImageTypeName(SPIRV::SPIRVTypeSampledImage* ST) {
return getSPIRVTypeName(kSPIRVTypeName::SampledImg,
getSPIRVImageTypePostfixes(getSPIRVImageSampledTypeName(
ST->getImageType()->getSampledType()),
ST->getImageType()->getDescriptor(),
ST->getImageType()->getAccessQualifier()));
}
std::string
SPIRVToLLVM::transOCLPipeTypeName(SPIRV::SPIRVTypePipe* PT) {
return kSPR2TypeName::Pipe;
}
Type *
SPIRVToLLVM::transType(SPIRVType *T) {
auto Loc = TypeMap.find(T);
if (Loc != TypeMap.end())
return Loc->second;
SPIRVDBG(spvdbgs() << "[transType] " << *T << " -> ";)
T->validate();
switch(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:
return mapType(T, ArrayType::get(transType(T->getArrayElementType()),
T->getArrayLength()));
case OpTypePointer:
return mapType(T, PointerType::get(transType(T->getPointerElementType()),
SPIRSPIRVAddrSpaceMap::rmap(T->getPointerStorageClass())));
case OpTypeVector:
return mapType(T, VectorType::get(transType(T->getVectorComponentType()),
T->getVectorComponentCount()));
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 OpTypeSampler:
return mapType(T, Type::getInt32Ty(*Context));
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 = M->getTypeByName(Name))
OldST->setName("");
}
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)));
StructTy->setBody(MT, ST->isPacked());
return StructTy;
}
case OpTypePipe: {
auto PT = static_cast<SPIRVTypePipe *>(T);
return mapType(T, getOrCreateOpaquePtrType(M,
transOCLPipeTypeName(PT),
getOCLOpaqueTypeAddrSpace(T->getOpCode())));
}
default: {
auto OC = T->getOpCode();
if (isOpaqueGenericTypeOpCode(OC))
return mapType(T, getOrCreateOpaquePtrType(M,
OCLOpaqueTypeOpCodeMap::rmap(OC),
getOCLOpaqueTypeAddrSpace(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:
llvm_unreachable("invalid integer size");
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:
return transTypeToOCLTypeName(T->getPointerElementType()) + "*";
case OpTypeVector:
return transTypeToOCLTypeName(T->getVectorComponentType()) +
T->getVectorComponentCount();
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:
return rmap<std::string>(static_cast<SPIRVTypeImage *>(T)->getDescriptor());
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;
}
bool
SPIRVToLLVM::isSPIRVCmpInstTransToLLVMInst(SPIRVInstruction* BI) const {
auto OC = BI->getOpCode();
return isCmpOpCode(OC) &&
!(OC >= OpLessOrGreater && OC <= OpUnordered);
}
void
SPIRVToLLVM::transFlags(llvm::Value* V) {
if(!isa<Instruction>(V))
return;
auto OC = cast<Instruction>(V)->getOpcode();
if (OC == Instruction::AShr || OC == Instruction::LShr) {
cast<BinaryOperator>(V)->setIsExact();
return;
}
}
void
SPIRVToLLVM::setName(llvm::Value* V, SPIRVValue* BV) {
auto Name = BV->getName();
if (!Name.empty() && (!V->hasName() || Name != V->getName()))
V->setName(Name);
}
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;
}
transFlags(V);
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:
CO = Instruction::AddrSpaceCast;
break;
case OpSConvert:
CO = IsExt ? Instruction::SExt : Instruction::Trunc;
break;
case OpUConvert:
CO = IsExt ? Instruction::ZExt : Instruction::Trunc;
break;
case OpFConvert:
CO = IsExt ? Instruction::FPExt : Instruction::FPTrunc;
break;
default:
CO = static_cast<CastInst::CastOps>(OpCodeMap::rmap(BC->getOpCode()));
}
assert(CastInst::isCast(CO) && "Invalid cast op code");
SPIRVDBG(if (!CastInst::castIsValid(CO, Src, Dst)) {
spvdbgs() << "Invalid cast: " << *BV << " -> ";
dbgs() << "Op = " << CO << ", Src = " << *Src << " Dst = " << *Dst << '\n';
})
if (BB)
return CastInst::Create(CO, Src, Dst, BV->getName(), BB);
return ConstantExpr::getCast(CO, dyn_cast<Constant>(Src), Dst);
}
BinaryOperator *SPIRVToLLVM::transShiftLogicalBitwiseInst(SPIRVValue* BV,
BasicBlock* BB,Function* F) {
SPIRVBinary* BBN = static_cast<SPIRVBinary*>(BV);
assert(BB && "Invalid BB");
Instruction::BinaryOps BO;
auto OP = BBN->getOpCode();
if (isLogicalOpCode(OP))
OP = IntBoolOpMap::rmap(OP);
BO = static_cast<Instruction::BinaryOps>(OpCodeMap::rmap(OP));
auto Inst = BinaryOperator::Create(BO,
transValue(BBN->getOperand(0), F, BB),
transValue(BBN->getOperand(1), F, BB), BV->getName(), BB);
return Inst;
}
Instruction *
SPIRVToLLVM::transCmpInst(SPIRVValue* BV, BasicBlock* BB, Function* F) {
SPIRVCompare* BC = static_cast<SPIRVCompare*>(BV);
assert(BB && "Invalid BB");
SPIRVType* BT = BC->getOperand(0)->getType();
Instruction* Inst = nullptr;
auto OP = BC->getOpCode();
if (isLogicalOpCode(OP))
OP = IntBoolOpMap::rmap(OP);
if (BT->isTypeVectorOrScalarInt() || BT->isTypeVectorOrScalarBool() ||
BT->isTypePointer())
Inst = new ICmpInst(*BB, CmpMap::rmap(OP),
transValue(BC->getOperand(0), F, BB),
transValue(BC->getOperand(1), F, BB));
else if (BT->isTypeVectorOrScalarFloat())
Inst = new FCmpInst(*BB, CmpMap::rmap(OP),
transValue(BC->getOperand(0), F, BB),
transValue(BC->getOperand(1), F, BB));
assert(Inst && "not implemented");
return Inst;
}
bool
SPIRVToLLVM::postProcessOCL() {
std::string DemangledName;
SPIRVWord SrcLangVer = 0;
BM->getSourceLanguage(&SrcLangVer);
bool isCPP = SrcLangVer == kOCLVer::CL21;
for (auto I = M->begin(), E = M->end(); I != E;) {
auto F = I++;
if (F->hasName() && F->isDeclaration()) {
DEBUG(dbgs() << "[postProcessOCL sret] " << *F << '\n');
if (F->getReturnType()->isStructTy() &&
oclIsBuiltin(F->getName(), &DemangledName, isCPP)) {
if (!postProcessOCLBuiltinReturnStruct(&*F))
return false;
}
}
}
for (auto I = M->begin(), E = M->end(); I != E;) {
auto F = I++;
if (F->hasName() && F->isDeclaration()) {
DEBUG(dbgs() << "[postProcessOCL func ptr] " << *F << '\n');
auto AI = F->arg_begin();
if (hasFunctionPointerArg(&*F, AI) && isDecoratedSPIRVFunc(&*F))
if (!postProcessOCLBuiltinWithFuncPointer(&*F, AI))
return false;
}
}
for (auto I = M->begin(), E = M->end(); I != E;) {
auto F = I++;
if (F->hasName() && F->isDeclaration()) {
DEBUG(dbgs() << "[postProcessOCL array arg] " << *F << '\n');
if (hasArrayArg(&*F) && oclIsBuiltin(F->getName(), &DemangledName, isCPP))
if (!postProcessOCLBuiltinWithArrayArguments(&*F, DemangledName))
return false;
}
}
return true;
}
bool
SPIRVToLLVM::postProcessOCLBuiltinReturnStruct(Function *F) {
std::string Name = F->getName();
F->setName(Name + ".old");
for (auto I = F->user_begin(), E = F->user_end(); I != E;) {
if (auto CI = dyn_cast<CallInst>(*I++)) {
auto ST = dyn_cast<StoreInst>(*(CI->user_begin()));
assert(ST);
std::vector<Type *> ArgTys;
getFunctionTypeParameterTypes(F->getFunctionType(), ArgTys);
ArgTys.insert(ArgTys.begin(), PointerType::get(F->getReturnType(),
SPIRAS_Private));
auto newF = getOrCreateFunction(M, Type::getVoidTy(*Context),
ArgTys, Name);
newF->setCallingConv(F->getCallingConv());