forked from KhronosGroup/SPIRV-LLVM-Translator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OCLToSPIRV.cpp
1949 lines (1798 loc) · 78.4 KB
/
OCLToSPIRV.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
//===- OCLToSPIRV.cpp - Transform OCL to SPIR-V builtins --------*- 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.
//
//===----------------------------------------------------------------------===//
//
// This file implements preprocessing of OpenCL C built-in functions into SPIR-V
// friendly IR form for further translation into SPIR-V
//
//===----------------------------------------------------------------------===//
#include "OCLToSPIRV.h"
#include "OCLTypeToSPIRV.h"
#include "SPIRVInternal.h"
#include "libSPIRV/SPIRVDebug.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <regex>
#include <set>
#define DEBUG_TYPE "ocl-to-spv"
using namespace llvm;
using namespace PatternMatch;
using namespace SPIRV;
using namespace OCLUtil;
namespace SPIRV {
static size_t getOCLCpp11AtomicMaxNumOps(StringRef Name) {
return StringSwitch<size_t>(Name)
.Cases("load", "flag_test_and_set", "flag_clear", 3)
.Cases("store", "exchange", 4)
.StartsWith("compare_exchange", 6)
.StartsWith("fetch", 4)
.Default(0);
}
static Type *getBlockStructType(Value *Parameter) {
// In principle, this information should be passed to us from Clang via
// an elementtype attribute. However, said attribute requires that the
// function call be an intrinsic, which it is not. Instead, we rely on being
// able to trace this to the declaration of a variable: OpenCL C specification
// section 6.12.5 should guarantee that we can do this.
Value *UnderlyingObject = Parameter->stripPointerCasts();
Type *ParamType = nullptr;
if (auto *GV = dyn_cast<GlobalValue>(UnderlyingObject))
ParamType = GV->getValueType();
else if (auto *Alloca = dyn_cast<AllocaInst>(UnderlyingObject))
ParamType = Alloca->getAllocatedType();
else
llvm_unreachable("Blocks in OpenCL C must be traceable to allocation site");
return ParamType;
}
/// Return one of the SPIR-V 1.4 SignExtend or ZeroExtend image operands
/// for a demangled function name, or 0 if the function does not return an
/// integer type (e.g. read_imagef).
static unsigned getImageSignZeroExt(StringRef DemangledName) {
bool IsSigned = !DemangledName.ends_with("ui") && DemangledName.back() == 'i';
bool IsUnsigned = DemangledName.ends_with("ui");
if (IsSigned)
return ImageOperandsMask::ImageOperandsSignExtendMask;
if (IsUnsigned)
return ImageOperandsMask::ImageOperandsZeroExtendMask;
return 0;
}
bool OCLToSPIRVLegacy::runOnModule(Module &M) {
setOCLTypeToSPIRV(&getAnalysis<OCLTypeToSPIRVLegacy>());
return runOCLToSPIRV(M);
}
void OCLToSPIRVLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<OCLTypeToSPIRVLegacy>();
}
llvm::PreservedAnalyses OCLToSPIRVPass::run(llvm::Module &M,
llvm::ModuleAnalysisManager &MAM) {
setOCLTypeToSPIRV(&MAM.getResult<OCLTypeToSPIRVPass>(M));
return runOCLToSPIRV(M) ? llvm::PreservedAnalyses::none()
: llvm::PreservedAnalyses::all();
}
/// Get vector width from OpenCL vload* function name.
SPIRVWord OCLToSPIRVBase::getVecLoadWidth(const std::string &DemangledName) {
SPIRVWord Width = 0;
if (DemangledName == "vloada_half")
Width = 1;
else {
unsigned Loc = 5;
if (DemangledName.find("vload_half") == 0)
Loc = 10;
else if (DemangledName.find("vloada_half") == 0)
Loc = 11;
std::stringstream SS(DemangledName.substr(Loc));
SS >> Width;
}
return Width;
}
/// Transform OpenCL vload/vstore function name.
void OCLToSPIRVBase::transVecLoadStoreName(std::string &DemangledName,
const std::string &Stem,
bool AlwaysN) {
auto HalfStem = Stem + "_half";
auto HalfStemR = HalfStem + "_r";
if (!AlwaysN && DemangledName == HalfStem)
return;
if (!AlwaysN && DemangledName.find(HalfStemR) == 0) {
DemangledName = HalfStemR;
return;
}
if (DemangledName.find(HalfStem) == 0) {
auto OldName = DemangledName;
DemangledName = HalfStem + "n";
if (OldName.find("_r") != std::string::npos)
DemangledName += "_r";
return;
}
if (DemangledName.find(Stem) == 0) {
DemangledName = Stem + "n";
return;
}
}
char OCLToSPIRVLegacy::ID = 0;
bool OCLToSPIRVBase::runOCLToSPIRV(Module &Module) {
initialize(Module);
Ctx = &M->getContext();
auto Src = getSPIRVSource(&Module);
// This is a pre-processing pass, which transform LLVM IR module to a more
// suitable form for the SPIR-V translation: it is specifically designed to
// handle OpenCL C built-in functions and shouldn't be launched for other
// source languages
if (std::get<0>(Src) != spv::SourceLanguageOpenCL_C)
return false;
CLVer = std::get<1>(Src);
LLVM_DEBUG(dbgs() << "Enter OCLToSPIRV:\n");
visit(*M);
for (Instruction *I : ValuesToDelete)
I->eraseFromParent();
eraseUselessFunctions(M); // remove unused functions declarations
LLVM_DEBUG(dbgs() << "After OCLToSPIRV:\n" << *M);
verifyRegularizationPass(*M, "OCLToSPIRV");
return true;
}
// The order of handling OCL builtin functions is important.
// Workgroup functions need to be handled before pipe functions since
// there are functions fall into both categories.
void OCLToSPIRVBase::visitCallInst(CallInst &CI) {
LLVM_DEBUG(dbgs() << "[visistCallInst] " << CI << '\n');
auto *F = CI.getCalledFunction();
if (!F)
return;
auto MangledName = F->getName();
StringRef DemangledName;
if (!oclIsBuiltin(MangledName, DemangledName))
return;
LLVM_DEBUG(dbgs() << "DemangledName: " << DemangledName << '\n');
if (DemangledName.find(kOCLBuiltinName::NDRangePrefix) == 0) {
visitCallNDRange(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::All) {
visitCallAllAny(OpAll, &CI);
return;
}
if (DemangledName == kOCLBuiltinName::Any) {
visitCallAllAny(OpAny, &CI);
return;
}
if (DemangledName.find(kOCLBuiltinName::AsyncWorkGroupCopy) == 0 ||
DemangledName.find(kOCLBuiltinName::AsyncWorkGroupStridedCopy) == 0) {
visitCallAsyncWorkGroupCopy(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::AtomicPrefix) == 0 ||
DemangledName.find(kOCLBuiltinName::AtomPrefix) == 0) {
// Compute atomic builtins do not support floating types.
if (CI.getType()->isFloatingPointTy() &&
isComputeAtomicOCLBuiltin(DemangledName))
return;
auto *PCI = &CI;
if (DemangledName == kOCLBuiltinName::AtomicInit) {
visitCallAtomicInit(PCI);
return;
}
if (DemangledName == kOCLBuiltinName::AtomicWorkItemFence) {
visitCallAtomicWorkItemFence(PCI);
return;
}
if (DemangledName == kOCLBuiltinName::AtomicCmpXchgWeak ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgStrong ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgWeakExplicit ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgStrongExplicit) {
assert((CLVer == kOCLVer::CL20 || CLVer == kOCLVer::CL30) &&
"Wrong version of OpenCL");
PCI = visitCallAtomicCmpXchg(PCI);
}
visitCallAtomicLegacy(PCI, MangledName, DemangledName);
visitCallAtomicCpp11(PCI, MangledName, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::ConvertPrefix) == 0) {
visitCallConvert(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageWidth ||
DemangledName == kOCLBuiltinName::GetImageHeight ||
DemangledName == kOCLBuiltinName::GetImageDepth ||
DemangledName == kOCLBuiltinName::GetImageDim ||
DemangledName == kOCLBuiltinName::GetImageArraySize) {
visitCallGetImageSize(&CI, DemangledName);
return;
}
if ((DemangledName.find(kOCLBuiltinName::WorkGroupPrefix) == 0 &&
DemangledName != kOCLBuiltinName::WorkGroupBarrier) ||
DemangledName == kOCLBuiltinName::WaitGroupEvent ||
(DemangledName.find(kOCLBuiltinName::SubGroupPrefix) == 0 &&
DemangledName != kOCLBuiltinName::SubGroupBarrier)) {
visitCallGroupBuiltin(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::MemFence ||
DemangledName == kOCLBuiltinName::ReadMemFence ||
DemangledName == kOCLBuiltinName::WriteMemFence) {
visitCallMemFence(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::ReadImage) == 0) {
if (MangledName.find(kMangledName::Sampler) != StringRef::npos) {
visitCallReadImageWithSampler(&CI, MangledName, DemangledName);
return;
}
if (MangledName.find("msaa") != StringRef::npos) {
visitCallReadImageMSAA(&CI, MangledName);
return;
}
}
if (DemangledName.find(kOCLBuiltinName::ReadImage) == 0 ||
DemangledName.find(kOCLBuiltinName::WriteImage) == 0) {
visitCallReadWriteImage(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::ToGlobal ||
DemangledName == kOCLBuiltinName::ToLocal ||
DemangledName == kOCLBuiltinName::ToPrivate) {
visitCallToAddr(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::VLoadPrefix) == 0 ||
DemangledName.find(kOCLBuiltinName::VStorePrefix) == 0) {
visitCallVecLoadStore(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::IsFinite ||
DemangledName == kOCLBuiltinName::IsInf ||
DemangledName == kOCLBuiltinName::IsNan ||
DemangledName == kOCLBuiltinName::IsNormal ||
DemangledName == kOCLBuiltinName::Signbit) {
visitCallRelational(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::WorkGroupBarrier ||
DemangledName == kOCLBuiltinName::Barrier ||
DemangledName == kOCLBuiltinName::SubGroupBarrier) {
visitCallBarrier(&CI);
return;
}
if (DemangledName == kOCLBuiltinName::GetFence) {
visitCallGetFence(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::Dot &&
CI.getOperand(0)->getType()->isFloatingPointTy()) {
visitCallDot(&CI);
return;
}
if (DemangledName == kOCLBuiltinName::Dot ||
DemangledName == kOCLBuiltinName::DotAccSat ||
DemangledName.starts_with(kOCLBuiltinName::Dot4x8PackedPrefix) ||
DemangledName.starts_with(kOCLBuiltinName::DotAccSat4x8PackedPrefix)) {
if (CI.getOperand(0)->getType()->isVectorTy()) {
auto *VT = (VectorType *)(CI.getOperand(0)->getType());
if (!isa<llvm::IntegerType>(VT->getElementType())) {
visitCallBuiltinSimple(&CI, MangledName, DemangledName);
return;
}
}
visitCallDot(&CI, MangledName, DemangledName);
return;
}
if (DemangledName.starts_with(kOCLBuiltinName::ClockReadPrefix)) {
visitCallClockRead(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::FMin ||
DemangledName == kOCLBuiltinName::FMax ||
DemangledName == kOCLBuiltinName::Min ||
DemangledName == kOCLBuiltinName::Max ||
DemangledName == kOCLBuiltinName::Step ||
DemangledName == kOCLBuiltinName::SmoothStep ||
DemangledName == kOCLBuiltinName::Clamp ||
DemangledName == kOCLBuiltinName::Mix) {
visitCallScalToVec(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageChannelDataType) {
visitCallGetImageChannel(&CI, DemangledName, OCLImageChannelDataTypeOffset);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageChannelOrder) {
visitCallGetImageChannel(&CI, DemangledName, OCLImageChannelOrderOffset);
return;
}
if (isEnqueueKernelBI(MangledName)) {
visitCallEnqueueKernel(&CI, DemangledName);
return;
}
if (isKernelQueryBI(MangledName)) {
visitCallKernelQuery(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupBlockReadINTELPrefix) == 0) {
visitSubgroupBlockReadINTEL(&CI);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupBlockWriteINTELPrefix) == 0) {
visitSubgroupBlockWriteINTEL(&CI);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupImageMediaBlockINTELPrefix) ==
0) {
visitSubgroupImageMediaBlockINTEL(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::SplitBarrierINTELPrefix) == 0) {
visitCallSplitBarrierINTEL(&CI, DemangledName);
return;
}
// Handle 'cl_intel_device_side_avc_motion_estimation' extension built-ins
if (DemangledName.find(kOCLSubgroupsAVCIntel::Prefix) == 0 ||
// Workaround for a bug in the extension specification
DemangledName.find("intel_sub_group_ime_ref_window_size") == 0) {
if (MangledName.find(kMangledName::Sampler) != StringRef::npos)
visitSubgroupAVCBuiltinCallWithSampler(&CI, DemangledName);
else
visitSubgroupAVCBuiltinCall(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::LDEXP) == 0) {
visitCallLdexp(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::ConvertBFloat16AsUShort ||
DemangledName == kOCLBuiltinName::ConvertBFloat162AsUShort2 ||
DemangledName == kOCLBuiltinName::ConvertBFloat163AsUShort3 ||
DemangledName == kOCLBuiltinName::ConvertBFloat164AsUShort4 ||
DemangledName == kOCLBuiltinName::ConvertBFloat168AsUShort8 ||
DemangledName == kOCLBuiltinName::ConvertBFloat1616AsUShort16) {
visitCallConvertBFloat16AsUshort(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::ConvertAsBFloat16Float ||
DemangledName == kOCLBuiltinName::ConvertAsBFloat162Float2 ||
DemangledName == kOCLBuiltinName::ConvertAsBFloat163Float3 ||
DemangledName == kOCLBuiltinName::ConvertAsBFloat164Float4 ||
DemangledName == kOCLBuiltinName::ConvertAsBFloat168Float8 ||
DemangledName == kOCLBuiltinName::ConvertAsBFloat1616Float16) {
visitCallConvertAsBFloat16Float(&CI, DemangledName);
return;
}
visitCallBuiltinSimple(&CI, MangledName, DemangledName);
}
void OCLToSPIRVBase::visitCallNDRange(CallInst *CI, StringRef DemangledName) {
assert(DemangledName.find(kOCLBuiltinName::NDRangePrefix) == 0);
StringRef LenStr = DemangledName.substr(8, 1);
auto Len = atoi(LenStr.data());
assert(Len >= 1 && Len <= 3);
// Translate ndrange_ND into differently named SPIR-V
// decorated functions because they have array arugments
// of different dimension which mangled the same way.
std::string Postfix("_");
Postfix += LenStr;
Postfix += 'D';
std::string FuncName = getSPIRVFuncName(OpBuildNDRange, Postfix);
auto Mutator = mutateCallInst(CI, FuncName);
// SPIR-V ndrange structure requires 3 members in the following order:
// global work offset
// global work size
// local work size
// The arguments need to add missing members.
for (size_t I = 1, E = CI->arg_size(); I != E; ++I)
Mutator.mapArg(I, [=](Value *V) {
return getScalarOrArray(V, Len, CI->getIterator());
});
switch (CI->arg_size()) {
case 2: {
// Has global work size.
auto *T = Mutator.getArg(1)->getType();
auto *C = getScalarOrArrayConstantInt(CI->getIterator(), T, Len, 0);
Mutator.appendArg(C);
Mutator.appendArg(C);
break;
}
case 3: {
// Has global and local work size.
auto *T = Mutator.getArg(1)->getType();
Mutator.appendArg(
getScalarOrArrayConstantInt(CI->getIterator(), T, Len, 0));
break;
}
case 4: {
// Move offset arg to the end
Mutator.moveArg(1, CI->arg_size() - 1);
break;
}
default:
assert(0 && "Invalid number of arguments");
}
}
void OCLToSPIRVBase::visitCallAsyncWorkGroupCopy(CallInst *CI,
StringRef DemangledName) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
auto Mutator = mutateCallInst(CI, OpGroupAsyncCopy);
if (DemangledName == OCLUtil::kOCLBuiltinName::AsyncWorkGroupCopy)
Mutator.insertArg(3, addSizet(1));
Mutator.insertArg(0, addInt32(ScopeWorkgroup));
}
CallInst *OCLToSPIRVBase::visitCallAtomicCmpXchg(CallInst *CI) {
CallInst *NewCI = nullptr;
{
auto Mutator = mutateCallInst(CI, kOCLBuiltinName::AtomicCmpXchgStrong);
Value *Expected = Mutator.getArg(1);
Type *MemTy = Mutator.getArg(2)->getType();
if (MemTy->isFloatTy() || MemTy->isDoubleTy()) {
MemTy =
MemTy->isFloatTy() ? Type::getInt32Ty(*Ctx) : Type::getInt64Ty(*Ctx);
Mutator.replaceArg(
0,
{Mutator.getArg(0),
TypedPointerType::get(
MemTy, Mutator.getArg(0)->getType()->getPointerAddressSpace())});
Mutator.mapArg(2, [=](IRBuilder<> &Builder, Value *V) {
return Builder.CreateBitCast(V, MemTy);
});
}
assert(MemTy->isIntegerTy() &&
"In SPIR-V 1.0 arguments of OpAtomicCompareExchange must be "
"an integer type scalars");
Mutator.mapArg(1, [=](IRBuilder<> &Builder, Value *V) {
return Builder.CreateLoad(MemTy, V, "exp");
});
Mutator.changeReturnType(
MemTy, [Expected, &NewCI](IRBuilder<> &Builder, CallInst *NCI) {
NewCI = NCI;
Builder.CreateStore(NCI, Expected);
return Builder.CreateICmpEQ(NCI, NCI->getArgOperand(1));
});
}
return NewCI;
}
void OCLToSPIRVBase::visitCallAtomicInit(CallInst *CI) {
auto *ST = new StoreInst(CI->getArgOperand(1), CI->getArgOperand(0),
CI->getIterator());
ST->takeName(CI);
CI->dropAllReferences();
CI->eraseFromParent();
}
void OCLToSPIRVBase::visitCallAllAny(spv::Op OC, CallInst *CI) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
auto Args = getArguments(CI);
assert(Args.size() == 1);
auto *ArgTy = Args[0]->getType();
auto *Zero = Constant::getNullValue(Args[0]->getType());
auto *Cmp = CmpInst::Create(CmpInst::ICmp, CmpInst::ICMP_SLT, Args[0], Zero,
"cast", CI->getIterator());
if (!isa<VectorType>(ArgTy)) {
auto *Cast = CastInst::CreateZExtOrBitCast(
Cmp, Type::getInt32Ty(*Ctx), "", Cmp->getNextNode()->getIterator());
CI->replaceAllUsesWith(Cast);
CI->eraseFromParent();
} else {
mutateCallInst(CI, OC).setArgs({Cmp}).changeReturnType(
Type::getInt32Ty(*Ctx), [](IRBuilder<> &Builder, CallInst *CI) {
return Builder.CreateZExtOrBitCast(CI, Builder.getInt32Ty());
});
}
}
void OCLToSPIRVBase::visitCallAtomicWorkItemFence(CallInst *CI) {
transMemoryBarrier(CI, getAtomicWorkItemFenceLiterals(CI));
}
void OCLToSPIRVBase::visitCallMemFence(CallInst *CI, StringRef DemangledName) {
OCLMemOrderKind MO = StringSwitch<OCLMemOrderKind>(DemangledName)
.Case(kOCLBuiltinName::ReadMemFence, OCLMO_acquire)
.Case(kOCLBuiltinName::WriteMemFence, OCLMO_release)
.Default(OCLMO_acq_rel); // kOCLBuiltinName::MemFence
transMemoryBarrier(
CI,
std::make_tuple(cast<ConstantInt>(CI->getArgOperand(0))->getZExtValue(),
MO, OCLMS_work_group));
}
void OCLToSPIRVBase::transMemoryBarrier(CallInst *CI,
AtomicWorkItemFenceLiterals Lit) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
mutateCallInst(CI, OpMemoryBarrier)
.setArgs({addInt32(map<Scope>(std::get<2>(Lit))),
addInt32(mapOCLMemSemanticToSPIRV(std::get<0>(Lit),
std::get<1>(Lit)))});
}
void OCLToSPIRVBase::visitCallAtomicLegacy(CallInst *CI, StringRef MangledName,
StringRef DemangledName) {
StringRef Stem = DemangledName;
if (Stem.starts_with("atom_"))
Stem = Stem.drop_front(strlen("atom_"));
else if (Stem.starts_with("atomic_"))
Stem = Stem.drop_front(strlen("atomic_"));
else
return;
std::string Sign;
std::string Postfix;
std::string Prefix;
if (Stem == "add" || Stem == "sub" || Stem == "and" || Stem == "or" ||
Stem == "xor" || Stem == "min" || Stem == "max") {
if ((Stem == "min" || Stem == "max") &&
isMangledTypeUnsigned(MangledName.back()))
Sign = 'u';
Prefix = "fetch_";
Postfix = "_explicit";
} else if (Stem == "xchg") {
Stem = "exchange";
Postfix = "_explicit";
} else if (Stem == "cmpxchg") {
Stem = "compare_exchange_strong";
Postfix = "_explicit";
} else if (Stem == "inc" || Stem == "dec") {
// do nothing
} else
return;
OCLBuiltinTransInfo Info;
Info.UniqName = "atomic_" + Prefix + Sign + Stem.str() + Postfix;
std::vector<int> PostOps;
PostOps.push_back(OCLLegacyAtomicMemOrder);
if (Stem.starts_with("compare_exchange"))
PostOps.push_back(OCLLegacyAtomicMemOrder);
PostOps.push_back(OCLLegacyAtomicMemScope);
Info.PostProc = [=](BuiltinCallMutator &Mutator) {
for (auto &I : PostOps) {
Mutator.appendArg(addInt32(I));
}
};
transAtomicBuiltin(CI, Info);
}
void OCLToSPIRVBase::visitCallAtomicCpp11(CallInst *CI, StringRef MangledName,
StringRef DemangledName) {
StringRef Stem = DemangledName;
if (Stem.starts_with("atomic_"))
Stem = Stem.drop_front(strlen("atomic_"));
else
return;
std::string NewStem(Stem);
std::vector<int> PostOps;
if (Stem.starts_with("store") || Stem.starts_with("load") ||
Stem.starts_with("exchange") || Stem.starts_with("compare_exchange") ||
Stem.starts_with("fetch") || Stem.starts_with("flag")) {
if ((Stem.starts_with("fetch_min") || Stem.starts_with("fetch_max")) &&
containsUnsignedAtomicType(MangledName))
NewStem.insert(NewStem.begin() + strlen("fetch_"), 'u');
if (!Stem.ends_with("_explicit")) {
NewStem = NewStem + "_explicit";
PostOps.push_back(OCLMO_seq_cst);
if (Stem.starts_with("compare_exchange"))
PostOps.push_back(OCLMO_seq_cst);
PostOps.push_back(OCLMS_device);
} else {
auto MaxOps =
getOCLCpp11AtomicMaxNumOps(Stem.drop_back(strlen("_explicit")));
if (CI->arg_size() < MaxOps)
PostOps.push_back(OCLMS_device);
}
} else if (Stem == "work_item_fence") {
// do nothing
} else
return;
OCLBuiltinTransInfo Info;
Info.UniqName = std::string("atomic_") + NewStem;
Info.PostProc = [=](BuiltinCallMutator &Mutator) {
for (auto &I : PostOps) {
Mutator.appendArg(addInt32(I));
}
};
transAtomicBuiltin(CI, Info);
}
void OCLToSPIRVBase::transAtomicBuiltin(CallInst *CI,
OCLBuiltinTransInfo &Info) {
llvm::Type *AtomicBuiltinsReturnType = CI->getType();
auto SPIRVFunctionName =
getSPIRVFuncName(OCLSPIRVBuiltinMap::map(Info.UniqName));
bool NeedsNegate = false;
if (AtomicBuiltinsReturnType->isFloatingPointTy()) {
// Translate FP-typed atomic builtins. Currently we only need to
// translate atomic_fetch_[add, sub, max, min] and atomic_fetch_[add,
// sub, max, min]_explicit to related float instructions.
// Translate atomic_fetch_sub to OpAtomicFAddEXT with negative value
// operand
auto SPIRFunctionNameForFloatAtomics =
llvm::StringSwitch<std::string>(SPIRVFunctionName)
.Case("__spirv_AtomicIAdd", "__spirv_AtomicFAddEXT")
.Case("__spirv_AtomicISub", "__spirv_AtomicFAddEXT")
.Case("__spirv_AtomicSMax", "__spirv_AtomicFMaxEXT")
.Case("__spirv_AtomicSMin", "__spirv_AtomicFMinEXT")
.Default("others");
if (SPIRVFunctionName == "__spirv_AtomicISub") {
NeedsNegate = true;
}
if (SPIRFunctionNameForFloatAtomics != "others")
SPIRVFunctionName = SPIRFunctionNameForFloatAtomics;
}
auto Mutator = mutateCallInst(CI, SPIRVFunctionName);
Info.PostProc(Mutator);
// Order of args in OCL20:
// object, 0-2 other args, 1-2 order, scope
const size_t NumOrder = getAtomicBuiltinNumMemoryOrderArgs(Info.UniqName);
const size_t ArgsCount = Mutator.arg_size();
const size_t ScopeIdx = ArgsCount - 1;
const size_t OrderIdx = ScopeIdx - NumOrder;
if (NeedsNegate) {
Mutator.mapArg(1, [=](Value *V) {
IRBuilder<> IRB(CI);
return IRB.CreateFNeg(V);
});
}
Mutator.mapArg(ScopeIdx, [=](Value *V) {
return transOCLMemScopeIntoSPIRVScope(V, OCLMS_device, CI);
});
for (size_t I = 0; I < NumOrder; ++I) {
Mutator.mapArg(OrderIdx + I, [=](Value *V) {
return transOCLMemOrderIntoSPIRVMemorySemantics(V, OCLMO_seq_cst, CI);
});
}
// Order of args in SPIR-V:
// object, scope, 1-2 order, 0-2 other args
for (size_t I = 0; I < NumOrder; ++I) {
Mutator.moveArg(OrderIdx + I, I + 1);
}
Mutator.moveArg(ScopeIdx, 1);
if (Info.UniqName.find("atomic_compare_exchange") == 0) {
// For atomic_compare_exchange, the two "other args" are in the opposite
// order from the SPIR-V order. Swap these two arguments.
Mutator.moveArg(Mutator.arg_size() - 1, Mutator.arg_size() - 2);
}
}
void OCLToSPIRVBase::visitCallBarrier(CallInst *CI) {
auto Lit = getBarrierLiterals(CI);
// Use sequential consistent memory order by default.
// But if the flags argument is set to 0, we use
// None(Relaxed) memory order.
unsigned MemFenceFlag = std::get<0>(Lit);
OCLMemOrderKind MemOrder = MemFenceFlag ? OCLMO_seq_cst : OCLMO_relaxed;
mutateCallInst(CI, OpControlBarrier)
.setArgs({// Execution scope
addInt32(map<Scope>(std::get<2>(Lit))),
// Memory scope
addInt32(map<Scope>(std::get<1>(Lit))),
// Memory semantics
addInt32(mapOCLMemSemanticToSPIRV(MemFenceFlag, MemOrder))});
}
void OCLToSPIRVBase::visitCallConvert(CallInst *CI, StringRef MangledName,
StringRef DemangledName) {
// OpenCL Explicit Conversions (6.4.3) formed as below for scalars:
// destType convert_destType<_sat><_roundingMode>(sourceType)
// and for vector type:
// destTypeN convert_destTypeN<_sat><_roundingMode>(sourceTypeN)
// If the demangled name is not matching the suggested pattern and does not
// meet allowed destination type restrictions - this is not an OpenCL builtin,
// return from the function and translate such CallInst as a function call.
if (eraseUselessConvert(CI, MangledName, DemangledName))
return;
Op OC = OpNop;
auto *TargetTy = CI->getType();
auto *SrcTy = CI->getArgOperand(0)->getType();
if (auto *VecTy = dyn_cast<VectorType>(TargetTy))
TargetTy = VecTy->getElementType();
if (auto *VecTy = dyn_cast<VectorType>(SrcTy))
SrcTy = VecTy->getElementType();
auto IsTargetInt = isa<IntegerType>(TargetTy);
// Validate conversion function name and vector size if present
std::regex Expr(
"convert_(float|double|half|u?char|u?short|u?int|u?long)(2|3|4|8|16)*"
"(_sat)*(_rt[ezpn])*$");
std::smatch DestTyMatch;
std::string ConversionFunc(DemangledName.str());
if (!std::regex_match(ConversionFunc, DestTyMatch, Expr))
return;
// The first sub_match is the whole string; the next
// sub_matches are the parenthesized expressions.
enum { TypeIdx = 1, VecSizeIdx = 2, SatIdx = 3, RoundingIdx = 4 };
std::string DestTy = DestTyMatch[TypeIdx].str();
std::string VecSize = DestTyMatch[VecSizeIdx].str();
std::string Sat = DestTyMatch[SatIdx].str();
std::string Rounding = DestTyMatch[RoundingIdx].str();
bool TargetSigned = DestTy[0] != 'u';
if (isa<IntegerType>(SrcTy)) {
bool Signed = isLastFuncParamSigned(MangledName);
if (IsTargetInt) {
if (!Sat.empty() && TargetSigned != Signed) {
OC = Signed ? OpSatConvertSToU : OpSatConvertUToS;
Sat = "";
} else
OC = Signed ? OpSConvert : OpUConvert;
} else
OC = Signed ? OpConvertSToF : OpConvertUToF;
} else {
if (IsTargetInt) {
OC = TargetSigned ? OpConvertFToS : OpConvertFToU;
} else
OC = OpFConvert;
}
if (!Rounding.empty() && (isa<IntegerType>(SrcTy) && IsTargetInt))
return;
assert(CI->getCalledFunction() && "Unexpected indirect call");
mutateCallInst(
CI, getSPIRVFuncName(OC, "_R" + DestTy + VecSize + Sat + Rounding));
}
void OCLToSPIRVBase::visitCallGroupBuiltin(CallInst *CI,
StringRef OrigDemangledName) {
auto *F = CI->getCalledFunction();
std::vector<int> PreOps;
std::string DemangledName{OrigDemangledName};
if (DemangledName == kOCLBuiltinName::WorkGroupBarrier)
return;
if (DemangledName == kOCLBuiltinName::WaitGroupEvent) {
PreOps.push_back(ScopeWorkgroup);
} else if (DemangledName.find(kOCLBuiltinName::WorkGroupPrefix) == 0) {
DemangledName.erase(0, strlen(kOCLBuiltinName::WorkPrefix));
PreOps.push_back(ScopeWorkgroup);
} else if (DemangledName.find(kOCLBuiltinName::SubGroupPrefix) == 0) {
DemangledName.erase(0, strlen(kOCLBuiltinName::SubPrefix));
PreOps.push_back(ScopeSubgroup);
} else
return;
if (DemangledName != kOCLBuiltinName::WaitGroupEvent) {
StringRef FuncName = DemangledName;
FuncName = FuncName.drop_front(strlen(kSPIRVName::GroupPrefix));
SPIRSPIRVGroupOperationMap::foreachConditional(
[&](const std::string &S, SPIRVGroupOperationKind G) {
if (!FuncName.starts_with(S))
return true; // continue
PreOps.push_back(G);
StringRef Op =
StringSwitch<StringRef>(FuncName)
.StartsWith("ballot", "group_ballot_bit_count_")
.StartsWith("non_uniform", kSPIRVName::GroupNonUniformPrefix)
.Default(kSPIRVName::GroupPrefix);
// clustered functions are handled with non uniform group opcodes
StringRef ClusteredOp =
FuncName.contains("clustered_") ? "non_uniform_" : "";
StringRef LogicalOp = FuncName.contains("logical_") ? "logical_" : "";
StringRef GroupOp = StringSwitch<StringRef>(FuncName)
.Case("ballot_bit_count", "add")
.Case("ballot_inclusive_scan", "add")
.Case("ballot_exclusive_scan", "add")
.Default(FuncName.take_back(
3)); // assumes op is three characters
(void)(GroupOp.consume_front("_")); // when op is two characters
assert(!GroupOp.empty() && "Invalid OpenCL group builtin function");
char OpTyC = 0;
auto *OpTy = F->getReturnType();
if (OpTy->isFloatingPointTy())
OpTyC = 'f';
else if (OpTy->isIntegerTy()) {
auto NeedSign = GroupOp == "max" || GroupOp == "min";
if (!NeedSign)
OpTyC = 'i';
else {
// clustered reduce args are (type, uint)
// other operation args are (type)
auto MangledName = F->getName();
auto MangledTyC = ClusteredOp.empty()
? MangledName.back()
: MangledName.take_back(2).front();
if (isMangledTypeSigned(MangledTyC))
OpTyC = 's';
else
OpTyC = 'u';
}
} else
llvm_unreachable("Invalid OpenCL group builtin argument type");
DemangledName = Op.str() + ClusteredOp.str() + LogicalOp.str() +
OpTyC + GroupOp.str();
return false; // break out of loop
});
}
const bool IsElect = DemangledName == "group_elect";
const bool IsAllOrAny = (DemangledName.find("_all") != std::string::npos ||
DemangledName.find("_any") != std::string::npos);
const bool IsAllEqual = DemangledName.find("_all_equal") != std::string::npos;
const bool IsBallot = DemangledName == "group_ballot";
const bool IsInverseBallot = DemangledName == "group_inverse_ballot";
const bool IsBallotBitExtract = DemangledName == "group_ballot_bit_extract";
const bool IsLogical = DemangledName.find("_logical") != std::string::npos;
const bool HasBoolReturnType = IsElect || IsAllOrAny || IsAllEqual ||
IsInverseBallot || IsBallotBitExtract ||
IsLogical;
const bool HasBoolArg = (IsAllOrAny && !IsAllEqual) || IsBallot || IsLogical;
auto Consts = getInt32(M, PreOps);
OCLBuiltinTransInfo Info;
if (HasBoolReturnType)
Info.RetTy = Type::getInt1Ty(*Ctx);
Info.UniqName = DemangledName;
Info.PostProc = [=](BuiltinCallMutator &Mutator) {
if (HasBoolArg) {
Mutator.mapArg(0, [&](Value *V) {
IRBuilder<> IRB(CI);
return IRB.CreateICmpNE(V, IRB.getInt32(0));
});
}
size_t E = Mutator.arg_size();
if (DemangledName == "group_broadcast" && E > 2) {
assert(E == 3 || E == 4);
std::vector<Value *> Ops = getArguments(CI);
makeVector(CI, Ops, std::make_pair(Ops.begin() + 1, Ops.end()));
while (Mutator.arg_size() > 1)
Mutator.removeArg(1);
Mutator.appendArg(Ops.back());
}
for (unsigned I = 0; I < Consts.size(); I++)
Mutator.insertArg(I, Consts[I]);
};
transBuiltin(CI, Info);
}
void OCLToSPIRVBase::transBuiltin(CallInst *CI, OCLBuiltinTransInfo &Info) {
Op OC = OpNop;
unsigned ExtOp = ~0U;
SPIRVBuiltinVariableKind BVKind = BuiltInMax;
if (StringRef(Info.UniqName).starts_with(kSPIRVName::Prefix))
return;
if (OCLSPIRVBuiltinMap::find(Info.UniqName, &OC)) {
if (OC == OpImageRead) {
// There are several read_image* functions defined by OpenCL C spec, but
// all of them use the same SPIR-V Instruction - some of them might only
// differ by return type, so, we need to include return type into the
// mangling scheme to get them differentiated.
//
// Example: int4 read_imagei(image2d_t, sampler_t, int2)
// uint4 read_imageui(image2d_t, sampler_t, int2)
// Both functions above are represented by the same SPIR-V
// instruction: argument types are the same, only return type is
// different
Info.UniqName = getSPIRVFuncName(OC, CI->getType());
} else {
Info.UniqName = getSPIRVFuncName(OC);
}
} else if ((ExtOp = getExtOp(Info.MangledName, Info.UniqName)) != ~0U)
Info.UniqName = getSPIRVExtFuncName(SPIRVEIS_OpenCL, ExtOp);
else if (SPIRSPIRVBuiltinVariableMap::find(Info.UniqName, &BVKind)) {
// Map OCL work item builtins to SPV-IR work item builtins.
// e.g. get_global_id() --> __spirv_BuiltinGlobalInvocationId()
Info.UniqName = getSPIRVFuncName(BVKind);
} else
return;
BuiltinCallMutator Mutator = mutateCallInst(CI, Info.UniqName + Info.Postfix);
Info.PostProc(Mutator);
if (Info.RetTy) {
Type *OldRetTy = CI->getType();
Mutator.changeReturnType(
Info.RetTy, [OldRetTy, &Info](IRBuilder<> &Builder, CallInst *NewCI) {
if (Info.RetTy->isIntegerTy() && OldRetTy->isIntegerTy()) {
return Builder.CreateIntCast(NewCI, OldRetTy, false);
}
return Builder.CreatePointerBitCastOrAddrSpaceCast(NewCI, OldRetTy);
});
}
}
void OCLToSPIRVBase::visitCallReadImageMSAA(CallInst *CI,
StringRef MangledName) {
assert(MangledName.find("msaa") != StringRef::npos);
mutateCallInst(
CI, getSPIRVFuncName(OpImageRead, std::string(kSPIRVPostfix::ExtDivider) +
getPostfixForReturnType(CI)))
.insertArg(2, getInt32(M, ImageOperandsSampleMask));
}
void OCLToSPIRVBase::visitCallReadImageWithSampler(CallInst *CI,
StringRef MangledName,
StringRef DemangledName) {
assert(MangledName.find(kMangledName::Sampler) != StringRef::npos);
assert(CI->getCalledFunction() && "Unexpected indirect call");
Function *Func = CI->getCalledFunction();
bool IsRetScalar = !CI->getType()->isVectorTy();
Type *Ret = CI->getType();
auto *ImageTy = OCLTypeToSPIRVPtr->getAdaptedArgumentType(Func, 0);
if (!ImageTy)
ImageTy = getCallValueType(CI, 0);
auto Mutator = mutateCallInst(
CI, getSPIRVFuncName(OpImageSampleExplicitLod,
std::string(kSPIRVPostfix::ExtDivider) +
getPostfixForReturnType(Ret)));
Mutator.mapArg(0, [&](IRBuilder<> &Builder, Value *ImgArg, Type *ImgType) {
auto *SampledImgTy = adjustImageType(ImageTy, kSPIRVTypeName::Image,
kSPIRVTypeName::SampledImg);
Value *SampledImgArgs[] = {CI->getArgOperand(0), CI->getArgOperand(1)};
return addSPIRVCallPair(Builder, OpSampledImage, SampledImgTy,
SampledImgArgs, {ImgType, Mutator.getType(1)},
kSPIRVName::TempSampledImage);