-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathAstExporter.cpp
More file actions
3212 lines (2715 loc) · 117 KB
/
AstExporter.cpp
File metadata and controls
3212 lines (2715 loc) · 117 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
#include <algorithm>
#include <clang/AST/Type.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <optional>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Path.h"
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TypeVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/CompilerInstance.h"
#if CLANG_VERSION_MAJOR < 10
#include "clang/Frontend/LangStandard.h"
#else
#include "clang/Basic/LangStandard.h"
#endif // CLANG_VERSION_MAJOR < 10
#include "clang/Tooling/Tooling.h"
#include "AstExporter.hpp"
#include "ExportResult.hpp"
#include "FloatingLexer.h"
#include "ast_tags.hpp"
#include <tinycbor/cbor.h>
using namespace llvm;
using namespace clang;
using namespace clang::tooling;
#define DEBUG_TYPE "c2rust-ast-exporter"
#ifndef LLVM_DEBUG
#define LLVM_DEBUG DEBUG
#endif
using clang::ASTContext;
using clang::QualType;
using std::string;
namespace { // for local definitions, preferred to making each `static`
// Encode a string object assuming that it is valid UTF-8 encoded text
void cbor_encode_string(CborEncoder *encoder, const std::string &str) {
auto ptr = str.data();
auto len = str.size();
cbor_encode_text_string(encoder, ptr, len);
}
// Encode an array of strings assuming that it is valid UTF-8 encoded text
void cbor_encode_string_array(CborEncoder *encoder,
const ArrayRef<std::string> strs) {
CborEncoder array;
cbor_encoder_create_array(encoder, &array, strs.size());
for (auto &s : strs) {
cbor_encode_string(&array, s);
}
cbor_encoder_close_container(encoder, &array);
}
std::string make_realpath(std::string const &path) {
if (auto abs_path = realpath(path.c_str(), nullptr)) {
auto result = std::string(abs_path);
free(abs_path);
return result;
} else {
std::cerr << "make_realpath: File not found: " << path << std::endl;
abort();
}
}
// Helper to smooth out differences between versions of clang
#if CLANG_VERSION_MAJOR < 17
Optional<APSInt> getIntegerConstantExpr(const Expr &E, const ASTContext &Ctx) {
#if CLANG_VERSION_MAJOR < 12
APSInt value;
if (E.isIntegerConstantExpr(value, Ctx))
return {value};
else
return Optional<APSInt>();
#else
return E.getIntegerConstantExpr(Ctx);
#endif // CLANG_VERSION_MAJOR
}
#else
std::optional<APSInt> getIntegerConstantExpr(const Expr &E,
const ASTContext &Ctx) {
return E.getIntegerConstantExpr(Ctx);
}
#endif // CLANG_VERSION_MAJOR
DiagnosticBuilder getDiagBuilder(ASTContext *Context,
SourceLocation Loc,
DiagnosticsEngine::Level Lvl) {
auto &DiagEngine = Context->getDiagnostics();
// Prefix warnings with `c2rust`, so the user can distinguish
// our warning messages from those generated by clang itself.
const auto ID = DiagEngine.getCustomDiagID(Lvl, "c2rust: %0");
return DiagEngine.Report(Loc, ID);
}
void printDiag(ASTContext *Context,
DiagnosticsEngine::Level Lvl,
std::string Message,
SourceLocation S,
SourceRange R = SourceRange()) {
auto DiagBuilder =
getDiagBuilder(Context, S, Lvl);
DiagBuilder.AddString(Message);
DiagBuilder.AddSourceRange(
CharSourceRange::getCharRange(R));
}
SourceLocation getSourceLocation(const Decl *D) {
return D->getLocation();
}
SourceLocation getSourceLocation(const Expr *E) {
return E->getExprLoc();
}
SourceLocation getSourceLocation(const Stmt *S) {
#if CLANG_VERSION_MAJOR < 8
return S->getLocStart();
#else
return S->getBeginLoc();
#endif
}
template <class T> // Usually `Decl`, `Expr`, or `Stmt`.
void printDiag(ASTContext *Context, DiagnosticsEngine::Level Lvl, std::string Message, const T *t) {
const SourceLocation loc = getSourceLocation(t);
if (loc.isInvalid()) {
t->dump();
}
printDiag(Context, Lvl, Message, loc, t->getSourceRange());
}
// Extend the source range to include its entire final token. Clang source
// ranges are stored as ranges of tokens, and their end will point to the
// first byte of the final token, rather than its last byte. This converts
// the range to a character range and extends its endpoint to the final
// character of the final token.
void expandSpanToFinalChar(SourceRange& span, ASTContext* Context) {
auto &Mgr = Context->getSourceManager();
auto charRange = clang::CharSourceRange::getCharRange(span);
charRange.setEnd(clang::Lexer::getLocForEndOfToken(span.getEnd(), 0, Mgr, Context->getLangOpts()));
span = charRange.getAsRange();
}
} // namespace
class TranslateASTVisitor;
class TypeEncoder final : public TypeVisitor<TypeEncoder> {
ASTContext *Context;
CborEncoder *encoder;
std::unordered_map<void *, QualType> *sugared;
TranslateASTVisitor *astEncoder;
// Bounds recursion when visiting self-referential record declarations
std::unordered_set<const clang::RecordDecl *> recordDeclsUnderVisit;
std::unordered_set<const clang::Type *> exports;
public:
/// Set before `TypeEncoder::VisitQualType(ty)` in `TypeEncoder::VisitQualTypeOf`.
SourceLocation src_loc;
SourceRange src_range;
private:
bool markExported(const clang::Type *ptr) {
return exports.emplace(ptr).second;
}
bool isExported(const clang::Type *ptr) {
return exports.find(ptr) != exports.end();
}
void encodeType(
const clang::Type *T, TypeTag tag,
std::function<void(CborEncoder *)> extra = [](CborEncoder *) {}) {
if (!markExported(T))
return;
CborEncoder local;
cbor_encoder_create_array(encoder, &local, CborIndefiniteLength);
// 1 - Entity ID
cbor_encode_uint(&local, uintptr_t(T));
// 2 - Type tag
cbor_encode_uint(&local, tag);
// 3 - extras
extra(&local);
cbor_encoder_close_container(encoder, &local);
}
public:
uintptr_t encodeQualType(QualType t) {
auto s = t.split();
auto desugared = sugared->find((void *)s.Ty);
if (desugared != sugared->end())
return encodeQualType(desugared->second);
auto i = uintptr_t(s.Ty);
if (t.isConstQualified()) {
i |= 1;
}
if (t.isRestrictQualified()) {
i |= 2;
}
if (t.isVolatileQualified()) {
i |= 4;
}
return i;
}
explicit TypeEncoder(ASTContext *Context, CborEncoder *encoder,
std::unordered_map<void *, QualType> *sugared,
TranslateASTVisitor *ast)
: Context(Context), encoder(encoder), sugared(sugared),
astEncoder(ast) {}
template <class T> // Usually `Decl`, `Expr`, or `Stmt`.
void VisitQualTypeOf(const QualType &QT, const T *t) {
src_loc = getSourceLocation(t);
src_range = t->getSourceRange();
VisitQualType(QT);
}
void VisitQualType(const QualType &QT) {
if (!QT.isNull()) {
auto s = QT.split();
auto desugared = sugared->find((void *)s.Ty);
if (desugared != sugared->end())
VisitQualType(desugared->second);
else if (!isExported(s.Ty)) {
Visit(s.Ty);
}
}
}
void VisitAttributedType(const AttributedType *T) {
auto t = T->getModifiedType();
auto qt = encodeQualType(t);
auto k = T->getAttrKind();
encodeType(T, TagAttributedType, [qt, k](CborEncoder *local) {
cbor_encode_uint(local, qt);
const char *tag;
switch (k) {
default: tag = nullptr; break;
#if CLANG_VERSION_MAJOR < 8
case AttributedType::attr_noreturn:
#else
case attr::NoReturn:
#endif // CLANG_VERSION_MAJOR
tag = "noreturn";
break;
#if CLANG_VERSION_MAJOR < 8
case AttributedType::attr_nonnull:
#else
case attr::TypeNonNull:
#endif // CLANG_VERSION_MAJOR
tag = "notnull";
break;
#if CLANG_VERSION_MAJOR < 8
case AttributedType::attr_nullable:
#else
case attr::TypeNullable:
#endif // CLANG_VERSION_MAJOR
tag = "nullable";
break;
}
if (tag) {
cbor_encode_text_stringz(local, tag);
} else {
cbor_encode_null(local);
}
});
VisitQualType(t);
}
#if CLANG_VERSION_MAJOR >= 19
void VisitCountAttributedType(const CountAttributedType *T);
#endif
void VisitParenType(const ParenType *T) {
auto t = T->getInnerType();
auto qt = encodeQualType(t);
encodeType(T, TagParenType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
void VisitEnumType(const EnumType *T);
void VisitConstantArrayType(const ConstantArrayType *T) {
auto t = T->getElementType();
auto qt = encodeQualType(t);
encodeType(T, TagConstantArrayType, [T, qt](CborEncoder *local) {
cbor_encode_uint(local, qt);
cbor_encode_uint(local, T->getSize().getLimitedValue());
});
VisitQualType(t);
}
void VisitVariableArrayType(const VariableArrayType *T);
void VisitAtomicType(const AtomicType *AT);
void VisitIncompleteArrayType(const IncompleteArrayType *T) {
auto t = T->getElementType();
auto qt = encodeQualType(t);
encodeType(T, TagIncompleteArrayType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
void VisitBlockPointerType(const BlockPointerType *T) {
auto t = T->getPointeeType();
auto qt = encodeQualType(t);
encodeType(T, TagBlockPointer,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
// definition below due to recursive call into AST translator
void VisitRecordType(const RecordType *T);
void VisitVectorType(const clang::VectorType *T) {
auto t = T->getElementType();
auto qt = encodeQualType(t);
encodeType(T, TagVectorType, [T, qt](CborEncoder *local) {
cbor_encode_uint(local, qt);
cbor_encode_uint(local, T->getNumElements());
});
VisitQualType(t);
}
void VisitComplexType(const ComplexType *T) {
auto t = T->getElementType();
auto qt = encodeQualType(t);
encodeType(T, TagComplexType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
void VisitBuiltinType(const BuiltinType *T) {
auto kind = T->getKind();
#if CLANG_VERSION_MAJOR >= 10
// Handle built-in vector types as if they're normal vector types
if (kind >= BuiltinType::SveInt8 && kind <= BuiltinType::SveBool
#if CLANG_VERSION_MAJOR >= 13
/* RISC-V vector types */
|| kind >= BuiltinType::RvvInt8mf8 && kind <= BuiltinType::RvvBool64
#endif // CLANG_VERSION_MAJOR >= 13
) {
// Declare ElemType and ElemCount as needed by various Clang versions
#if CLANG_VERSION_MAJOR >= 11
auto Info = Context->getBuiltinVectorTypeInfo(T);
auto ElemType = Info.ElementType;
#if CLANG_VERSION_MAJOR >= 12
auto ElemCount = Info.EC.getKnownMinValue() * Info.NumVectors;
#else // CLANG_VERSION_MAJOR >= 12
// getKnownMinValue was added in Clang 12.
auto ElemCount = Info.EC.Min * Info.NumVectors;
#endif // CLANG_VERSION_MAJOR >= 12
#else // CLANG_VERSION_MAJOR >= 11
auto &Ctx = *Context;
// Copy-pasted from Type::getSveEltType introduced after Clang 10:
// (Not extended for RISCV types
// as they are not available in that version anyway).
auto ElemType = [&] {
switch (kind) {
default: llvm_unreachable("Unknown builtin SVE type!");
case BuiltinType::SveInt8: return Ctx.SignedCharTy;
case BuiltinType::SveUint8: return Ctx.UnsignedCharTy;
case BuiltinType::SveBool: return Ctx.UnsignedCharTy;
case BuiltinType::SveInt16: return Ctx.ShortTy;
case BuiltinType::SveUint16: return Ctx.UnsignedShortTy;
case BuiltinType::SveInt32: return Ctx.IntTy;
case BuiltinType::SveUint32: return Ctx.UnsignedIntTy;
case BuiltinType::SveInt64: return Ctx.LongTy;
case BuiltinType::SveUint64: return Ctx.UnsignedLongTy;
case BuiltinType::SveFloat16: return Ctx.Float16Ty;
case BuiltinType::SveFloat32: return Ctx.FloatTy;
case BuiltinType::SveFloat64: return Ctx.DoubleTy;
}
}();
// All the SVE types present in Clang 10 are 128-bit vectors
// (see `AArch64SVEACLETypes.def`), so we can divide 128
// by their element size to get element count.
auto ElemCount = 128 / Context->getTypeSize(ElemType);
#endif // CLANG_VERSION_MAJOR >= 11
auto ElemTypeTag = encodeQualType(ElemType);
encodeType(T, TagVectorType,
[&](CborEncoder *local) {
cbor_encode_uint(local, ElemTypeTag);
cbor_encode_uint(local, ElemCount);
});
VisitQualType(ElemType);
return;
}
#endif // CLANG_VERSION_MAJOR >= 10
const TypeTag tag = [&] {
switch (kind) {
case BuiltinType::BuiltinFn: return TagBuiltinFn;
case BuiltinType::UInt128: return TagUInt128;
case BuiltinType::Int128: return TagInt128;
case BuiltinType::Short: return TagShort;
case BuiltinType::Int: return TagInt;
case BuiltinType::Long: return TagLong;
case BuiltinType::LongLong: return TagLongLong;
case BuiltinType::UShort: return TagUShort;
case BuiltinType::UInt: return TagUInt;
case BuiltinType::ULong: return TagULong;
case BuiltinType::ULongLong: return TagULongLong;
// Constructed as a consequence of the conversion of
// built-in to normal vector types.
case BuiltinType::Float16: return TagHalf;
case BuiltinType::Half: return TagHalf;
#if CLANG_VERSION_MAJOR >= 11
case BuiltinType::BFloat16: return TagBFloat16;
#endif
case BuiltinType::Float: return TagFloat;
case BuiltinType::Double: return TagDouble;
case BuiltinType::LongDouble: return TagLongDouble;
case BuiltinType::SChar: return TagSChar;
case BuiltinType::UChar: return TagUChar;
case BuiltinType::Char_U: return TagChar;
case BuiltinType::Char_S: return TagChar;
case BuiltinType::Void: return TagVoid;
case BuiltinType::Bool: return TagBool;
case BuiltinType::WChar_S: return TagSWChar;
case BuiltinType::WChar_U: return TagUWChar;
case BuiltinType::Float128: return TagFloat128;
#if CLANG_VERSION_MAJOR >= 17
// From `clang/include/clang/Basic/AArch64ACLETypes.def`,
// but we can't `#include` it in an external clang tool.
case BuiltinType::SveInt8:
case BuiltinType::SveInt16:
case BuiltinType::SveInt32:
case BuiltinType::SveInt64:
case BuiltinType::SveUint8:
case BuiltinType::SveUint16:
case BuiltinType::SveUint32:
case BuiltinType::SveUint64:
case BuiltinType::SveFloat16:
case BuiltinType::SveFloat32:
case BuiltinType::SveFloat64:
case BuiltinType::SveBFloat16:
case BuiltinType::SveInt8x2:
case BuiltinType::SveInt16x2:
case BuiltinType::SveInt32x2:
case BuiltinType::SveInt64x2:
case BuiltinType::SveUint8x2:
case BuiltinType::SveUint16x2:
case BuiltinType::SveUint32x2:
case BuiltinType::SveUint64x2:
case BuiltinType::SveFloat16x2:
case BuiltinType::SveFloat32x2:
case BuiltinType::SveFloat64x2:
case BuiltinType::SveBFloat16x2:
case BuiltinType::SveInt8x3:
case BuiltinType::SveInt16x3:
case BuiltinType::SveInt32x3:
case BuiltinType::SveInt64x3:
case BuiltinType::SveUint8x3:
case BuiltinType::SveUint16x3:
case BuiltinType::SveUint32x3:
case BuiltinType::SveUint64x3:
case BuiltinType::SveFloat16x3:
case BuiltinType::SveFloat32x3:
case BuiltinType::SveFloat64x3:
case BuiltinType::SveBFloat16x3:
case BuiltinType::SveInt8x4:
case BuiltinType::SveInt16x4:
case BuiltinType::SveInt32x4:
case BuiltinType::SveInt64x4:
case BuiltinType::SveUint8x4:
case BuiltinType::SveUint16x4:
case BuiltinType::SveUint32x4:
case BuiltinType::SveUint64x4:
case BuiltinType::SveFloat16x4:
case BuiltinType::SveFloat32x4:
case BuiltinType::SveFloat64x4:
case BuiltinType::SveBFloat16x4:
case BuiltinType::SveBool:
case BuiltinType::SveBoolx2:
case BuiltinType::SveBoolx4:
case BuiltinType::SveCount:
#endif // CLANG_VERSION_MAJOR >= 17
#if CLANG_VERSION_MAJOR >= 20
case BuiltinType::MFloat8:
case BuiltinType::SveMFloat8:
case BuiltinType::SveMFloat8x2:
case BuiltinType::SveMFloat8x3:
case BuiltinType::SveMFloat8x4:
#endif // CLANG_VERSION_MAJOR >= 20
return TagSve;
default:
auto pol = clang::PrintingPolicy(Context->getLangOpts());
auto warning = std::string("Encountered unsupported BuiltinType kind ") +
std::to_string((int)kind) + " for type " +
T->getName(pol).str();
printDiag(Context, DiagnosticsEngine::Warning, warning, src_loc, src_range);
return TagTypeUnknown;
}
}();
encodeType(T, tag);
}
// Clang represents function declarations with parameters as
// `FunctionProtoType` instances whereas functions w/o parameters are
// handled as `FunctionNoPrototype` instances. Note: we could handle both
// cases by overriding `VisitFunctionType` instead of the current
// two-function solution.
void VisitFunctionProtoType(const FunctionProtoType *T) {
LLVM_DEBUG(dbgs() << "Visit ");
LLVM_DEBUG(T->dump());
encodeType(T, TagFunctionType, [T, this](CborEncoder *local) {
CborEncoder arrayEncoder;
// Function types are encoded with an extra list of types. The
// return type is always the first element of the list followed by
// the parameters.
size_t elts = T->getNumParams() + 1;
cbor_encoder_create_array(local, &arrayEncoder, elts);
cbor_encode_uint(&arrayEncoder, encodeQualType(T->getReturnType()));
for (auto t : T->param_types()) {
cbor_encode_uint(&arrayEncoder, encodeQualType(t));
}
cbor_encoder_close_container(local, &arrayEncoder);
cbor_encode_boolean(local, T->getExtProtoInfo().Variadic);
cbor_encode_boolean(local, T->getNoReturnAttr());
cbor_encode_boolean(local, true); // has arguments
});
VisitQualType(T->getReturnType());
for (auto x : T->param_types()) {
VisitQualType(x);
}
}
// See `VisitFunctionProtoType`.
void VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
encodeType(T, TagFunctionType, [T](CborEncoder *local) {
CborEncoder arrayEncoder;
cbor_encoder_create_array(local, &arrayEncoder, 1);
cbor_encode_uint(&arrayEncoder,
uintptr_t(T->getReturnType().getTypePtrOrNull()));
cbor_encoder_close_container(local, &arrayEncoder);
cbor_encode_boolean(local, false); // Variable argument function
cbor_encode_boolean(local, T->getNoReturnAttr());
cbor_encode_boolean(local, false); // has arguments
});
VisitQualType(T->getReturnType());
}
void VisitPointerType(const clang::PointerType *T) {
auto pointee = T->getPointeeType();
auto qt = encodeQualType(pointee);
encodeType(T, TagPointer,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(pointee);
}
// Although C does not have references, Clang's built-in functions for
// `va_start`, `va_end`, etc. may use C++ references in 32-bit mode.
void VisitReferenceType(const clang::ReferenceType *T) {
auto pointee = T->getPointeeType();
auto qt = encodeQualType(pointee);
encodeType(T, TagReference,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(pointee);
}
void VisitTypedefType(const TypedefType *T);
void VisitTypeOfType(const TypeOfType *T) {
auto t = T->desugar();
auto qt = encodeQualType(t);
encodeType(T, TagTypeOfType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
void VisitTypeOfExprType(const TypeOfExprType *T) {
auto t = T->desugar();
auto qt = encodeQualType(t);
encodeType(T, TagTypeOfType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
#if CLANG_VERSION_MAJOR < 22
void VisitElaboratedType(const ElaboratedType *T) {
auto t = T->desugar();
auto qt = encodeQualType(t);
encodeType(T, TagElaboratedType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
#endif
void VisitDecayedType(const DecayedType *T) {
auto t = T->desugar();
auto qt = encodeQualType(t);
encodeType(T, TagDecayedType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
void VisitAutoType(const AutoType *T) {
if (!T->isGNUAutoType()) {
printDiag(Context, DiagnosticsEngine::Warning,
"Encountered unexpected auto type",
src_loc, src_range);
return;
}
auto t = T->desugar();
auto qt = encodeQualType(t);
encodeType(T, TagAutoType,
[qt](CborEncoder *local) { cbor_encode_uint(local, qt); });
VisitQualType(t);
}
#if CLANG_VERSION_MAJOR >= 22
void VisitPredefinedSugarType(const clang::PredefinedSugarType *T) {
auto t = T->desugar();
auto k = T->getKind();
encodeType(T, TagPredefinedSugarType,
[k](CborEncoder *local) { cbor_encode_uint(local, uint64_t(k)); });
VisitQualType(t);
}
#endif
};
class TranslateASTVisitor final
: public RecursiveASTVisitor<TranslateASTVisitor> {
struct MacroExpansionInfo {
StringRef Name;
};
ASTContext *Context;
TypeEncoder typeEncoder;
CborEncoder *encoder;
Preprocessor &PP;
std::vector<std::pair<string, SourceLocation>> files;
// Mapping from SourceManager FileID to index in files
DenseMap<FileID, size_t> file_id_mapping;
std::set<std::pair<void *, ASTEntryTag>> exportedTags;
std::unordered_map<MacroInfo*, MacroExpansionInfo> macros;
// This stores a raw encoding of the macro call site SourceLocation, since
// SourceLocation isn't hashable.
std::unordered_set<unsigned> macroCallSites;
SmallVector<MacroInfo*, 1> curMacroExpansionStack;
StringRef curMacroExpansionSource;
// Returns true when a new entry is added to exportedTags
bool markForExport(void *ptr, ASTEntryTag tag) {
return exportedTags.emplace(ptr, tag).second;
}
bool isExported(void *ptr, ASTEntryTag tag) {
auto search = exportedTags.find(std::make_pair(ptr, tag));
return search != std::end(exportedTags);
}
bool evaluateConstantInt(Expr *E, APSInt &constant) {
assert(E != nullptr);
auto value = getIntegerConstantExpr(*E, *Context);
if (value) {
constant = *value;
return true;
} else {
#if CLANG_VERSION_MAJOR < 8
APSInt eval_result;
#else
Expr::EvalResult eval_result;
#endif // CLANG_VERSION_MAJOR
bool hasValue = E->EvaluateAsInt(eval_result, *Context);
#if CLANG_VERSION_MAJOR < 8
constant = eval_result;
#else
if (hasValue) {
constant = eval_result.Val.getInt();
}
#endif // CLANG_VERSION_MAJOR
return hasValue;
}
}
// Template required because Decl and Stmt don't share a common base class
void encode_entry_raw(void *ast, ASTEntryTag tag, SourceRange loc,
const QualType ty, bool rvalue,
bool isVaList, bool encodeMacroExpansions,
const std::vector<void *> &childIds,
std::function<void(CborEncoder *)> extra) {
if (!markForExport(ast, tag))
return;
CborEncoder local, childEnc;
cbor_encoder_create_array(encoder, &local, CborIndefiniteLength);
// 0 - Entry ID
cbor_encode_uint(&local, uintptr_t(ast));
// 1 - Entry Tag
cbor_encode_uint(&local, tag);
// 2 - Entry Children
cbor_encoder_create_array(&local, &childEnc, childIds.size());
for (auto x : childIds) {
if (x == nullptr) {
cbor_encode_null(&childEnc);
} else {
cbor_encode_uint(&childEnc, uintptr_t(x));
}
}
cbor_encoder_close_container(&local, &childEnc);
// 3 - File number
// 4 - Begin Line number
// 5 - Begin Column number
// 6 - End Line number
// 7 - End Column number
encodeSourceSpan(&local, loc, isVaList);
// 8 - Type ID (only for expressions)
encode_qualtype(&local, ty);
// 9 - Is Rvalue (only for expressions)
cbor_encode_boolean(&local, rvalue);
// 10 - Macro expansion stack, starting with initial macro call and ending
// with the innermost replacement.
cbor_encoder_create_array(&local, &childEnc,
encodeMacroExpansions ? curMacroExpansionStack.size() : 0);
if (encodeMacroExpansions) {
for (auto I = curMacroExpansionStack.rbegin(), E = curMacroExpansionStack.rend();
I != E; ++I) {
cbor_encode_uint(&childEnc, uintptr_t(*I));
}
}
cbor_encoder_close_container(&local, &childEnc);
// 11 - Macro expansion source string, if applicable.
if (!curMacroExpansionSource.empty()) {
cbor_encode_string(&local, curMacroExpansionSource.str());
} else {
cbor_encode_null(&local);
}
// 12.. - Extra entries
extra(&local);
cbor_encoder_close_container(encoder, &local);
}
void encode_qualtype(CborEncoder *enc, QualType ty) {
if (ty.getTypePtrOrNull()) {
cbor_encode_uint(enc, typeEncoder.encodeQualType(ty));
} else {
cbor_encode_null(enc);
}
}
void encode_entry(
Expr *ast, ASTEntryTag tag, const std::vector<void *> &childIds,
std::function<void(CborEncoder *)> extra = [](CborEncoder *) {}) {
auto ty = ast->getType();
auto isVaList = false;
auto encodeMacroExpansions = true;
#if CLANG_VERSION_MAJOR < 13
bool isRValue = ast->isRValue();
#else
// prvalues are equivalent to rvalues in C++03.
//
// NOTE: We used to call ast->Classify(*Context).isRValue() but that may
// result in a segfault on LLVM 18 and 19 for certain string literals.
// See https://github.com/immunant/c2rust/issues/1124
bool isRValue = ast->getValueKind() == VK_PRValue;
#endif
auto span = ast->getSourceRange();
expandSpanToFinalChar(span, Context);
encode_entry_raw(ast, tag, span, ty, isRValue, isVaList,
encodeMacroExpansions, childIds, extra);
typeEncoder.VisitQualTypeOf(ty, ast);
}
void encode_entry(
Stmt *ast, ASTEntryTag tag, const std::vector<void *> &childIds,
std::function<void(CborEncoder *)> extra = [](CborEncoder *) {}) {
QualType s = QualType(static_cast<clang::Type *>(nullptr), 0);
auto rvalue = false;
auto isVaList = false;
auto encodeMacroExpansions = false;
auto span = ast->getSourceRange();
expandSpanToFinalChar(span, Context);
encode_entry_raw(ast, tag, span, s, rvalue, isVaList,
encodeMacroExpansions, childIds, extra);
}
void encode_entry(
Decl *ast, ASTEntryTag tag, const std::vector<void *> &childIds,
const QualType T,
std::function<void(CborEncoder *)> extra = [](CborEncoder *) {}) {
auto rvalue = false;
auto encodeMacroExpansions = false;
auto span = ast->getSourceRange();
expandSpanToFinalChar(span, Context);
encode_entry_raw(ast, tag, span, T, rvalue,
isVaList(ast, T), encodeMacroExpansions, childIds, extra);
}
/// Explicitly override the source location of this decl for cases where the
/// definition location is not the same as the canonical declaration
/// location.
void encode_entry(
Decl *ast, ASTEntryTag tag, SourceRange loc,
const std::vector<void *> &childIds, const QualType T,
std::function<void(CborEncoder *)> extra = [](CborEncoder *) {}) {
auto rvalue = false;
auto encodeMacroExpansions = false;
expandSpanToFinalChar(loc, Context);
encode_entry_raw(ast, tag, loc, T, rvalue,
isVaList(ast, T), encodeMacroExpansions, childIds, extra);
}
MacroInfo* getMacroInfo(SourceLocation loc, StringRef &name) const {
auto &Mgr = Context->getSourceManager();
Token Result;
if (!Lexer::getRawToken(Mgr.getSpellingLoc(loc), Result,
Mgr, Context->getLangOpts(), false)) {
if (Result.is(tok::raw_identifier)) {
PP.LookUpIdentifierInfo(Result);
}
IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
if (IdentifierInfo && IdentifierInfo->hadMacroDefinition()) {
std::pair<FileID, unsigned int> DecLoc =
Mgr.getDecomposedExpansionLoc(loc);
// Get the definition just before the searched location
// so that a macro referenced in a '#undef MACRO' can
// still be found.
SourceLocation BeforeSearchedLocation =
Mgr.getMacroArgExpandedLocation(
Mgr.getLocForStartOfFile(DecLoc.first)
.getLocWithOffset(DecLoc.second - 1));
MacroDefinition MacroDef = PP.getMacroDefinitionAtLoc(
IdentifierInfo, BeforeSearchedLocation);
MacroInfo *MacroInf = MacroDef.getMacroInfo();
if (MacroInf) {
LLVM_DEBUG(dbgs() << IdentifierInfo->getName() << "\n");
LLVM_DEBUG(MacroInf->dump());
LLVM_DEBUG(dbgs() << "\n");
name = IdentifierInfo->getName();
return MacroInf;
}
}
}
return nullptr;
}
bool VisitMacro(StringRef name, SourceLocation loc, MacroInfo *mac, Expr *E) {
// TODO: handle builtin macros
if (mac->isBuiltinMacro())
return false;
// If this isn't the first time we've seen this macro call site, we
// shouldn't associate this expression with the macro as it is a subexpr
// of a previously seen expression.
if (!macroCallSites.insert(loc.getRawEncoding()).second)
return false;
auto &info = macros[mac];
if (info.Name.empty())
info.Name = name;
else if (info.Name != name)
return false;
typeEncoder.VisitQualTypeOf(E->getType(), E);
return true;
}
static bool isScalarAsmType(QualType ty) {
ty = ty.getCanonicalType();
switch (ty->getTypeClass()) {
case clang::Type::Builtin:
case clang::Type::Pointer:
case clang::Type::Vector:
case clang::Type::ExtVector:
case clang::Type::FunctionProto:
case clang::Type::FunctionNoProto:
case clang::Type::Enum:
return true;
case clang::Type::Atomic:
return isScalarAsmType(cast<AtomicType>(ty)->getValueType());
default:
return false;
}
}
public:
explicit TranslateASTVisitor(ASTContext *Context, CborEncoder *encoder,
std::unordered_map<void *, QualType> *sugared,
Preprocessor &PP)
: Context(Context), typeEncoder(Context, encoder, sugared, this),
encoder(encoder), PP(PP),
files{{"", {}}} {}
// Override the default behavior of the RecursiveASTVisitor
bool shouldVisitImplicitCode() const { return true; }
// Return the filenames as a vector. Indices correspond to file IDs.
const std::vector<std::pair<string, SourceLocation>> &getFiles() {
// Iterate file include locations until fix point
auto &manager = Context->getSourceManager();
size_t size;
do {
size = files.size();
/* Cannot use iterator over files here, as getExporterFileId
* potentially modifies files. This also prevents use of
* for (auto const &file : files) here. */
for (size_t idx = 0; idx < size; idx++) {