-
Notifications
You must be signed in to change notification settings - Fork 699
/
LowerESIMD.cpp
1645 lines (1480 loc) · 59.9 KB
/
LowerESIMD.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
//===-- LowerESIMD.cpp - lower Explicit SIMD (ESIMD) constructs -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// See intro comments in the header.
//
// Since the spir* targets use Itanium mangling for C/C++ symbols, the
// implementation uses the Itanium demangler to demangle device code's
// C++ intrinsics and access various information, such their C++ names and
// values of integer template parameters they were instantiated with.
//===----------------------------------------------------------------------===//
#include "llvm/SYCLLowerIR/ESIMD/LowerESIMD.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/Demangle/ItaniumDemangle.h"
#include "llvm/GenXIntrinsics/GenXIntrinsics.h"
#include "llvm/GenXIntrinsics/GenXMetadata.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
#include <cstring>
#include <unordered_map>
using namespace llvm;
namespace id = itanium_demangle;
#define DEBUG_TYPE "lower-esimd"
#define SLM_BTI 254
#define MAX_DIMS 3
namespace {
SmallPtrSet<Type *, 4> collectGenXVolatileTypes(Module &);
void generateKernelMetadata(Module &);
class SYCLLowerESIMDLegacyPass : public ModulePass {
public:
static char ID; // Pass identification, replacement for typeid
SYCLLowerESIMDLegacyPass() : ModulePass(ID) {
initializeSYCLLowerESIMDLegacyPassPass(*PassRegistry::getPassRegistry());
}
// run the LowerESIMD pass on the specified module
bool runOnModule(Module &M) override {
ModuleAnalysisManager MAM;
auto PA = Impl.run(M, MAM);
return !PA.areAllPreserved();
}
private:
SYCLLowerESIMDPass Impl;
};
} // namespace
char SYCLLowerESIMDLegacyPass::ID = 0;
INITIALIZE_PASS(SYCLLowerESIMDLegacyPass, "LowerESIMD",
"Lower constructs specific to Close To Metal", false, false)
// Public interface to the SYCLLowerESIMDPass.
ModulePass *llvm::createSYCLLowerESIMDPass() {
return new SYCLLowerESIMDLegacyPass();
}
namespace {
// The regexp for ESIMD intrinsics:
// /^_Z(\d+)__esimd_\w+/
static constexpr char ESIMD_INTRIN_PREF0[] = "_Z";
static constexpr char ESIMD_INTRIN_PREF1[] = "__esimd_";
static constexpr char SPIRV_INTRIN_PREF[] = "__spirv_BuiltIn";
static constexpr char GENX_KERNEL_METADATA[] = "genx.kernels";
struct ESIMDIntrinDesc {
// Denotes argument translation rule kind.
enum GenXArgRuleKind {
SRC_CALL_ARG, // is a call argument
SRC_CALL_ALL, // this and subsequent args are just copied from the src call
SRC_TMPL_ARG, // is an integer template argument
UNDEF, // is an undef value
CONST_INT8, // is an i8 constant
CONST_INT16, // is an i16 constant
CONST_INT32, // is an i32 constant
CONST_INT64, // is an i64 constant
};
enum class GenXArgConversion : int16_t {
NONE, // no conversion
TO_I1, // convert vector of N-bit integer to 1-bit
TO_I8, // convert vector of N-bit integer to 18-bit
TO_I16, // convert vector of N-bit integer to 16-bit
TO_I32, // convert vector of N-bit integer to 32-bit
};
// Denotes GenX intrinsic name suffix creation rule kind.
enum GenXSuffixRuleKind {
NO_RULE,
BIN_OP, // ".<binary operation>" - e.g. "*.add"
NUM_KIND // "<numeric kind>" - e.g. "*i" for integer, "*f" for float
};
// Represents a rule how a GenX intrinsic argument is created from the source
// call instruction.
struct ArgRule {
GenXArgRuleKind Kind;
union Info {
struct {
int16_t CallArgNo; // SRC_CALL_ARG: source call arg num
// SRC_TMPL_ARG: source template arg num
// UNDEF: source call arg num to get type from
// -1 denotes return value
GenXArgConversion Conv; // GenXArgConversion
} Arg;
int NRemArgs; // SRC_CALL_ALL: number of remaining args
unsigned int ArgConst; // CONST_I16 OR CONST_I32: constant value
} I;
};
// Represents a rule how a GenX intrinsic name suffix is created from the
// source call instruction.
struct NameRule {
GenXSuffixRuleKind Kind;
union Info {
int CallArgNo; // DATA_TYPE: source call arg num to get type from
int TmplArgNo; // BINOP: source template arg num denoting the binary op
} I;
};
std::string GenXSpelling;
SmallVector<ArgRule, 16> ArgRules;
NameRule SuffixRule = {NO_RULE, {0}};
int getNumGenXArgs() const {
auto NRules = ArgRules.size();
if (NRules == 0)
return 0;
// SRC_CALL_ALL is a "shortcut" to save typing, must be the last rule
if (ArgRules[NRules - 1].Kind == GenXArgRuleKind::SRC_CALL_ALL)
return ArgRules[NRules - 1].I.NRemArgs + (NRules - 1);
return NRules;
}
bool isValid() const { return !GenXSpelling.empty(); }
};
using IntrinTable = std::unordered_map<std::string, ESIMDIntrinDesc>;
class ESIMDIntrinDescTable {
private:
IntrinTable Table;
#define DEF_ARG_RULE(Nm, Kind) \
static constexpr ESIMDIntrinDesc::ArgRule Nm(int16_t N) { \
return ESIMDIntrinDesc::ArgRule{ESIMDIntrinDesc::Kind, {{N, {}}}}; \
}
DEF_ARG_RULE(l, SRC_CALL_ALL)
DEF_ARG_RULE(u, UNDEF)
static constexpr ESIMDIntrinDesc::ArgRule t(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_TMPL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::NONE}}};
}
static constexpr ESIMDIntrinDesc::ArgRule t1(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_TMPL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::TO_I1}}};
}
static constexpr ESIMDIntrinDesc::ArgRule t8(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_TMPL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::TO_I8}}};
}
static constexpr ESIMDIntrinDesc::ArgRule t16(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_TMPL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::TO_I16}}};
}
static constexpr ESIMDIntrinDesc::ArgRule t32(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_TMPL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::TO_I32}}};
}
static constexpr ESIMDIntrinDesc::ArgRule a(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_CALL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::NONE}}};
}
static constexpr ESIMDIntrinDesc::ArgRule ai1(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_CALL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::TO_I1}}};
}
// Just an alias for a(int16_t N) to mark surface index arguments.
static constexpr ESIMDIntrinDesc::ArgRule aSI(int16_t N) {
return ESIMDIntrinDesc::ArgRule{
ESIMDIntrinDesc::SRC_CALL_ARG,
{{N, ESIMDIntrinDesc::GenXArgConversion::NONE}}};
}
static constexpr ESIMDIntrinDesc::ArgRule c8(int16_t N) {
return ESIMDIntrinDesc::ArgRule{ESIMDIntrinDesc::CONST_INT8, {{N, {}}}};
}
static constexpr ESIMDIntrinDesc::ArgRule c16(int16_t N) {
return ESIMDIntrinDesc::ArgRule{ESIMDIntrinDesc::CONST_INT16, {{N, {}}}};
}
static constexpr ESIMDIntrinDesc::ArgRule c32(int16_t N) {
return ESIMDIntrinDesc::ArgRule{ESIMDIntrinDesc::CONST_INT32, {{N, {}}}};
}
static constexpr ESIMDIntrinDesc::ArgRule c64(int16_t N) {
return ESIMDIntrinDesc::ArgRule{ESIMDIntrinDesc::CONST_INT64, {{N, {}}}};
}
static constexpr ESIMDIntrinDesc::NameRule bo(int16_t N) {
return ESIMDIntrinDesc::NameRule{ESIMDIntrinDesc::BIN_OP, {N}};
}
static constexpr ESIMDIntrinDesc::NameRule nk(int16_t N) {
return ESIMDIntrinDesc::NameRule{ESIMDIntrinDesc::NUM_KIND, {N}};
}
public:
// The table which describes rules how to generate @llvm.genx.* intrinsics
// from templated __esimd* intrinsics. The general rule is that the order and
// the semantics of intrinsic arguments is the same in both intrinsic forms.
// But for some arguments, where @llvm.genx.* mandates that the argument must
// be 'constant' (see Intrinsic_definitions.py from the vcintrinsics repo),
// it is passed as template argument to the corrsponding __esimd* intrinsic,
// hence leading to some "gaps" in __esimd* form's arguments compared to the
// @llvm.genx.* form.
// TODO - fix all __esimd* intrinsics and table entries according to the rule
// above.
ESIMDIntrinDescTable() {
Table = {
// An element of the table is std::pair of <key, value>; key is the
// source
// spelling of and intrinsic (what follows the "__esimd_" prefix), and
// the
// value is an instance of the ESIMDIntrinDesc class.
// Example for the "rdregion" intrinsic encoding:
// "rdregion" - the GenX spelling of the intrinsic ("llvm.genx." prefix
// and type suffixes maybe added to get full GenX name)
// {a(0), t(3),...}
// defines a map from the resulting genx.* intrinsic call arguments
// to the source call's template or function call arguments, e.g.
// 0th genx arg - maps to 0th source call arg
// 1st genx arg - maps to 3rd template argument of the source call
// nk(N) or bo(N)
// a rule applied to the base intrinsic name in order to
// construct a full name ("llvm.genx." prefix s also added); e.g.
// - nk(-1) denotes adding the return type name-based suffix - "i"
// for integer, "f" - for floating point
{"rdregion",
{"rdregion", {a(0), t(3), t(4), t(5), a(1), t(6)}, nk(-1)}},
{"rdindirect",
{"rdregion", {a(0), c32(0), t(2), c32(0), a(1), t(3)}, nk(-1)}},
{{"wrregion"},
{{"wrregion"},
{a(0), a(1), t(3), t(4), t(5), a(2), t(6), ai1(3)},
nk(-1)}},
{{"wrindirect"},
{{"wrregion"},
{a(0), a(1), c32(0), t(2), c32(0), a(2), t(3), ai1(3)},
nk(-1)}},
{"vload", {"vload", {l(0)}}},
{"vstore", {"vstore", {a(1), a(0)}}},
{"svm_block_ld_unaligned", {"svm.block.ld.unaligned", {l(0)}}},
{"svm_block_ld", {"svm.block.ld", {l(0)}}},
{"svm_block_st", {"svm.block.st", {l(1)}}},
{"svm_gather", {"svm.gather", {ai1(2), a(1), a(0), u(-1)}}},
{"svm_gather4_scaled",
{"svm.gather4.scaled", {ai1(1), t(2), c16(0), c64(0), a(0), u(-1)}}},
{"svm_scatter", {"svm.scatter", {ai1(3), a(2), a(0), a(1)}}},
{"svm_scatter4_scaled",
{"svm.scatter4.scaled", {ai1(2), t(2), c16(0), c64(0), a(0), a(1)}}},
// intrinsics to query thread's coordinates:
{"group_id_x", {"group.id.x", {}}},
{"group_id_y", {"group.id.y", {}}},
{"group_id_z", {"group.id.z", {}}},
{"local_id", {"local.id", {}}},
{"local_size", {"local.size", {}}},
{"svm_atomic0", {"svm.atomic", {ai1(1), a(0), u(-1)}, bo(0)}},
{"svm_atomic1", {"svm.atomic", {ai1(2), a(0), a(1), u(-1)}, bo(0)}},
{"svm_atomic2",
{"svm.atomic", {ai1(3), a(0), a(1), a(2), u(-1)}, bo(0)}},
{"dp4", {"dp4", {a(0), a(1)}}},
{"fence", {"fence", {a(0)}}},
{"barrier", {"barrier", {}}},
{"sbarrier", {"sbarrier", {a(0)}}},
// arg0: i32 modifiers, constant
// arg1: i32 surface index
// arg2: i32 plane, constant
// arg3: i32 block width in bytes, constant
// (block height inferred from return type size and block width)
// arg4: i32 x byte offset
// arg5: i32 y byte offset
{"media_ld", {"media.ld", {t(3), aSI(0), t(5), t(6), a(1), a(2)}}},
// arg0: i32 modifiers, constant
// arg1: i32 surface index
// arg2: i32 plane, constant
// arg3: i32 block width in bytes, constant
// (block height inferred from data type size and block width)
// arg4: i32 x byte offset
// arg5: i32 y byte offset
// arg6: data to write (overloaded)
{"media_st",
{"media.st", {t(3), aSI(0), t(5), t(6), a(1), a(2), a(3)}}},
// arg0 : i32 is_modified, CONSTANT
// arg1 : i32 surface index
// arg2 : i32 offset(in owords for.ld / in bytes for.ld.unaligned)
{"oword_ld_unaligned", {"oword.ld.unaligned", {t(3), aSI(0), a(1)}}},
{"oword_ld", {"oword.ld", {t(3), aSI(0), a(1)}}},
// arg0: i32 surface index
// arg1: i32 offset (in owords)
// arg2: data to write (overloaded)
{"oword_st", {"oword.st", {aSI(0), a(1), a(2)}}},
// surface index-based gather/scatter:
// arg0: i32 log2 num blocks, CONSTANT (0/1/2 for num blocks 1/2/4)
// arg1: i16 scale, CONSTANT
// arg2: i32 surface index
// arg3: i32 global offset in bytes
// arg4: vXi32 element offset in bytes (overloaded)
{"gather_scaled2",
{"gather.scaled2", {t(3), t(4), aSI(0), a(1), a(2)}}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 log2 num blocks, CONSTANT (0/1/2 for num blocks 1/2/4)
// arg2: i16 scale, CONSTANT
// arg3: i32 surface index
// arg4: i32 global offset in bytes
// arg5: vXi32 element offset in bytes (overloaded)
// arg6: old value of the data read
{"gather_scaled",
{"gather.scaled", {ai1(0), t(3), t(4), aSI(1), a(2), a(3), u(-1)}}},
// arg0: i32 log2 num blocks, CONSTANT (0/1/2 for num blocks 1/2/4)
// arg1: i16 scale, CONSTANT
// arg2: i32 surface index
// arg3: i32 global offset in bytes
// arg4: vXi32 element offset in bytes (overloaded)
// arg5: vXi1 predicate (overloaded)
{"gather_masked_scaled2",
{"gather.masked.scaled2", {t(3), t(4), aSI(0), a(1), a(2), ai1(3)}}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 log2 num blocks, CONSTANT (0/1/2 for num blocks 1/2/4)
// arg2: i16 scale, CONSTANT
// arg3: i32 surface index
// arg4: i32 global offset in bytes
// arg5: vXi32 element offset (overloaded)
// arg6: data to write (overloaded)
{"scatter_scaled",
{"scatter.scaled", {ai1(0), t(3), t(4), aSI(1), a(2), a(3), a(4)}}},
// arg0: vXi1 predicate (overloaded) (overloaded)
// arg1: i32 channel mask, CONSTANT
// arg2: i16 scale, CONSTANT
// arg3: i32 surface index
// arg4: i32 global offset in bytes
// arg5: vXi32 element offset in bytes (overloaded)
// arg6: old value of the data read
{"gather4_scaled",
{"gather4.scaled", {ai1(0), t(3), t(4), aSI(1), a(2), a(3), u(-1)}}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 channel mask, constant
// arg2: i16 scale, constant
// arg3: i32 surface index
// arg4: i32 global offset in bytes
// arg5: vXi32 element offset in bytes (overloaded)
// arg6: data to write (overloaded)
{"scatter4_scaled",
{"scatter4.scaled", {ai1(0), t(3), t(4), aSI(1), a(2), a(3), a(4)}}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 surface index
// arg2: vXi32 element offset in bytes
// arg3: vXi32 original value of the register that the data is read into
{"dword_atomic0",
{"dword.atomic", {ai1(0), aSI(1), a(2), u(-1)}, bo(0)}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 surface index
// arg2: vXi32 element offset in bytes (overloaded)
// arg3: vXi32/vXfloat src
// arg4: vXi32/vXfloat original value of the register that the data is
// read into
{"dword_atomic1",
{"dword.atomic", {ai1(0), aSI(1), a(2), a(3), u(-1)}, bo(0)}},
// arg0: vXi1 predicate (overloaded)
// arg1: i32 surface index
// arg2: vXi32 element offset in bytes
// arg3: vXi32 src0
// arg4: vXi32 src1
// arg5: vXi32 original value of the register that the data is read into
{"dword_atomic2",
{"dword.atomic", {ai1(0), aSI(1), a(2), a(3), a(4), u(-1)}, bo(0)}},
{"raw_sends2",
{"raw.sends2",
{a(0), a(1), ai1(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9), a(10),
a(11)}}},
{"raw_send2",
{"raw.send2",
{a(0), a(1), ai1(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9)}}},
{"raw_sends2_noresult",
{"raw.sends2.noresult",
{a(0), a(1), ai1(2), a(3), a(4), a(5), a(6), a(7), a(8), a(9)}}},
{"raw_send2_noresult",
{"raw.send2.noresult",
{a(0), a(1), ai1(2), a(3), a(4), a(5), a(6), a(7)}}},
{"nbarrier", {"nbarrier", {a(0), a(1), a(2)}}},
{"raw_send_nbarrier_signal",
{"raw.send.noresult", {a(0), ai1(4), a(1), a(2), a(3)}}},
{"sat", {"sat", {a(0)}}},
{"fptoui_sat", {"fptoui.sat", {a(0)}}},
{"fptosi_sat", {"fptosi.sat", {a(0)}}},
{"uutrunc_sat", {"uutrunc.sat", {a(0)}}},
{"ustrunc_sat", {"ustrunc.sat", {a(0)}}},
{"sutrunc_sat", {"sutrunc.sat", {a(0)}}},
{"sstrunc_sat", {"sstrunc.sat", {a(0)}}},
{"abs", {"abs", {a(0)}, nk(-1)}},
{"ssshl", {"ssshl", {a(0), a(1)}}},
{"sushl", {"sushl", {a(0), a(1)}}},
{"usshl", {"usshl", {a(0), a(1)}}},
{"uushl", {"uushl", {a(0), a(1)}}},
{"ssshl_sat", {"ssshl.sat", {a(0), a(1)}}},
{"sushl_sat", {"sushl.sat", {a(0), a(1)}}},
{"usshl_sat", {"usshl.sat", {a(0), a(1)}}},
{"uushl_sat", {"uushl.sat", {a(0), a(1)}}},
{"rol", {"rol", {a(0), a(1)}}},
{"ror", {"ror", {a(0), a(1)}}},
{"rndd", {"rndd", {a(0)}}},
{"rnde", {"rnde", {a(0)}}},
{"rndu", {"rndu", {a(0)}}},
{"rndz", {"rndz", {a(0)}}},
{"umulh", {"umulh", {a(0), a(1)}}},
{"smulh", {"smulh", {a(0), a(1)}}},
{"frc", {"frc", {a(0)}}},
{"fmax", {"fmax", {a(0), a(1)}}},
{"umax", {"umax", {a(0), a(1)}}},
{"smax", {"smax", {a(0), a(1)}}},
{"lzd", {"lzd", {a(0)}}},
{"fmin", {"fmin", {a(0), a(1)}}},
{"umin", {"umin", {a(0), a(1)}}},
{"smin", {"smin", {a(0), a(1)}}},
{"bfrev", {"bfrev", {a(0)}}},
{"cbit", {"cbit", {a(0)}}},
{"bfi", {"bfi", {a(0), a(1), a(2), a(3)}}},
{"sbfe", {"sbfe", {a(0), a(1), a(2)}}},
{"fbl", {"fbl", {a(0)}}},
{"sfbh", {"sfbh", {a(0)}}},
{"ufbh", {"ufbh", {a(0)}}},
{"inv", {"inv", {a(0)}}},
{"log", {"log", {a(0)}}},
{"exp", {"exp", {a(0)}}},
{"sqrt", {"sqrt", {a(0)}}},
{"ieee_sqrt", {"ieee.sqrt", {a(0)}}},
{"rsqrt", {"rsqrt", {a(0)}}},
{"sin", {"sin", {a(0)}}},
{"cos", {"cos", {a(0)}}},
{"pow", {"pow", {a(0), a(1)}}},
{"ieee_div", {"ieee.div", {a(0), a(1)}}},
{"uudp4a", {"uudp4a", {a(0), a(1), a(2)}}},
{"usdp4a", {"usdp4a", {a(0), a(1), a(2)}}},
{"sudp4a", {"sudp4a", {a(0), a(1), a(2)}}},
{"ssdp4a", {"ssdp4a", {a(0), a(1), a(2)}}},
{"uudp4a_sat", {"uudp4a.sat", {a(0), a(1), a(2)}}},
{"usdp4a_sat", {"usdp4a.sat", {a(0), a(1), a(2)}}},
{"sudp4a_sat", {"sudp4a.sat", {a(0), a(1), a(2)}}},
{"ssdp4a_sat", {"ssdp4a.sat", {a(0), a(1), a(2)}}},
{"any", {"any", {ai1(0)}}},
{"all", {"all", {ai1(0)}}},
{"lane_id", {"lane.id", {}}},
{"test_src_tmpl_arg",
{"test.src.tmpl.arg", {t(0), t1(1), t8(2), t16(3), t32(4), c8(17)}}},
};
}
const IntrinTable &getTable() { return Table; }
};
// The C++11 "magic static" idiom to lazily initialize the ESIMD intrinsic table
static const IntrinTable &getIntrinTable() {
static ESIMDIntrinDescTable TheTable;
return TheTable.getTable();
}
static const ESIMDIntrinDesc &getIntrinDesc(StringRef SrcSpelling) {
static ESIMDIntrinDesc InvalidDesc{"", {}, {}};
const auto &Table = getIntrinTable();
auto It = Table.find(SrcSpelling.str());
if (It == Table.end()) {
Twine Msg("unknown ESIMD intrinsic: " + SrcSpelling);
llvm::report_fatal_error(Msg, false /*no crash diag*/);
}
return It->second;
}
// Simplest possible implementation of an allocator for the Itanium demangler
class SimpleAllocator {
protected:
SmallVector<void *, 128> Ptrs;
public:
void reset() {
for (void *Ptr : Ptrs) {
// Destructors are not called, but that is OK for the
// itanium_demangle::Node subclasses
std::free(Ptr);
}
Ptrs.resize(0);
}
template <typename T, typename... Args> T *makeNode(Args &&...args) {
void *Ptr = std::calloc(1, sizeof(T));
Ptrs.push_back(Ptr);
return new (Ptr) T(std::forward<Args>(args)...);
}
void *allocateNodeArray(size_t sz) {
void *Ptr = std::calloc(sz, sizeof(id::Node *));
Ptrs.push_back(Ptr);
return Ptr;
}
~SimpleAllocator() { reset(); }
};
Type *parsePrimitiveTypeString(StringRef TyStr, LLVMContext &Ctx) {
return llvm::StringSwitch<Type *>(TyStr)
.Case("bool", IntegerType::getInt1Ty(Ctx))
.Case("char", IntegerType::getInt8Ty(Ctx))
.Case("unsigned char", IntegerType::getInt8Ty(Ctx))
.Case("short", IntegerType::getInt16Ty(Ctx))
.Case("unsigned short", IntegerType::getInt16Ty(Ctx))
.Case("int", IntegerType::getInt32Ty(Ctx))
.Case("unsigned int", IntegerType::getInt32Ty(Ctx))
.Case("unsigned", IntegerType::getInt32Ty(Ctx))
.Case("unsigned long long", IntegerType::getInt64Ty(Ctx))
.Case("long long", IntegerType::getInt64Ty(Ctx))
.Case("_Float16", IntegerType::getHalfTy(Ctx))
.Case("float", IntegerType::getFloatTy(Ctx))
.Case("double", IntegerType::getDoubleTy(Ctx))
.Case("void", IntegerType::getVoidTy(Ctx))
.Default(nullptr);
}
template <typename T>
static const T *castNodeImpl(const id::Node *N, id::Node::Kind K) {
assert(N && N->getKind() == K && "unexpected demangler node kind");
return reinterpret_cast<const T *>(N);
}
#define castNode(NodeObj, NodeKind) \
castNodeImpl<id::NodeKind>(NodeObj, id::Node::K##NodeKind)
static APInt parseTemplateArg(id::FunctionEncoding *FE, unsigned int N,
Type *&Ty, LLVMContext &Ctx,
ESIMDIntrinDesc::GenXArgConversion Conv =
ESIMDIntrinDesc::GenXArgConversion::NONE) {
// parseTemplateArg returns APInt with a certain bitsize
// This bitsize (primitive size in bits) is deduced by the following rules:
// If Conv is not None, then bitsize is taken from Conv
// If Conv is None and Arg is IntegerLiteral, then bitsize is taken from
// Arg size
// If Conv is None and Arg is BoolExpr or Enum, the bitsize falls back to 32
const auto *Nm = castNode(FE->getName(), NameWithTemplateArgs);
const auto *ArgsN = castNode(Nm->TemplateArgs, TemplateArgs);
id::NodeArray Args = ArgsN->getParams();
assert(N < Args.size() && "too few template arguments");
id::StringView Val;
switch (Conv) {
case ESIMDIntrinDesc::GenXArgConversion::NONE:
// Default fallback case, if we cannot deduce bitsize
Ty = IntegerType::getInt32Ty(Ctx);
break;
case ESIMDIntrinDesc::GenXArgConversion::TO_I1:
Ty = IntegerType::getInt1Ty(Ctx);
break;
case ESIMDIntrinDesc::GenXArgConversion::TO_I8:
Ty = IntegerType::getInt8Ty(Ctx);
break;
case ESIMDIntrinDesc::GenXArgConversion::TO_I16:
Ty = IntegerType::getInt16Ty(Ctx);
break;
case ESIMDIntrinDesc::GenXArgConversion::TO_I32:
Ty = IntegerType::getInt32Ty(Ctx);
break;
}
switch (Args[N]->getKind()) {
case id::Node::KIntegerLiteral: {
auto *ValL = castNode(Args[N], IntegerLiteral);
const id::StringView &TyStr = ValL->getType();
if (Conv == ESIMDIntrinDesc::GenXArgConversion::NONE && TyStr.size() != 0)
// Overwrite Ty with IntegerLiteral's size
Ty =
parsePrimitiveTypeString(StringRef(TyStr.begin(), TyStr.size()), Ctx);
Val = ValL->getValue();
break;
}
case id::Node::KBoolExpr: {
auto *ValL = castNode(Args[N], BoolExpr);
ValL->match([&Val](bool Value) { Value ? Val = "1" : Val = "0"; });
break;
}
case id::Node::KEnumLiteral: {
auto *CE = castNode(Args[N], EnumLiteral);
Val = CE->getIntegerValue();
break;
}
default:
llvm_unreachable_internal("bad esimd intrinsic template parameter");
}
return APInt(Ty->getPrimitiveSizeInBits(), StringRef(Val.begin(), Val.size()),
10);
}
// Constructs a GenX intrinsic name suffix based on the original C++ name (stem)
// and the types of its parameters (some intrinsic names have additional
// suffixes depending on the parameter types).
static std::string getESIMDIntrinSuffix(id::FunctionEncoding *FE,
FunctionType *FT,
const ESIMDIntrinDesc::NameRule &Rule) {
std::string Suff;
switch (Rule.Kind) {
case ESIMDIntrinDesc::GenXSuffixRuleKind::BIN_OP: {
// e.g. ".add"
Type *Ty = nullptr;
APInt OpId = parseTemplateArg(FE, Rule.I.TmplArgNo, Ty, FT->getContext());
switch (OpId.getSExtValue()) {
case 0x0:
Suff = ".add";
break;
case 0x1:
Suff = ".sub";
break;
case 0x2:
Suff = ".inc";
break;
case 0x3:
Suff = ".dec";
break;
case 0x4:
Suff = ".min";
break;
case 0x5:
Suff = ".max";
break;
case 0x6:
Suff = ".xchg";
break;
case 0x7:
Suff = ".cmpxchg";
break;
case 0x8:
Suff = ".and";
break;
case 0x9:
Suff = ".or";
break;
case 0xa:
Suff = ".xor";
break;
case 0xb:
Suff = ".minsint";
break;
case 0xc:
Suff = ".maxsint";
break;
case 0x10:
Suff = ".fmax";
break;
case 0x11:
Suff = ".fmin";
break;
case 0x12:
Suff = ".fcmpwr";
break;
case 0xff:
Suff = ".predec";
break;
default:
llvm_unreachable("unknown atomic OP");
};
break;
}
case ESIMDIntrinDesc::GenXSuffixRuleKind::NUM_KIND: {
// e.g. "f"
int No = Rule.I.CallArgNo;
Type *Ty = No == -1 ? FT->getReturnType() : FT->getParamType(No);
if (Ty->isVectorTy())
Ty = cast<VectorType>(Ty)->getElementType();
assert(Ty->isFloatingPointTy() || Ty->isIntegerTy());
Suff = Ty->isFloatingPointTy() ? "f" : "i";
break;
}
default:
// It's ok if there is no suffix.
break;
}
return Suff;
}
// Turn a MDNode into llvm::value or its subclass.
// Return nullptr if the underlying value has type mismatch.
template <typename Ty = llvm::Value> Ty *getVal(llvm::Metadata *M) {
if (auto VM = dyn_cast<llvm::ValueAsMetadata>(M))
if (auto V = dyn_cast<Ty>(VM->getValue()))
return V;
return nullptr;
}
/// Return the MDNode that has the SLM size attribute.
static llvm::MDNode *getSLMSizeMDNode(llvm::Function *F) {
llvm::NamedMDNode *Nodes =
F->getParent()->getNamedMetadata(GENX_KERNEL_METADATA);
assert(Nodes && "invalid genx.kernels metadata");
for (auto Node : Nodes->operands()) {
if (Node->getNumOperands() >= 4 && getVal(Node->getOperand(0)) == F)
return Node;
}
// if F is not a kernel, keep looking into its callers
while (!F->use_empty()) {
auto CI = cast<CallInst>(F->use_begin()->getUser());
auto UF = CI->getParent()->getParent();
if (auto Node = getSLMSizeMDNode(UF))
return Node;
}
return nullptr;
}
static inline llvm::Metadata *getMD(llvm::Value *V) {
return llvm::ValueAsMetadata::get(V);
}
static void translateSLMInit(CallInst &CI) {
auto F = CI.getParent()->getParent();
auto *ArgV = CI.getArgOperand(0);
if (!isa<ConstantInt>(ArgV)) {
assert(false && "integral constant expected for slm size");
return;
}
auto NewVal = cast<llvm::ConstantInt>(ArgV)->getZExtValue();
assert(NewVal != 0 && "zero slm bytes being requested");
// find the corresponding kernel metadata and set the SLM size.
if (llvm::MDNode *Node = getSLMSizeMDNode(F)) {
if (llvm::Value *OldSz = getVal(Node->getOperand(4))) {
assert(isa<llvm::ConstantInt>(OldSz) && "integer constant expected");
llvm::Value *NewSz = llvm::ConstantInt::get(OldSz->getType(), NewVal);
uint64_t OldVal = cast<llvm::ConstantInt>(OldSz)->getZExtValue();
if (OldVal < NewVal)
Node->replaceOperandWith(3, getMD(NewSz));
}
} else {
// We check whether this call is inside a kernel function.
assert(false && "slm_init shall be called by a kernel");
}
}
static void translatePackMask(CallInst &CI) {
using Demangler = id::ManglingParser<SimpleAllocator>;
Function *F = CI.getCalledFunction();
assert(F && "function to translate is invalid");
StringRef MnglName = F->getName();
Demangler Parser(MnglName.begin(), MnglName.end());
id::Node *AST = Parser.parse();
if (!AST || !Parser.ForwardTemplateRefs.empty()) {
Twine Msg("failed to demangle ESIMD intrinsic: " + MnglName);
llvm::report_fatal_error(Msg, false /*no crash diag*/);
}
if (AST->getKind() != id::Node::KFunctionEncoding) {
Twine Msg("bad ESIMD intrinsic: " + MnglName);
llvm::report_fatal_error(Msg, false /*no crash diag*/);
}
auto *FE = static_cast<id::FunctionEncoding *>(AST);
llvm::LLVMContext &Context = CI.getContext();
Type *TTy = nullptr;
APInt Val = parseTemplateArg(FE, 0, TTy, Context);
unsigned N = Val.getZExtValue();
Value *Result = CI.getArgOperand(0);
assert(Result->getType()->isIntOrIntVectorTy());
Value *Zero = ConstantInt::get(Result->getType(), 0);
IRBuilder<> Builder(&CI);
// TODO CM_COMPAT
// In CM non LSB bits in mask elements are ignored, so e.g. '2' is treated as
// 'false' there. ESIMD adopts C++ semantics, where any non-zero is 'true'.
// For CM this ICmpInst should be replaced with truncation to i1.
Result = Builder.CreateICmp(ICmpInst::ICMP_NE, Result, Zero);
Result = Builder.CreateBitCast(Result, llvm::Type::getIntNTy(Context, N));
if (N != 32) {
Result = Builder.CreateCast(llvm::Instruction::ZExt, Result,
llvm::Type::getInt32Ty(Context));
}
Result->setName(CI.getName());
cast<llvm::Instruction>(Result)->setDebugLoc(CI.getDebugLoc());
CI.replaceAllUsesWith(Result);
}
static void translateUnPackMask(CallInst &CI) {
using Demangler = id::ManglingParser<SimpleAllocator>;
Function *F = CI.getCalledFunction();
assert(F && "function to translate is invalid");
StringRef MnglName = F->getName();
Demangler Parser(MnglName.begin(), MnglName.end());
id::Node *AST = Parser.parse();
if (!AST || !Parser.ForwardTemplateRefs.empty()) {
Twine Msg("failed to demangle ESIMD intrinsic: " + MnglName);
llvm::report_fatal_error(Msg, false /*no crash diag*/);
}
if (AST->getKind() != id::Node::KFunctionEncoding) {
Twine Msg("bad ESIMD intrinsic: " + MnglName);
llvm::report_fatal_error(Msg, false /*no crash diag*/);
}
auto *FE = static_cast<id::FunctionEncoding *>(AST);
llvm::LLVMContext &Context = CI.getContext();
Type *TTy = nullptr;
APInt Val = parseTemplateArg(FE, 0, TTy, Context);
unsigned N = Val.getZExtValue();
// get N x i1
assert(CI.arg_size() == 1);
llvm::Value *Arg0 = CI.getArgOperand(0);
unsigned Width = Arg0->getType()->getPrimitiveSizeInBits();
IRBuilder<> Builder(&CI);
if (Width > N) {
llvm::Type *Ty = llvm::IntegerType::get(Context, N);
Arg0 = Builder.CreateTrunc(Arg0, Ty);
if (auto *Trunc = dyn_cast<llvm::Instruction>(Arg0))
Trunc->setDebugLoc(CI.getDebugLoc());
}
assert(Arg0->getType()->getPrimitiveSizeInBits() == N);
Arg0 = Builder.CreateBitCast(
Arg0, llvm::FixedVectorType::get(llvm::Type::getInt1Ty(Context), N));
// get N x i16
llvm::Value *TransCI = Builder.CreateZExt(
Arg0, llvm::FixedVectorType::get(llvm::Type::getInt16Ty(Context), N));
TransCI->takeName(&CI);
if (llvm::Instruction *TransCInst = dyn_cast<llvm::Instruction>(TransCI))
TransCInst->setDebugLoc(CI.getDebugLoc());
CI.replaceAllUsesWith(TransCI);
}
// This function sets VCNamedBarrierCount attribute to set
// the number of named barriers required by a kernel
static void translateNbarrierInit(CallInst &CI) {
auto *F = CI.getFunction();
auto *ArgV = CI.getArgOperand(0);
assert(isa<ConstantInt>(ArgV) &&
"integral constant expected for nbarrier count");
auto NewVal = cast<llvm::ConstantInt>(ArgV)->getZExtValue();
assert(NewVal != 0 && "zero nbarrier count being requested");
if (llvm::MDNode *Node = getSLMSizeMDNode(F)) {
if (llvm::Value *OldCount =
getVal(Node->getOperand(genx::KernelMDOp::NBarrierCnt))) {
assert(isa<llvm::ConstantInt>(OldCount) && "integer constant expected");
llvm::Value *NewCount =
llvm::ConstantInt::get(OldCount->getType(), NewVal);
uint64_t OldVal = cast<llvm::ConstantInt>(OldCount)->getZExtValue();
if (OldVal < NewVal)
Node->replaceOperandWith(genx::KernelMDOp::NBarrierCnt,
getMD(NewCount));
}
} else {
llvm_unreachable("esimd_nbarrier_init can only be called by a kernel");
}
}
static bool translateVLoad(CallInst &CI, SmallPtrSet<Type *, 4> &GVTS) {
if (GVTS.find(CI.getType()) != GVTS.end())
return false;
IRBuilder<> Builder(&CI);
auto LI = Builder.CreateLoad(CI.getType(), CI.getArgOperand(0), CI.getName());
LI->setDebugLoc(CI.getDebugLoc());
CI.replaceAllUsesWith(LI);
return true;
}
static bool translateVStore(CallInst &CI, SmallPtrSet<Type *, 4> &GVTS) {
if (GVTS.find(CI.getOperand(1)->getType()) != GVTS.end())
return false;
IRBuilder<> Builder(&CI);
auto SI = Builder.CreateStore(CI.getArgOperand(1), CI.getArgOperand(0));
SI->setDebugLoc(CI.getDebugLoc());
return true;
}
static void translateGetSurfaceIndex(CallInst &CI) {
auto opnd = CI.getArgOperand(0);
assert(opnd->getType()->isPointerTy());
IRBuilder<> Builder(&CI);
auto SV =
Builder.CreatePtrToInt(opnd, IntegerType::getInt32Ty(CI.getContext()));
auto *SI = cast<CastInst>(SV);
SI->setDebugLoc(CI.getDebugLoc());
CI.replaceAllUsesWith(SI);
}
// Newly created GenX intrinsic might have different return type than expected.
// This helper function creates cast operation from GenX intrinsic return type
// to currently expected. Returns pointer to created cast instruction if it
// was created, otherwise returns NewI.
static Instruction *addCastInstIfNeeded(Instruction *OldI, Instruction *NewI) {
Type *NITy = NewI->getType();
Type *OITy = OldI->getType();
if (OITy != NITy) {
auto CastOpcode = CastInst::getCastOpcode(NewI, false, OITy, false);
NewI = CastInst::Create(CastOpcode, NewI, OITy,
NewI->getName() + ".cast.ty", OldI);
NewI->setDebugLoc(OldI->getDebugLoc());
}
return NewI;
}
/// Returns the index from the given extract element instruction \p EEI.
/// It is checked here that the index is either 0, 1, or 2.
static uint64_t getIndexFromExtract(ExtractElementInst *EEI) {
Value *IndexV = EEI->getIndexOperand();
uint64_t IndexValue = cast<ConstantInt>(IndexV)->getZExtValue();
assert(IndexValue < MAX_DIMS &&
"Extract element index should be either 0, 1, or 2");
return IndexValue;
}
/// Generates the call of GenX intrinsic \p IntrinName and inserts it
/// right before the given extract element instruction \p EEI using the result
/// of vector load. The parameter \p IsVectorCall tells what version of GenX
/// intrinsic (scalar or vector) to use to lower the load from SPIRV global.
static Instruction *generateGenXCall(ExtractElementInst *EEI,
StringRef IntrinName, bool IsVectorCall) {
uint64_t IndexValue = getIndexFromExtract(EEI);
std::string Suffix =
IsVectorCall
? ".v3i32"
: (Twine(".") + Twine(static_cast<char>('x' + IndexValue))).str();
std::string FullIntrinName = (Twine(GenXIntrinsic::getGenXIntrinsicPrefix()) +
Twine(IntrinName) + Suffix)
.str();
auto ID = GenXIntrinsic::lookupGenXIntrinsicID(FullIntrinName);
Type *I32Ty = Type::getInt32Ty(EEI->getModule()->getContext());
Function *NewFDecl =
IsVectorCall
? GenXIntrinsic::getGenXDeclaration(
EEI->getModule(), ID, FixedVectorType::get(I32Ty, MAX_DIMS))
: GenXIntrinsic::getGenXDeclaration(EEI->getModule(), ID);
std::string ResultName = (Twine(EEI->getName()) + "." + FullIntrinName).str();
Instruction *Inst = IntrinsicInst::Create(NewFDecl, {}, ResultName, EEI);
Inst->setDebugLoc(EEI->getDebugLoc());