forked from KhronosGroup/SPIRV-LLVM-Translator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPIRVUtil.cpp
2606 lines (2419 loc) · 93.7 KB
/
SPIRVUtil.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
//===- SPIRVUtil.cpp - SPIR-V Utilities -------------------------*- C++ -*-===//
//
// The LLVM/SPIRV 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 defines utility classes and functions shared by SPIR-V
/// reader/writer.
///
//===----------------------------------------------------------------------===//
// This file needs to be included before anything that declares
// llvm::PointerType to avoid a compilation bug on MSVC.
#include "llvm/Demangle/ItaniumDemangle.h"
#include "FunctionDescriptor.h"
#include "ManglingUtils.h"
#include "NameMangleAPI.h"
#include "OCLUtil.h"
#include "ParameterType.h"
#include "SPIRVInternal.h"
#include "SPIRVMDWalker.h"
#include "libSPIRV/SPIRVDecorate.h"
#include "libSPIRV/SPIRVValue.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/TypedPointerType.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ToolOutputFile.h"
#include <functional>
#include <sstream>
#define DEBUG_TYPE "spirv"
namespace SPIRV {
#ifdef _SPIRV_SUPPORT_TEXT_FMT
cl::opt<bool, true>
UseTextFormat("spirv-text",
cl::desc("Use text format for SPIR-V for debugging purpose"),
cl::location(SPIRVUseTextFormat));
#endif
#ifdef _SPIRVDBG
cl::opt<bool, true> EnableDbgOutput("spirv-debug",
cl::desc("Enable SPIR-V debug output"),
cl::location(SPIRVDbgEnable));
#endif
bool isSupportedTriple(Triple T) { return T.isSPIR() || T.isSPIRV(); }
void addFnAttr(CallInst *Call, Attribute::AttrKind Attr) {
Call->addFnAttr(Attr);
}
void removeFnAttr(CallInst *Call, Attribute::AttrKind Attr) {
Call->removeFnAttr(Attr);
}
Value *extendVector(Value *V, FixedVectorType *NewType,
IRBuilderBase &Builder) {
unsigned OldSize = cast<FixedVectorType>(V->getType())->getNumElements();
unsigned NewSize = NewType->getNumElements();
assert(OldSize < NewSize);
std::vector<Constant *> Components;
IntegerType *Int32Ty = Builder.getInt32Ty();
for (unsigned I = 0; I < NewSize; I++) {
if (I < OldSize)
Components.push_back(ConstantInt::get(Int32Ty, I));
else
Components.push_back(PoisonValue::get(Int32Ty));
}
return Builder.CreateShuffleVector(V, PoisonValue::get(V->getType()),
ConstantVector::get(Components), "vecext");
}
void saveLLVMModule(Module *M, const std::string &OutputFile) {
std::error_code EC;
ToolOutputFile Out(OutputFile.c_str(), EC, sys::fs::OF_None);
if (EC) {
SPIRVDBG(errs() << "Fails to open output file: " << EC.message();)
return;
}
WriteBitcodeToFile(*M, Out.os());
Out.keep();
}
std::string mapLLVMTypeToOCLType(const Type *Ty, bool Signed, Type *PET) {
if (Ty->isHalfTy())
return "half";
if (Ty->isFloatTy())
return "float";
if (Ty->isDoubleTy())
return "double";
if (const auto *IntTy = dyn_cast<IntegerType>(Ty)) {
std::string SignPrefix;
std::string Stem;
if (!Signed)
SignPrefix = "u";
switch (IntTy->getIntegerBitWidth()) {
case 8:
Stem = "char";
break;
case 16:
Stem = "short";
break;
case 32:
Stem = "int";
break;
case 64:
Stem = "long";
break;
default:
Stem = "invalid_type";
break;
}
return SignPrefix + Stem;
}
if (const auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
Type *EleTy = VecTy->getElementType();
unsigned Size = VecTy->getNumElements();
std::stringstream Ss;
Ss << mapLLVMTypeToOCLType(EleTy, Signed) << Size;
return Ss.str();
}
// It is expected that `Ty` can be mapped to `ReturnType` from "Optional
// Postfixes for SPIR-V Builtin Function Names" section of
// SPIRVRepresentationInLLVM.rst document (aka SPIRV-friendly IR).
// If `Ty` is not a scalar or vector type mentioned in the document (return
// value of some SPIR-V instructions may be represented as pointer to a struct
// in LLVM IR) we can mangle the type.
BuiltinFuncMangleInfo MangleInfo;
if (Ty->isPointerTy())
Ty = TypedPointerType::get(PET, Ty->getPointerAddressSpace());
std::string MangledName =
mangleBuiltin("", const_cast<Type *>(Ty), &MangleInfo);
// Remove "_Z0"(3 characters) from the front of the name
return MangledName.erase(0, 3);
}
StructType *getOrCreateOpaqueStructType(Module *M, StringRef Name) {
auto *OpaqueType = StructType::getTypeByName(M->getContext(), Name);
if (!OpaqueType)
OpaqueType = StructType::create(M->getContext(), Name);
return OpaqueType;
}
void getFunctionTypeParameterTypes(llvm::FunctionType *FT,
SmallVector<Type *> &ArgTys) {
for (auto I = FT->param_begin(), E = FT->param_end(); I != E; ++I) {
ArgTys.push_back(*I);
}
}
bool isVoidFuncTy(FunctionType *FT) { return FT->getReturnType()->isVoidTy(); }
bool isOCLImageType(llvm::Type *Ty, StringRef *Name) {
if (auto *TPT = dyn_cast_or_null<TypedPointerType>(Ty))
if (auto *ST = dyn_cast_or_null<StructType>(TPT->getElementType()))
if (ST->isOpaque()) {
auto FullName = ST->getName();
if (FullName.find(kSPR2TypeName::ImagePrefix) == 0) {
if (Name)
*Name = FullName.drop_front(strlen(kSPR2TypeName::OCLPrefix));
return true;
}
}
if (auto *TET = dyn_cast_or_null<TargetExtType>(Ty)) {
assert(!Name && "Cannot get the name for a target-extension type image");
return TET->getName() == "spirv.Image";
}
return false;
}
/// \param BaseTyName is the type Name as in spirv.BaseTyName.Postfixes
/// \param Postfix contains postfixes extracted from the SPIR-V image
/// type Name as spirv.BaseTyName.Postfixes.
bool isSPIRVStructType(llvm::Type *Ty, StringRef BaseTyName,
StringRef *Postfix) {
auto *ST = dyn_cast<StructType>(Ty);
if (!ST)
return false;
if (ST->isOpaque()) {
auto FullName = ST->getName();
std::string N =
std::string(kSPIRVTypeName::PrefixAndDelim) + BaseTyName.str();
if (FullName != N)
N = N + kSPIRVTypeName::Delimiter;
if (FullName.starts_with(N)) {
if (Postfix)
*Postfix = FullName.drop_front(N.size());
return true;
}
}
return false;
}
bool isSYCLHalfType(llvm::Type *Ty) {
if (auto *ST = dyn_cast<StructType>(Ty)) {
if (!ST->hasName())
return false;
StringRef Name = ST->getName();
if (!Name.consume_front("class."))
return false;
if ((Name.starts_with("sycl::") || Name.starts_with("cl::sycl::") ||
Name.starts_with("__sycl_internal::")) &&
Name.ends_with("::half")) {
return true;
}
}
return false;
}
bool isSYCLBfloat16Type(llvm::Type *Ty) {
if (auto *ST = dyn_cast<StructType>(Ty)) {
if (!ST->hasName())
return false;
StringRef Name = ST->getName();
if (!Name.consume_front("class."))
return false;
if ((Name.starts_with("sycl::") || Name.starts_with("cl::sycl::") ||
Name.starts_with("__sycl_internal::")) &&
Name.ends_with("::bfloat16")) {
return true;
}
}
return false;
}
Function *getOrCreateFunction(Module *M, Type *RetTy, ArrayRef<Type *> ArgTypes,
StringRef Name, BuiltinFuncMangleInfo *Mangle,
AttributeList *Attrs, bool TakeName) {
std::string MangledName{Name};
bool IsVarArg = false;
if (Mangle) {
MangledName = mangleBuiltin(Name, ArgTypes, Mangle);
IsVarArg = 0 <= Mangle->getVarArg();
if (IsVarArg)
ArgTypes = ArgTypes.slice(0, Mangle->getVarArg());
}
FunctionType *FT = FunctionType::get(RetTy, ArgTypes, IsVarArg);
Function *F = M->getFunction(MangledName);
if (!TakeName && F && F->getFunctionType() != FT && Mangle != nullptr) {
std::string S;
raw_string_ostream SS(S);
SS << "Error: Attempt to redefine function: " << *F << " => " << *FT
<< '\n';
report_fatal_error(llvm::Twine(SS.str()), false);
}
if (!F || F->getFunctionType() != FT) {
auto *NewF =
Function::Create(FT, GlobalValue::ExternalLinkage, MangledName, M);
if (F && TakeName) {
NewF->takeName(F);
LLVM_DEBUG(
dbgs() << "[getOrCreateFunction] Warning: taking function Name\n");
}
if (NewF->getName() != MangledName) {
LLVM_DEBUG(
dbgs() << "[getOrCreateFunction] Warning: function Name changed\n");
}
LLVM_DEBUG(dbgs() << "[getOrCreateFunction] ";
if (F) dbgs() << *F << " => "; dbgs() << *NewF << '\n';);
if (F)
NewF->setDSOLocal(F->isDSOLocal());
F = NewF;
F->setCallingConv(CallingConv::SPIR_FUNC);
if (Attrs)
F->setAttributes(*Attrs);
}
return F;
}
std::vector<Value *> getArguments(CallInst *CI, unsigned Start, unsigned End) {
std::vector<Value *> Args;
if (End == 0)
End = CI->arg_size();
for (; Start != End; ++Start) {
Args.push_back(CI->getArgOperand(Start));
}
return Args;
}
uint64_t getArgAsInt(CallInst *CI, unsigned I) {
return cast<ConstantInt>(CI->getArgOperand(I))->getZExtValue();
}
Scope getArgAsScope(CallInst *CI, unsigned I) {
return static_cast<Scope>(getArgAsInt(CI, I));
}
std::string prefixSPIRVName(const std::string &S) {
return std::string(kSPIRVName::Prefix) + S;
}
StringRef dePrefixSPIRVName(StringRef R, SmallVectorImpl<StringRef> &Postfix) {
const size_t Start = strlen(kSPIRVName::Prefix);
if (!R.starts_with(kSPIRVName::Prefix))
return R;
R = R.drop_front(Start);
R.split(Postfix, "_", -1, false);
auto Name = Postfix.front();
Postfix.erase(Postfix.begin());
return Name;
}
std::string getSPIRVFuncName(Op OC, StringRef PostFix) {
return prefixSPIRVName(getName(OC) + PostFix.str());
}
std::string getSPIRVFuncName(Op OC, const Type *PRetTy, bool IsSigned,
Type *PET) {
return prefixSPIRVName(getName(OC) + kSPIRVPostfix::Divider +
getPostfixForReturnType(PRetTy, IsSigned, PET));
}
std::string getSPIRVFuncName(SPIRVBuiltinVariableKind BVKind) {
return prefixSPIRVName(getName(BVKind));
}
std::string getSPIRVExtFuncName(SPIRVExtInstSetKind Set, unsigned ExtOp,
StringRef PostFix) {
std::string ExtOpName;
switch (Set) {
default:
llvm_unreachable("invalid extended instruction set");
ExtOpName = "unknown";
break;
case SPIRVEIS_OpenCL:
ExtOpName = getName(static_cast<OCLExtOpKind>(ExtOp));
break;
}
return prefixSPIRVName(SPIRVExtSetShortNameMap::map(Set) + '_' + ExtOpName +
PostFix.str());
}
SPIRVDecorate *mapPostfixToDecorate(StringRef Postfix, SPIRVEntry *Target) {
if (Postfix == kSPIRVPostfix::Sat)
return new SPIRVDecorate(spv::DecorationSaturatedConversion, Target);
if (Postfix.starts_with(kSPIRVPostfix::Rt))
return new SPIRVDecorate(spv::DecorationFPRoundingMode, Target,
map<SPIRVFPRoundingModeKind>(Postfix.str()));
return nullptr;
}
SPIRVValue *addDecorations(SPIRVValue *Target,
const SmallVectorImpl<std::string> &Decs) {
for (auto &I : Decs)
if (auto *Dec = mapPostfixToDecorate(I, Target))
Target->addDecorate(Dec);
return Target;
}
std::string getPostfixForReturnType(CallInst *CI, bool IsSigned) {
return getPostfixForReturnType(CI->getType(), IsSigned);
}
std::string getPostfixForReturnType(const Type *PRetTy, bool IsSigned,
Type *PET) {
return std::string(kSPIRVPostfix::Return) +
mapLLVMTypeToOCLType(PRetTy, IsSigned, PET);
}
// Enqueue kernel, kernel query, pipe and address space cast built-ins
// are not mangled.
bool isNonMangledOCLBuiltin(StringRef Name) {
if (!Name.starts_with("__"))
return false;
return isEnqueueKernelBI(Name) || isKernelQueryBI(Name) ||
isPipeOrAddressSpaceCastBI(Name.drop_front(2));
}
Op getSPIRVFuncOC(StringRef S, SmallVectorImpl<std::string> *Dec) {
Op OC;
SmallVector<StringRef, 2> Postfix;
StringRef Name;
if (!oclIsBuiltin(S, Name))
Name = S;
StringRef R(Name);
if ((!Name.starts_with(kSPIRVName::Prefix) && !isNonMangledOCLBuiltin(S)) ||
!getByName(dePrefixSPIRVName(R, Postfix).str(), OC)) {
return OpNop;
}
if (Dec)
for (auto &I : Postfix)
Dec->push_back(I.str());
return OC;
}
bool getSPIRVBuiltin(const std::string &OrigName, spv::BuiltIn &B) {
SmallVector<StringRef, 2> Postfix;
StringRef R(OrigName);
R = dePrefixSPIRVName(R, Postfix);
if (!Postfix.empty())
return false;
return getByName(R.str(), B);
}
// Demangled name is a substring of the name. The DemangledName is updated only
// if true is returned
bool oclIsBuiltin(StringRef Name, StringRef &DemangledName, bool IsCpp) {
if (Name == "printf") {
DemangledName = "__spirv_ocl_printf";
return true;
}
if (isNonMangledOCLBuiltin(Name)) {
DemangledName = Name.drop_front(2);
return true;
}
if (!Name.starts_with("_Z"))
return false;
// OpenCL C++ built-ins are declared in cl namespace.
// TODO: consider using 'St' abbriviation for cl namespace mangling.
// Similar to ::std:: in C++.
if (IsCpp) {
if (!Name.starts_with("_ZN"))
return false;
// Skip CV and ref qualifiers.
size_t NameSpaceStart = Name.find_first_not_of("rVKRO", 3);
// All built-ins are in the ::cl:: namespace.
if (Name.substr(NameSpaceStart, 11) != "2cl7__spirv")
return false;
size_t DemangledNameLenStart = NameSpaceStart + 11;
size_t Start = Name.find_first_not_of("0123456789", DemangledNameLenStart);
size_t Len = 0;
if (!Name.substr(DemangledNameLenStart, Start - DemangledNameLenStart)
.getAsInteger(10, Len)) {
DemangledName = Name.substr(Start, Len);
return true;
}
SPIRVDBG(errs() << "Error in extracting integer value");
return false;
}
size_t Start = Name.find_first_not_of("0123456789", 2);
size_t Len = 0;
if (!Name.substr(2, Start - 2).getAsInteger(10, Len)) {
DemangledName = Name.substr(Start, Len);
return true;
}
SPIRVDBG(errs() << "Error in extracting integer value");
return false;
}
// Check if a mangled type Name is unsigned
bool isMangledTypeUnsigned(char Mangled) {
return Mangled == 'h' /* uchar */
|| Mangled == 't' /* ushort */
|| Mangled == 'j' /* uint */
|| Mangled == 'm' /* ulong */;
}
// Check if a mangled type Name is signed
bool isMangledTypeSigned(char Mangled) {
return Mangled == 'c' /* char */
|| Mangled == 'a' /* signed char */
|| Mangled == 's' /* short */
|| Mangled == 'i' /* int */
|| Mangled == 'l' /* long */;
}
// Check if a mangled type Name is floating point (excludes half)
bool isMangledTypeFP(char Mangled) {
return Mangled == 'f' /* float */
|| Mangled == 'd'; /* double */
}
// Check if a mangled type Name is half
bool isMangledTypeHalf(std::string Mangled) {
return Mangled == "Dh"; /* half */
}
void eraseSubstitutionFromMangledName(std::string &MangledName) {
auto Len = MangledName.length();
while (Len >= 2 && MangledName.substr(Len - 2, 2) == "S_") {
Len -= 2;
MangledName.erase(Len, 2);
}
}
ParamType lastFuncParamType(StringRef MangledName) {
std::string Copy(MangledName);
eraseSubstitutionFromMangledName(Copy);
char Mangled = Copy.back();
std::string Mangled2 = Copy.substr(Copy.size() - 2);
if (isMangledTypeFP(Mangled) || isMangledTypeHalf(Mangled2)) {
return ParamType::FLOAT;
} else if (isMangledTypeUnsigned(Mangled)) {
return ParamType::UNSIGNED;
} else if (isMangledTypeSigned(Mangled)) {
return ParamType::SIGNED;
}
return ParamType::UNKNOWN;
}
// Check if the last argument is signed
bool isLastFuncParamSigned(StringRef MangledName) {
return lastFuncParamType(MangledName) == ParamType::SIGNED;
}
// Check if a mangled function Name contains unsigned atomic type
bool containsUnsignedAtomicType(StringRef Name) {
auto Loc = Name.find(kMangledName::AtomicPrefixIncoming);
if (Loc == StringRef::npos)
return false;
return isMangledTypeUnsigned(
Name[Loc + strlen(kMangledName::AtomicPrefixIncoming)]);
}
bool hasArrayArg(Function *F) {
for (auto I = F->arg_begin(), E = F->arg_end(); I != E; ++I) {
LLVM_DEBUG(dbgs() << "[hasArrayArg] " << *I << '\n');
if (I->getType()->isArrayTy()) {
return true;
}
}
return false;
}
/// Convert a struct name from the name given to it in Itanium name mangling to
/// the name given to it as an LLVM opaque struct.
static std::string demangleBuiltinOpenCLTypeName(StringRef MangledStructName) {
assert(MangledStructName.starts_with("ocl_") &&
"Not a valid builtin OpenCL mangled name");
// Bare structure type that starts with ocl_ is a builtin opencl type.
// See clang/lib/CodeGen/CGOpenCLRuntime for how these map to LLVM types
// and clang/lib/AST/ItaniumMangle for how they are mangled.
// In general, ocl_<foo> is mapped to pointer-to-%opencl.<foo>, but
// there is some variance around whether or not _t is included in the
// mangled name.
std::string LlvmStructName = StringSwitch<StringRef>(MangledStructName)
.Case("ocl_sampler", "opencl.sampler_t")
.Case("ocl_event", "opencl.event_t")
.Case("ocl_clkevent", "opencl.clk_event_t")
.Case("ocl_queue", "opencl.queue_t")
.Case("ocl_reserveid", "opencl.reserve_id_t")
.Default("")
.str();
if (LlvmStructName.empty()) {
LlvmStructName = "opencl.";
LlvmStructName += MangledStructName.substr(4); // Strip off ocl_
if (!MangledStructName.ends_with("_t"))
LlvmStructName += "_t";
}
return LlvmStructName;
}
/// Convert a C/C++ type name into an LLVM type, if it's a basic integer or
/// floating point type.
static Type *parsePrimitiveType(LLVMContext &Ctx, StringRef Name) {
return StringSwitch<Type *>(Name)
.Cases("char", "signed char", "unsigned char", Type::getInt8Ty(Ctx))
.Cases("short", "unsigned short", Type::getInt16Ty(Ctx))
.Cases("int", "unsigned int", Type::getInt32Ty(Ctx))
.Cases("long", "unsigned long", Type::getInt64Ty(Ctx))
.Cases("long long", "unsigned long long", Type::getInt64Ty(Ctx))
.Case("half", Type::getHalfTy(Ctx))
.Case("float", Type::getFloatTy(Ctx))
.Case("double", Type::getDoubleTy(Ctx))
.Case("void", Type::getInt8Ty(Ctx))
.Default(nullptr);
}
} // namespace SPIRV
// The demangler node hierarchy doesn't use LLVM's RTTI helper functions (as it
// also needs to live in libcxxabi). By specializing this implementation here,
// we can add support for these functions.
#define NODE(X) \
template <typename From> struct llvm::isa_impl<itanium_demangle::X, From> { \
static inline bool doit(const From &Val) { \
return Val.getKind() == itanium_demangle::Node::K##X; \
} \
};
#include "llvm/Demangle/ItaniumNodes.def"
namespace SPIRV {
namespace {
// An allocator to use with the demangler API.
class DefaultAllocator {
BumpPtrAllocator Alloc;
public:
void reset() { Alloc.Reset(); }
template <typename T, typename... Args> T *makeNode(Args &&...ArgList) {
return new (Alloc.Allocate(sizeof(T), alignof(T)))
T(std::forward<Args>(ArgList)...);
}
void *allocateNodeArray(size_t Sz) {
using namespace llvm::itanium_demangle;
return Alloc.Allocate(sizeof(Node *) * Sz, alignof(Node *));
}
};
} // unnamed namespace
static StringRef stringify(const itanium_demangle::NameType *Node) {
return Node->getName();
}
/// Convert a mangled name that represents a basic integer, floating-point,
/// etc. type into the corresponding LLVM type.
static Type *getPrimitiveType(LLVMContext &Ctx,
const llvm::itanium_demangle::Node *N) {
using namespace llvm::itanium_demangle;
if (auto *Name = dyn_cast<NameType>(N)) {
return parsePrimitiveType(Ctx, stringify(Name));
}
if (auto *BitInt = dyn_cast<BitIntType>(N)) {
unsigned BitWidth = 0;
BitInt->match([&](const Node *NodeSize, bool) {
const StringRef SizeStr(stringify(cast<NameType>(NodeSize)));
SizeStr.getAsInteger(10, BitWidth);
});
return Type::getIntNTy(Ctx, BitWidth);
}
if (auto *FP = dyn_cast<BinaryFPType>(N)) {
StringRef SizeStr;
FP->match([&](const Node *NodeDimension) {
SizeStr = stringify(cast<NameType>(NodeDimension));
});
return StringSwitch<Type *>(SizeStr)
.Case("16", Type::getHalfTy(Ctx))
.Case("32", Type::getFloatTy(Ctx))
.Case("64", Type::getDoubleTy(Ctx))
.Case("128", Type::getFP128Ty(Ctx))
.Default(nullptr);
}
return nullptr;
}
template <typename FnType>
static TypedPointerType *
parseNode(Module *M, const llvm::itanium_demangle::Node *ParamType,
FnType GetStructType) {
using namespace llvm::itanium_demangle;
Type *PointeeTy = nullptr;
unsigned AS = 0;
if (auto *Name = dyn_cast<NameType>(ParamType)) {
// This corresponds to a simple class name. Since we only care about
// pointer element types, the only relevant names are those corresponding
// to the OpenCL special types (which all begin with "ocl_").
StringRef Arg(stringify(Name));
if (Arg.starts_with("ocl_")) {
const std::string StructName = demangleBuiltinOpenCLTypeName(Arg);
PointeeTy = GetStructType(StructName);
} else if (Arg.consume_front("__spirv_")) {
// This is a pointer to a SPIR-V OpType* opaque struct. In general,
// convert __spirv_<Type>[__Suffix] to %spirv.Type[._Suffix]
auto NameSuffixPair = Arg.split('_');
std::string StructName = "spirv.";
StructName += NameSuffixPair.first;
if (!NameSuffixPair.second.empty()) {
StructName += ".";
StructName += NameSuffixPair.second;
}
PointeeTy = GetStructType(StructName);
} else if (Arg == "ndrange_t") {
PointeeTy = GetStructType(Arg);
}
} else if (auto *P = dyn_cast<itanium_demangle::PointerType>(ParamType)) {
const Node *Pointee = P->getPointee();
// Strip through all of the qualifiers on the pointee type.
while (true) {
if (auto *VendorTy = dyn_cast<VendorExtQualType>(Pointee)) {
Pointee = VendorTy->getTy();
StringRef Qualifier(&*VendorTy->getExt().begin(),
VendorTy->getExt().size());
if (Qualifier.consume_front("AS")) {
Qualifier.getAsInteger(10, AS);
}
} else if (auto *Qual = dyn_cast<QualType>(Pointee)) {
Pointee = Qual->getChild();
} else {
break;
}
}
if (auto *Name = dyn_cast<NameType>(Pointee)) {
StringRef MangledStructName(stringify(Name));
if (MangledStructName.consume_front("__spirv_")) {
// This is a pointer to a SPIR-V OpType* opaque struct. In general,
// convert __spirv_<Type>[__Suffix] to %spirv.Type[._Suffix]
auto NameSuffixPair = MangledStructName.split('_');
std::string StructName = "spirv.";
StructName += NameSuffixPair.first;
if (!NameSuffixPair.second.empty()) {
StructName += ".";
StructName += NameSuffixPair.second;
}
PointeeTy = GetStructType(StructName);
} else if (MangledStructName.starts_with("opencl.")) {
PointeeTy = GetStructType(MangledStructName);
} else if (MangledStructName.starts_with("ocl_")) {
const std::string StructName =
demangleBuiltinOpenCLTypeName(MangledStructName);
PointeeTy = TypedPointerType::get(GetStructType(StructName), 0);
} else {
PointeeTy = parsePrimitiveType(M->getContext(), MangledStructName);
}
} else if (auto *Ty = getPrimitiveType(M->getContext(), Pointee)) {
PointeeTy = Ty;
} else if (auto *Vec = dyn_cast<itanium_demangle::VectorType>(Pointee)) {
unsigned ElemCount = 0;
const StringRef ElemCountStr(
stringify(cast<NameType>(Vec->getDimension())));
ElemCountStr.getAsInteger(10, ElemCount);
if (auto *Ty = getPrimitiveType(M->getContext(), Vec->getBaseType())) {
PointeeTy = llvm::VectorType::get(Ty, ElemCount, false);
}
} else if (llvm::isa<itanium_demangle::PointerType>(Pointee)) {
PointeeTy = parseNode(M, Pointee, GetStructType);
} else {
// Other possible pointee types do not correspond to any of the special
// struct types were are looking for here.
}
} else if (auto *VendorTy = dyn_cast<VendorExtQualType>(ParamType)) {
// This is a block parameter. Decode the pointee type as if it were a
// void (*)(void) function pointer type.
if (VendorTy->getExt() == "block_pointer") {
PointeeTy =
llvm::FunctionType::get(Type::getVoidTy(M->getContext()), false);
}
} else {
// Other parameter types are not likely to be pointer types, so we can
// ignore these.
}
return PointeeTy ? TypedPointerType::get(PointeeTy, AS) : nullptr;
}
bool getParameterTypes(Function *F, SmallVectorImpl<Type *> &ArgTys,
std::function<std::string(StringRef)> NameMapFn) {
using namespace llvm::itanium_demangle;
// If there's no mangled name, we can't do anything. Also, if there's no
// parameters, do nothing.
StringRef Name = F->getName();
if (!Name.starts_with("_Z") || F->arg_empty())
return Name.starts_with("_Z");
Module *M = F->getParent();
auto GetStructType = [&](StringRef Name) {
return getOrCreateOpaqueStructType(M, NameMapFn ? NameMapFn(Name) : Name);
};
// Start by filling in a skeleton of information we can get from the LLVM type
// itself.
ArgTys.clear();
auto *FT = F->getFunctionType();
ArgTys.reserve(FT->getNumParams());
bool HasSret = false;
for (Argument &Arg : F->args()) {
if (!Arg.getType()->isPointerTy())
ArgTys.push_back(Arg.getType());
else if (Type *Ty = Arg.getParamStructRetType()) {
assert(!HasSret && &Arg == F->getArg(0) &&
"sret parameter should only appear on the first argument");
HasSret = true;
unsigned AS = Arg.getType()->getPointerAddressSpace();
if (auto *STy = dyn_cast<StructType>(Ty))
if (STy->hasName())
ArgTys.push_back(
TypedPointerType::get(GetStructType(STy->getName()), AS));
else
ArgTys.push_back(TypedPointerType::get(STy, AS));
else
ArgTys.push_back(TypedPointerType::get(Ty, AS));
} else {
ArgTys.push_back(Arg.getType());
}
}
// Skip the first argument if it's an sret parameter--this would be an
// implicit parameter not recognized as part of the function parameters.
auto *ArgIter = ArgTys.begin();
if (HasSret)
++ArgIter;
// Demangle the function arguments. If we get an input name of
// "_Z12write_imagei20ocl_image1d_array_woDv2_iiDv4_i", then we expect
// that Demangler.getFunctionParameters will return
// "(ocl_image1d_array_wo, int __vector(2), int, int __vector(4))" (in other
// words, the stuff between the parentheses if you ran C++ filt, including
// the parentheses itself).
const StringRef MangledName(F->getName());
ManglingParser<DefaultAllocator> Demangler(MangledName.begin(),
MangledName.end());
// We expect to see only function name encodings here. If it's not a function
// name encoding, bail out.
auto *RootNode = dyn_cast_or_null<FunctionEncoding>(Demangler.parse());
if (!RootNode)
return false;
// Get the parameter list. If the function is a vararg function, drop the last
// parameter.
NodeArray Params = RootNode->getParams();
if (F->isVarArg()) {
bool HasVarArgParam = false;
if (!Params.empty()) {
if (auto *Name = dyn_cast<NameType>(Params[Params.size() - 1])) {
if (stringify(Name) == "...")
HasVarArgParam = true;
}
}
if (HasVarArgParam) {
Params = NodeArray(Params.begin(), Params.size() - 1);
} else {
LLVM_DEBUG(dbgs() << "[getParameterTypes] function " << MangledName
<< " was expected to have a varargs parameter\n");
return false;
}
}
// Sanity check that the name mangling matches up to the expected number of
// arguments.
if (Params.size() != (size_t)(ArgTys.end() - ArgIter)) {
LLVM_DEBUG(dbgs() << "[getParameterTypes] function " << MangledName
<< " appears to have " << Params.size()
<< " arguments but has " << (ArgTys.end() - ArgIter)
<< "\n");
return false;
}
// Overwrite the types of pointer-typed arguments with information from
// demangling.
bool DemangledSuccessfully = true;
for (auto *ParamType : Params) {
Type *ArgTy = *ArgIter;
Type *DemangledTy = parseNode(M, ParamType, GetStructType);
if (ArgTy->isPointerTy() && DemangledTy == nullptr) {
DemangledTy = TypedPointerType::get(Type::getInt8Ty(ArgTy->getContext()),
ArgTy->getPointerAddressSpace());
LLVM_DEBUG(dbgs() << "Failed to recover type of argument " << *ArgTy
<< " of function " << F->getName() << "\n");
DemangledSuccessfully = false;
} else if (ArgTy->isTargetExtTy() || !DemangledTy)
DemangledTy = ArgTy;
if (auto *TPT = dyn_cast<TypedPointerType>(DemangledTy))
if (ArgTy->isPointerTy() &&
TPT->getAddressSpace() != ArgTy->getPointerAddressSpace())
DemangledTy = TypedPointerType::get(TPT->getElementType(),
ArgTy->getPointerAddressSpace());
*ArgIter++ = DemangledTy;
}
return DemangledSuccessfully;
}
bool getRetParamSignedness(Function *F, ParamSignedness &RetSignedness,
SmallVectorImpl<ParamSignedness> &ArgSignedness) {
using namespace llvm::itanium_demangle;
StringRef Name = F->getName();
if (!Name.starts_with("_Z") || F->arg_empty())
return false;
ManglingParser<DefaultAllocator> Demangler(Name.begin(), Name.end());
// If it's not a function name encoding, bail out.
auto *RootNode = dyn_cast_or_null<FunctionEncoding>(Demangler.parse());
if (!RootNode)
return false;
auto GetSignedness = [](const itanium_demangle::Node *N) {
if (!N)
return ParamSignedness::Unknown;
if (const auto *Vec = dyn_cast<itanium_demangle::VectorType>(N))
N = Vec->getBaseType();
if (const auto *Name = dyn_cast<NameType>(N)) {
StringRef Arg(stringify(Name));
if (Arg.starts_with("unsigned"))
return ParamSignedness::Unsigned;
if (Arg == "char" || Arg == "short" || Arg == "int" || Arg == "long")
return ParamSignedness::Signed;
}
return ParamSignedness::Unknown;
};
RetSignedness = GetSignedness(RootNode->getReturnType());
ArgSignedness.resize(F->arg_size());
for (const auto &[I, ParamType] : llvm::enumerate(RootNode->getParams())) {
if (F->getArg(I)->getType()->isIntOrIntVectorTy())
ArgSignedness[I] = GetSignedness(ParamType);
else
ArgSignedness[I] = ParamSignedness::Unknown;
}
return true;
}
CallInst *mutateCallInst(
Module *M, CallInst *CI,
std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate,
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) {
LLVM_DEBUG(dbgs() << "[mutateCallInst] " << *CI);
auto Args = getArguments(CI);
auto NewName = ArgMutate(CI, Args);
std::string InstName;
if (!CI->getType()->isVoidTy() && CI->hasName()) {
InstName = CI->getName().str();
CI->setName(InstName + ".old");
}
auto *NewCI = addCallInst(M, NewName, CI->getType(), Args, Attrs, CI, Mangle,
InstName, TakeFuncName);
NewCI->setDebugLoc(CI->getDebugLoc());
LLVM_DEBUG(dbgs() << " => " << *NewCI << '\n');
CI->replaceAllUsesWith(NewCI);
CI->eraseFromParent();
return NewCI;
}
Instruction *mutateCallInst(
Module *M, CallInst *CI,
std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)>
ArgMutate,
std::function<Instruction *(CallInst *)> RetMutate,
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) {
LLVM_DEBUG(dbgs() << "[mutateCallInst] " << *CI);
auto Args = getArguments(CI);
Type *RetTy = CI->getType();
auto NewName = ArgMutate(CI, Args, RetTy);
StringRef InstName = CI->getName();
auto *NewCI = addCallInst(M, NewName, RetTy, Args, Attrs, CI, Mangle,
InstName, TakeFuncName);
auto *NewI = RetMutate(NewCI);
NewI->takeName(CI);
NewI->setDebugLoc(CI->getDebugLoc());
LLVM_DEBUG(dbgs() << " => " << *NewI << '\n');
if (!CI->getType()->isVoidTy())
CI->replaceAllUsesWith(NewI);
CI->eraseFromParent();
return NewI;
}
void mutateFunction(
Function *F,
std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate,
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) {
auto *M = F->getParent();
for (auto I = F->user_begin(), E = F->user_end(); I != E;) {
if (auto *CI = dyn_cast<CallInst>(*I++))
mutateCallInst(M, CI, ArgMutate, Mangle, Attrs, TakeFuncName);
}
if (F->use_empty())
F->eraseFromParent();
}
void mutateFunction(
Function *F,
std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)>
ArgMutate,
std::function<Instruction *(CallInst *)> RetMutate,
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeName) {
auto *M = F->getParent();
for (auto I = F->user_begin(), E = F->user_end(); I != E;) {
if (auto *CI = dyn_cast<CallInst>(*I++))