forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaSYCL.cpp
2789 lines (2475 loc) · 106 KB
/
SemaSYCL.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
//===- SemaSYCL.cpp - Semantic Analysis for SYCL 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
//
//===----------------------------------------------------------------------===//
// This implements Semantic Analysis for SYCL constructs.
//===----------------------------------------------------------------------===//
#include "TreeTransform.h"
#include "clang/AST/AST.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/QualTypeNames.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Analysis/CallGraph.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <array>
#include <functional>
#include <initializer_list>
using namespace clang;
using namespace std::placeholders;
using KernelParamKind = SYCLIntegrationHeader::kernel_param_kind_t;
enum target {
global_buffer = 2014,
constant_buffer,
local,
image,
host_buffer,
host_image,
image_array
};
using ParamDesc = std::tuple<QualType, IdentifierInfo *, TypeSourceInfo *>;
enum KernelInvocationKind {
InvokeUnknown,
InvokeSingleTask,
InvokeParallelFor,
InvokeParallelForWorkGroup
};
const static std::string InitMethodName = "__init";
const static std::string FinalizeMethodName = "__finalize";
namespace {
/// Various utilities.
class Util {
public:
using DeclContextDesc = std::pair<clang::Decl::Kind, StringRef>;
/// Checks whether given clang type is a full specialization of the SYCL
/// accessor class.
static bool isSyclAccessorType(const QualType &Ty);
/// Checks whether given clang type is a full specialization of the SYCL
/// sampler class.
static bool isSyclSamplerType(const QualType &Ty);
/// Checks whether given clang type is a full specialization of the SYCL
/// stream class.
static bool isSyclStreamType(const QualType &Ty);
/// Checks whether given clang type is a full specialization of the SYCL
/// half class.
static bool isSyclHalfType(const QualType &Ty);
/// Checks whether given clang type is a standard SYCL API class with given
/// name.
/// \param Ty the clang type being checked
/// \param Name the class name checked against
/// \param Tmpl whether the class is template instantiation or simple record
static bool isSyclType(const QualType &Ty, StringRef Name, bool Tmpl = false);
/// Checks whether given clang type is a full specialization of the SYCL
/// specialization constant class.
static bool isSyclSpecConstantType(const QualType &Ty);
/// Checks whether given clang type is declared in the given hierarchy of
/// declaration contexts.
/// \param Ty the clang type being checked
/// \param Scopes the declaration scopes leading from the type to the
/// translation unit (excluding the latter)
static bool matchQualifiedTypeName(const QualType &Ty,
ArrayRef<Util::DeclContextDesc> Scopes);
};
} // anonymous namespace
// This information is from Section 4.13 of the SYCL spec
// https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf
// This function returns false if the math lib function
// corresponding to the input builtin is not supported
// for SYCL
static bool IsSyclMathFunc(unsigned BuiltinID) {
switch (BuiltinID) {
case Builtin::BIlround:
case Builtin::BI__builtin_lround:
case Builtin::BIceill:
case Builtin::BI__builtin_ceill:
case Builtin::BIcopysignl:
case Builtin::BI__builtin_copysignl:
case Builtin::BIcosl:
case Builtin::BI__builtin_cosl:
case Builtin::BIexpl:
case Builtin::BI__builtin_expl:
case Builtin::BIexp2l:
case Builtin::BI__builtin_exp2l:
case Builtin::BIfabsl:
case Builtin::BI__builtin_fabsl:
case Builtin::BIfloorl:
case Builtin::BI__builtin_floorl:
case Builtin::BIfmal:
case Builtin::BI__builtin_fmal:
case Builtin::BIfmaxl:
case Builtin::BI__builtin_fmaxl:
case Builtin::BIfminl:
case Builtin::BI__builtin_fminl:
case Builtin::BIfmodl:
case Builtin::BI__builtin_fmodl:
case Builtin::BIlogl:
case Builtin::BI__builtin_logl:
case Builtin::BIlog10l:
case Builtin::BI__builtin_log10l:
case Builtin::BIlog2l:
case Builtin::BI__builtin_log2l:
case Builtin::BIpowl:
case Builtin::BI__builtin_powl:
case Builtin::BIrintl:
case Builtin::BI__builtin_rintl:
case Builtin::BIroundl:
case Builtin::BI__builtin_roundl:
case Builtin::BIsinl:
case Builtin::BI__builtin_sinl:
case Builtin::BIsqrtl:
case Builtin::BI__builtin_sqrtl:
case Builtin::BItruncl:
case Builtin::BI__builtin_truncl:
case Builtin::BIlroundl:
case Builtin::BI__builtin_lroundl:
case Builtin::BIcopysign:
case Builtin::BI__builtin_copysign:
case Builtin::BIfloor:
case Builtin::BI__builtin_floor:
case Builtin::BIfmax:
case Builtin::BI__builtin_fmax:
case Builtin::BIfmin:
case Builtin::BI__builtin_fmin:
case Builtin::BInearbyint:
case Builtin::BI__builtin_nearbyint:
case Builtin::BIrint:
case Builtin::BI__builtin_rint:
case Builtin::BIround:
case Builtin::BI__builtin_round:
case Builtin::BItrunc:
case Builtin::BI__builtin_trunc:
case Builtin::BIcopysignf:
case Builtin::BI__builtin_copysignf:
case Builtin::BIfloorf:
case Builtin::BI__builtin_floorf:
case Builtin::BIfmaxf:
case Builtin::BI__builtin_fmaxf:
case Builtin::BIfminf:
case Builtin::BI__builtin_fminf:
case Builtin::BInearbyintf:
case Builtin::BI__builtin_nearbyintf:
case Builtin::BIrintf:
case Builtin::BI__builtin_rintf:
case Builtin::BIroundf:
case Builtin::BI__builtin_roundf:
case Builtin::BItruncf:
case Builtin::BI__builtin_truncf:
case Builtin::BIlroundf:
case Builtin::BI__builtin_lroundf:
case Builtin::BI__builtin_fpclassify:
case Builtin::BI__builtin_isfinite:
case Builtin::BI__builtin_isinf:
case Builtin::BI__builtin_isnormal:
return false;
default:
break;
}
return true;
}
bool Sema::isKnownGoodSYCLDecl(const Decl *D) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
const IdentifierInfo *II = FD->getIdentifier();
const DeclContext *DC = FD->getDeclContext();
if (II && II->isStr("__spirv_ocl_printf") &&
!FD->isDefined() &&
FD->getLanguageLinkage() == CXXLanguageLinkage &&
DC->getEnclosingNamespaceContext()->isTranslationUnit())
return true;
}
return false;
}
static bool isZeroSizedArray(QualType Ty) {
if (const auto *CATy = dyn_cast<ConstantArrayType>(Ty))
return CATy->getSize() == 0;
return false;
}
static void checkSYCLType(Sema &S, QualType Ty, SourceRange Loc,
llvm::DenseSet<QualType> Visited,
SourceRange UsedAtLoc = SourceRange()) {
// Not all variable types are supported inside SYCL kernels,
// for example the quad type __float128 will cause errors in the
// SPIR-V translation phase.
// Here we check any potentially unsupported declaration and issue
// a deferred diagnostic, which will be emitted iff the declaration
// is discovered to reside in kernel code.
// The optional UsedAtLoc param is used when the SYCL usage is at a
// different location than the variable declaration and we need to
// inform the user of both, e.g. struct member usage vs declaration.
bool Emitting = false;
//--- check types ---
// zero length arrays
if (isZeroSizedArray(Ty)) {
S.SYCLDiagIfDeviceCode(Loc.getBegin(), diag::err_typecheck_zero_array_size);
Emitting = true;
}
// variable length arrays
if (Ty->isVariableArrayType()) {
S.SYCLDiagIfDeviceCode(Loc.getBegin(), diag::err_vla_unsupported);
Emitting = true;
}
// Sub-reference array or pointer, then proceed with that type.
while (Ty->isAnyPointerType() || Ty->isArrayType())
Ty = QualType{Ty->getPointeeOrArrayElementType(), 0};
// __int128, __int128_t, __uint128_t, long double, __float128
if (Ty->isSpecificBuiltinType(BuiltinType::Int128) ||
Ty->isSpecificBuiltinType(BuiltinType::UInt128) ||
Ty->isSpecificBuiltinType(BuiltinType::LongDouble) ||
(Ty->isSpecificBuiltinType(BuiltinType::Float128) &&
!S.Context.getTargetInfo().hasFloat128Type())) {
S.SYCLDiagIfDeviceCode(Loc.getBegin(), diag::err_type_unsupported)
<< Ty.getUnqualifiedType().getCanonicalType();
Emitting = true;
}
if (Emitting && UsedAtLoc.isValid())
S.SYCLDiagIfDeviceCode(UsedAtLoc.getBegin(), diag::note_used_here);
//--- now recurse ---
// Pointers complicate recursion. Add this type to Visited.
// If already there, bail out.
if (!Visited.insert(Ty).second)
return;
if (const auto *ATy = dyn_cast<AttributedType>(Ty))
return checkSYCLType(S, ATy->getModifiedType(), Loc, Visited);
if (const auto *RD = Ty->getAsRecordDecl()) {
for (const auto &Field : RD->fields())
checkSYCLType(S, Field->getType(), Field->getSourceRange(), Visited, Loc);
} else if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
for (const auto &ParamTy : FPTy->param_types())
checkSYCLType(S, ParamTy, Loc, Visited);
checkSYCLType(S, FPTy->getReturnType(), Loc, Visited);
}
}
void Sema::checkSYCLDeviceVarDecl(VarDecl *Var) {
assert(getLangOpts().SYCLIsDevice &&
"Should only be called during SYCL compilation");
QualType Ty = Var->getType();
SourceRange Loc = Var->getLocation();
llvm::DenseSet<QualType> Visited;
checkSYCLType(*this, Ty, Loc, Visited);
}
// Tests whether given function is a lambda function or '()' operator used as
// SYCL kernel body function (e.g. in parallel_for).
// NOTE: This is incomplete implemenation. See TODO in the FE TODO list for the
// ESIMD extension.
static bool isSYCLKernelBodyFunction(FunctionDecl *FD) {
return FD->getOverloadedOperator() == OO_Call;
}
// Helper function to report conflicting function attributes.
// F - the function, A1 - function attribute, A2 - the attribute it conflicts
// with.
static void reportConflictingAttrs(Sema &S, FunctionDecl *F, const Attr *A1,
const Attr *A2) {
S.Diag(F->getLocation(), diag::err_conflicting_sycl_kernel_attributes);
S.Diag(A1->getLocation(), diag::note_conflicting_attribute);
S.Diag(A2->getLocation(), diag::note_conflicting_attribute);
F->setInvalidDecl();
}
/// Returns the signed constant integer value represented by given expression
static int64_t getIntExprValue(const Expr *E, ASTContext &Ctx) {
llvm::APSInt Val(32);
bool IsValid = E->isIntegerConstantExpr(Val, Ctx);
assert(IsValid && "expression must be constant integer");
(void)IsValid;
return Val.getSExtValue();
}
class MarkDeviceFunction : public RecursiveASTVisitor<MarkDeviceFunction> {
public:
MarkDeviceFunction(Sema &S)
: RecursiveASTVisitor<MarkDeviceFunction>(), SemaRef(S) {}
bool VisitCallExpr(CallExpr *e) {
if (FunctionDecl *Callee = e->getDirectCallee()) {
Callee = Callee->getCanonicalDecl();
assert(Callee && "Device function canonical decl must be available");
// Remember that all SYCL kernel functions have deferred
// instantiation as template functions. It means that
// all functions used by kernel have already been parsed and have
// definitions.
if (RecursiveSet.count(Callee)) {
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< Sema::KernelCallRecursiveFunction;
SemaRef.Diag(Callee->getSourceRange().getBegin(),
diag::note_sycl_recursive_function_declared_here)
<< Sema::KernelCallRecursiveFunction;
}
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Callee))
if (Method->isVirtual())
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< Sema::KernelCallVirtualFunction;
if (auto const *FD = dyn_cast<FunctionDecl>(Callee)) {
// FIXME: We need check all target specified attributes for error if
// that function with attribute can not be called from sycl kernel. The
// info is in ParsedAttr. We don't have to map from Attr to ParsedAttr
// currently. Erich is currently working on that in LLVM, once that is
// committed we need to change this".
if (FD->hasAttr<DLLImportAttr>()) {
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< Sema::KernelCallDllimportFunction;
SemaRef.Diag(FD->getLocation(), diag::note_callee_decl) << FD;
}
}
// Specifically check if the math library function corresponding to this
// builtin is supported for SYCL
unsigned BuiltinID = Callee->getBuiltinID();
if (BuiltinID && !IsSyclMathFunc(BuiltinID)) {
StringRef Name = SemaRef.Context.BuiltinInfo.getName(BuiltinID);
SemaRef.Diag(e->getExprLoc(), diag::err_builtin_target_unsupported)
<< Name << "SYCL device";
}
} else if (!SemaRef.getLangOpts().SYCLAllowFuncPtr &&
!e->isTypeDependent() &&
!isa<CXXPseudoDestructorExpr>(e->getCallee()))
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< Sema::KernelCallFunctionPointer;
return true;
}
bool VisitCXXTypeidExpr(CXXTypeidExpr *E) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict) << Sema::KernelRTTI;
return true;
}
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict) << Sema::KernelRTTI;
return true;
}
// The call graph for this translation unit.
CallGraph SYCLCG;
// The set of functions called by a kernel function.
llvm::SmallPtrSet<FunctionDecl *, 10> KernelSet;
// The set of recursive functions identified while building the
// kernel set, this is used for error diagnostics.
llvm::SmallPtrSet<FunctionDecl *, 10> RecursiveSet;
// Determines whether the function FD is recursive.
// CalleeNode is a function which is called either directly
// or indirectly from FD. If recursion is detected then create
// diagnostic notes on each function as the callstack is unwound.
void CollectKernelSet(FunctionDecl *CalleeNode, FunctionDecl *FD,
llvm::SmallPtrSet<FunctionDecl *, 10> VisitedSet) {
// We're currently checking CalleeNode on a different
// trace through the CallGraph, we avoid infinite recursion
// by using KernelSet to keep track of this.
if (!KernelSet.insert(CalleeNode).second)
// Previously seen, stop recursion.
return;
if (CallGraphNode *N = SYCLCG.getNode(CalleeNode)) {
for (const CallGraphNode *CI : *N) {
if (FunctionDecl *Callee = dyn_cast<FunctionDecl>(CI->getDecl())) {
Callee = Callee->getCanonicalDecl();
if (VisitedSet.count(Callee)) {
// There's a stack frame to visit this Callee above
// this invocation. Do not recurse here.
RecursiveSet.insert(Callee);
RecursiveSet.insert(CalleeNode);
} else {
VisitedSet.insert(Callee);
CollectKernelSet(Callee, FD, VisitedSet);
VisitedSet.erase(Callee);
}
}
}
}
}
// Traverses over CallGraph to collect list of attributes applied to
// functions called by SYCLKernel (either directly and indirectly) which needs
// to be propagated down to callers and applied to SYCL kernels.
// For example, reqd_work_group_size, vec_len_hint, reqd_sub_group_size
// Attributes applied to SYCLKernel are also included
// Returns the kernel body function found during traversal.
FunctionDecl *
CollectPossibleKernelAttributes(FunctionDecl *SYCLKernel,
llvm::SmallPtrSet<Attr *, 4> &Attrs) {
typedef std::pair<FunctionDecl *, FunctionDecl *> ChildParentPair;
llvm::SmallPtrSet<FunctionDecl *, 16> Visited;
llvm::SmallVector<ChildParentPair, 16> WorkList;
WorkList.push_back({SYCLKernel, nullptr});
FunctionDecl *KernelBody = nullptr;
while (!WorkList.empty()) {
FunctionDecl *FD = WorkList.back().first;
FunctionDecl *ParentFD = WorkList.back().second;
if ((ParentFD == SYCLKernel) && isSYCLKernelBodyFunction(FD)) {
assert(!KernelBody && "inconsistent call graph - only one kernel body "
"function can be called");
KernelBody = FD;
}
WorkList.pop_back();
if (!Visited.insert(FD).second)
continue; // We've already seen this Decl
if (auto *A = FD->getAttr<IntelReqdSubGroupSizeAttr>())
Attrs.insert(A);
if (auto *A = FD->getAttr<ReqdWorkGroupSizeAttr>())
Attrs.insert(A);
// Allow the following kernel attributes only on lambda functions and
// function objects that are called directly from a kernel (i.e. the one
// passed to the parallel_for function). For all other cases,
// emit a warning and ignore.
if (auto *A = FD->getAttr<SYCLIntelKernelArgsRestrictAttr>()) {
if (ParentFD == SYCLKernel) {
Attrs.insert(A);
} else {
SemaRef.Diag(A->getLocation(), diag::warn_attribute_ignored) << A;
FD->dropAttr<SYCLIntelKernelArgsRestrictAttr>();
}
}
if (auto *A = FD->getAttr<SYCLIntelNumSimdWorkItemsAttr>()) {
if (ParentFD == SYCLKernel) {
Attrs.insert(A);
} else {
SemaRef.Diag(A->getLocation(), diag::warn_attribute_ignored) << A;
FD->dropAttr<SYCLIntelNumSimdWorkItemsAttr>();
}
}
if (auto *A = FD->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
if (ParentFD == SYCLKernel) {
Attrs.insert(A);
} else {
SemaRef.Diag(A->getLocation(), diag::warn_attribute_ignored) << A;
FD->dropAttr<SYCLIntelMaxWorkGroupSizeAttr>();
}
}
if (auto *A = FD->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
if (ParentFD == SYCLKernel) {
Attrs.insert(A);
} else {
SemaRef.Diag(A->getLocation(), diag::warn_attribute_ignored) << A;
FD->dropAttr<SYCLIntelMaxGlobalWorkDimAttr>();
}
}
if (auto *A = FD->getAttr<SYCLIntelNoGlobalWorkOffsetAttr>()) {
if (ParentFD == SYCLKernel) {
Attrs.insert(A);
} else {
SemaRef.Diag(A->getLocation(), diag::warn_attribute_ignored) << A;
FD->dropAttr<SYCLIntelNoGlobalWorkOffsetAttr>();
}
}
if (auto *A = FD->getAttr<SYCLSimdAttr>())
Attrs.insert(A);
// Propagate the explicit SIMD attribute through call graph - it is used
// to distinguish ESIMD code in ESIMD LLVM passes.
if (KernelBody && KernelBody->hasAttr<SYCLSimdAttr>() &&
(KernelBody != FD) && !FD->hasAttr<SYCLSimdAttr>())
FD->addAttr(SYCLSimdAttr::CreateImplicit(SemaRef.getASTContext()));
// TODO: vec_len_hint should be handled here
CallGraphNode *N = SYCLCG.getNode(FD);
if (!N)
continue;
for (const CallGraphNode *CI : *N) {
if (auto *Callee = dyn_cast<FunctionDecl>(CI->getDecl())) {
Callee = Callee->getCanonicalDecl();
if (!Visited.count(Callee))
WorkList.push_back({Callee, FD});
}
}
}
return KernelBody;
}
private:
Sema &SemaRef;
};
class KernelBodyTransform : public TreeTransform<KernelBodyTransform> {
public:
KernelBodyTransform(std::pair<DeclaratorDecl *, DeclaratorDecl *> &MPair,
Sema &S)
: TreeTransform<KernelBodyTransform>(S), MappingPair(MPair), SemaRef(S) {}
bool AlwaysRebuild() { return true; }
ExprResult TransformDeclRefExpr(DeclRefExpr *DRE) {
auto Ref = dyn_cast<DeclaratorDecl>(DRE->getDecl());
if (Ref && Ref == MappingPair.first) {
auto NewDecl = MappingPair.second;
return DeclRefExpr::Create(
SemaRef.getASTContext(), DRE->getQualifierLoc(),
DRE->getTemplateKeywordLoc(), NewDecl, false,
DeclarationNameInfo(DRE->getNameInfo().getName(), SourceLocation(),
DRE->getNameInfo().getInfo()),
NewDecl->getType(), DRE->getValueKind());
}
return DRE;
}
StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
MultiStmtArg Statements,
SourceLocation RBraceLoc, bool IsStmtExpr) {
// Build a new compound statement but clear the source locations.
return getSema().ActOnCompoundStmt(SourceLocation(), SourceLocation(),
Statements, IsStmtExpr);
}
private:
std::pair<DeclaratorDecl *, DeclaratorDecl *> MappingPair;
Sema &SemaRef;
};
// Searches for a call to PFWG lambda function and captures it.
class FindPFWGLambdaFnVisitor
: public RecursiveASTVisitor<FindPFWGLambdaFnVisitor> {
public:
// LambdaObjTy - lambda type of the PFWG lambda object
FindPFWGLambdaFnVisitor(const CXXRecordDecl *LambdaObjTy)
: LambdaFn(nullptr), LambdaObjTy(LambdaObjTy) {}
bool VisitCallExpr(CallExpr *Call) {
auto *M = dyn_cast<CXXMethodDecl>(Call->getDirectCallee());
if (!M || (M->getOverloadedOperator() != OO_Call))
return true;
const int NumPFWGLambdaArgs = 2; // group and lambda obj
if (Call->getNumArgs() != NumPFWGLambdaArgs)
return true;
if (!Util::isSyclType(Call->getArg(1)->getType(), "group", true /*Tmpl*/))
return true;
if (Call->getArg(0)->getType()->getAsCXXRecordDecl() != LambdaObjTy)
return true;
LambdaFn = M; // call to PFWG lambda found - record the lambda
return false; // ... and stop searching
}
// Returns the captured lambda function or nullptr;
CXXMethodDecl *getLambdaFn() const { return LambdaFn; }
private:
CXXMethodDecl *LambdaFn;
const CXXRecordDecl *LambdaObjTy;
};
class MarkWIScopeFnVisitor : public RecursiveASTVisitor<MarkWIScopeFnVisitor> {
public:
MarkWIScopeFnVisitor(ASTContext &Ctx) : Ctx(Ctx) {}
bool VisitCXXMemberCallExpr(CXXMemberCallExpr *Call) {
FunctionDecl *Callee = Call->getDirectCallee();
if (!Callee)
// not a direct call - continue search
return true;
QualType Ty = Ctx.getRecordType(Call->getRecordDecl());
if (!Util::isSyclType(Ty, "group", true /*Tmpl*/))
// not a member of cl::sycl::group - continue search
return true;
auto Name = Callee->getName();
if (((Name != "parallel_for_work_item") && (Name != "wait_for")) ||
Callee->hasAttr<SYCLScopeAttr>())
return true;
// it is a call to cl::sycl::group::parallel_for_work_item/wait_for -
// mark the callee
Callee->addAttr(
SYCLScopeAttr::CreateImplicit(Ctx, SYCLScopeAttr::Level::WorkItem));
// continue search as there can be other PFWI or wait_for calls
return true;
}
private:
ASTContext &Ctx;
};
static bool isSYCLPrivateMemoryVar(VarDecl *VD) {
return Util::isSyclType(VD->getType(), "private_memory", true /*Tmpl*/);
}
static void addScopeAttrToLocalVars(CXXMethodDecl &F) {
for (Decl *D : F.decls()) {
VarDecl *VD = dyn_cast<VarDecl>(D);
if (!VD || isa<ParmVarDecl>(VD) ||
VD->getStorageDuration() != StorageDuration::SD_Automatic)
continue;
// Local variables of private_memory type in the WG scope still have WI
// scope, all the rest - WG scope. Simple logic
// "if no scope than it is WG scope" won't work, because compiler may add
// locals not declared in user code (lambda object parameter, byval
// arguments) which will result in alloca w/o any attribute, so need WI
// scope too.
SYCLScopeAttr::Level L = isSYCLPrivateMemoryVar(VD)
? SYCLScopeAttr::Level::WorkItem
: SYCLScopeAttr::Level::WorkGroup;
VD->addAttr(SYCLScopeAttr::CreateImplicit(F.getASTContext(), L));
}
}
/// Return method by name
static CXXMethodDecl *getMethodByName(const CXXRecordDecl *CRD,
const std::string &MethodName) {
CXXMethodDecl *Method;
auto It = std::find_if(CRD->methods().begin(), CRD->methods().end(),
[&MethodName](const CXXMethodDecl *Method) {
return Method->getNameAsString() == MethodName;
});
Method = (It != CRD->methods().end()) ? *It : nullptr;
return Method;
}
static KernelInvocationKind
getKernelInvocationKind(FunctionDecl *KernelCallerFunc) {
return llvm::StringSwitch<KernelInvocationKind>(KernelCallerFunc->getName())
.Case("kernel_single_task", InvokeSingleTask)
.Case("kernel_parallel_for", InvokeParallelFor)
.Case("kernel_parallel_for_work_group", InvokeParallelForWorkGroup)
.Default(InvokeUnknown);
}
static CXXRecordDecl *getKernelObjectType(FunctionDecl *Caller) {
return (*Caller->param_begin())->getType()->getAsCXXRecordDecl();
}
/// Creates a kernel parameter descriptor
/// \param Src field declaration to construct name from
/// \param Ty the desired parameter type
/// \return the constructed descriptor
static ParamDesc makeParamDesc(const FieldDecl *Src, QualType Ty) {
ASTContext &Ctx = Src->getASTContext();
std::string Name = (Twine("_arg_") + Src->getName()).str();
return std::make_tuple(Ty, &Ctx.Idents.get(Name),
Ctx.getTrivialTypeSourceInfo(Ty));
}
static ParamDesc makeParamDesc(ASTContext &Ctx, const CXXBaseSpecifier &Src,
QualType Ty) {
// TODO: There is no name for the base available, but duplicate names are
// seemingly already possible, so we'll give them all the same name for now.
// This only happens with the accessor types.
std::string Name = "_arg__base";
return std::make_tuple(Ty, &Ctx.Idents.get(Name),
Ctx.getTrivialTypeSourceInfo(Ty));
}
/// \return the target of given SYCL accessor type
static target getAccessTarget(const ClassTemplateSpecializationDecl *AccTy) {
return static_cast<target>(
AccTy->getTemplateArgs()[3].getAsIntegral().getExtValue());
}
// The first template argument to the kernel caller function is used to identify
// the kernel itself.
static QualType calculateKernelNameType(ASTContext &Ctx,
FunctionDecl *KernelCallerFunc) {
const TemplateArgumentList *TAL =
KernelCallerFunc->getTemplateSpecializationArgs();
assert(TAL && "No template argument info");
return TAL->get(0).getAsType().getCanonicalType();
}
// Gets a name for the OpenCL kernel function, calculated from the first
// template argument of the kernel caller function.
static std::pair<std::string, std::string>
constructKernelName(Sema &S, FunctionDecl *KernelCallerFunc,
MangleContext &MC) {
QualType KernelNameType =
calculateKernelNameType(S.getASTContext(), KernelCallerFunc);
SmallString<256> Result;
llvm::raw_svector_ostream Out(Result);
MC.mangleTypeName(KernelNameType, Out);
return {std::string(Out.str()),
PredefinedExpr::ComputeName(S.getASTContext(),
PredefinedExpr::UniqueStableNameType,
KernelNameType)};
}
// anonymous namespace so these don't get linkage.
namespace {
template <typename T> struct bind_param { using type = T; };
template <> struct bind_param<CXXBaseSpecifier &> {
using type = const CXXBaseSpecifier &;
};
template <> struct bind_param<FieldDecl *&> { using type = FieldDecl *; };
template <> struct bind_param<FieldDecl *const &> { using type = FieldDecl *; };
template <typename T> using bind_param_t = typename bind_param<T>::type;
class KernelObjVisitor {
Sema &SemaRef;
public:
KernelObjVisitor(Sema &S) : SemaRef(S) {}
// These enable handler execution only when previous handlers succeed.
template <typename... Tn>
bool handleField(FieldDecl *FD, QualType FDTy, Tn &&... tn) {
bool result = true;
std::initializer_list<int>{(result = result && tn(FD, FDTy), 0)...};
return result;
}
template <typename... Tn>
bool handleField(const CXXBaseSpecifier &BD, QualType BDTy, Tn &&... tn) {
bool result = true;
std::initializer_list<int>{(result = result && tn(BD, BDTy), 0)...};
return result;
}
// This definition using std::bind is necessary because of a gcc 7.x bug.
#define KF_FOR_EACH(FUNC, Item, Qt) \
handleField( \
Item, Qt, \
std::bind(static_cast<bool (std::decay_t<decltype(handlers)>::*)( \
bind_param_t<decltype(Item)>, QualType)>( \
&std::decay_t<decltype(handlers)>::FUNC), \
std::ref(handlers), _1, _2)...)
// The following simpler definition works with gcc 8.x and later.
//#define KF_FOR_EACH(FUNC) \
// handleField(Field, FieldTy, ([&](FieldDecl *FD, QualType FDTy) { \
// return handlers.f(FD, FDTy); \
// })...)
// Implements the 'for-each-visitor' pattern.
template <typename... Handlers>
void VisitElement(CXXRecordDecl *Owner, FieldDecl *ArrayField,
QualType ElementTy, Handlers &... handlers) {
if (Util::isSyclAccessorType(ElementTy))
KF_FOR_EACH(handleSyclAccessorType, ArrayField, ElementTy);
else if (Util::isSyclStreamType(ElementTy))
KF_FOR_EACH(handleSyclStreamType, ArrayField, ElementTy);
else if (Util::isSyclSamplerType(ElementTy))
KF_FOR_EACH(handleSyclSamplerType, ArrayField, ElementTy);
else if (Util::isSyclHalfType(ElementTy))
KF_FOR_EACH(handleSyclHalfType, ArrayField, ElementTy);
else if (ElementTy->isStructureOrClassType())
VisitRecord(Owner, ArrayField, ElementTy->getAsCXXRecordDecl(),
handlers...);
else if (ElementTy->isArrayType())
VisitArrayElements(ArrayField, ElementTy, handlers...);
else if (ElementTy->isScalarType())
KF_FOR_EACH(handleScalarType, ArrayField, ElementTy);
}
template <typename... Handlers>
void VisitArrayElements(FieldDecl *FD, QualType FieldTy,
Handlers &... handlers) {
const ConstantArrayType *CAT = cast<ConstantArrayType>(FieldTy);
QualType ET = CAT->getElementType();
int64_t ElemCount = CAT->getSize().getSExtValue();
std::initializer_list<int>{(handlers.enterArray(), 0)...};
for (int64_t Count = 0; Count < ElemCount; Count++) {
VisitElement(nullptr, FD, ET, handlers...);
(void)std::initializer_list<int>{(handlers.nextElement(ET), 0)...};
}
(void)std::initializer_list<int>{
(handlers.leaveArray(FD, ET, ElemCount), 0)...};
}
template <typename ParentTy, typename... Handlers>
void VisitRecord(CXXRecordDecl *Owner, ParentTy &Parent,
CXXRecordDecl *Wrapper, Handlers &... handlers);
template <typename... Handlers>
void VisitRecordHelper(CXXRecordDecl *Owner,
clang::CXXRecordDecl::base_class_range Range,
Handlers &... handlers) {
for (const auto &Base : Range) {
(void)std::initializer_list<int>{
(handlers.enterField(Owner, Base), 0)...};
QualType BaseTy = Base.getType();
// Handle accessor class as base
if (Util::isSyclAccessorType(BaseTy)) {
(void)std::initializer_list<int>{
(handlers.handleSyclAccessorType(Base, BaseTy), 0)...};
} else if (Util::isSyclStreamType(BaseTy)) {
// Handle stream class as base
(void)std::initializer_list<int>{
(handlers.handleSyclStreamType(Base, BaseTy), 0)...};
} else
// For all other bases, visit the record
VisitRecord(Owner, Base, BaseTy->getAsCXXRecordDecl(), handlers...);
(void)std::initializer_list<int>{
(handlers.leaveField(Owner, Base), 0)...};
}
}
template <typename... Handlers>
void VisitRecordHelper(CXXRecordDecl *Owner,
clang::RecordDecl::field_range Range,
Handlers &... handlers) {
VisitRecordFields(Owner, handlers...);
}
// FIXME: Can this be refactored/handled some other way?
template <typename ParentTy, typename... Handlers>
void VisitStreamRecord(CXXRecordDecl *Owner, ParentTy &Parent,
CXXRecordDecl *Wrapper, Handlers &... handlers) {
(void)std::initializer_list<int>{
(handlers.enterStruct(Owner, Parent), 0)...};
for (const auto &Field : Wrapper->fields()) {
QualType FieldTy = Field->getType();
(void)std::initializer_list<int>{
(handlers.enterField(Wrapper, Field), 0)...};
// Required to initialize accessors inside streams.
if (Util::isSyclAccessorType(FieldTy))
KF_FOR_EACH(handleSyclAccessorType, Field, FieldTy);
(void)std::initializer_list<int>{
(handlers.leaveField(Wrapper, Field), 0)...};
}
(void)std::initializer_list<int>{
(handlers.leaveStruct(Owner, Parent), 0)...};
}
template <typename... Handlers>
void VisitRecordBases(CXXRecordDecl *KernelFunctor, Handlers &... handlers) {
VisitRecordHelper(KernelFunctor, KernelFunctor->bases(), handlers...);
}
// A visitor function that dispatches to functions as defined in
// SyclKernelFieldHandler for the purposes of kernel generation.
template <typename... Handlers>
void VisitRecordFields(CXXRecordDecl *Owner, Handlers &... handlers) {
for (const auto Field : Owner->fields()) {
(void)std::initializer_list<int>{
(handlers.enterField(Owner, Field), 0)...};
QualType FieldTy = Field->getType();
if (Util::isSyclAccessorType(FieldTy))
KF_FOR_EACH(handleSyclAccessorType, Field, FieldTy);
else if (Util::isSyclSamplerType(FieldTy))
KF_FOR_EACH(handleSyclSamplerType, Field, FieldTy);
else if (Util::isSyclHalfType(FieldTy))
KF_FOR_EACH(handleSyclHalfType, Field, FieldTy);
else if (Util::isSyclSpecConstantType(FieldTy))
KF_FOR_EACH(handleSyclSpecConstantType, Field, FieldTy);
else if (Util::isSyclStreamType(FieldTy)) {
CXXRecordDecl *RD = FieldTy->getAsCXXRecordDecl();
// Handle accessors in stream class.
VisitStreamRecord(Owner, Field, RD, handlers...);
KF_FOR_EACH(handleSyclStreamType, Field, FieldTy);
} else if (FieldTy->isStructureOrClassType()) {
if (KF_FOR_EACH(handleStructType, Field, FieldTy)) {
CXXRecordDecl *RD = FieldTy->getAsCXXRecordDecl();
VisitRecord(Owner, Field, RD, handlers...);
}
} else if (FieldTy->isReferenceType())
KF_FOR_EACH(handleReferenceType, Field, FieldTy);
else if (FieldTy->isPointerType())
KF_FOR_EACH(handlePointerType, Field, FieldTy);
else if (FieldTy->isArrayType()) {
if (KF_FOR_EACH(handleArrayType, Field, FieldTy))
VisitArrayElements(Field, FieldTy, handlers...);
} else if (FieldTy->isScalarType() || FieldTy->isVectorType())
KF_FOR_EACH(handleScalarType, Field, FieldTy);
else
KF_FOR_EACH(handleOtherType, Field, FieldTy);
(void)std::initializer_list<int>{
(handlers.leaveField(Owner, Field), 0)...};
}
}
#undef KF_FOR_EACH
};
// Parent contains the FieldDecl or CXXBaseSpecifier that was used to enter
// the Wrapper structure that we're currently visiting. Owner is the parent
// type (which doesn't exist in cases where it is a FieldDecl in the
// 'root'), and Wrapper is the current struct being unwrapped.
template <typename ParentTy, typename... Handlers>
void KernelObjVisitor::VisitRecord(CXXRecordDecl *Owner, ParentTy &Parent,
CXXRecordDecl *Wrapper,
Handlers &... handlers) {
(void)std::initializer_list<int>{(handlers.enterStruct(Owner, Parent), 0)...};
VisitRecordHelper(Wrapper, Wrapper->bases(), handlers...);
VisitRecordHelper(Wrapper, Wrapper->fields(), handlers...);
(void)std::initializer_list<int>{(handlers.leaveStruct(Owner, Parent), 0)...};
}
// A base type that the SYCL OpenCL Kernel construction task uses to implement
// individual tasks.
template <typename Derived> class SyclKernelFieldHandler {
protected:
Sema &SemaRef;
SyclKernelFieldHandler(Sema &S) : SemaRef(S) {}
public:
// Mark these virtual so that we can use override in the implementer classes,
// despite virtual dispatch never being used.
// Accessor can be a base class or a field decl, so both must be handled.
virtual bool handleSyclAccessorType(const CXXBaseSpecifier &, QualType) {
return true;
}
virtual bool handleSyclAccessorType(FieldDecl *, QualType) { return true; }
virtual bool handleSyclSamplerType(const CXXBaseSpecifier &, QualType) {
return true;
}
virtual bool handleSyclSamplerType(FieldDecl *, QualType) { return true; }
virtual bool handleSyclSpecConstantType(FieldDecl *, QualType) {
return true;
}
virtual bool handleSyclStreamType(const CXXBaseSpecifier &, QualType) {
return true;
}
virtual bool handleSyclStreamType(FieldDecl *, QualType) { return true; }
virtual bool handleSyclHalfType(const CXXBaseSpecifier &, QualType) {
return true;
}
virtual bool handleSyclHalfType(FieldDecl *, QualType) { return true; }
virtual bool handleStructType(FieldDecl *, QualType) { return true; }
virtual bool handleReferenceType(FieldDecl *, QualType) { return true; }
virtual bool handlePointerType(FieldDecl *, QualType) { return true; }
virtual bool handleArrayType(FieldDecl *, QualType) { return true; }
virtual bool handleScalarType(const CXXBaseSpecifier &, QualType) {
return true;
}
virtual bool handleScalarType(FieldDecl *, QualType) { return true; }
// Most handlers shouldn't be handling this, just the field checker.
virtual bool handleOtherType(FieldDecl *, QualType) { return true; }
// The following are only used for keeping track of where we are in the base
// class/field graph. Int Headers use this to calculate offset, most others
// don't have a need for these.
virtual bool enterStruct(const CXXRecordDecl *, FieldDecl *) { return true; }
virtual bool leaveStruct(const CXXRecordDecl *, FieldDecl *) { return true; }
virtual bool enterStruct(const CXXRecordDecl *, const CXXBaseSpecifier &) {
return true;
}
virtual bool leaveStruct(const CXXRecordDecl *, const CXXBaseSpecifier &) {
return true;
}
// The following are used for stepping through array elements.
virtual bool enterField(const CXXRecordDecl *, const CXXBaseSpecifier &) {
return true;
}
virtual bool leaveField(const CXXRecordDecl *, const CXXBaseSpecifier &) {
return true;
}
virtual bool enterField(const CXXRecordDecl *, FieldDecl *) { return true; }
virtual bool leaveField(const CXXRecordDecl *, FieldDecl *) { return true; }