-
Notifications
You must be signed in to change notification settings - Fork 520
/
Copy pathParser.cpp
5192 lines (4326 loc) · 160 KB
/
Parser.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
/************************************************************************
*
* CppSharp
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#ifdef DEBUG
#undef DEBUG // workaround DEBUG define messing with LLVM COFF headers
#endif
#include "Parser.h"
#include "ELFDumper.h"
#include "APValuePrinter.h"
#include <iostream>
#include <stdlib.h>
#include <llvm/TargetParser/Host.h>
#include <llvm/Support/Path.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Object/Archive.h>
#include <llvm/Object/COFF.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/Object/ELFObjectFile.h>
#include <llvm/Object/MachO.h>
#include <llvm/Option/ArgList.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/DataLayout.h>
#include <clang/Basic/Builtins.h>
#include <clang/Basic/Version.h>
#include <clang/Config/config.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/Comment.h>
#include <clang/AST/DeclFriend.h>
#include <clang/AST/ExprCXX.h>
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Lex/DirectoryLookup.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/PreprocessorOptions.h>
#include <clang/Lex/PreprocessingRecord.h>
#include <clang/Parse/ParseAST.h>
#include <clang/Sema/Sema.h>
#include <clang/Sema/SemaConsumer.h>
#include <clang/Sema/Template.h>
#include <clang/Frontend/Utils.h>
#include <clang/Driver/Driver.h>
#include <clang/Driver/ToolChain.h>
#include <clang/Driver/Util.h>
#include <clang/Index/USRGeneration.h>
#include <CodeGen/TargetInfo.h>
#include <CodeGen/CGCall.h>
#include <CodeGen/CGCXXABI.h>
#include <Driver/ToolChains/Linux.h>
#include <Driver/ToolChains/MSVC.h>
#include "ASTNameMangler.h"
#if defined(__APPLE__) || defined(__linux__)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <dlfcn.h>
#define HAVE_DLFCN
#endif
// Internals of assertm with or without abort.
#define _assertm(condition, message, call) \
do \
{ \
if (!(condition)) \
{ \
std::cerr << "Assert at `" \
<< __FILE__ \
<< ":" \
<< __LINE__ \
<< "` in `" \
<< __FUNCTION__ \
<< "` failed. " \
<< message; \
call; \
} \
} \
while (0)
// Internals of assertml with or without abort.
#define _assertml(condition, message, sm, loc, call) \
do \
{ \
if (!(condition)) \
{ \
const clang::SourceManager& _sm = sm; \
clang::SourceLocation _loc = loc; \
std::cerr << "Assert at `" \
<< __FILE__ \
<< ":" \
<< __LINE__ \
<< "` in `" \
<< __FUNCTION__ \
<< "` failed. " \
<< message \
<< " Filename `" \
<< _sm.getFilename(_loc).str() \
<< ":" \
<< _sm.getSpellingLineNumber(_loc) \
<< "`\n"; \
call; \
} \
} \
while (0)
// Macros which output messages to console if parsing encounters oddity.
// In debug builds, macros abort unless DEBUG_NO_ABORT is defined.
//
// Macro assertm outputs a message if condition is false.
// Macro assertml outputs a message and parsing file and line on given source manager and source line.
//
// assertml adds newline ending.
#ifdef NDEBUG
#define debug_break() ((void)0)
#define debug_fail() ((void)0)
#else
#if __GNUC__
#define debug_break() \
__builtin_trap()
#elif _MSC_VER
#define debug_break() \
__debugbreak()
#else
#define debug_break(c) \
*reinterpret_cast<volatile int*>(0) = 47283;
#endif
#ifdef DEBUG_NO_ABORT
#define debug_fail() debug_break()
#else
#define debug_fail() \
debug_break(); \
abort()
#endif
#endif
#define assertm(condition, message) _assertm(condition, message, debug_fail())
#define assertml(condition, message, sm, source) _assertml(condition, message, sm, source, debug_fail())
using namespace CppSharp::CppParser;
using namespace CppSharp::CppParser::AST;
// We use this as a placeholder for pointer values that should be ignored.
void* IgnorePtr = reinterpret_cast<void*>(0x1);
//-----------------------------------//
Parser::Parser(CppParserOptions* Opts)
: opts(Opts)
, supportedStdTypes{ Opts->SupportedStdTypes.begin(), Opts->SupportedStdTypes.end() }
, supportedFunctionTemplates{ Opts->SupportedFunctionTemplates.begin(), Opts->SupportedFunctionTemplates.end() }
{
supportedStdTypes.insert("allocator");
supportedStdTypes.insert("basic_string");
}
LayoutField Parser::WalkVTablePointer(Class* Class,
const clang::CharUnits& Offset,
const std::string& prefix)
{
LayoutField LayoutField;
LayoutField.offset = Offset.getQuantity();
LayoutField.name = prefix + "_" + Class->name;
LayoutField.qualifiedType = GetQualifiedType(c->getASTContext().VoidPtrTy);
return LayoutField;
}
static CppAbi GetClassLayoutAbi(clang::TargetCXXABI::Kind abi)
{
switch (abi)
{
case clang::TargetCXXABI::Microsoft:
return CppAbi::Microsoft;
case clang::TargetCXXABI::GenericItanium:
return CppAbi::Itanium;
case clang::TargetCXXABI::GenericARM:
return CppAbi::ARM;
case clang::TargetCXXABI::GenericAArch64:
return CppAbi::AArch64;
case clang::TargetCXXABI::iOS:
return CppAbi::iOS;
case clang::TargetCXXABI::AppleARM64:
return CppAbi::AppleARM64;
case clang::TargetCXXABI::WebAssembly:
return CppAbi::WebAssembly;
default:
llvm_unreachable("Unsupported C++ ABI kind");
}
}
void Parser::ReadClassLayout(Class* Class, const clang::RecordDecl* RD, clang::CharUnits Offset, bool IncludeVirtualBases)
{
using namespace clang;
const auto& Layout = c->getASTContext().getASTRecordLayout(RD);
auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
auto Parent = static_cast<AST::Class*>(
WalkDeclaration(RD));
if (Class != Parent)
{
LayoutBase LayoutBase;
LayoutBase.offset = Offset.getQuantity();
LayoutBase._class = Parent;
Class->layout->Bases.push_back(LayoutBase);
}
// Dump bases.
if (CXXRD)
{
const CXXRecordDecl* PrimaryBase = Layout.getPrimaryBase();
bool HasOwnVFPtr = Layout.hasOwnVFPtr();
bool HasOwnVBPtr = Layout.hasOwnVBPtr();
// Vtable pointer.
if (CXXRD->isDynamicClass() && !PrimaryBase &&
!c->getTarget().getCXXABI().isMicrosoft())
{
auto VPtr = WalkVTablePointer(Parent, Offset, "vptr");
Class->layout->Fields.push_back(VPtr);
}
else if (HasOwnVFPtr)
{
auto VTPtr = WalkVTablePointer(Parent, Offset, "vfptr");
Class->layout->Fields.push_back(VTPtr);
}
// Collect nvbases.
SmallVector<const CXXRecordDecl*, 4> Bases;
for (const CXXBaseSpecifier& Base : CXXRD->bases())
{
assertm(!Base.getType()->isDependentType(), "Cannot layout class with dependent bases.\n");
if (!Base.isVirtual())
Bases.push_back(Base.getType()->getAsCXXRecordDecl());
}
// Sort nvbases by offset.
std::stable_sort(Bases.begin(), Bases.end(),
[&](const CXXRecordDecl* L, const CXXRecordDecl* R)
{
return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
});
// Dump (non-virtual) bases
for (const CXXRecordDecl* Base : Bases)
{
CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
ReadClassLayout(Class, Base, BaseOffset,
/*IncludeVirtualBases=*/false);
}
// vbptr (for Microsoft C++ ABI)
if (HasOwnVBPtr)
{
auto VBPtr = WalkVTablePointer(Parent,
Offset + Layout.getVBPtrOffset(), "vbptr");
Class->layout->Fields.push_back(VBPtr);
}
}
// Dump fields.
uint64_t FieldNo = 0;
for (const FieldDecl* Field : RD->fields())
{
uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo++);
CharUnits FieldOffset =
Offset + c->getASTContext().toCharUnitsFromBits(LocalFieldOffsetInBits);
auto F = WalkFieldCXX(Field, Parent);
LayoutField LayoutField;
LayoutField.offset = FieldOffset.getQuantity();
LayoutField.name = F->name;
LayoutField.qualifiedType = GetQualifiedType(Field->getType());
LayoutField.fieldPtr = (void*)Field;
Class->layout->Fields.push_back(LayoutField);
}
// Dump virtual bases.
if (CXXRD && IncludeVirtualBases)
{
const ASTRecordLayout::VBaseOffsetsMapTy& VtorDisps =
Layout.getVBaseOffsetsMap();
for (const CXXBaseSpecifier& Base : CXXRD->vbases())
{
assertm(Base.isVirtual(), "Found non-virtual class!\n");
const CXXRecordDecl* VBase = Base.getType()->getAsCXXRecordDecl();
CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
if (VtorDisps.find(VBase)->second.hasVtorDisp())
{
auto VtorDisp = WalkVTablePointer(Parent,
VBaseOffset - CharUnits::fromQuantity(4), "vtordisp");
Class->layout->Fields.push_back(VtorDisp);
}
ReadClassLayout(Class, VBase, VBaseOffset,
/*IncludeVirtualBases=*/false);
}
}
}
//-----------------------------------//
static clang::TargetCXXABI::Kind
ConvertToClangTargetCXXABI(CppAbi abi)
{
using namespace clang;
switch (abi)
{
case CppAbi::Itanium:
return TargetCXXABI::GenericItanium;
case CppAbi::Microsoft:
return TargetCXXABI::Microsoft;
case CppAbi::ARM:
return TargetCXXABI::GenericARM;
case CppAbi::AArch64:
return TargetCXXABI::GenericAArch64;
case CppAbi::iOS:
return TargetCXXABI::iOS;
case CppAbi::AppleARM64:
return TargetCXXABI::AppleARM64;
}
llvm_unreachable("Unsupported C++ ABI.");
}
void Parser::Setup(bool Compile)
{
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
using namespace clang;
std::vector<const char*> args;
args.push_back("-cc1");
if (Compile)
{
for (const std::string& CompilationOption : opts->CompilationOptions)
{
args.push_back(CompilationOption.c_str());
if (opts->verbose)
printf("Compiler argument: %s\n", CompilationOption.c_str());
}
}
for (unsigned I = 0, E = opts->Arguments.size(); I != E; ++I)
{
const auto& Arg = opts->Arguments[I];
args.push_back(Arg.c_str());
if (opts->verbose)
printf("Compiler argument: %s\n", Arg.c_str());
}
c.reset(new CompilerInstance());
c->createDiagnostics();
CompilerInvocation* Inv = new CompilerInvocation();
ArrayRef<const char*> arguments(args.data(), args.data() + args.size());
CompilerInvocation::CreateFromArgs(*Inv, arguments, c->getDiagnostics());
c->setInvocation(std::shared_ptr<CompilerInvocation>(Inv));
c->getLangOpts() = *Inv->LangOpts;
auto& TO = Inv->TargetOpts;
if (opts->targetTriple.empty())
opts->targetTriple = llvm::sys::getDefaultTargetTriple();
TO->Triple = llvm::Triple::normalize(opts->targetTriple);
if (opts->verbose)
printf("Target triple: %s\n", TO->Triple.c_str());
TargetInfo* TI = TargetInfo::CreateTargetInfo(c->getDiagnostics(), TO);
if (!TI)
{
// We might have no target info due to an invalid user-provided triple.
// Try again with the default triple.
opts->targetTriple = llvm::sys::getDefaultTargetTriple();
TO->Triple = llvm::Triple::normalize(opts->targetTriple);
TI = TargetInfo::CreateTargetInfo(c->getDiagnostics(), TO);
}
assertm(TI, "Expected valid target info!\n");
c->setTarget(TI);
c->createFileManager();
c->createSourceManager(c->getFileManager());
auto& HSOpts = c->getHeaderSearchOpts();
auto& PPOpts = c->getPreprocessorOpts();
auto& LangOpts = c->getLangOpts();
if (opts->noStandardIncludes)
{
HSOpts.UseStandardSystemIncludes = false;
HSOpts.UseStandardCXXIncludes = false;
}
if (opts->noBuiltinIncludes)
HSOpts.UseBuiltinIncludes = false;
if (opts->verbose)
HSOpts.Verbose = true;
for (unsigned I = 0, E = opts->IncludeDirs.size(); I != E; ++I)
{
const auto& s = opts->IncludeDirs[I];
HSOpts.AddPath(s, frontend::Angled, false, false);
}
for (unsigned I = 0, E = opts->SystemIncludeDirs.size(); I != E; ++I)
{
const auto& s = opts->SystemIncludeDirs[I];
HSOpts.AddPath(s, frontend::System, false, false);
}
for (unsigned I = 0, E = opts->Defines.size(); I != E; ++I)
{
const auto& define = opts->Defines[I];
PPOpts.addMacroDef(define);
}
for (unsigned I = 0, E = opts->Undefines.size(); I != E; ++I)
{
const auto& undefine = opts->Undefines[I];
PPOpts.addMacroUndef(undefine);
}
#ifdef _MSC_VER
if (opts->microsoftMode)
{
LangOpts.MSCompatibilityVersion = opts->toolSetToUse;
if (!LangOpts.MSCompatibilityVersion)
LangOpts.MSCompatibilityVersion = 1700;
}
#endif
llvm::opt::InputArgList Args(0, 0);
driver::Driver D("", TO->Triple, c->getDiagnostics());
driver::ToolChain* TC = nullptr;
llvm::Triple Target(TO->Triple);
if (Target.getOS() == llvm::Triple::Linux)
TC = new driver::toolchains::Linux(D, Target, Args);
else if (Target.getEnvironment() == llvm::Triple::EnvironmentType::MSVC)
TC = new driver::toolchains::MSVCToolChain(D, Target, Args);
if (TC && !opts->noStandardIncludes)
{
llvm::opt::ArgStringList Includes;
TC->AddClangSystemIncludeArgs(Args, Includes);
TC->AddClangCXXStdlibIncludeArgs(Args, Includes);
for (auto& Arg : Includes)
{
if (strlen(Arg) > 0 && Arg[0] != '-')
HSOpts.AddPath(Arg, frontend::System, /*IsFramework=*/false,
/*IgnoreSysRoot=*/false);
}
}
if (TC)
delete TC;
// Enable preprocessing record.
PPOpts.DetailedRecord = true;
c->createPreprocessor(TU_Complete);
Preprocessor& PP = c->getPreprocessor();
PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
c->createASTContext();
NameMangler.reset(new ASTNameMangler(c->getASTContext()));
}
//-----------------------------------//
std::string Parser::GetDeclMangledName(const clang::Decl* D) const
{
// Source adapted from https://clang.llvm.org/doxygen/JSONNodeDumper_8cpp_source.html#l00845
using namespace clang;
auto ND = dyn_cast_or_null<NamedDecl>(D);
if (!ND || !ND->getDeclName())
return {};
// If the declaration is dependent or is in a dependent context, then the
// mangling is unlikely to be meaningful (and in some cases may cause
// "don't know how to mangle this" assertion failures.)
if (ND->isTemplated())
return {};
/*bool CanMangle = isa<FunctionDecl>(D) || isa<VarDecl>(D)
|| isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D);
if (!CanMangle)
return {};*/
// FIXME: There are likely other contexts in which it makes no sense to ask
// for a mangled name.
if (isa<RequiresExprBodyDecl>(ND->getDeclContext()))
return {};
// Do not mangle template deduction guides.
if (isa<CXXDeductionGuideDecl>(ND))
return {};
// Mangled names are not meaningful for locals, and may not be well-defined
// in the case of VLAs.
auto* VD = dyn_cast<VarDecl>(ND);
if (VD && VD->hasLocalStorage())
return {};
std::string MangledName = NameMangler->GetName(ND);
// Strip away LLVM name marker.
if (!MangledName.empty() && MangledName[0] == '\01')
MangledName = MangledName.substr(1);
return MangledName;
}
//-----------------------------------//
static std::string GetDeclName(const clang::NamedDecl* D)
{
if (const clang::IdentifierInfo* II = D->getIdentifier())
return II->getName().str();
return D->getNameAsString();
}
static std::string GetTagDeclName(const clang::TagDecl* D)
{
using namespace clang;
if (auto Typedef = D->getTypedefNameForAnonDecl())
{
assertm(Typedef->getIdentifier(), "Typedef without identifier?\n");
return GetDeclName(Typedef);
}
return GetDeclName(D);
}
static std::string GetDeclUSR(const clang::Decl* D)
{
using namespace clang;
SmallString<128> usr;
if (!index::generateUSRForDecl(D, usr))
return usr.str().str();
return "<invalid>";
}
static clang::Decl* GetPreviousDeclInContext(const clang::Decl* D)
{
assertm(!D->getLexicalDeclContext()->decls_empty(), "No previous declaration.\n");
clang::Decl* prevDecl = nullptr;
for (auto it = D->getDeclContext()->decls_begin();
it != D->getDeclContext()->decls_end(); it++)
{
if ((*it) == D)
return prevDecl;
prevDecl = (*it);
}
return nullptr;
}
static bool IsExplicit(const clang::Decl* D)
{
using namespace clang;
auto CTS = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D);
return !CTS ||
CTS->getSpecializationKind() == TSK_ExplicitSpecialization ||
CTS->getSpecializationKind() == TSK_ExplicitInstantiationDeclaration ||
CTS->getSpecializationKind() == TSK_ExplicitInstantiationDefinition;
}
static clang::SourceLocation GetDeclStartLocation(clang::CompilerInstance* C,
const clang::Decl* D)
{
auto& SM = C->getSourceManager();
auto startLoc = SM.getExpansionLoc(D->getBeginLoc());
auto startOffset = SM.getFileOffset(startLoc);
if (clang::dyn_cast_or_null<clang::TranslationUnitDecl>(D) || !startLoc.isValid())
return startLoc;
auto lineNo = SM.getExpansionLineNumber(startLoc);
auto lineBeginLoc = SM.translateLineCol(SM.getFileID(startLoc), lineNo, 1);
auto lineBeginOffset = SM.getFileOffset(lineBeginLoc);
assertm(lineBeginOffset <= startOffset, "Line starts before the file!\n");
if (D->getLexicalDeclContext()->decls_empty())
return lineBeginLoc;
auto prevDecl = GetPreviousDeclInContext(D);
if (!prevDecl || !IsExplicit(prevDecl))
return lineBeginLoc;
auto prevDeclEndLoc = SM.getExpansionLoc(prevDecl->getEndLoc());
auto prevDeclEndOffset = SM.getFileOffset(prevDeclEndLoc);
if (SM.getFileID(prevDeclEndLoc) != SM.getFileID(startLoc))
return lineBeginLoc;
// TODO: Figure out why this asserts
// assert(prevDeclEndOffset <= startOffset);
if (prevDeclEndOffset < lineBeginOffset)
return lineBeginLoc;
// Declarations don't share same macro expansion
if (SM.getExpansionLoc(prevDecl->getBeginLoc()) != startLoc)
return prevDeclEndLoc;
return GetDeclStartLocation(C, prevDecl);
}
std::string Parser::GetTypeName(const clang::Type* Type) const
{
using namespace clang;
if (Type->isAnyPointerType() || Type->isReferenceType())
Type = Type->getPointeeType().getTypePtr();
if (Type->isEnumeralType() || Type->isRecordType())
{
const clang::TagType* Tag = Type->getAs<clang::TagType>();
return GetTagDeclName(Tag->getDecl());
}
PrintingPolicy pp(c->getLangOpts());
pp.SuppressTagKeyword = true;
std::string TypeName;
QualType::getAsStringInternal(Type, Qualifiers(), TypeName, pp);
return TypeName;
}
static TypeQualifiers GetTypeQualifiers(const clang::QualType& Type)
{
TypeQualifiers quals;
quals.isConst = Type.isLocalConstQualified();
quals.isRestrict = Type.isLocalRestrictQualified();
quals.isVolatile = Type.isVolatileQualified();
return quals;
}
QualifiedType Parser::GetQualifiedType(clang::QualType qual, const clang::TypeLoc* TL)
{
if (qual.isNull())
return QualifiedType();
QualifiedType qualType;
qualType.type = WalkType(qual, TL);
qualType.qualifiers = GetTypeQualifiers(qual);
return qualType;
}
//-----------------------------------//
static AccessSpecifier ConvertToAccess(clang::AccessSpecifier AS)
{
switch (AS)
{
case clang::AS_private:
return AccessSpecifier::Private;
case clang::AS_protected:
return AccessSpecifier::Protected;
case clang::AS_public:
return AccessSpecifier::Public;
case clang::AS_none:
return AccessSpecifier::Public;
}
llvm_unreachable("Unknown AccessSpecifier");
}
VTableComponent
Parser::WalkVTableComponent(const clang::VTableComponent& Component)
{
using namespace clang;
AST::VTableComponent VTC;
switch (Component.getKind())
{
case clang::VTableComponent::CK_VCallOffset:
{
VTC.kind = VTableComponentKind::VBaseOffset;
VTC.offset = Component.getVCallOffset().getQuantity();
break;
}
case clang::VTableComponent::CK_VBaseOffset:
{
VTC.kind = VTableComponentKind::VBaseOffset;
VTC.offset = Component.getVBaseOffset().getQuantity();
break;
}
case clang::VTableComponent::CK_OffsetToTop:
{
VTC.kind = VTableComponentKind::OffsetToTop;
VTC.offset = Component.getOffsetToTop().getQuantity();
break;
}
case clang::VTableComponent::CK_RTTI:
{
VTC.kind = VTableComponentKind::RTTI;
auto RD = Component.getRTTIDecl();
VTC.declaration = WalkRecordCXX(RD);
break;
}
case clang::VTableComponent::CK_FunctionPointer:
{
VTC.kind = VTableComponentKind::FunctionPointer;
auto MD = Component.getFunctionDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_CompleteDtorPointer:
{
VTC.kind = VTableComponentKind::CompleteDtorPointer;
auto MD = Component.getDestructorDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_DeletingDtorPointer:
{
VTC.kind = VTableComponentKind::DeletingDtorPointer;
auto MD = Component.getDestructorDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
case clang::VTableComponent::CK_UnusedFunctionPointer:
{
VTC.kind = VTableComponentKind::UnusedFunctionPointer;
auto MD = Component.getUnusedFunctionDecl();
VTC.declaration = WalkMethodCXX(MD);
break;
}
default:
llvm_unreachable("Unknown vtable component kind");
}
return VTC;
}
VTableLayout Parser::WalkVTableLayout(const clang::VTableLayout& VTLayout)
{
auto Layout = VTableLayout();
for (const auto& VTC : VTLayout.vtable_components())
{
auto VTComponent = WalkVTableComponent(VTC);
Layout.Components.push_back(VTComponent);
}
return Layout;
}
void Parser::WalkVTable(const clang::CXXRecordDecl* RD, Class* C)
{
using namespace clang;
assertm(RD->isDynamicClass(), "Only dynamic classes have virtual tables!\n");
if (!C->layout)
C->layout = new ClassLayout();
auto targetABI = c->getTarget().getCXXABI().getKind();
C->layout->ABI = GetClassLayoutAbi(targetABI);
auto& AST = c->getASTContext();
switch (targetABI)
{
case TargetCXXABI::Microsoft:
{
MicrosoftVTableContext VTContext(AST);
const auto& VFPtrs = VTContext.getVFPtrOffsets(RD);
for (const auto& VFPtrInfo : VFPtrs)
{
VFTableInfo Info;
Info.VFPtrOffset = VFPtrInfo->NonVirtualOffset.getQuantity();
Info.VFPtrFullOffset = VFPtrInfo->FullOffsetInMDC.getQuantity();
auto& VTLayout = VTContext.getVFTableLayout(RD, VFPtrInfo->FullOffsetInMDC);
Info.layout = WalkVTableLayout(VTLayout);
C->layout->VFTables.push_back(Info);
}
break;
}
default:
{
ItaniumVTableContext VTContext(AST);
auto& VTLayout = VTContext.getVTableLayout(RD);
C->layout->layout = WalkVTableLayout(VTLayout);
break;
}
}
}
void Parser::EnsureCompleteRecord(const clang::RecordDecl* Record,
DeclarationContext* NS,
Class* RC)
{
using namespace clang;
if (!RC->isIncomplete || RC->completeDeclaration)
return;
Decl* Definition;
if (auto CXXRecord = dyn_cast<CXXRecordDecl>(Record))
Definition = CXXRecord->getDefinition();
else
Definition = Record->getDefinition();
if (!Definition)
return;
RC->completeDeclaration = WalkDeclaration(Definition);
}
Class* Parser::GetRecord(const clang::RecordDecl* Record, bool& Process)
{
using namespace clang;
Process = false;
auto NS = GetNamespace(Record);
assertm(NS, "Expected a valid namespace!\n");
bool isCompleteDefinition = Record->isCompleteDefinition();
Class* RC = nullptr;
auto Name = GetTagDeclName(Record);
auto HasEmptyName = Record->getDeclName().isEmpty();
if (HasEmptyName)
{
auto USR = GetDeclUSR(Record);
if (auto AR = NS->FindAnonymous(USR))
RC = static_cast<Class*>(AR);
}
else
{
RC = NS->FindClass(opts->unityBuild ? Record : 0, Name,
isCompleteDefinition, /*Create=*/false);
}
if (RC)
return RC;
RC = NS->FindClass(opts->unityBuild ? Record : 0, Name,
isCompleteDefinition, /*Create=*/true);
RC->isInjected = Record->isInjectedClassName();
HandleDeclaration(Record, RC);
EnsureCompleteRecord(Record, NS, RC);
for (auto Redecl : Record->redecls())
{
if (Redecl->isImplicit() || Redecl == Record)
continue;
RC->Redeclarations.push_back(WalkDeclaration(Redecl));
}
if (HasEmptyName)
{
auto USR = GetDeclUSR(Record);
NS->anonymous[USR] = RC;
}
if (!isCompleteDefinition)
return RC;
Process = true;
return RC;
}
Class* Parser::WalkRecord(const clang::RecordDecl* Record)
{
bool Process;
auto RC = GetRecord(Record, Process);
if (!RC || !Process)
return RC;
WalkRecord(Record, RC);
return RC;
}
Class* Parser::WalkRecordCXX(const clang::CXXRecordDecl* Record)
{
bool Process;
auto RC = GetRecord(Record, Process);
if (!RC || !Process)
return RC;
WalkRecordCXX(Record, RC);
return RC;
}
static int I = 0;
static bool IsRecordValid(const clang::RecordDecl* RC,
std::unordered_set<const clang::RecordDecl*>& Visited)
{
using namespace clang;
if (Visited.find(RC) != Visited.end())
return true;
Visited.insert(RC);
if (RC->isInvalidDecl())
return false;
for (auto Field : RC->fields())
{
auto Type = Field->getType()->getUnqualifiedDesugaredType();
const auto* RD = const_cast<CXXRecordDecl*>(Type->getAsCXXRecordDecl());
if (!RD)
RD = Type->getPointeeCXXRecordDecl();
if (RD && !IsRecordValid(RD, Visited))
return false;
}
return true;
}
static bool IsRecordValid(const clang::RecordDecl* RC)
{
std::unordered_set<const clang::RecordDecl*> Visited;
return IsRecordValid(RC, Visited);
}
static clang::CXXRecordDecl* GetCXXRecordDeclFromTemplateName(const clang::TemplateName& Name)
{
using namespace clang;
switch (Name.getKind())
{
case TemplateName::Template:
return dyn_cast<CXXRecordDecl>(Name.getAsTemplateDecl()->getTemplatedDecl());
case TemplateName::QualifiedTemplate:
return GetCXXRecordDeclFromTemplateName(Name.getAsQualifiedTemplateName()->getUnderlyingTemplate());
default:
assertm(0, "Unknown template name kind?\n");
return nullptr;
}
}
static clang::CXXRecordDecl* GetCXXRecordDeclFromBaseType(const clang::ASTContext& context, const clang::CXXBaseSpecifier& base, const clang::QualType& Ty)
{
using namespace clang;
if (auto RT = Ty->getAs<RecordType>())
return dyn_cast<CXXRecordDecl>(RT->getDecl());
else if (auto TST = Ty->getAs<clang::TemplateSpecializationType>())
return GetCXXRecordDeclFromTemplateName(TST->getTemplateName());
else if (auto Injected = Ty->getAs<clang::InjectedClassNameType>())
return Injected->getDecl();
else if (auto TTPT = Ty->getAs<TemplateTypeParmType>())
{
return nullptr;
}
else if (auto DNT = Ty->getAs<clang::DependentNameType>())
{
return nullptr;