-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimpl.cpp
More file actions
3345 lines (3158 loc) · 143 KB
/
Copy pathimpl.cpp
File metadata and controls
3345 lines (3158 loc) · 143 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 "generated.h"
#include "clang/Driver/Driver.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/MacroArgs.h"
#include "clang/Tooling/CompilationDatabase.h"
#include "clang/Tooling/Tooling.h"
#include <dlfcn.h>
#include <map>
#include <optional>
#include <sstream>
#include <unordered_set>
#include <vector>
using namespace clang;
using namespace clang::tooling;
using rust::Ref;
using rust::RefMut;
using rust::std::rc::Rc;
using rust::std::vec::Vec;
using namespace rust::pal::clang;
namespace ir = rust::pal::ir;
using OptExpr = rust::core::option::Option<Rc<ir::Expr>>;
llvm::StringRef toStringRef(Ref<rust::Str> str) {
return llvm::StringRef((char const *)str.as_ptr(), str.len());
}
std::string toString(Ref<rust::Str> str) {
return std::string((char const *)str.as_ptr(), str.len());
}
Ref<rust::Str> toStr(llvm::StringRef const &str) {
return str_from_parts((uint8_t const *)str.data(), str.size());
}
Ref<rust::Str> toStr(std::string const &str) {
return str_from_parts((uint8_t const *)str.data(), str.size());
}
// Returns true if `s` contains a `continue` that binds to the enclosing loop,
// i.e. a `continue` that is not nested inside another loop. Nested `for`,
// `while`, and `do-while` loops act as boundaries (their `continue` belongs to
// them), so we do not descend into them. A `switch` does NOT capture `continue`
// in C, so we descend into it (and into `if`, blocks, labels, etc.).
static bool hasTopLevelContinue(const Stmt *s) {
if (!s)
return false;
if (isa<ContinueStmt>(s))
return true;
if (isa<ForStmt>(s) || isa<WhileStmt>(s) || isa<DoStmt>(s))
return false;
for (const Stmt *child : s->children())
if (hasTopLevelContinue(child))
return true;
return false;
}
using SnipMap = rust::pal::hauntedc::SnippetMap;
using TargetIntWidths = rust::pal::hauntedc::TargetIntWidths;
template <> struct std::hash<FileID> {
std::size_t operator()(FileID const &s) const noexcept {
return s.getHashValue();
}
};
struct RangeMap {
RangeMap(RefMut<Ctx> &c) : ctx(c) {}
RefMut<Ctx> ctx;
std::unordered_map<FileID, Rc<rust::Str>> files;
Rc<rust::Str> getFileName(SourceManager &sm, FileID id) {
if (auto result = files.find(id); result != files.end()) {
return result->second.clone();
} else {
rust::Ref<rust::Str> fn = "<unknown>"_rs;
if (id.isValid()) {
if (auto entryRef = sm.getFileEntryRefForID(id)) {
fn = toStr(entryRef->getName());
}
}
auto res = ctx.intern_str(fn);
files[id] = res.clone();
return res;
}
}
Rc<ir::SourceInfo> getExpansionRange(SourceManager &sm, SourceRange range) {
return mk_original_location(
getFileName(sm, sm.getFileID(sm.getExpansionLoc(range.getBegin()))),
sm.getExpansionLineNumber(range.getBegin()),
sm.getExpansionColumnNumber(range.getBegin()),
sm.getExpansionLineNumber(range.getEnd()),
sm.getExpansionColumnNumber(range.getEnd()));
}
};
class MacroTracker : public PPCallbacks {
public:
MacroTracker(RangeMap &m, SnipMap &s, CompilerInstance &ci)
: rangeMap(m), snippets(s), compilerInst(ci) {}
RangeMap &rangeMap;
SnipMap &snippets;
CompilerInstance &compilerInst;
void MacroExpands(Token const &MacroNameTok, MacroDefinition const &MD,
SourceRange Range, MacroArgs const *Args) override {
auto &sm = compilerInst.getSourceManager();
auto &langOpts = compilerInst.getLangOpts();
if (Args) {
InlineCodeBuilder toks = InlineCodeBuilder::new_();
unsigned numArgs = Args->getNumMacroArguments();
for (unsigned i = 0; i < numArgs; ++i) {
Token const *argTokens = Args->getUnexpArgument(i);
unsigned numTokens = Args->getArgLength(argTokens);
for (unsigned j = 0; j < numTokens; ++j) {
auto &tok = argTokens[j];
std::string spelling = Lexer::getSpelling(tok, sm, langOpts);
Rc<ir::SourceInfo> loc;
SourceLocation tokLoc = sm.getSpellingLoc(tok.getLocation());
if (auto fileID = sm.getFileID(tokLoc); fileID.isValid()) {
unsigned beginLine = sm.getSpellingLineNumber(tokLoc);
unsigned beginChar = sm.getSpellingColumnNumber(tokLoc);
unsigned endLine = beginLine;
unsigned endChar = beginChar + spelling.length();
loc = mk_original_location(rangeMap.getFileName(sm, fileID),
beginLine, beginChar, endLine, endChar);
} else {
auto expansionRange = sm.getExpansionRange(
SourceRange(tok.getLocation(), tok.getEndLoc()));
unsigned beginLine =
sm.getExpansionLineNumber(expansionRange.getBegin());
unsigned beginChar =
sm.getExpansionColumnNumber(expansionRange.getBegin());
unsigned endLine =
sm.getExpansionLineNumber(expansionRange.getEnd());
unsigned endChar =
sm.getExpansionColumnNumber(expansionRange.getEnd());
loc = mk_fallback_sourceinfo(mk_original_location(
rangeMap.getFileName(sm,
sm.getFileID(expansionRange.getBegin())),
beginLine, beginChar, endLine, endChar));
}
Ref<rust::Str> before = tok.isAtStartOfLine() ? "\n"_rs
: tok.hasLeadingSpace() ? " "_rs
: ""_rs;
toks.push_token(before, std::move(loc), toStr(spelling));
}
}
unsigned ctr = compilerInst.getPreprocessor().getCounterValue();
toks.insert_into_map(ctr, snippets);
}
}
};
Rc<rust::num_bigint::BigInt> toBigInt(llvm::APInt const &n) {
llvm::SmallString<16> out;
n.toStringSigned(out);
return mk_bigint(toStr(out));
}
Rc<rust::num_bigint::BigInt> toBigInt(llvm::APSInt const &n) {
llvm::SmallString<16> out;
n.toString(out);
return mk_bigint(toStr(out));
}
struct AnonNameGen {
llvm::StringRef base;
unsigned i = 0;
AnonNameGen(llvm::StringRef b) : base(b) {}
std::string next() {
std::ostringstream out;
out.write(base.data(), base.size());
out << "_anon_" << ++i;
return out.str();
}
};
class PALConsumer : public ASTConsumer {
public:
PALConsumer(RefMut<Ctx> c, RangeMap &m, SnipMap &s, CompilerInstance &ci)
: ctx(c), rangeMap(m), snippets(s), sm(ci.getSourceManager()) {}
RefMut<Ctx> ctx;
RangeMap &rangeMap;
SnipMap &snippets;
SourceManager &sm;
ASTContext *astCtx = nullptr;
std::unordered_set<RecordDecl *>
alreadyDefined; // guard against recursive structures
std::unordered_map<RecordDecl *, std::string>
structNames; // map record decls to generated struct names
Expr *forLoopIncrement = nullptr;
// When inside a switch desugaring, break sets this flag instead of mk_break
Rc<ir::Ident> *switchBreakId = nullptr;
// TODO: should probably wait with translation until after parsing
void Initialize(ASTContext &Context) override {
astCtx = &Context;
auto const &TI = Context.getTargetInfo();
ctx.set_target_int_widths(
TargetIntWidths(TI.getCharWidth(), TI.getShortWidth(), TI.getIntWidth(),
TI.getLongWidth(), TI.getLongLongWidth()));
}
virtual bool HandleTopLevelDecl(DeclGroupRef DG) override {
for (auto D : DG)
HandleDecl(D);
return ASTConsumer::HandleTopLevelDecl(DG);
}
Rc<ir::Ident> getDeclName(NamedDecl *d) {
auto loc = mk_fallback_sourceinfo(
getRange(d->getSourceRange())); // TODO: get range of name token
return ctx.mk_ident(toStr(d->getName()), std::move(loc));
}
// Name to use for a struct/union field. Unnamed fields (e.g. C11 anonymous
// struct/union members) have no identifier, so we synthesize a stable name
// from the field's index within its record. The index is deterministic and
// shared by the field definition and every member access referring to it, so
// the synthesized names stay consistent across the whole translation.
std::string fieldNameStr(FieldDecl const *f) {
if (f->getIdentifier())
return f->getName().str();
return "_unnamed" + std::to_string(f->getFieldIndex());
}
RecordDecl *recordKey(RecordDecl *decl) {
return cast<RecordDecl>(decl->getCanonicalDecl());
}
Rc<ir::SourceInfo> getRange(SourceRange const &range) {
return rangeMap.getExpansionRange(sm, range);
}
template <typename T>
void reportUnsupported(SourceRange const &rng, Rc<ir::SourceInfo> const &loc,
char const *msg, T const &extra) {
if (!sm.isInMainFile(sm.getExpansionLoc(rng.getBegin()))) {
// only complain about unsupported syntax in main file
return;
}
ctx.report_diag(loc.clone(), true, toStr(std::string(msg) + extra));
}
// Translate a single struct/union field into the IR, pushing it onto the
// given builder. Handles plain fields and unsigned bit-fields; rejects
// signed bit-fields and skips anonymous/zero-width padding bit-fields.
void addRecordField(DeclBuilder &builder, FieldDecl *f,
AnonNameGen *liftStructs, bool inUnion) {
auto floc = getRange(f->getSourceRange());
if (f->isBitField()) {
// Anonymous / zero-width bit-fields are pure padding with no accessible
// value; drop them entirely.
if (f->isUnnamedBitField())
return;
// Bit-fields are only modeled inside structs; union bit-fields would need
// the same value-based encoding layered on the union variant model.
if (inUnion) {
reportUnsupported(f->getSourceRange(), floc,
"unsupported bit-field in union", "");
return;
}
// Only unsigned (and _Bool) bit-fields are modeled. Signed bit-fields
// would need sign-extension on read and have implementation-defined
// out-of-range write semantics (C11 6.3.1.3p3), so reject them.
if (!f->getType()->isUnsignedIntegerType()) {
reportUnsupported(
f->getSourceRange(), floc,
"unsupported signed bit-field (only unsigned bit-fields are "
"supported)",
"");
return;
}
unsigned width = f->getBitWidthValue();
builder.field_bitfield(
ctx.mk_ident(toStr(fieldNameStr(f)), std::move(floc)),
trQualType(f->getType(), f->getSourceRange(), liftStructs), width);
return;
}
auto qt = f->getType();
auto *qtPtr = qt.IgnoreParens().getTypePtr();
if (auto *iat = dyn_cast<IncompleteArrayType>(qtPtr)) {
// Flexible array member: `T name[]` as the last field of a struct (C11
// 6.7.2.1). Clang guarantees it is the last field. Model it inline as an
// unsized `array_spec T` in the noeq record; a `_refines(...)` clause on
// the field supplies an optional length refinement.
if (inUnion) {
reportUnsupported(f->getSourceRange(), floc,
"unsupported flexible array member in union", "");
return;
}
auto elemTy =
trQualType(iat->getElementType(), f->getSourceRange(), liftStructs);
builder.field(
ctx.mk_ident(toStr(fieldNameStr(f)), std::move(floc)),
trTypeAttrs(f->getAttrs(),
mk_flex_array_type(getRange(f->getSourceRange()),
std::move(elemTy))));
} else if (isa<VariableArrayType>(qtPtr)) {
reportUnsupported(f->getSourceRange(), floc,
"unsupported non-constant-length array field", "");
} else {
builder.field(
ctx.mk_ident(toStr(fieldNameStr(f)), std::move(floc)),
trTypeAttrs(f->getAttrs(),
trQualType(f->getType(), f->getSourceRange(), liftStructs,
findFnProtoTypeLoc(f->getTypeSourceInfo())),
f->getType(), f->getSourceRange()));
}
}
void trRecordDecl(Rc<ir::Ident> ident, RecordDecl *decl,
AnonNameGen *liftStructs) {
auto key = recordKey(decl);
if (!decl->isCompleteDefinition()) {
if (decl->getTagKind() == TagTypeKind::Struct) {
auto loc = getRange(decl->getSourceRange());
ctx.add_struct_decl(std::move(loc), std::move(ident));
}
return;
}
if (!alreadyDefined.insert(key).second)
return;
auto loc = getRange(decl->getSourceRange());
auto builder = DeclBuilder::new_(loc.clone(), ident.clone());
if (decl->getTagKind() == TagTypeKind::Struct) {
builder.refines(trTypeAttrs(decl->getAttrs(),
mk_type_struct(loc.clone(), ident.clone())));
// Check for struct-level attributes
if (decl->hasAttrs()) {
for (auto *attr : decl->getAttrs()) {
if (auto *ann = dyn_cast<AnnotateAttr>(attr)) {
if (ann->getAnnotation() == "pal-eager-unfold-predicate" &&
ann->args_size() == 0) {
builder.set_eager_unfold_pred();
}
}
}
}
// Process nested record declarations (inner structs/unions)
for (auto *D : decl->decls()) {
if (auto *inner = dyn_cast<RecordDecl>(D)) {
if (inner->isCompleteDefinition() && inner->getIdentifier()) {
auto innerLoc = getRange(inner->getSourceRange());
auto innerName =
ctx.mk_ident(toStr(inner->getName()), innerLoc.clone());
auto innerAnon = AnonNameGen(inner->getName());
trRecordDecl(std::move(innerName), inner, &innerAnon);
}
}
}
for (auto f : decl->fields()) {
addRecordField(builder, f, liftStructs, /*inUnion=*/false);
}
ctx.add_struct(std::move(builder));
} else if (decl->getTagKind() == TagTypeKind::Union) {
// Process nested record declarations (inner structs/unions)
for (auto *D : decl->decls()) {
if (auto *inner = dyn_cast<RecordDecl>(D)) {
if (inner->isCompleteDefinition() && inner->getIdentifier()) {
auto innerLoc = getRange(inner->getSourceRange());
auto innerName =
ctx.mk_ident(toStr(inner->getName()), innerLoc.clone());
auto innerAnon = AnonNameGen(inner->getName());
trRecordDecl(std::move(innerName), inner, &innerAnon);
}
}
}
for (auto f : decl->fields()) {
addRecordField(builder, f, liftStructs, /*inUnion=*/true);
}
ctx.add_union(std::move(builder));
} else {
reportUnsupported(decl->getSourceRange(), loc, "unsupported record kind",
"");
}
}
Rc<ir::Type> trFnPtrType(const FunctionProtoType *proto, SourceRange range,
Rc<ir::SourceInfo> loc,
AnonNameGen *liftStructs = nullptr,
FunctionProtoTypeLoc protoLoc = {}) {
auto args = Vec<Rc<ir::Type>>::new_();
for (unsigned i = 0; i < proto->getNumParams(); ++i) {
ParmVarDecl *paramDecl = protoLoc && i < protoLoc.getNumParams()
? protoLoc.getParam(i)
: nullptr;
SourceRange paramRange = paramDecl ? paramDecl->getSourceRange() : range;
auto param = trQualType(
proto->getParamType(i), paramRange, liftStructs,
paramDecl ? findFnProtoTypeLoc(paramDecl->getTypeSourceInfo())
: FunctionProtoTypeLoc{});
if (paramDecl) {
param = trTypeAttrs(paramDecl->getAttrs(), std::move(param),
paramDecl->getType(), paramRange);
}
args.push(std::move(param));
}
auto ret = trQualType(proto->getReturnType(), range, liftStructs);
return mk_type_fnptr(std::move(loc), std::move(args), std::move(ret));
}
FunctionProtoTypeLoc findFnProtoTypeLoc(TypeSourceInfo *typeInfo) {
if (!typeInfo)
return {};
for (TypeLoc typeLoc = typeInfo->getTypeLoc(); typeLoc;
typeLoc = typeLoc.getNextTypeLoc()) {
if (auto protoLoc = typeLoc.getAs<FunctionProtoTypeLoc>())
return protoLoc;
}
return {};
}
Rc<ir::Type> trQualType(QualType t, SourceRange range,
AnonNameGen *liftStructs = nullptr,
FunctionProtoTypeLoc protoLoc = {}) {
t = t.IgnoreParens();
auto loc = getRange(range);
if (t.getAsString() == "size_t") {
return mk_sizet(std::move(loc));
} else if (auto typeOf = dyn_cast<TypeOfType>(t)) {
return trQualType(typeOf->desugar(), range, liftStructs);
} else if (auto typeOfExpr = dyn_cast<TypeOfExprType>(t)) {
return trQualType(typeOfExpr->desugar(), range, liftStructs);
} else if (auto tydef = dyn_cast<TypedefType>(t)) {
auto id = ctx.mk_ident(toStr(tydef->getDecl()->getName()), loc.clone());
return mk_type_typedef(std::move(loc), std::move(id));
#if LLVM_VERSION_MAJOR < 22
} else if (auto elab = dyn_cast<ElaboratedType>(t)) {
return trQualType(elab->desugar(), range, liftStructs);
#endif
} else if (auto ptr = dyn_cast<PointerType>(t)) {
// Pointer to a (prototyped) function: `R (*)(A0, A1, ...)`. Modeled as a
// dedicated function-pointer IR type with the argument types collected in
// order and tupled on emission.
if (auto proto = ptr->getPointeeType()->getAs<FunctionProtoType>()) {
return trFnPtrType(proto, range, loc.clone(), liftStructs, protoLoc);
}
return mk_pointer_unknown(
std::move(loc),
trQualType(ptr->getPointeeType(), /*TODO*/ range, liftStructs));
} else if (auto proto = t->getAs<FunctionProtoType>()) {
// A bare (undecayed) function type reached as a value type — treat the
// function-to-pointer decay result the same as a function pointer.
return trFnPtrType(proto, range, std::move(loc), liftStructs, protoLoc);
} else if (auto adj = dyn_cast<AdjustedType>(t)) {
return trQualType(adj->getOriginalType(), range, liftStructs, protoLoc);
} else if (auto cat = dyn_cast<ConstantArrayType>(t)) {
return mk_fixed_array_type(
std::move(loc),
trQualType(cat->getElementType(), /* TODO */ range, liftStructs),
cat->getSize().getZExtValue());
} else if (auto arr = dyn_cast<ArrayType>(t)) {
// VLA or incomplete array — decays to pointer
return mk_pointer_array(
std::move(loc),
trQualType(arr->getElementType(), /* TODO */ range, liftStructs));
} else if (auto rec = dyn_cast<RecordType>(t)) {
auto decl = rec->getDecl();
auto key = recordKey(decl);
Rc<ir::Ident> name;
if (auto it = structNames.find(key); it != structNames.end()) {
name = ctx.mk_ident(toStr(it->second), loc.clone());
} else if (decl->getIdentifier()) {
structNames.emplace(key, decl->getName().str());
name = ctx.mk_ident(toStr(decl->getName()), loc.clone());
} else if (liftStructs) {
auto nameStr = liftStructs->next();
structNames.emplace(key, nameStr);
name = ctx.mk_ident(toStr(nameStr), loc.clone());
trRecordDecl(name.clone(), decl, liftStructs);
} else {
reportUnsupported(
range, loc, "unsupported anonymous struct/union outside of typedef",
"");
return mk_type_err(std::move(loc));
}
switch (decl->getTagKind()) {
case TagTypeKind::Struct: {
return mk_type_struct(std::move(loc), std::move(name));
}
case TagTypeKind::Union: {
return mk_type_union(std::move(loc), std::move(name));
}
default: {
reportUnsupported(range, loc, "unsupported record kind", "");
return mk_type_err(std::move(loc));
}
}
}
if (t->isVoidType()) {
return mk_void_type(std::move(loc));
}
if (isBoolType(t)) {
return mk_bool_type(std::move(loc));
}
if (t->isSpecificBuiltinType(BuiltinType::Float)) {
return mk_float_type(std::move(loc), 32);
}
if (t->isSpecificBuiltinType(BuiltinType::Double)) {
return mk_float_type(std::move(loc), 64);
}
if (t->isFloatingType()) {
reportUnsupported(range, loc, "unsupported floating-point type ",
t.getAsString());
return mk_type_err(std::move(loc));
}
if (t->isSignedIntegerType() || t->isUnsignedIntegerType()) {
bool isSigned = t->isSignedIntegerType();
unsigned width = astCtx->getIntWidth(t);
return mk_int_type(std::move(loc), isSigned, width);
}
reportUnsupported(range, loc, "unsupported type ", t->getTypeClassName());
return mk_type_err(std::move(loc));
}
// `_array`, `_arrayptr` and `_core_ref` reclassify a *pointer*. When the
// declared type only reaches the pointer through a typedef (e.g.
// `typedef E* PE;`), the translated type is an opaque type reference and the
// classification has nothing to attach to. Desugar to the underlying pointer
// type in that case so the attribute applies to the pointer it names.
static bool isPointerKindAttr(AnnotateAttr *ann) {
if (ann->args_size() != 0)
return false;
auto name = ann->getAnnotation();
return name == "pal-array" || name == "pal-arrayptr" ||
name == "pal-core-ref";
}
Rc<ir::Type> desugarPointerTypedef(Rc<ir::Type> &&ty, QualType declQt,
SourceRange declRange) {
if (declQt.isNull())
return std::move(ty);
auto qt = declQt.IgnoreParens();
auto ptr = qt->getAs<PointerType>();
if (!ptr || isa<PointerType>(qt.getTypePtr()))
return std::move(ty);
return trQualType(astCtx->getPointerType(ptr->getPointeeType()), declRange);
}
Rc<ir::Type> trTypeAttrs(AttrVec const &attrs, Rc<ir::Type> &&ty,
QualType declQt = QualType(),
SourceRange declRange = SourceRange()) {
for (auto attr : attrs) {
if (auto ann = dyn_cast<AnnotateAttr>(attr)) {
if (isPointerKindAttr(ann)) {
ty = desugarPointerTypedef(std::move(ty), declQt, declRange);
break;
}
}
}
bool sawNullable = false;
std::optional<Rc<ir::SourceInfo>> nullableLoc;
for (auto it = attrs.rbegin(); it != attrs.rend(); ++it) {
if (auto ann = dyn_cast<AnnotateAttr>(*it)) {
auto loc = getRange(ann->getRange());
if (auto ref = isUnaryAttrOf(ann, "pal-refine")) {
ty = mk_type_refine(std::move(loc), std::move(ty),
std::move(ref.value()));
} else if (auto ref = isUnaryAttrOf(ann, "pal-refine-always")) {
ty = mk_type_refine_always(std::move(loc), std::move(ty),
std::move(ref.value()));
} else if (auto ref = isUnaryAttrOf(ann, "pal-refines")) {
// `_refines(p)` on a flexible array member: an always-true length
// refinement (relating the FAM length to a sibling field). Modeled
// as `RefineAlways`; emit lifts the relation into a `pure` fact in
// the struct predicate.
ty = mk_type_refine_always(std::move(loc), std::move(ty),
std::move(ref.value()));
} else if (auto ref = isUnaryAttrOf(ann, "pal-refine-uninit")) {
ty = mk_type_refine_uninit(std::move(loc), std::move(ty),
std::move(ref.value()));
} else if (ann->getAnnotation() == "pal-refine-value" &&
ann->args_size() == 2) {
std::optional<unsigned> binding_ctr, pred_ctr;
if (auto v0 = ann->args_begin()[0]->getIntegerConstantExpr(*astCtx)) {
binding_ctr = v0->getZExtValue();
}
if (auto v1 = ann->args_begin()[1]->getIntegerConstantExpr(*astCtx)) {
pred_ctr = v1->getZExtValue();
}
if (binding_ctr && pred_ctr) {
ty = mk_type_refine_value(std::move(loc), std::move(ty),
*binding_ctr, *pred_ctr, snippets);
}
} else if (ann->getAnnotation() == "pal-plain" &&
ann->args_size() == 0) {
ty = mk_type_plain(std::move(loc), std::move(ty));
} else if (ann->getAnnotation() == "pal-nullable" &&
ann->args_size() == 0) {
sawNullable = true;
if (!nullableLoc)
nullableLoc = getRange(ann->getRange());
ty = mk_type_nullable(std::move(loc), std::move(ty));
} else if (ann->getAnnotation() == "pal-array" &&
ann->args_size() == 0) {
ty = mk_type_array(std::move(loc), std::move(ty));
} else if (ann->getAnnotation() == "pal-arrayptr" &&
ann->args_size() == 0) {
ty = mk_type_arrayptr(std::move(loc), std::move(ty));
} else if (ann->getAnnotation() == "pal-core-ref" &&
ann->args_size() == 0) {
ty = mk_type_core_ref(std::move(loc), std::move(ty));
}
}
}
(void)sawNullable;
(void)nullableLoc;
return ty;
}
bool hasConsumesAttr(AttrVec const &attrs) {
for (auto it = attrs.rbegin(); it != attrs.rend(); ++it) {
if (auto ann = dyn_cast<AnnotateAttr>(*it)) {
if (ann->getAnnotation() == "pal-consumes" && ann->args_size() == 0) {
return true;
}
}
}
return false;
}
bool hasOutAttr(AttrVec const &attrs) {
for (auto it = attrs.rbegin(); it != attrs.rend(); ++it) {
if (auto ann = dyn_cast<AnnotateAttr>(*it)) {
if (ann->getAnnotation() == "pal-out" && ann->args_size() == 0) {
return true;
}
}
}
return false;
}
bool isBoolType(QualType t) {
return t->isUnsignedIntegerType() && astCtx->getIntWidth(t) == 1;
}
Rc<ir::Expr> trLValue(Expr *e) {
auto loc = getRange(e->getSourceRange());
if (auto generic = dyn_cast<GenericSelectionExpr>(e)) {
return trLValue(generic->getResultExpr());
} else if (auto dre = dyn_cast<DeclRefExpr>(e)) {
auto id = ctx.mk_ident(toStr(dre->getDecl()->getName()), loc.clone());
return mk_lvalue_var(std::move(loc), std::move(id));
} else if (auto p = dyn_cast<ParenExpr>(e)) {
return trLValue(p->getSubExpr());
} else if (auto uo = dyn_cast<UnaryOperator>(e)) {
switch (uo->getOpcode()) {
case UO_Deref:
return mk_deref(std::move(loc), trRValue(uo->getSubExpr()));
default:;
// continue to error case
}
} else if (auto m = dyn_cast<MemberExpr>(e)) {
auto *md = m->getMemberDecl();
std::string nameStr;
if (auto *fd = dyn_cast<FieldDecl>(md))
nameStr = fieldNameStr(fd);
else
nameStr = md->getName().str();
auto id = ctx.mk_ident(toStr(nameStr), loc.clone());
auto base = m->isArrow() ? mk_deref(loc.clone(), trRValue(m->getBase()))
: trLValue(m->getBase());
return mk_lvalue_member(std::move(loc), std::move(base), std::move(id));
} else if (auto sub = dyn_cast<ArraySubscriptExpr>(e)) {
return mk_index(std::move(loc), trRValue(sub->getBase()),
trRValue(sub->getIdx()));
} else if (auto ic = dyn_cast<ImplicitCastExpr>(e)) {
if (ic->getCastKind() == CK_NoOp) {
return trLValue(ic->getSubExpr());
}
} else if (isa<CompoundLiteralExpr>(e)) {
// C11 6.5.2.5p4 makes a compound literal an lvalue, so `(T){...}.f` and
// `&(T){...}` are both legal. The object it names is unnamed and fresh,
// though, so nothing stored through it can be observed by any later
// expression -- which means translating it as its own value loses
// nothing. That is what lets a read like `((T){.f = 0}).f`, the shape a
// named-constant macro expands to, go through.
return trRValue(e);
}
reportUnsupported(e->getSourceRange(), loc,
"unsupported lvalue expression ", e->getStmtClassName());
return mk_lvalue_err(std::move(loc),
trQualType(e->getType(), e->getSourceRange()));
}
// C11 6.7.9p21: elements of an aggregate that the initializer list does not
// reach are initialized as objects with static storage duration, i.e. to
// zero. Build that zero value for `qt`, so a partial array initializer can be
// padded out to the array's declared length.
Rc<ir::Expr> trZeroInit(QualType qt, SourceRange range,
Rc<ir::SourceInfo> loc) {
auto desugared = qt.getDesugaredType(*astCtx);
if (auto *cat = dyn_cast<ConstantArrayType>(desugared.getTypePtr())) {
auto elemTy = trQualType(cat->getElementType(), range);
auto elems = Vec<Rc<ir::Expr>>::new_();
uint64_t n = cat->getSize().getLimitedValue();
for (uint64_t i = 0; i < n; ++i)
elems.push(trZeroInit(cat->getElementType(), range, loc.clone()));
return mk_array_init(std::move(loc), std::move(elemTy), std::move(elems),
false);
}
if (auto *rec = dyn_cast<RecordType>(desugared.getTypePtr())) {
auto *decl = rec->getDecl();
auto it = structNames.find(recordKey(decl));
if (it != structNames.end() &&
decl->getTagKind() == TagTypeKind::Struct) {
// An empty field list means "every field takes its type's default",
// which is what emission already does for fields omitted from a
// designated initializer.
auto structName = ctx.mk_ident(toStr(it->second), loc.clone());
return StructInitBuilder::new_(loc.clone(), std::move(structName))
.build();
}
reportUnsupported(range, loc, "unsupported zero initializer for type ",
qt.getAsString().c_str());
return mk_rvalue_err(std::move(loc), trQualType(qt, range));
}
if (desugared->isScalarType()) {
// Covers integers, enums, floating point, booleans and pointers; a null
// pointer constant is a zero literal of the pointer's type, which is how
// `isNull` casts are already translated.
return mk_int_lit(std::move(loc), mk_bigint("0"_rs),
trQualType(qt, range));
}
reportUnsupported(range, loc, "unsupported zero initializer for type ",
qt.getAsString().c_str());
return mk_rvalue_err(std::move(loc), trQualType(qt, range));
}
Rc<ir::Expr> trInitList(InitListExpr *init, SourceRange range,
Rc<ir::SourceInfo> loc) {
auto qt = init->getType().getDesugaredType(*astCtx);
// Handle array initializer lists
if (auto *cat = dyn_cast<ConstantArrayType>(qt.getTypePtr())) {
auto elemTy = trQualType(cat->getElementType(), range);
auto elems = Vec<Rc<ir::Expr>>::new_();
unsigned given = init->getNumInits();
for (unsigned i = 0; i < given; ++i) {
elems.push(trRValue(init->getInit(i)));
}
// An initializer list may be shorter than the array; the array's length
// comes from its type, not from the list. Pad the tail with the filler
// Clang recorded, or with zeroes when that filler is the implicit one.
// Without this the array literal takes the length of the list and the
// result no longer has the array's type.
uint64_t declared = cat->getSize().getLimitedValue();
Expr *filler = init->getArrayFiller();
for (uint64_t i = given; i < declared; ++i) {
if (filler && !isa<ImplicitValueInitExpr>(filler))
elems.push(trRValue(filler));
else
elems.push(trZeroInit(cat->getElementType(), range, getRange(range)));
}
return mk_array_init(std::move(loc), std::move(elemTy), std::move(elems),
false);
}
// A braced initializer for a scalar object: C permits `int x = {0}` and
// `T x = {}`, and BOSS reaches it through typedefs whose definition on one
// platform is a struct and on another a plain integer -- `SNAP_LE_UINT32`
// and `SNAP_CRC64` are both. The list holds at most one element, and it
// initializes the object directly.
if (qt->isScalarType()) {
if (init->getNumInits() == 0) {
return trZeroInit(init->getType(), range, std::move(loc));
}
if (init->getNumInits() == 1) {
return trRValue(init->getInit(0));
}
reportUnsupported(range, loc,
"initializer list for a scalar type has more than one "
"element",
"");
return mk_rvalue_err(std::move(loc), trQualType(init->getType(), range));
}
auto *rec = dyn_cast<RecordType>(qt.getTypePtr());
if (!rec) {
reportUnsupported(range, loc,
"unsupported initializer list for non-record type", "");
return mk_rvalue_err(std::move(loc), trQualType(init->getType(), range));
}
auto *decl = rec->getDecl();
auto it = structNames.find(recordKey(decl));
if (it == structNames.end()) {
reportUnsupported(range, loc, "unknown record in initializer list", "");
return mk_rvalue_err(std::move(loc), trQualType(init->getType(), range));
}
if (decl->getTagKind() == TagTypeKind::Union) {
if (init->getNumInits() != 1) {
reportUnsupported(range, loc,
"union initializer must have exactly one field", "");
return mk_rvalue_err(std::move(loc),
trQualType(init->getType(), range));
}
auto unionName = ctx.mk_ident(toStr(it->second), loc.clone());
auto *fieldInit = init->getInit(0);
auto *field = init->getInitializedFieldInUnion();
auto floc = getRange(fieldInit->getSourceRange());
auto fieldName =
ctx.mk_ident(toStr(fieldNameStr(field)), std::move(floc));
return mk_union_init(std::move(loc), std::move(unionName),
std::move(fieldName), trRValue(fieldInit));
}
if (decl->getTagKind() != TagTypeKind::Struct) {
reportUnsupported(range, loc,
"unsupported initializer list for non-struct type", "");
return mk_rvalue_err(std::move(loc), trQualType(init->getType(), range));
}
auto structName = ctx.mk_ident(toStr(it->second), loc.clone());
auto builder = StructInitBuilder::new_(loc.clone(), std::move(structName));
for (unsigned i = 0; i < init->getNumInits(); ++i) {
auto *fieldInit = init->getInit(i);
auto *field = *std::next(decl->field_begin(), i);
// A flexible array member cannot be initialized in a C compound literal;
// Clang supplies an implicit (empty) initializer for it. Skip it here so
// the emitter fills it with its default (a length-0 array).
if (field->getType()->isIncompleteArrayType())
continue;
// A field omitted from a designated initializer (e.g. `{ .initialized =
// 42 }` leaving other fields unset) is represented by Clang's semantic
// InitListExpr as an ImplicitValueInitExpr placeholder. Per C11
// 6.7.9p21, such fields are implicitly zero-initialized, the same as an
// object of static storage duration. Skip translating the placeholder
// itself (trRValue has no case for it, so it would otherwise become an
// error/admit()) and let the emitter fill it with its type's zero/null
// default, exactly as it does for a field absent entirely from the
// initializer list.
if (isa<ImplicitValueInitExpr>(fieldInit))
continue;
auto floc = getRange(fieldInit->getSourceRange());
auto fieldName =
ctx.mk_ident(toStr(fieldNameStr(field)), std::move(floc));
builder.field(std::move(fieldName), trRValue(fieldInit));
}
return builder.build();
}
// Recognize a `sizeof` operand in an allocation size expression. Both
// spellings are accepted: a type operand (`sizeof(T)`) and an expression
// operand (`sizeof(*p)`, `sizeof *p`), the latter being the common C idiom
// `p = malloc(sizeof(*p))`. The operand type is read off with
// `getTypeOfArgument()`, which covers both. Returns nullptr if `e` is not a
// `sizeof`.
static const UnaryExprOrTypeTraitExpr *asSizeof(Expr *e) {
auto *s = dyn_cast<UnaryExprOrTypeTraitExpr>(e->IgnoreParenImpCasts());
if (!s || s->getKind() != UETT_SizeOf)
return nullptr;
// A VLA operand has no static size, so it does not denote an allocation
// unit; an incomplete operand type cannot be translated either.
auto argTy = s->getTypeOfArgument();
if (argTy->isIncompleteType() || argTy->isDependentType() ||
argTy->isVariableArrayType())
return nullptr;
return s;
}
// For a flexible-array-member allocation's trailing size term, return the
// count operand `n` of `n * sizeof(elem)` or `sizeof(elem) * n` (the
// non-sizeof multiplicand). Returns nullptr if the term is not a recognized
// product with a sizeof factor.
static Expr *flexArrayCountSide(Expr *e) {
auto *mul = dyn_cast<BinaryOperator>(e->IgnoreParenImpCasts());
if (!mul || mul->getOpcode() != BO_Mul)
return nullptr;
if (asSizeof(mul->getLHS()))
return mul->getRHS();
if (asSizeof(mul->getRHS()))
return mul->getLHS();
return nullptr;
}
bool canOmitVariadicArgument(Expr *e) {
if (e->HasSideEffects(*astCtx))
return false;
e = e->IgnoreParenImpCasts();
if (isa<IntegerLiteral, CharacterLiteral, FloatingLiteral>(e))
return true;
bool address = false;
if (auto *op = dyn_cast<UnaryOperator>(e);
op && op->getOpcode() == UO_AddrOf) {
address = true;
e = op->getSubExpr()->IgnoreParens();
}
auto *ref = dyn_cast<DeclRefExpr>(e);
auto *var = ref ? dyn_cast<VarDecl>(ref->getDecl()) : nullptr;
if (!var || (!isa<ParmVarDecl>(var) && !var->hasLocalStorage()))
return false;
auto ty = var->getType();
return !ty.isVolatileQualified() && !ty->isAtomicType() &&
(address || ty->isScalarType());
}
Rc<ir::Expr> trRValue(Expr *e) {
auto loc = getRange(e->getSourceRange());
if (auto generic = dyn_cast<GenericSelectionExpr>(e)) {
return trRValue(generic->getResultExpr());
}
if (auto ic = dyn_cast<CastExpr>(e)) {
switch (ic->getCastKind()) {
case CK_LValueToRValue:
if (dyn_cast<CompoundLiteralExpr>(
ic->getSubExpr()->IgnoreParenImpCasts())) {
return trRValue(ic->getSubExpr());
}
return mk_rvalue_lvalue(std::move(loc), trLValue(ic->getSubExpr()));
case CK_NoOp:
return trRValue(ic->getSubExpr());
case CK_FunctionToPointerDecay:
// `add` used as a value decays to a function pointer; translate the
// underlying function reference directly (the DeclRefExpr arm below
// produces a FnRef for a FunctionDecl).
return trRValue(ic->getSubExpr());
case CK_ArrayToPointerDecay: {
auto *subExpr = ic->getSubExpr()->IgnoreParenImpCasts();
if (dyn_cast<StringLiteral>(subExpr) ||
dyn_cast<CompoundLiteralExpr>(subExpr)) {
return trRValue(ic->getSubExpr());
}
return mk_rvalue_lvalue(std::move(loc), trLValue(ic->getSubExpr()));
}
case CK_PointerToIntegral: {
auto *target = ic->getType()->getAs<BuiltinType>();
auto source = ic->getSubExpr()->getType();
if (target &&
(target->getKind() == BuiltinType::Long ||
target->getKind() == BuiltinType::ULong) &&
source->isPointerType() &&
!source->getPointeeType()->isFunctionType()) {
return mk_rvalue_cast(std::move(loc), trRValue(ic->getSubExpr()),
trQualType(ic->getType(), e->getSourceRange()));
}
reportUnsupported(e->getSourceRange(), loc,
"unsupported pointer-to-integer cast",
"only object or void pointers to long or unsigned "
"long are supported");
return mk_rvalue_err(std::move(loc),
trQualType(e->getType(), e->getSourceRange()));
}
case CK_IntegralCast:
case CK_IntegralToBoolean:
case CK_PointerToBoolean:
case CK_FloatingCast:
case CK_IntegralToFloating:
case CK_FloatingToIntegral:
case CK_FloatingToBoolean:
return mk_rvalue_cast(std::move(loc), trRValue(ic->getSubExpr()),
trQualType(ic->getType(), ic->getSourceRange()));
default:;
if (isNull(ic)) {
return mk_int_lit(std::move(loc), mk_bigint("0"_rs),
trQualType(ic->getType(), ic->getSourceRange()));
}
// Detect (T*) malloc(sizeof(T)) and (T*) malloc(sizeof(T) * n)
if (auto *call =
dyn_cast<CallExpr>(ic->getSubExpr()->IgnoreParenImpCasts())) {
if (auto *callee = call->getDirectCallee()) {
if (callee->getName() == "malloc" && call->getNumArgs() == 1) {
auto *arg = call->getArg(0)->IgnoreParenImpCasts();
// Single element: malloc(sizeof(T)) or malloc(sizeof(*p))
if (auto *sizeofExpr = asSizeof(arg)) {
auto allocTy = trQualType(sizeofExpr->getTypeOfArgument(),
sizeofExpr->getSourceRange());
return mk_malloc(std::move(loc), std::move(allocTy));
}
// Flexible array member allocation:
// malloc(sizeof(struct foo) + n * sizeof(elem))
// The trailing-array term is runtime sizing that Pulse models via
// the inline ghost `array_spec`; translate identically to a plain
// struct malloc of the header type (dropping the array term).
if (auto *binOp = dyn_cast<BinaryOperator>(arg)) {
if (binOp->getOpcode() == BO_Add) {
auto structSizeofSide =
[&](Expr *e) -> const UnaryExprOrTypeTraitExpr * {
auto *s = asSizeof(e);
if (s && s->getTypeOfArgument()->isRecordType())
return s;
return nullptr;
};
const UnaryExprOrTypeTraitExpr *structSide =
structSizeofSide(binOp->getLHS());