-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathAnalysisInfo.h
More file actions
3194 lines (2933 loc) · 122 KB
/
AnalysisInfo.h
File metadata and controls
3194 lines (2933 loc) · 122 KB
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
//===--------------- AnalysisInfo.h ---------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#ifndef DPCT_ANALYSIS_INFO_H
#define DPCT_ANALYSIS_INFO_H
#include "ErrorHandle/Error.h"
#include "RuleInfra/ExprAnalysis.h"
#include "ExtReplacements.h"
#include "RulesInclude/InclusionHeaders.h"
#include "UserDefinedRules/UserDefinedRules.h"
#include "FileGenerator/GenFiles.h"
#include "MigrationReport/Statics.h"
#include "TextModification.h"
#include "Utility.h"
#include "CommandOption/ValidateArguments.h"
#include <bitset>
#include <memory>
#include <optional>
#include <unordered_set>
#include <vector>
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/ParentMapContext.h"
#include "clang/Basic/Cuda.h"
#include "clang/Format/Format.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/Core/UnifiedPath.h"
llvm::StringRef getReplacedName(const clang::NamedDecl *D);
void setGetReplacedNamePtr(llvm::StringRef (*Ptr)(const clang::NamedDecl *D));
namespace clang {
namespace dpct {
using format::FormatRange;
using LocInfo = std::pair<tooling::UnifiedPath, unsigned int>;
template <class F, class... Ts>
std::string buildStringFromPrinter(F Func, Ts &&...Args) {
std::string Ret;
llvm::raw_string_ostream OS(Ret);
Func(OS, std::forward<Ts>(Args)...);
return OS.str();
}
enum class HelperFuncType : int {
HFT_InitValue = 0,
HFT_DefaultQueue = 1,
HFT_CurrentDevice = 2,
HFT_DefaultQueuePtr = 3
};
enum class KernelArgType : int {
KAT_Stream = 0,
KAT_Texture,
KAT_Accessor1D,
KAT_Accessor2D,
KAT_Accessor3D,
KAT_Array1D,
KAT_Array2D,
KAT_Array3D,
KAT_Default,
KAT_MaxParameterSize
};
// This struct defines a set of Repls with priority.
// The priority is designated by an unsigned number, the
// higher the number, the higher the priority.
struct PriorityReplInfo {
std::vector<std::shared_ptr<ExtReplacement>> Repls;
std::vector<std::function<void(void)>> RelatedAction;
unsigned int Priority = 0;
};
class CudaMallocInfo;
class TextureInfo;
class KernelCallExpr;
class DeviceFunctionInfo;
class CallFunctionExpr;
class DeviceFunctionDecl;
class MemVarInfo;
class VarInfo;
class ExplicitInstantiationDecl;
class KernelPrinter;
struct EventSyncTypeInfo {
EventSyncTypeInfo(unsigned int Length, std::string ReplText, bool NeedReport,
bool IsAssigned)
: Length(Length), ReplText(ReplText), NeedReport(NeedReport),
IsAssigned(IsAssigned) {}
void buildInfo(clang::tooling::UnifiedPath FilePath, unsigned int Offset);
unsigned int Length;
std::string ReplText;
bool NeedReport = false;
bool IsAssigned = false;
};
struct TimeStubTypeInfo {
TimeStubTypeInfo(unsigned int Length, std::string StrWithSB,
std::string StrWithoutSB)
: Length(Length), StrWithSB(StrWithSB), StrWithoutSB(StrWithoutSB) {}
void buildInfo(clang::tooling::UnifiedPath FilePath, unsigned int Offset,
bool isReplTxtWithSB);
unsigned int Length;
std::string StrWithSB;
std::string StrWithoutSB;
};
struct BuiltinVarInfo {
BuiltinVarInfo(unsigned int Len, std::string Repl,
std::shared_ptr<DeviceFunctionInfo> DFI)
: Len(Len), Repl(Repl), DFI(DFI) {}
void buildInfo(clang::tooling::UnifiedPath FilePath, unsigned int Offset,
unsigned int Dim);
unsigned int Len = 0;
std::string Repl;
std::shared_ptr<DeviceFunctionInfo> DFI = nullptr;
};
struct FormatInfo {
FormatInfo() : EnableFormat(false), IsAllParamsOneLine(true) {}
bool EnableFormat;
bool IsAllParamsOneLine;
bool IsEachParamNL = false;
int CurrentLength = 0;
int NewLineIndentLength = 0;
std::string NewLineIndentStr;
bool IsFirstArg = false;
};
enum HDFuncInfoType { HDFI_Def, HDFI_Decl, HDFI_Call };
struct HostDeviceFuncLocInfo {
clang::tooling::UnifiedPath FilePath;
std::string FuncContentCache;
unsigned FuncStartOffset = 0;
unsigned FuncEndOffset = 0;
unsigned FuncNameOffset = 0;
bool Processed = false;
bool CalledByHostDeviceFunction = false;
HDFuncInfoType Type;
};
struct HostDeviceFuncInfo {
std::unordered_map<std::string, HostDeviceFuncLocInfo> LocInfos;
bool isDefInserted = false;
bool needGenerateHostCode = false;
int PostFixId = -1;
static int MaxId;
};
enum IfType { IT_Unknow, IT_If, IT_Ifdef, IT_Ifndef, IT_Elif };
struct DirectiveInfo {
unsigned NumberSignLoc = 0;
unsigned DirectiveLoc = 0;
unsigned ConditionLoc = 0;
std::string Condition;
};
struct CudaArchPPInfo {
IfType DT = IfType::IT_Unknow;
DirectiveInfo IfInfo;
DirectiveInfo ElseInfo;
DirectiveInfo EndInfo;
std::unordered_map<unsigned, DirectiveInfo> ElInfo;
bool isInHDFunc = false;
};
// Field: The member field of user defined class type.
// Base: The base class of user defined class type.
// Alias: The alias name of user defined class type.
// The enum is using to clarify the different user defined type when
// migrate the codepin with user defined class.
enum class CodePinVarInfoType { Field, Base, Alias };
struct MemberOrBaseInfoForCodePin {
bool UserDefinedTypeFlag = false;
int PointerDepth = 0;
bool IsBaseMember = false;
std::vector<int> Dims;
std::string TypeNameInCuda;
std::string TypeNameInSycl;
std::string MemberName;
std::string CodePinMemberName;
};
struct VarInfoForCodePin {
bool TemplateFlag = false;
bool TopTypeFlag = false;
bool IsValid = false;
bool IsTypeDef = false;
std::string OrgTypeName;
std::string HashKey;
std::string VarRecordType;
std::string VarName;
std::string VarNameWithoutScopeAndTemplateArgs;
std::string TemplateInstArgs;
std::vector<std::string> Namespaces;
std::vector<std::string> TemplateArgs;
std::vector<MemberOrBaseInfoForCodePin> Bases;
std::vector<MemberOrBaseInfoForCodePin> Members;
};
struct MemcpyOrderAnalysisInfo {
MemcpyOrderAnalysisInfo(
std::vector<std::pair<const Stmt *, MemcpyOrderAnalysisNodeKind>>
MemcpyOrderVec,
std::vector<unsigned int> DREOffsetVec)
: MemcpyOrderVec(MemcpyOrderVec), DREOffsetVec(DREOffsetVec) {}
MemcpyOrderAnalysisInfo() : MemcpyOrderVec({}), DREOffsetVec({}) {}
std::vector<std::pair<const Stmt *, MemcpyOrderAnalysisNodeKind>>
MemcpyOrderVec;
std::vector<unsigned int> DREOffsetVec;
};
struct RnnBackwardFuncInfo {
clang::tooling::UnifiedPath FilePath;
unsigned int Offset;
unsigned int Length;
bool isAssigned;
bool isDataGradient;
std::string CompoundLoc;
std::vector<std::string> RnnInputDeclLoc;
std::vector<std::string> FuncArgs;
};
struct DeviceFunctionInfoForWrapper {
std::vector<std::pair<std::string, std::string>> ParametersInfo;
std::vector<std::pair<std::string, std::string>> TemplateParametersInfo;
std::shared_ptr<KernelCallExpr> KernelForWrapper;
};
// <function name, Info>
using HDFuncInfoMap = std::unordered_map<std::string, HostDeviceFuncInfo>;
// <file path, <Offset, Info>>
using CudaArchPPMap =
std::unordered_map<clang::tooling::UnifiedPath,
std::unordered_map<unsigned int, CudaArchPPInfo>>;
using CudaArchDefMap =
std::unordered_map<std::string,
std::unordered_map<unsigned int, unsigned int>>;
class ParameterStream {
public:
ParameterStream() { FormatInformation = FormatInfo(); }
ParameterStream(FormatInfo FormatInformation, int ColumnLimit)
: FormatInformation(FormatInformation), ColumnLimit(ColumnLimit) {}
ParameterStream &operator<<(const std::string &InputParamStr);
ParameterStream &operator<<(int InputInt);
std::string Str = "";
FormatInfo FormatInformation;
int ColumnLimit = 80;
};
struct StmtWithWarning {
StmtWithWarning(std::string Str, std::vector<std::string> Warnings = {})
: StmtStr(Str), Warnings(Warnings) {}
std::string StmtStr;
std::vector<std::string> Warnings;
};
using StmtList = std::vector<StmtWithWarning>;
template <class T> using GlobalMap = std::map<unsigned, std::shared_ptr<T>>;
using MemVarInfoMap = GlobalMap<MemVarInfo>;
template <class T> inline void merge(T &Master, const T &Branch) {
Master.insert(Branch.begin(), Branch.end());
}
inline void appendString(llvm::raw_string_ostream &OS) {}
template <class FirstArgT, class... ArgsT>
inline void appendString(llvm::raw_string_ostream &OS, FirstArgT &&First,
ArgsT &&...Args) {
OS << std::forward<FirstArgT>(First);
appendString(OS, std::forward<ArgsT>(Args)...);
}
template <class... Arguments>
inline std::string buildString(Arguments &&...Args) {
std::string Result;
llvm::raw_string_ostream OS(Result);
appendString(OS, std::forward<Arguments>(Args)...);
return OS.str();
}
template <class MapType>
inline typename MapType::mapped_type
findObject(const MapType &Map, const typename MapType::key_type &Key) {
auto Itr = Map.find(Key);
if (Itr == Map.end())
return typename MapType::mapped_type();
return Itr->second;
}
template <class MapType,
class ObjectType = typename MapType::mapped_type::element_type,
class... Args>
inline typename MapType::mapped_type
insertObject(MapType &Map, const typename MapType::key_type &Key,
Args &&...InitArgs) {
auto &Obj = Map[Key];
if (!Obj)
Obj = std::make_shared<ObjectType>(Key, std::forward<Args>(InitArgs)...);
return Obj;
}
void initHeaderSpellings();
enum UsingType {
UT_Queue_P,
};
// clang-format off
//
// DpctGlobalInfo
// |
// --------------------------------------------------------
// | | |
// DpctFileInfo DpctFileInfo ... (other info)
// |
// ------------------------------------------------------------------------------------
// | | | |
// MemVarInfo DeviceFunctionDecl KernelCallExpr CudaMallocInfo
// (Global Variable) | (inherit from CallFunctionExpr)
// DeviceFunctionInfo
// |
// ----------------------------
// | |
// CallFunctionExpr MemVarInfo
// (Call Expr in Function) (Defined in Function)
// |
// DeviceFunctionInfo
// (Callee Info)
//
// clang-format on
// Store analysis info (eg. memory variable info, kernel function info,
// replacements and so on) of each file
class DpctFileInfo {
public:
DpctFileInfo(const clang::tooling::UnifiedPath &FilePathIn)
: ReplsSYCL(std::make_shared<ExtReplacements>(FilePathIn)),
ReplsCUDA(std::make_shared<ExtReplacements>(FilePathIn)),
FilePath(FilePathIn) {
buildLinesInfo();
}
template <class Obj> std::shared_ptr<Obj> findNode(unsigned Offset) {
return findObject(getMap<Obj>(), Offset);
}
template <class Obj, class Node>
std::shared_ptr<Obj> insertNode(unsigned Offset, const Node *N) {
return insertObject(getMap<Obj>(), Offset, FilePath, N);
}
template <class Obj, class MappedT, class... Args>
std::shared_ptr<MappedT> insertNode(unsigned Offset, Args &&...Arguments) {
return insertObject<GlobalMap<MappedT>, Obj>(
getMap<MappedT>(), Offset, FilePath, std::forward<Args>(Arguments)...);
}
template <class Obj>
std::shared_ptr<Obj> insertNode(unsigned Offset,
std::shared_ptr<Obj> Object) {
return getMap<Obj>().insert(std::make_pair(Offset, Object)).first->second;
}
const clang::tooling::UnifiedPath &getFilePath() { return FilePath; }
// Build kernel and device function declaration replacements and store them.
void buildReplacements();
void setKernelCallDim();
void setKernelDim();
void buildUnionFindSet();
void buildUnionFindSetForUncalledFunc();
void buildKernelInfo();
void buildRnnBackwardFuncInfo();
void postProcess();
// Emplace stored replacements into replacement set.
void emplaceReplacements(std::map<clang::tooling::UnifiedPath,
tooling::Replacements> &ReplSet /*out*/);
void addReplacement(std::shared_ptr<ExtReplacement> Repl);
bool isInAnalysisScope();
std::shared_ptr<ExtReplacements> getReplsSYCL() { return ReplsSYCL; }
std::shared_ptr<ExtReplacements> getReplsCUDA() { return ReplsCUDA; }
size_t getFileSize() const { return FileSize; }
std::string &getFileContent() { return FileContentCache; }
// Header inclusion directive insertion functions
void setFileEnterOffset(unsigned Offset);
void setFirstIncludeOffset(unsigned Offset);
void setLastIncludeOffset(unsigned Offset) { LastIncludeOffset = Offset; }
void setHeaderInserted(HeaderType Header);
void setMathHeaderInserted(bool B = true);
void setAlgorithmHeaderInserted(bool B = true);
void setTimeHeaderInserted(bool B = true);
void concatHeader(llvm::raw_string_ostream &OS);
template <class FirstT, class... Args>
void concatHeader(llvm::raw_string_ostream &OS, FirstT &&First,
Args &&...Arguments);
std::optional<HeaderType> findHeaderType(StringRef Header);
StringRef getHeaderSpelling(HeaderType Type);
// Insert one or more header inclusion directives at a specified offset
template <typename ReplacementT>
void insertHeader(ReplacementT &&Repl, unsigned Offset,
InsertPosition InsertPos = IP_Left,
ReplacementType IsForCodePin = RT_ForSYCLMigration) {
auto R = std::make_shared<ExtReplacement>(
FilePath, Offset, 0, std::forward<ReplacementT>(Repl), nullptr);
R->setSYCLHeaderNeeded(false);
R->setInsertPosition(InsertPos);
R->IsForCodePin = IsForCodePin;
IncludeDirectiveInsertions.push_back(R);
}
template <typename ReplacementT>
void insertCustomizedHeader(ReplacementT &&Repl) {
if (auto Type = findHeaderType(Repl))
return insertHeader(Type.value());
if (std::find(InsertedHeaders.begin(), InsertedHeaders.end(), Repl) ==
InsertedHeaders.end()) {
InsertedHeaders.push_back(Repl);
}
}
void insertHeader(HeaderType Type, unsigned Offset,
ReplacementType IsForCodePin = RT_ForSYCLMigration);
void insertHeader(HeaderType Type,
ReplacementType IsForCodePin = RT_ForSYCLMigration);
// Record line info in file.
struct SourceLineInfo {
SourceLineInfo() : SourceLineInfo(-1, -1, -1, StringRef()) {}
SourceLineInfo(unsigned LineNumber, unsigned Offset, unsigned End,
StringRef Buffer)
: Number(LineNumber), Offset(Offset), Length(End - Offset),
Line(Buffer.substr(Offset, Length)) {}
SourceLineInfo(unsigned LineNumber, ArrayRef<unsigned> LineCache,
StringRef Buffer)
: SourceLineInfo(LineNumber, LineCache[LineNumber - 1],
LineCache[LineNumber], Buffer) {}
// Line number.
const unsigned Number;
// Offset at the begin of line.
const unsigned Offset;
// Length of the line.
const unsigned Length;
// String of the line, ref to FileContentCache.
StringRef Line;
};
const SourceLineInfo &getLineInfo(unsigned LineNumber);
StringRef getLineString(unsigned LineNumber) {
return getLineInfo(LineNumber).Line;
}
// Get line number by offset
unsigned getLineNumber(unsigned Offset) {
return getLineInfoFromOffset(Offset).Number;
}
// Set line range info of replacement
void setLineRange(ExtReplacements::SourceLineRange &LineRange,
std::shared_ptr<ExtReplacement> Repl);
void insertIncludedFilesInfo(std::shared_ptr<DpctFileInfo> Info);
std::map<const CompoundStmt *, MemcpyOrderAnalysisInfo> &
getMemcpyOrderAnalysisResultMap() {
return MemcpyOrderAnalysisResultMap;
}
std::map<std::string, std::vector<std::pair<unsigned int, unsigned int>>> &
getFuncDeclRangeMap() {
return FuncDeclRangeMap;
}
std::map<unsigned int, EventSyncTypeInfo> &getEventSyncTypeMap() {
return EventSyncTypeMap;
}
std::map<unsigned int, TimeStubTypeInfo> &getTimeStubTypeMap() {
return TimeStubTypeMap;
}
std::map<unsigned int, BuiltinVarInfo> &getBuiltinVarInfoMap() {
return BuiltinVarInfoMap;
}
std::unordered_set<std::shared_ptr<DpctFileInfo>> &getIncludedFilesInfoSet() {
return IncludedFilesInfoSet;
}
std::set<unsigned int> &getSpBLASSet() { return SpBLASSet; }
std::unordered_set<std::shared_ptr<TextModification>> &
getConstantMacroTMSet() {
return ConstantMacroTMSet;
}
std::vector<tooling::Replacement> &getReplacements() {
return PreviousTUReplFromYAML->Replacements;
}
std::unordered_map<std::string, std::tuple<unsigned int, std::string, bool>> &
getAtomicMap() {
return AtomicMap;
}
void setAddOneDplHeaders(bool Value) { AddOneDplHeaders = Value; }
std::vector<std::pair<unsigned int, unsigned int>> &getTimeStubBounds() {
return TimeStubBounds;
}
std::vector<std::pair<unsigned int, unsigned int>> &getExternCRanges() {
return ExternCRanges;
}
std::vector<RnnBackwardFuncInfo> &getRnnBackwardFuncInfo() {
return RBFuncInfo;
}
void setRTVersionValue(std::string Value) { RTVersionValue = Value; }
std::string getRTVersionValue() { return RTVersionValue; }
void setMajorVersionValue(std::string Value) { MajorVersionValue = Value; }
std::string getMajorVersionValue() { return MajorVersionValue; }
void setMinorVersionValue(std::string Value) { MinorVersionValue = Value; }
std::string getMinorVersionValue() { return MinorVersionValue; }
void setCCLVerValue(std::string Value) { CCLVerValue = Value; }
std::string getCCLVerValue() { return CCLVerValue; }
std::shared_ptr<tooling::TranslationUnitReplacements> PreviousTUReplFromYAML =
nullptr;
private:
std::vector<std::pair<unsigned int, unsigned int>> TimeStubBounds;
std::unordered_set<std::shared_ptr<DpctFileInfo>> IncludedFilesInfoSet;
template <class Obj> GlobalMap<Obj> &getMap() {
llvm::dbgs() << "[DpctFileInfo::getMap] Unknow map type";
static GlobalMap<Obj> NullMap;
return NullMap;
}
bool isReplTxtWithSubmitBarrier(unsigned Offset);
// TODO: implement one of this for each source language.
bool isInCudaPath();
void buildLinesInfo();
const SourceLineInfo &getLineInfoFromOffset(unsigned Offset);
std::map<const CompoundStmt *, MemcpyOrderAnalysisInfo>
MemcpyOrderAnalysisResultMap;
std::map<std::string /*Function name*/,
std::vector<
std::pair<unsigned int /*Begin location of function signature*/,
unsigned int /*End location of function signature*/>>>
FuncDeclRangeMap;
std::map<unsigned int, EventSyncTypeInfo> EventSyncTypeMap;
std::map<unsigned int, TimeStubTypeInfo> TimeStubTypeMap;
std::map<unsigned int, BuiltinVarInfo> BuiltinVarInfoMap;
GlobalMap<MemVarInfo> MemVarMap;
GlobalMap<DeviceFunctionDecl> FuncMap;
GlobalMap<KernelCallExpr> KernelMap;
GlobalMap<CudaMallocInfo> CudaMallocMap;
GlobalMap<TextureInfo> TextureMap;
std::set<unsigned int> SpBLASSet;
std::unordered_set<std::shared_ptr<TextModification>> ConstantMacroTMSet;
std::unordered_map<std::string, std::tuple<unsigned int, std::string, bool>>
AtomicMap;
std::shared_ptr<ExtReplacements> ReplsSYCL;
std::shared_ptr<ExtReplacements> ReplsCUDA;
size_t FileSize = 0;
std::vector<SourceLineInfo> Lines;
clang::tooling::UnifiedPath FilePath;
std::string FileContentCache;
// Save the FirstIncludeOffset in each MainFile
std::map<std::shared_ptr<DpctFileInfo> /*MainFile*/, unsigned>
FirstIncludeOffset;
unsigned LastIncludeOffset = 0;
const unsigned FileBeginOffset = 0;
// Save the status whether FirstIncludeOffset is set by setFirstIncludeOffset
// for each MainFile
std::set<std::shared_ptr<DpctFileInfo> /*MainFile*/> HasInclusionDirectiveSet;
std::vector<std::string> InsertedHeaders;
std::vector<std::string> InsertedHeadersCUDA;
std::bitset<32> UsingInsertedBitMap;
bool AddOneDplHeaders = false;
std::vector<std::shared_ptr<ExtReplacement>> IncludeDirectiveInsertions;
std::vector<std::pair<unsigned int, unsigned int>> ExternCRanges;
std::vector<RnnBackwardFuncInfo> RBFuncInfo;
std::string RTVersionValue = "";
std::string MajorVersionValue = "";
std::string MinorVersionValue = "";
std::string CCLVerValue = "";
};
template <> inline GlobalMap<MemVarInfo> &DpctFileInfo::getMap() {
return MemVarMap;
}
template <> inline GlobalMap<DeviceFunctionDecl> &DpctFileInfo::getMap() {
return FuncMap;
}
template <> inline GlobalMap<KernelCallExpr> &DpctFileInfo::getMap() {
return KernelMap;
}
template <> inline GlobalMap<CudaMallocInfo> &DpctFileInfo::getMap() {
return CudaMallocMap;
}
template <> inline GlobalMap<TextureInfo> &DpctFileInfo::getMap() {
return TextureMap;
}
class DpctGlobalInfo {
public:
static DpctGlobalInfo &getInstance() {
static DpctGlobalInfo Info;
return Info;
}
class MacroDefRecord {
public:
clang::tooling::UnifiedPath FilePath;
unsigned Offset;
bool IsInAnalysisScope;
MacroDefRecord(SourceLocation NTL, bool IIAS);
};
// This class is used to store information about macro arguments in a
// macro definition. For example, consider the macro definition:
// "#define CALL(x, y) x(y)".
// - For the first argument "x", the member ArgName will be "x", ArgLoc will
// be the source location of the token "x" in the macro definition, and
// ArgIndex will be 0.
// - For the second argument "y", the member ArgName will be "y", ArgLoc will
// be the source location of the token "y" in the macro definition, and
// ArgIndex will be 1.
class MacroArgRecord {
public:
std::string ArgName;
SourceLocation ArgLoc;
int ArgIndex;
MacroArgRecord(const MacroInfo *MI, int ArgIndex);
};
class MacroExpansionRecord {
public:
std::string Name;
int NumTokens;
clang::tooling::UnifiedPath FilePath;
unsigned ReplaceTokenBeginOffset;
unsigned ReplaceTokenEndOffset;
SourceRange Range;
bool IsInAnalysisScope;
bool IsFunctionLike;
int TokenIndex;
MacroExpansionRecord(IdentifierInfo *ID, const MacroInfo *MI,
SourceRange Range, bool IsInAnalysisScope,
int TokenIndex);
};
struct HelperFuncReplInfo {
HelperFuncReplInfo(const clang::tooling::UnifiedPath DeclLocFile =
clang::tooling::UnifiedPath(),
unsigned int DeclLocOffset = 0,
bool IsLocationValid = false)
: DeclLocFile(DeclLocFile), DeclLocOffset(DeclLocOffset),
IsLocationValid(IsLocationValid) {}
clang::tooling::UnifiedPath DeclLocFile;
unsigned int DeclLocOffset = 0;
bool IsLocationValid = false;
};
struct TempVariableDeclCounter {
TempVariableDeclCounter(int DefaultQueueCounter = 0,
int CurrentDeviceCounter = 0)
: DefaultQueueCounter(DefaultQueueCounter),
CurrentDeviceCounter(CurrentDeviceCounter),
PlaceholderStr{
"", DpctGlobalInfo::getDefaultQueueFreeFuncCall(),
MapNames::getDpctNamespace() + "get_current_device()",
(DpctGlobalInfo::useSYCLCompat()
? buildString(MapNames::getDpctNamespace() +
"get_current_device().default_queue()")
: buildString(
"&", DpctGlobalInfo::getDefaultQueueFreeFuncCall()))} {
}
int DefaultQueueCounter = 0;
int CurrentDeviceCounter = 0;
std::string PlaceholderStr[4];
};
static std::string removeSymlinks(clang::FileManager &FM,
std::string FilePathStr);
static bool isInRoot(SourceLocation SL) {
return isInRoot(DpctGlobalInfo::getLocInfo(SL).first);
}
static bool isInRoot(const clang::tooling::UnifiedPath &FilePath);
static bool isInAnalysisScope(SourceLocation SL) {
return isInAnalysisScope(DpctGlobalInfo::getLocInfo(SL).first);
}
static bool isInAnalysisScope(const clang::tooling::UnifiedPath &FilePath) {
return std::any_of(AnalysisScope.begin(), AnalysisScope.end(),
[&](const clang::tooling::UnifiedPath &P) {
return isChildPath(P, FilePath);
});
}
static bool isExcluded(const clang::tooling::UnifiedPath &FilePath);
// TODO: implement one of this for each source language.
static bool isInCudaPath(SourceLocation SL);
// TODO: implement one of this for each source language.
static bool isInCudaPath(clang::tooling::UnifiedPath FilePath) {
return isChildPath(CudaPath, FilePath);
}
static void setInRoot(const clang::tooling::UnifiedPath &InRootPath) {
InRoot = InRootPath;
}
static const clang::tooling::UnifiedPath &getInRoot() { return InRoot; }
static void setOutRoot(const clang::tooling::UnifiedPath &OutRootPath) {
OutRoot = OutRootPath;
}
static const clang::tooling::UnifiedPath &getOutRoot() { return OutRoot; }
static void setAnalysisScope(
const std::vector<clang::tooling::UnifiedPath> &InputAnalysisScope) {
AnalysisScope = InputAnalysisScope;
}
static const std::vector<clang::tooling::UnifiedPath> &getAnalysisScope() {
return AnalysisScope;
}
static void addChangeExtensions(const std::string &Extension) {
assert(!Extension.empty());
ChangeExtensions.insert(Extension);
}
static const std::unordered_set<std::string> &getChangeExtensions() {
return ChangeExtensions;
}
static const std::string &getSYCLSourceExtension() {
return SYCLSourceExtension;
}
static const std::string &getSYCLHeaderExtension() {
return SYCLHeaderExtension;
}
static void setSYCLFileExtension(SYCLFileExtensionEnum Extension);
// TODO: implement one of this for each source language.
static void setCudaPath(const clang::tooling::UnifiedPath &InputCudaPath) {
CudaPath = InputCudaPath;
}
// TODO: implement one of this for each source language.
static const clang::tooling::UnifiedPath &getCudaPath() { return CudaPath; }
static const std::string getCudaVersion() {
return clang::CudaVersionToString(SDKVersion);
}
static void printItem(llvm::raw_ostream &, const Stmt *,
const FunctionDecl *FD = nullptr);
static std::string getItem(const Stmt *, const FunctionDecl *FD = nullptr);
static void registerNDItemUser(const Stmt *,
const FunctionDecl *FD = nullptr);
static void printGroup(llvm::raw_ostream &, const Stmt *,
const FunctionDecl *FD = nullptr);
static std::string getGroup(const Stmt *, const FunctionDecl *FD = nullptr);
static void printSubGroup(llvm::raw_ostream &, const Stmt *,
const FunctionDecl *FD = nullptr);
static std::string getSubGroup(const Stmt *,
const FunctionDecl *FD = nullptr);
static std::string getDefaultQueue(const Stmt *);
static const std::string &getDefaultQueueFreeFuncCall();
static const std::string &getDefaultQueueMemFuncName();
static const std::string &getStreamName() {
const static std::string StreamName = "stream" + getCTFixedSuffix();
return StreamName;
}
static const std::string &getSyncName() {
const static std::string SyncName = "sync" + getCTFixedSuffix();
return SyncName;
}
static const std::string &getInRootHash() {
const static std::string Hash = getHashAsString(getInRoot()).substr(0, 6);
return Hash;
}
static void setContext(ASTContext &C);
static void setRuleFile(const std::string &Path) { RuleFile = Path; }
static ASTContext &getContext() {
assert(Context);
return *Context;
}
static SourceManager &getSourceManager() {
assert(SM);
return *SM;
}
static FileManager &getFileManager() {
assert(FM);
return *FM;
}
static bool isKeepOriginCode() { return KeepOriginCode; }
static void setKeepOriginCode(bool KOC) { KeepOriginCode = KOC; }
static bool isSyclNamedLambda() { return SyclNamedLambda; }
static void setSyclNamedLambda(bool SNL) { SyclNamedLambda = SNL; }
static void setCheckUnicodeSecurityFlag(bool CUS) {
CheckUnicodeSecurityFlag = CUS;
}
static bool getCheckUnicodeSecurityFlag() { return CheckUnicodeSecurityFlag; }
static void setEnablepProfilingFlag(bool EP) { EnablepProfilingFlag = EP; }
static bool getEnablepProfilingFlag() { return EnablepProfilingFlag; }
static bool getGuessIndentWidthMatcherFlag() {
return GuessIndentWidthMatcherFlag;
}
static void setGuessIndentWidthMatcherFlag(bool Flag) {
GuessIndentWidthMatcherFlag = Flag;
}
static void setIndentWidth(unsigned int W) { IndentWidth = W; }
static unsigned int getIndentWidth() { return IndentWidth; }
static void insertKCIndentWidth(unsigned int W);
static unsigned int getKCIndentWidth();
static UsmLevel getUsmLevel() { return UsmLvl; }
static void setUsmLevel(UsmLevel UL) { UsmLvl = UL; }
static unsigned getBuildScript() { return BuildScriptType; }
static void setBuildScript(unsigned BS_type) { BuildScriptType = BS_type; }
template <BuildScriptKind BS_kind> static bool getMigrateBuildScriptType() {
return BuildScriptType & (1 << static_cast<unsigned>(BS_kind));
}
static bool migrateCMakeScripts() {
return getMigrateBuildScriptType<BuildScriptKind::BS_CMake>();
}
static bool migratePythonScripts() {
return getMigrateBuildScriptType<BuildScriptKind::BS_Python>();
}
static clang::CudaVersion getSDKVersion() { return SDKVersion; }
static void setSDKVersion(clang::CudaVersion V) { SDKVersion = V; }
static bool isIncMigration() { return IsIncMigration; }
static void setIsIncMigration(bool Flag) { IsIncMigration = Flag; }
static bool isQueryAPIMapping() { return IsQueryAPIMapping; }
static void setIsQueryAPIMapping(bool Flag) { IsQueryAPIMapping = Flag; }
static bool needDpctDeviceExt() { return NeedDpctDeviceExt; }
static void setNeedDpctDeviceExt() { NeedDpctDeviceExt = true; }
static unsigned int getAssumedNDRangeDim() { return AssumedNDRangeDim; }
static void setAssumedNDRangeDim(unsigned int Dim) {
AssumedNDRangeDim = Dim;
}
static bool getUsingExtensionDE(DPCPPExtensionsDefaultEnabled Ext) {
return ExtensionDEFlag & (1 << static_cast<unsigned>(Ext));
}
static void setExtensionDEFlag(unsigned Flag) {
// The bits in Flag was reversed, so we need to check whether the ExtDE_All
// bit of Flag is 0. That means disable all default enabled extensions,
// otherwise disable the extensions represented by the 0 bit
if (Flag &
(1 << static_cast<unsigned>(DPCPPExtensionsDefaultEnabled::ExtDE_All)))
ExtensionDEFlag = Flag;
else
ExtensionDEFlag = 0;
}
static unsigned getExtensionDEFlag() { return ExtensionDEFlag; }
static bool getUsingExtensionDD(DPCPPExtensionsDefaultDisabled Ext) {
return ExtensionDDFlag & (1 << static_cast<unsigned>(Ext));
}
static void setExtensionDDFlag(unsigned Flag) {
// If the ExtDD_All bit is 1, enable all default disabled extensions.
if (Flag &
(1 << static_cast<unsigned>(DPCPPExtensionsDefaultDisabled::ExtDD_All)))
ExtensionDDFlag = static_cast<unsigned>(-1);
else
ExtensionDDFlag = Flag;
}
static unsigned getExtensionDDFlag() { return ExtensionDDFlag; }
template <ExperimentalFeatures Exp> static bool getUsingExperimental() {
return ExperimentalFlag & (1 << static_cast<unsigned>(Exp));
}
static void setExperimentalFlag(unsigned Flag) {
// If the ExtDD_All bit is 1, enable all default disabled experimental
// features.
if (Flag & (1 << static_cast<unsigned>(ExperimentalFeatures::Exp_All)))
ExperimentalFlag = static_cast<unsigned>(-1);
else
ExperimentalFlag = Flag;
}
static unsigned getExperimentalFlag() { return ExperimentalFlag; }
static bool getHelperFuncPreference(HelperFuncPreference HFP) {
return HelperFuncPreferenceFlag & (1 << static_cast<unsigned>(HFP));
}
static void setHelperFuncPreferenceFlag(unsigned Flag) {
HelperFuncPreferenceFlag = Flag;
}
static unsigned getHelperFuncPreferenceFlag() {
return HelperFuncPreferenceFlag;
}
static bool isAnalysisModeEnabled() { return AnalysisModeFlag; }
static void enableAnalysisMode() { AnalysisModeFlag = true; }
static format::FormatRange getFormatRange() { return FmtRng; }
static void setFormatRange(format::FormatRange FR) { FmtRng = FR; }
static DPCTFormatStyle getFormatStyle() { return FmtST; }
static void setFormatStyle(DPCTFormatStyle FS) { FmtST = FS; }
// Processing the folder or file by following rules:
// Rule1: For {child path, parent path}, only parent path will be kept.
// Rule2: Ignore invalid path.
// Rule3: If path is not in --in-root, then ignore it.
static void setExcludePath(std::vector<std::string> ExcludePathVec);
static std::unordered_map<std::string, bool> getExcludePath() {
return ExcludePath;
}
static bool isCtadEnabled() { return EnableCtad; }
static void setCtadEnabled(bool Enable) { EnableCtad = Enable; }
static bool isCodePinEnabled() { return EnableCodePin; }
static void setCodePinEnabled(bool Enable = false) { EnableCodePin = Enable; }
static bool isGenBuildScript() { return GenBuildScript; }
static void setGenBuildScriptEnabled(bool Enable = true) {
GenBuildScript = Enable;
}
static bool IsMigrateBuildScriptOnlyEnabled() {
return MigrateBuildScriptOnly;
}
static void setMigrateBuildScriptOnlyEnabled(bool Enable = true) {
MigrateBuildScriptOnly = Enable;
}
static bool isCommentsEnabled() { return EnableComments; }
static void setCommentsEnabled(bool Enable = true) {
EnableComments = Enable;
}
static bool isDPCTNamespaceTempEnabled() { return TempEnableDPCTNamespace; }
static void setDPCTNamespaceTempEnabled() { TempEnableDPCTNamespace = true; }
static std::unordered_set<std::string> &getPrecAndDomPairSet() {
return PrecAndDomPairSet;
}
static bool isMKLHeaderUsed() { return IsMLKHeaderUsed; }
static void setMKLHeaderUsed(bool Used = true) { IsMLKHeaderUsed = Used; }
static int getSuffixIndexInitValue(std::string FileNameAndOffset);
static void updateInitSuffixIndexInRule(int InitVal) {
CurrentIndexInRule = InitVal;
}
static int getSuffixIndexInRuleThenInc();
static int getSuffixIndexGlobalThenInc();
static const std::string &getGlobalQueueName() {
const static std::string Q = "q_ct1";
return Q;
}
static const std::string &getGlobalDeviceName() {
const static std::string D = "dev_ct1";
return D;
}
static std::string getStringForRegexReplacement(StringRef);
static void setCodeFormatStyle(const clang::format::FormatStyle &Style) {
CodeFormatStyle = Style;
}
static clang::format::FormatStyle getCodeFormatStyle() {
return CodeFormatStyle;
}
static bool IsVarUsedByRuntimeSymbolAPI(std::shared_ptr<MemVarInfo> Info);
private:
template <class T, class T1, class... Ts>
static constexpr bool IsSameAsAnyTy = (std::is_same_v<T, Ts> || ...);
template <typename T>
static constexpr bool IsNonPtrNode =
IsSameAsAnyTy<T, TemplateArgument, TemplateArgumentLoc,
NestedNameSpecifierLoc, QualType, TypeLoc, ObjCProtocolLoc>;
public:
template <class TargetTy, class NodeTy>
static inline std::conditional_t<IsNonPtrNode<TargetTy>,
std::optional<TargetTy>, const TargetTy *>
findAncestor(const NodeTy *N,
const std::function<bool(const DynTypedNode &)> &Condition) {
if (LLVM_LIKELY(N)) {
auto &Context = getContext();
clang::DynTypedNodeList Parents = Context.getParents(*N);
while (!Parents.empty()) {
auto &Cur = Parents[0];
if (Condition(Cur)) {
if constexpr (IsNonPtrNode<TargetTy>)
return *Cur.get<TargetTy>();
else
return Cur.get<TargetTy>();
}
Parents = Context.getParents(Cur);
}
}
if constexpr (IsNonPtrNode<TargetTy>)
return std::nullopt;
else
return nullptr;
}
template <class NodeTy>
static inline bool checkSpecificBO(const NodeTy *Node,
const BinaryOperator *BO) {
return findAncestor<BinaryOperator>(
Node, [&](const DynTypedNode &Cur) -> bool {
return Cur.get<BinaryOperator>() == BO;
});
}