forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaSYCL.cpp
1415 lines (1260 loc) · 54.5 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/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>
using namespace clang;
typedef llvm::DenseMap<DeclaratorDecl *, DeclaratorDecl *> DeclMap;
using KernelParamKind = SYCLIntegrationHeader::kernel_param_kind_t;
enum target {
global_buffer = 2014,
constant_buffer,
local,
image,
host_buffer,
host_image,
image_array
};
enum RestrictKind {
KernelGlobalVariable,
KernelRTTI,
KernelNonConstStaticDataVariable,
KernelCallVirtualFunction,
KernelCallRecursiveFunction,
KernelCallFunctionPointer,
KernelAllocateStorage,
KernelUseExceptions,
KernelUseAssembly
};
using ParamDesc = std::tuple<QualType, IdentifierInfo *, TypeSourceInfo *>;
/// 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 the SYCL stream class.
static bool isSyclStreamType(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);
};
static CXXRecordDecl *getKernelObjectType(FunctionDecl *Caller) {
return (*Caller->param_begin())->getType()->getAsCXXRecordDecl();
}
class MarkDeviceFunction : public RecursiveASTVisitor<MarkDeviceFunction> {
public:
MarkDeviceFunction(Sema &S)
: RecursiveASTVisitor<MarkDeviceFunction>(), SemaRef(S) {}
bool VisitCallExpr(CallExpr *e) {
for (const auto &Arg : e->arguments())
CheckSYCLType(Arg->getType(), Arg->getSourceRange());
if (FunctionDecl *Callee = e->getDirectCallee()) {
Callee = Callee->getCanonicalDecl();
// 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)
<< KernelCallRecursiveFunction;
SemaRef.Diag(Callee->getSourceRange().getBegin(),
diag::note_sycl_recursive_function_declared_here)
<< KernelCallRecursiveFunction;
}
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Callee))
if (Method->isVirtual())
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< KernelCallVirtualFunction;
CheckSYCLType(Callee->getReturnType(), Callee->getSourceRange());
if (FunctionDecl *Def = Callee->getDefinition()) {
if (!Def->hasAttr<SYCLDeviceAttr>()) {
Def->addAttr(SYCLDeviceAttr::CreateImplicit(SemaRef.Context));
SemaRef.AddSyclKernel(Def);
}
}
} else if (!SemaRef.getLangOpts().SYCLAllowFuncPtr)
SemaRef.Diag(e->getExprLoc(), diag::err_sycl_restrict)
<< KernelCallFunctionPointer;
return true;
}
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
for (const auto &Arg : E->arguments())
CheckSYCLType(Arg->getType(), Arg->getSourceRange());
CXXConstructorDecl *Ctor = E->getConstructor();
if (FunctionDecl *Def = Ctor->getDefinition()) {
Def->addAttr(SYCLDeviceAttr::CreateImplicit(SemaRef.Context));
SemaRef.AddSyclKernel(Def);
}
const auto *ConstructedType = Ctor->getParent();
if (ConstructedType->hasUserDeclaredDestructor()) {
CXXDestructorDecl *Dtor = ConstructedType->getDestructor();
if (FunctionDecl *Def = Dtor->getDefinition()) {
Def->addAttr(SYCLDeviceAttr::CreateImplicit(SemaRef.Context));
SemaRef.AddSyclKernel(Def);
}
}
return true;
}
bool VisitCXXTypeidExpr(CXXTypeidExpr *E) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict) << KernelRTTI;
return true;
}
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict) << KernelRTTI;
return true;
}
bool VisitTypedefNameDecl(TypedefNameDecl *TD) {
CheckSYCLType(TD->getUnderlyingType(), TD->getLocation());
return true;
}
bool VisitRecordDecl(RecordDecl *RD) {
CheckSYCLType(QualType{RD->getTypeForDecl(), 0}, RD->getLocation());
return true;
}
bool VisitParmVarDecl(VarDecl *VD) {
CheckSYCLType(VD->getType(), VD->getLocation());
return true;
}
bool VisitVarDecl(VarDecl *VD) {
CheckSYCLType(VD->getType(), VD->getLocation());
return true;
}
bool VisitMemberExpr(MemberExpr *E) {
if (VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
bool IsConst = VD->getType().getNonReferenceType().isConstQualified();
if (!IsConst && VD->isStaticDataMember())
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict)
<< KernelNonConstStaticDataVariable;
}
return true;
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
CheckSYCLType(E->getType(), E->getSourceRange());
if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
bool IsConst = VD->getType().getNonReferenceType().isConstQualified();
if (!IsConst && VD->isStaticDataMember())
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict)
<< KernelNonConstStaticDataVariable;
else if (!IsConst && VD->hasGlobalStorage() && !VD->isStaticLocal() &&
!VD->isStaticDataMember() && !isa<ParmVarDecl>(VD))
SemaRef.Diag(E->getLocation(), diag::err_sycl_restrict)
<< KernelGlobalVariable;
}
return true;
}
bool VisitCXXNewExpr(CXXNewExpr *E) {
// Memory storage allocation is not allowed in kernels.
// All memory allocation for the device is done on
// the host using accessor classes. Consequently, the default
// allocation operator new overloads that allocate
// storage are disallowed in a SYCL kernel. The placement
// new operator and any user-defined overloads that
// do not allocate storage are permitted.
if (FunctionDecl *FD = E->getOperatorNew()) {
if (FD->isReplaceableGlobalAllocationFunction()) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict)
<< KernelAllocateStorage;
} else if (FunctionDecl *Def = FD->getDefinition()) {
if (!Def->hasAttr<SYCLDeviceAttr>()) {
Def->addAttr(SYCLDeviceAttr::CreateImplicit(SemaRef.Context));
SemaRef.AddSyclKernel(Def);
}
}
}
return true;
}
bool VisitCXXThrowExpr(CXXThrowExpr *E) {
SemaRef.Diag(E->getExprLoc(), diag::err_sycl_restrict)
<< KernelUseExceptions;
return true;
}
bool VisitCXXCatchStmt(CXXCatchStmt *S) {
SemaRef.Diag(S->getBeginLoc(), diag::err_sycl_restrict)
<< KernelUseExceptions;
return true;
}
bool VisitCXXTryStmt(CXXTryStmt *S) {
SemaRef.Diag(S->getBeginLoc(), diag::err_sycl_restrict)
<< KernelUseExceptions;
return true;
}
bool VisitSEHTryStmt(SEHTryStmt *S) {
SemaRef.Diag(S->getBeginLoc(), diag::err_sycl_restrict)
<< KernelUseExceptions;
return true;
}
bool VisitGCCAsmStmt(GCCAsmStmt *S) {
SemaRef.Diag(S->getBeginLoc(), diag::err_sycl_restrict)
<< KernelUseAssembly;
return true;
}
bool VisitMSAsmStmt(MSAsmStmt *S) {
SemaRef.Diag(S->getBeginLoc(), diag::err_sycl_restrict)
<< KernelUseAssembly;
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
void CollectPossibleKernelAttributes(FunctionDecl *SYCLKernel,
llvm::SmallPtrSet<Attr *, 4> &Attrs) {
llvm::SmallPtrSet<FunctionDecl *, 16> Visited;
llvm::SmallVector<FunctionDecl *, 16> WorkList;
WorkList.push_back(SYCLKernel);
while (!WorkList.empty()) {
FunctionDecl *FD = WorkList.back();
WorkList.pop_back();
if (!Visited.insert(FD).second)
continue; // We've already seen this Decl
if (auto *A = FD->getAttr<IntelReqdSubGroupSizeAttr>())
Attrs.insert(A);
// TODO: reqd_work_group_size, 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);
}
}
}
}
private:
bool CheckSYCLType(QualType Ty, SourceRange Loc) {
if (Ty->isVariableArrayType()) {
SemaRef.Diag(Loc.getBegin(), diag::err_vla_unsupported);
return false;
}
while (Ty->isAnyPointerType() || Ty->isArrayType())
Ty = QualType{Ty->getPointeeOrArrayElementType(), 0};
if (const auto *CRD = Ty->getAsCXXRecordDecl()) {
if (CRD->isPolymorphic()) {
SemaRef.Diag(CRD->getLocation(), diag::err_sycl_virtual_types);
SemaRef.Diag(Loc.getBegin(), diag::note_sycl_used_here);
return false;
}
for (const auto &Field : CRD->fields()) {
if (!CheckSYCLType(Field->getType(), Field->getSourceRange())) {
SemaRef.Diag(Loc.getBegin(), diag::note_sycl_used_here);
return false;
}
}
} else if (const auto *RD = Ty->getAsRecordDecl()) {
for (const auto &Field : RD->fields()) {
if (!CheckSYCLType(Field->getType(), Field->getSourceRange())) {
SemaRef.Diag(Loc.getBegin(), diag::note_sycl_used_here);
return false;
}
}
} else if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
for (const auto &ParamTy : FPTy->param_types())
if (!CheckSYCLType(ParamTy, Loc))
return false;
return CheckSYCLType(FPTy->getReturnType(), Loc);
} else if (const auto *FTy = dyn_cast<FunctionType>(Ty)) {
return CheckSYCLType(FTy->getReturnType(), Loc);
}
return true;
}
Sema &SemaRef;
};
class KernelBodyTransform : public TreeTransform<KernelBodyTransform> {
public:
KernelBodyTransform(llvm::DenseMap<DeclaratorDecl *, DeclaratorDecl *> &Map,
Sema &S)
: TreeTransform<KernelBodyTransform>(S), DMap(Map), SemaRef(S) {}
bool AlwaysRebuild() { return true; }
ExprResult TransformDeclRefExpr(DeclRefExpr *DRE) {
auto Ref = dyn_cast<DeclaratorDecl>(DRE->getDecl());
if (Ref) {
auto NewDecl = DMap[Ref];
if (NewDecl) {
return DeclRefExpr::Create(
SemaRef.getASTContext(), DRE->getQualifierLoc(),
DRE->getTemplateKeywordLoc(), NewDecl, false, DRE->getNameInfo(),
NewDecl->getType(), DRE->getValueKind());
}
}
return DRE;
}
private:
DeclMap DMap;
Sema &SemaRef;
};
static FunctionDecl *CreateSYCLKernelFunction(ASTContext &Context,
StringRef Name,
ArrayRef<ParamDesc> ParamDescs) {
DeclContext *DC = Context.getTranslationUnitDecl();
FunctionProtoType::ExtProtoInfo Info(CC_OpenCLKernel);
QualType RetTy = Context.VoidTy;
SmallVector<QualType, 8> ArgTys;
// extract argument types from the descriptor array:
std::transform(
ParamDescs.begin(), ParamDescs.end(), std::back_inserter(ArgTys),
[](const ParamDesc &PD) -> QualType { return std::get<0>(PD); });
QualType FuncTy = Context.getFunctionType(RetTy, ArgTys, Info);
DeclarationName DN = DeclarationName(&Context.Idents.get(Name));
FunctionDecl *SYCLKernel = FunctionDecl::Create(
Context, DC, SourceLocation(), SourceLocation(), DN, FuncTy,
Context.getTrivialTypeSourceInfo(RetTy), SC_None);
llvm::SmallVector<ParmVarDecl *, 16> Params;
int i = 0;
for (const auto &PD : ParamDescs) {
auto P = ParmVarDecl::Create(Context, SYCLKernel, SourceLocation(),
SourceLocation(), std::get<1>(PD),
std::get<0>(PD), std::get<2>(PD), SC_None, 0);
P->setScopeInfo(0, i++);
P->setIsUsed();
Params.push_back(P);
}
SYCLKernel->setParams(Params);
SYCLKernel->addAttr(SYCLDeviceAttr::CreateImplicit(Context));
SYCLKernel->addAttr(OpenCLKernelAttr::CreateImplicit(Context));
SYCLKernel->addAttr(AsmLabelAttr::CreateImplicit(Context, Name));
SYCLKernel->addAttr(ArtificialAttr::CreateImplicit(Context));
// To see kernel in AST-dump.
DC->addDecl(SYCLKernel);
return SYCLKernel;
}
/// Return __init method
static CXXMethodDecl *getInitMethod(const CXXRecordDecl *CRD) {
CXXMethodDecl *InitMethod;
auto It = std::find_if(CRD->methods().begin(), CRD->methods().end(),
[](const CXXMethodDecl *Method) {
return Method->getNameAsString() == "__init";
});
InitMethod = (It != CRD->methods().end()) ? *It : nullptr;
return InitMethod;
}
static CompoundStmt *
CreateSYCLKernelBody(Sema &S, FunctionDecl *KernelCallerFunc, DeclContext *DC) {
llvm::SmallVector<Stmt *, 16> BodyStmts;
CXXRecordDecl *LC = getKernelObjectType(KernelCallerFunc);
assert(LC && "Kernel object must be available");
TypeSourceInfo *TSInfo = LC->isLambda() ? LC->getLambdaTypeInfo() : nullptr;
// Create a local kernel object (lambda or functor) assembled from the
// incoming formal parameters
auto KernelObjClone = VarDecl::Create(
S.Context, DC, SourceLocation(), SourceLocation(), LC->getIdentifier(),
QualType(LC->getTypeForDecl(), 0), TSInfo, SC_None);
Stmt *DS = new (S.Context) DeclStmt(DeclGroupRef(KernelObjClone),
SourceLocation(), SourceLocation());
BodyStmts.push_back(DS);
auto CloneRef =
DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(), SourceLocation(),
KernelObjClone, false, DeclarationNameInfo(),
QualType(LC->getTypeForDecl(), 0), VK_LValue);
auto TargetFunc = dyn_cast<FunctionDecl>(DC);
assert(TargetFunc && "Not FunctionDecl");
auto TargetFuncParam =
TargetFunc->param_begin(); // Iterator to ParamVarDecl (VarDecl)
if (TargetFuncParam) {
for (auto Field : LC->fields()) {
auto getExprForPointer = [](Sema &S, const QualType ¶mTy,
DeclRefExpr *DRE) {
// C++ address space attribute != OpenCL address space attribute
Expr *qualifiersCast = ImplicitCastExpr::Create(
S.Context, paramTy, CK_NoOp, DRE, nullptr, VK_LValue);
Expr *Res =
ImplicitCastExpr::Create(S.Context, paramTy, CK_LValueToRValue,
qualifiersCast, nullptr, VK_RValue);
return Res;
};
auto getExprForRangeOrOffset = [](Sema &S, const QualType ¶mTy,
DeclRefExpr *DRE) {
Expr *Res = ImplicitCastExpr::Create(S.Context, paramTy, CK_NoOp, DRE,
nullptr, VK_RValue);
return Res;
};
auto getExprForAccessorInit = [&](const QualType ¶mTy,
FieldDecl *Field,
const CXXRecordDecl *CRD, Expr *Base) {
// Since this is an accessor next 4 TargetFuncParams including current
// should be set in __init method: _ValueType*, range<int>, range<int>,
// id<int>
const size_t NumParams = 4;
llvm::SmallVector<DeclRefExpr *, NumParams> ParamDREs(NumParams);
auto TFP = TargetFuncParam;
for (size_t I = 0; I < NumParams; ++TFP, ++I) {
QualType ParamType = (*TFP)->getOriginalType();
ParamDREs[I] = DeclRefExpr::Create(
S.Context, NestedNameSpecifierLoc(), SourceLocation(), *TFP,
false, DeclarationNameInfo(), ParamType, VK_LValue);
}
std::advance(TargetFuncParam, NumParams - 1);
DeclAccessPair FieldDAP = DeclAccessPair::make(Field, AS_none);
// [kenrel_obj or wrapper object].accessor
auto AccessorME = MemberExpr::Create(
S.Context, Base, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), Field, FieldDAP,
DeclarationNameInfo(Field->getDeclName(), SourceLocation()),
nullptr, Field->getType(), VK_LValue, OK_Ordinary);
CXXMethodDecl *InitMethod = getInitMethod(CRD);
assert(InitMethod && "The accessor must have the __init method");
// [kenrel_obj or wrapper object].accessor.__init
DeclAccessPair MethodDAP = DeclAccessPair::make(InitMethod, AS_none);
auto ME = MemberExpr::Create(
S.Context, AccessorME, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), InitMethod, MethodDAP,
InitMethod->getNameInfo(), nullptr, InitMethod->getType(),
VK_LValue, OK_Ordinary);
// Not referenced -> not emitted
S.MarkFunctionReferenced(SourceLocation(), InitMethod, true);
QualType ResultTy = InitMethod->getReturnType();
ExprValueKind VK = Expr::getValueKindForType(ResultTy);
ResultTy = ResultTy.getNonLValueExprType(S.Context);
// __init needs four parameter
auto ParamItr = InitMethod->param_begin();
// kernel_parameters
llvm::SmallVector<Expr *, NumParams> ParamStmts;
ParamStmts.push_back(getExprForPointer(
S, (*(ParamItr++))->getOriginalType(), ParamDREs[0]));
ParamStmts.push_back(getExprForRangeOrOffset(
S, ((*ParamItr++))->getOriginalType(), ParamDREs[1]));
ParamStmts.push_back(getExprForRangeOrOffset(
S, ((*ParamItr++))->getOriginalType(), ParamDREs[2]));
ParamStmts.push_back(getExprForRangeOrOffset(
S, ((*ParamItr++))->getOriginalType(), ParamDREs[3]));
// [kenrel_obj or wrapper object].accessor.__init(_ValueType*,
// range<int>, range<int>, id<int>)
CXXMemberCallExpr *Call = CXXMemberCallExpr::Create(
S.Context, ME, ParamStmts, ResultTy, VK, SourceLocation());
BodyStmts.push_back(Call);
};
// Recursively search for accessor fields to initialize them with kernel
// parameters
std::function<void(const CXXRecordDecl *, Expr *)>
getExprForWrappedAccessorInit = [&](const CXXRecordDecl *CRD,
Expr *Base) {
for (auto *WrapperFld : CRD->fields()) {
QualType FldType = WrapperFld->getType();
CXXRecordDecl *WrapperFldCRD = FldType->getAsCXXRecordDecl();
if (FldType->isStructureOrClassType()) {
if (Util::isSyclAccessorType(FldType)) {
// Accessor field found - create expr to initialize this
// accessor object. Need to start from the next target
// function parameter, since current one is the wrapper object
// or parameter of the previous processed accessor object.
TargetFuncParam++;
getExprForAccessorInit(FldType, WrapperFld, WrapperFldCRD,
Base);
} else {
// Field is a structure or class so change the wrapper object
// and recursively search for accessor field.
DeclAccessPair WrapperFieldDAP =
DeclAccessPair::make(WrapperFld, AS_none);
auto NewBase = MemberExpr::Create(
S.Context, Base, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), WrapperFld,
WrapperFieldDAP,
DeclarationNameInfo(WrapperFld->getDeclName(),
SourceLocation()),
nullptr, WrapperFld->getType(), VK_LValue, OK_Ordinary);
getExprForWrappedAccessorInit(WrapperFldCRD, NewBase);
}
}
}
};
QualType FieldType = Field->getType();
CXXRecordDecl *CRD = FieldType->getAsCXXRecordDecl();
if (Util::isSyclAccessorType(FieldType)) {
getExprForAccessorInit(FieldType, Field, CRD, CloneRef);
} else if (CRD && Util::isSyclSamplerType(FieldType)) {
// Sampler has only one TargetFuncParam, which should be set in
// __init method: _ValueType
const size_t NumParams = 1;
llvm::SmallVector<DeclRefExpr *, NumParams> ParamDREs(NumParams);
auto TFP = TargetFuncParam;
QualType ParamType = (*TFP)->getOriginalType();
ParamDREs[0] = DeclRefExpr::Create(
S.Context, NestedNameSpecifierLoc(), SourceLocation(), *TFP,
false, DeclarationNameInfo(), ParamType, VK_LValue);
DeclAccessPair FieldDAP = DeclAccessPair::make(Field, AS_none);
// kernel_obj.sampler
auto SamplerME = MemberExpr::Create(
S.Context, CloneRef, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), Field, FieldDAP,
DeclarationNameInfo(Field->getDeclName(), SourceLocation()),
nullptr, Field->getType(), VK_LValue, OK_Ordinary);
CXXMethodDecl *InitMethod = getInitMethod(CRD);
assert(InitMethod && "The sampler must have the __init method");
// kernel_obj.sampler.__init
DeclAccessPair MethodDAP = DeclAccessPair::make(InitMethod, AS_none);
auto ME = MemberExpr::Create(
S.Context, SamplerME, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), InitMethod, MethodDAP,
InitMethod->getNameInfo(), nullptr, InitMethod->getType(),
VK_LValue, OK_Ordinary);
// Not referenced -> not emitted
S.MarkFunctionReferenced(SourceLocation(), InitMethod, true);
QualType ResultTy = InitMethod->getReturnType();
ExprValueKind VK = Expr::getValueKindForType(ResultTy);
ResultTy = ResultTy.getNonLValueExprType(S.Context);
// __init needs one parameter
auto ParamItr = InitMethod->param_begin();
// kernel_parameters
llvm::SmallVector<Expr *, NumParams> ParamStmts;
ParamStmts.push_back(getExprForPointer(
S, (*ParamItr)->getOriginalType(), ParamDREs[0]));
CXXMemberCallExpr *Call = CXXMemberCallExpr::Create(
S.Context, ME, ParamStmts, ResultTy, VK, SourceLocation());
BodyStmts.push_back(Call);
} else if (CRD || FieldType->isScalarType()) {
// If field have built-in or a structure/class type just initialize
// this field with corresponding kernel argument using '=' binary
// operator. The structure/class type must be copy assignable - this
// holds because SYCL kernel lambdas capture arguments by copy.
QualType ParamType = (*TargetFuncParam)->getOriginalType();
auto DRE =
DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
SourceLocation(), *TargetFuncParam, false,
DeclarationNameInfo(), ParamType, VK_LValue);
DeclAccessPair FieldDAP = DeclAccessPair::make(Field, AS_none);
auto Lhs = MemberExpr::Create(
S.Context, CloneRef, false, SourceLocation(),
NestedNameSpecifierLoc(), SourceLocation(), Field, FieldDAP,
DeclarationNameInfo(Field->getDeclName(), SourceLocation()),
nullptr, Field->getType(), VK_LValue, OK_Ordinary);
auto Rhs = ImplicitCastExpr::Create(
S.Context, ParamType, CK_LValueToRValue, DRE, nullptr, VK_RValue);
// lambda.field = kernel_parameter
Expr *Res = new (S.Context)
BinaryOperator(Lhs, Rhs, BO_Assign, FieldType, VK_LValue,
OK_Ordinary, SourceLocation(), FPOptions());
BodyStmts.push_back(Res);
// If a structure/class type has accessor fields then we need to
// initialize these accessors in proper way by calling __init method of
// the accessor and passing corresponding kernel parameters.
if (CRD)
getExprForWrappedAccessorInit(CRD, Lhs);
} else {
llvm_unreachable("unsupported field type");
}
TargetFuncParam++;
}
}
// In function from headers lambda is function parameter, we need
// to replace all refs to this lambda with our vardecl.
// I used TreeTransform here, but I'm not sure that it is good solution
// Also I used map and I'm not sure about it too.
// TODO SYCL review the above design concerns
Stmt *FunctionBody = KernelCallerFunc->getBody();
DeclMap DMap;
ParmVarDecl *KernelObjParam = *(KernelCallerFunc->param_begin());
// DeclRefExpr with valid source location but with decl which is not marked
// as used is invalid.
KernelObjClone->setIsUsed();
DMap[KernelObjParam] = KernelObjClone;
// Without PushFunctionScope I had segfault. Maybe we also need to do pop.
S.PushFunctionScope();
KernelBodyTransform KBT(DMap, S);
Stmt *NewBody = KBT.TransformStmt(FunctionBody).get();
BodyStmts.push_back(NewBody);
return CompoundStmt::Create(S.Context, BodyStmts, SourceLocation(),
SourceLocation());
}
/// 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));
}
/// \return the target of given SYCL accessor type
static target getAccessTarget(const ClassTemplateSpecializationDecl *AccTy) {
return static_cast<target>(
AccTy->getTemplateArgs()[3].getAsIntegral().getExtValue());
}
static void buildArgTys(ASTContext &Context, CXXRecordDecl *KernelObj,
SmallVectorImpl<ParamDesc> &ParamDescs) {
const LambdaCapture *Cpt = KernelObj->captures_begin();
auto CreateAndAddPrmDsc = [&](const FieldDecl *Fld, const QualType &ArgType) {
// create a parameter descriptor and append it to the result
ParamDescs.push_back(makeParamDesc(Fld, ArgType));
};
auto createAccessorParamDesc = [&](const FieldDecl *Fld,
const QualType &ArgTy) {
// the parameter is a SYCL accessor object
const auto *RecordDecl = ArgTy->getAsCXXRecordDecl();
assert(RecordDecl && "accessor must be of a record type");
const auto *TemplateDecl =
cast<ClassTemplateSpecializationDecl>(RecordDecl);
// First accessor template parameter - data type
QualType PointeeType = TemplateDecl->getTemplateArgs()[0].getAsType();
// Fourth parameter - access target
target AccessTarget = getAccessTarget(TemplateDecl);
Qualifiers Quals = PointeeType.getQualifiers();
// TODO: Support all access targets
switch (AccessTarget) {
case target::global_buffer:
Quals.setAddressSpace(LangAS::opencl_global);
break;
case target::constant_buffer:
Quals.setAddressSpace(LangAS::opencl_constant);
break;
case target::local:
Quals.setAddressSpace(LangAS::opencl_local);
break;
default:
llvm_unreachable("Unsupported access target");
}
PointeeType =
Context.getQualifiedType(PointeeType.getUnqualifiedType(), Quals);
QualType PointerType = Context.getPointerType(PointeeType);
CreateAndAddPrmDsc(Fld, PointerType);
CXXMethodDecl *InitMethod = getInitMethod(RecordDecl);
assert(InitMethod && "accessor must have __init method");
// Expected accessor __init method has four parameters
// void __init(_ValueType *Ptr, range<dimensions> AccessRange,
// range<dimensions> MemRange, id<dimensions> Offset)
auto *FuncDecl = cast<FunctionDecl>(InitMethod);
ParmVarDecl *AccessRangeFld = FuncDecl->getParamDecl(1);
ParmVarDecl *MemRangeFld = FuncDecl->getParamDecl(2);
ParmVarDecl *OffsetFld = FuncDecl->getParamDecl(3);
assert(AccessRangeFld &&
"The accessor __init method must contain the AccessRange parameter");
assert(MemRangeFld &&
"The accessor __init method must contain the MemRange parameter");
assert(OffsetFld &&
"The accessor __init method must contain the Offset parameter");
CreateAndAddPrmDsc(Fld, AccessRangeFld->getType());
CreateAndAddPrmDsc(Fld, MemRangeFld->getType());
CreateAndAddPrmDsc(Fld, OffsetFld->getType());
};
std::function<void(const FieldDecl *, const QualType &ArgTy)>
createParamDescForWrappedAccessors =
[&](const FieldDecl *Fld, const QualType &ArgTy) {
const auto *Wrapper = ArgTy->getAsCXXRecordDecl();
for (const auto *WrapperFld : Wrapper->fields()) {
QualType FldType = WrapperFld->getType();
if (FldType->isStructureOrClassType()) {
if (Util::isSyclAccessorType(FldType)) {
// accessor field is found - create descriptor
createAccessorParamDesc(WrapperFld, FldType);
} else {
// field is some class or struct - recursively check for
// accessor fields
createParamDescForWrappedAccessors(WrapperFld, FldType);
}
}
}
};
for (const auto *Fld : KernelObj->fields()) {
QualType ArgTy = Fld->getType();
if (Util::isSyclAccessorType(ArgTy)) {
createAccessorParamDesc(Fld, ArgTy);
} else if (Util::isSyclSamplerType(ArgTy)) {
// the parameter is a SYCL sampler object
const auto *RecordDecl = ArgTy->getAsCXXRecordDecl();
assert(RecordDecl && "sampler must be of a record type");
CXXMethodDecl *InitMethod = getInitMethod(RecordDecl);
assert(InitMethod && "sampler must have __init method");
// sampler __init method has only one parameter
auto *FuncDecl = cast<FunctionDecl>(InitMethod);
ParmVarDecl *SamplerArg = FuncDecl->getParamDecl(0);
assert(SamplerArg && "sampler __init method must have sampler parameter");
CreateAndAddPrmDsc(Fld, SamplerArg->getType());
} else if (Util::isSyclStreamType(ArgTy)) {
// the parameter is a SYCL stream object
llvm_unreachable("streams not supported yet");
} else if (ArgTy->isStructureOrClassType()) {
if (!ArgTy->isStandardLayoutType()) {
const DeclaratorDecl *V =
Cpt ? cast<DeclaratorDecl>(Cpt->getCapturedVar())
: cast<DeclaratorDecl>(Fld);
KernelObj->getASTContext().getDiagnostics().Report(
V->getLocation(), diag::err_sycl_non_std_layout_type);
}
// structure or class typed parameter - the same handling as a scalar
CreateAndAddPrmDsc(Fld, ArgTy);
// create descriptors for each accessor field in the class or struct
createParamDescForWrappedAccessors(Fld, ArgTy);
} else if (ArgTy->isScalarType()) {
// scalar typed parameter
CreateAndAddPrmDsc(Fld, ArgTy);
} else {
llvm_unreachable("unsupported kernel parameter type");
}
}
}
/// Adds necessary data describing given kernel to the integration header.
/// \param H the integration header object
/// \param Name kernel name
/// \param NameType type representing kernel name (first template argument
/// of
/// single_task, parallel_for, etc)
/// \param KernelObjTy kernel object type
static void populateIntHeader(SYCLIntegrationHeader &H, const StringRef Name,
QualType NameType, CXXRecordDecl *KernelObjTy) {
ASTContext &Ctx = KernelObjTy->getASTContext();
const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(KernelObjTy);
H.startKernel(Name, NameType);
auto populateHeaderForAccessor = [&](const QualType &ArgTy, uint64_t Offset) {
// The parameter is a SYCL accessor object.
// The Info field of the parameter descriptor for accessor contains
// two template parameters packed into thid integer field:
// - target (e.g. global_buffer, constant_buffer, local);
// - dimension of the accessor.
const auto *AccTy = ArgTy->getAsCXXRecordDecl();
assert(AccTy && "accessor must be of a record type");
const auto *AccTmplTy = cast<ClassTemplateSpecializationDecl>(AccTy);
int Dims = static_cast<int>(
AccTmplTy->getTemplateArgs()[1].getAsIntegral().getExtValue());
int Info = getAccessTarget(AccTmplTy) | (Dims << 11);
H.addParamDesc(SYCLIntegrationHeader::kind_accessor, Info, Offset);
};
std::function<void(const QualType &, uint64_t Offset)>
populateHeaderForWrappedAccessors = [&](const QualType &ArgTy,
uint64_t Offset) {
const auto *Wrapper = ArgTy->getAsCXXRecordDecl();
for (const auto *WrapperFld : Wrapper->fields()) {
QualType FldType = WrapperFld->getType();
if (FldType->isStructureOrClassType()) {
ASTContext &WrapperCtx = Wrapper->getASTContext();
const ASTRecordLayout &WrapperLayout =
WrapperCtx.getASTRecordLayout(Wrapper);
// Get offset (in bytes) of the field in wrapper class or struct
uint64_t OffsetInWrapper =
WrapperLayout.getFieldOffset(WrapperFld->getFieldIndex()) / 8;
if (Util::isSyclAccessorType(FldType)) {
// This is an accesor - populate the header appropriately
populateHeaderForAccessor(FldType, Offset + OffsetInWrapper);
} else {
// This is an other class or struct - recursively search for an
// accessor field
populateHeaderForWrappedAccessors(FldType,
Offset + OffsetInWrapper);
}
}
}
};
for (const auto Fld : KernelObjTy->fields()) {
QualType ActualArgType;
QualType ArgTy = Fld->getType();
// Get offset in bytes
uint64_t Offset = Layout.getFieldOffset(Fld->getFieldIndex()) / 8;
if (Util::isSyclAccessorType(ArgTy)) {
populateHeaderForAccessor(ArgTy, Offset);
} else if (Util::isSyclSamplerType(ArgTy)) {
// The parameter is a SYCL sampler object
const auto *SamplerTy = ArgTy->getAsCXXRecordDecl();
assert(SamplerTy && "sampler must be of a record type");
CXXMethodDecl *InitMethod = getInitMethod(SamplerTy);
assert(InitMethod && "sampler must have __init method");
// sampler __init method has only one argument
auto *FuncDecl = cast<FunctionDecl>(InitMethod);
ParmVarDecl *SamplerArg = FuncDecl->getParamDecl(0);
assert(SamplerArg && "sampler __init method must have sampler parameter");
uint64_t Sz = Ctx.getTypeSizeInChars(SamplerArg->getType()).getQuantity();
H.addParamDesc(SYCLIntegrationHeader::kind_sampler,
static_cast<unsigned>(Sz), static_cast<unsigned>(Offset));
} else if (Util::isSyclStreamType(ArgTy)) {
// the parameter is a SYCL stream object
llvm_unreachable("streams not supported yet");
} else if (ArgTy->isStructureOrClassType() || ArgTy->isScalarType()) {
// the parameter is an object of standard layout type or scalar;
// the check for standard layout is done elsewhere
uint64_t Sz = Ctx.getTypeSizeInChars(Fld->getType()).getQuantity();
H.addParamDesc(SYCLIntegrationHeader::kind_std_layout,
static_cast<unsigned>(Sz), static_cast<unsigned>(Offset));
// check for accessor fields in structure or class and populate the
// integration header appropriately
if (ArgTy->isStructureOrClassType()) {
populateHeaderForWrappedAccessors(ArgTy, Offset);
}
} else {
llvm_unreachable("unsupported kernel parameter type");
}
}
}
// Removes all "(anonymous namespace)::" substrings from given string
static std::string eraseAnonNamespace(std::string S) {
const char S1[] = "(anonymous namespace)::";
for (auto Pos = S.find(S1); Pos != StringRef::npos; Pos = S.find(S1, Pos))
S.erase(Pos, sizeof(S1) - 1);
return S;
}
// Creates a mangled kernel name for given kernel name type
static std::string constructKernelName(QualType KernelNameType,
ASTContext &AC) {
std::unique_ptr<MangleContext> MC(AC.createMangleContext());
SmallString<256> Result;
llvm::raw_svector_ostream Out(Result);
MC->mangleTypeName(KernelNameType, Out);
return Out.str();
}
void Sema::ConstructSYCLKernel(FunctionDecl *KernelCallerFunc) {
// TODO: Case when kernel is functor
CXXRecordDecl *LE = getKernelObjectType(KernelCallerFunc);
assert(LE && "invalid kernel caller");
llvm::SmallVector<ParamDesc, 16> ParamDescs;
buildArgTys(getASTContext(), LE, ParamDescs);
// Get Name for our kernel.
const TemplateArgumentList *TemplateArgs =
KernelCallerFunc->getTemplateSpecializationArgs();
assert(TemplateArgs && "No template argument info");
// The first template argument always describes the kernel name - whether
// it is lambda or functor.
QualType KernelNameType = TypeName::getFullyQualifiedType(
TemplateArgs->get(0).getAsType(), getASTContext(), true);
std::string Name = constructKernelName(KernelNameType, getASTContext());
populateIntHeader(getSyclIntegrationHeader(), Name, KernelNameType, LE);
FunctionDecl *SYCLKernel =
CreateSYCLKernelFunction(getASTContext(), Name, ParamDescs);
// Let's copy source location of a functor/lambda to emit nicer diagnostics
SYCLKernel->setLocation(LE->getLocation());
CompoundStmt *SYCLKernelBody =
CreateSYCLKernelBody(*this, KernelCallerFunc, SYCLKernel);
SYCLKernel->setBody(SYCLKernelBody);
AddSyclKernel(SYCLKernel);
}
void Sema::MarkDevice(void) {
// Let's mark all called functions with SYCL Device attribute.
// Create the call graph so we can detect recursion and check the validity
// of new operator overrides. Add the kernel function itself in case
// it is recursive.
MarkDeviceFunction Marker(*this);
Marker.SYCLCG.addToCallGraph(getASTContext().getTranslationUnitDecl());
for (Decl *D : SyclKernels()) {
if (auto SYCLKernel = dyn_cast<FunctionDecl>(D)) {
llvm::SmallPtrSet<FunctionDecl *, 10> VisitedSet;