-
Notifications
You must be signed in to change notification settings - Fork 12.4k
/
Copy pathItaniumMangle.cpp
7182 lines (6364 loc) · 246 KB
/
ItaniumMangle.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
//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Implements C++ name mangling according to the Itanium C++ ABI,
// which is used in GCC 3.2 and newer (and many compilers that are
// ABI-compatible with GCC):
//
// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/ABI.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Thunk.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TargetParser/RISCVTargetParser.h"
#include <optional>
using namespace clang;
namespace {
static bool isLocalContainerContext(const DeclContext *DC) {
return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
}
static const FunctionDecl *getStructor(const FunctionDecl *fn) {
if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
return ftd->getTemplatedDecl();
return fn;
}
static const NamedDecl *getStructor(const NamedDecl *decl) {
const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
return (fn ? getStructor(fn) : decl);
}
static bool isLambda(const NamedDecl *ND) {
const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
if (!Record)
return false;
return Record->isLambda();
}
static const unsigned UnknownArity = ~0U;
class ItaniumMangleContextImpl : public ItaniumMangleContext {
typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
NamespaceDecl *StdNamespace = nullptr;
bool NeedsUniqueInternalLinkageNames = false;
public:
explicit ItaniumMangleContextImpl(
ASTContext &Context, DiagnosticsEngine &Diags,
DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
: ItaniumMangleContext(Context, Diags, IsAux),
DiscriminatorOverride(DiscriminatorOverride) {}
/// @name Mangler Entry Points
/// @{
bool shouldMangleCXXName(const NamedDecl *D) override;
bool shouldMangleStringLiteral(const StringLiteral *) override {
return false;
}
bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
void needsUniqueInternalLinkageNames() override {
NeedsUniqueInternalLinkageNames = true;
}
void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
raw_ostream &) override;
void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
const ThisAdjustment &ThisAdjustment,
raw_ostream &) override;
void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
raw_ostream &) override;
void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
const CXXRecordDecl *Type, raw_ostream &) override;
void mangleCXXRTTI(QualType T, raw_ostream &) override;
void mangleCXXRTTIName(QualType T, raw_ostream &,
bool NormalizeIntegers) override;
void mangleCanonicalTypeName(QualType T, raw_ostream &,
bool NormalizeIntegers) override;
void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
void mangleDynamicAtExitDestructor(const VarDecl *D,
raw_ostream &Out) override;
void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
raw_ostream &Out) override;
void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
raw_ostream &Out) override;
void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
void mangleItaniumThreadLocalWrapper(const VarDecl *D,
raw_ostream &) override;
void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
// Lambda closure types are already numbered.
if (isLambda(ND))
return false;
// Anonymous tags are already numbered.
if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
return false;
}
// Use the canonical number for externally visible decls.
if (ND->isExternallyVisible()) {
unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
if (discriminator == 1)
return false;
disc = discriminator - 2;
return true;
}
// Make up a reasonable number for internal decls.
unsigned &discriminator = Uniquifier[ND];
if (!discriminator) {
const DeclContext *DC = getEffectiveDeclContext(ND);
discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
}
if (discriminator == 1)
return false;
disc = discriminator-2;
return true;
}
std::string getLambdaString(const CXXRecordDecl *Lambda) override {
// This function matches the one in MicrosoftMangle, which returns
// the string that is used in lambda mangled names.
assert(Lambda->isLambda() && "RD must be a lambda!");
std::string Name("<lambda");
Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
unsigned LambdaId;
const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
const FunctionDecl *Func =
Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
if (Func) {
unsigned DefaultArgNo =
Func->getNumParams() - Parm->getFunctionScopeIndex();
Name += llvm::utostr(DefaultArgNo);
Name += "_";
}
if (LambdaManglingNumber)
LambdaId = LambdaManglingNumber;
else
LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
Name += llvm::utostr(LambdaId);
Name += '>';
return Name;
}
DiscriminatorOverrideTy getDiscriminatorOverride() const override {
return DiscriminatorOverride;
}
NamespaceDecl *getStdNamespace();
const DeclContext *getEffectiveDeclContext(const Decl *D);
const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
return getEffectiveDeclContext(cast<Decl>(DC));
}
bool isInternalLinkageDecl(const NamedDecl *ND);
/// @}
};
/// Manage the mangling of a single name.
class CXXNameMangler {
ItaniumMangleContextImpl &Context;
raw_ostream &Out;
/// Normalize integer types for cross-language CFI support with other
/// languages that can't represent and encode C/C++ integer types.
bool NormalizeIntegers = false;
bool NullOut = false;
/// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
/// This mode is used when mangler creates another mangler recursively to
/// calculate ABI tags for the function return value or the variable type.
/// Also it is required to avoid infinite recursion in some cases.
bool DisableDerivedAbiTags = false;
/// The "structor" is the top-level declaration being mangled, if
/// that's not a template specialization; otherwise it's the pattern
/// for that specialization.
const NamedDecl *Structor;
unsigned StructorType = 0;
// An offset to add to all template parameter depths while mangling. Used
// when mangling a template parameter list to see if it matches a template
// template parameter exactly.
unsigned TemplateDepthOffset = 0;
/// The next substitution sequence number.
unsigned SeqID = 0;
class FunctionTypeDepthState {
unsigned Bits = 0;
enum { InResultTypeMask = 1 };
public:
FunctionTypeDepthState() = default;
/// The number of function types we're inside.
unsigned getDepth() const {
return Bits >> 1;
}
/// True if we're in the return type of the innermost function type.
bool isInResultType() const {
return Bits & InResultTypeMask;
}
FunctionTypeDepthState push() {
FunctionTypeDepthState tmp = *this;
Bits = (Bits & ~InResultTypeMask) + 2;
return tmp;
}
void enterResultType() {
Bits |= InResultTypeMask;
}
void leaveResultType() {
Bits &= ~InResultTypeMask;
}
void pop(FunctionTypeDepthState saved) {
assert(getDepth() == saved.getDepth() + 1);
Bits = saved.Bits;
}
} FunctionTypeDepth;
// abi_tag is a gcc attribute, taking one or more strings called "tags".
// The goal is to annotate against which version of a library an object was
// built and to be able to provide backwards compatibility ("dual abi").
// For more information see docs/ItaniumMangleAbiTags.rst.
typedef SmallVector<StringRef, 4> AbiTagList;
// State to gather all implicit and explicit tags used in a mangled name.
// Must always have an instance of this while emitting any name to keep
// track.
class AbiTagState final {
public:
explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
Parent = LinkHead;
LinkHead = this;
}
// No copy, no move.
AbiTagState(const AbiTagState &) = delete;
AbiTagState &operator=(const AbiTagState &) = delete;
~AbiTagState() { pop(); }
void write(raw_ostream &Out, const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags) {
ND = cast<NamedDecl>(ND->getCanonicalDecl());
if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
assert(
!AdditionalAbiTags &&
"only function and variables need a list of additional abi tags");
if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
}
// Don't emit abi tags for namespaces.
return;
}
}
AbiTagList TagList;
if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
TagList.insert(TagList.end(), AbiTag->tags().begin(),
AbiTag->tags().end());
}
if (AdditionalAbiTags) {
UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
AdditionalAbiTags->end());
TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
AdditionalAbiTags->end());
}
llvm::sort(TagList);
TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
writeSortedUniqueAbiTags(Out, TagList);
}
const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
void setUsedAbiTags(const AbiTagList &AbiTags) {
UsedAbiTags = AbiTags;
}
const AbiTagList &getEmittedAbiTags() const {
return EmittedAbiTags;
}
const AbiTagList &getSortedUniqueUsedAbiTags() {
llvm::sort(UsedAbiTags);
UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
UsedAbiTags.end());
return UsedAbiTags;
}
private:
//! All abi tags used implicitly or explicitly.
AbiTagList UsedAbiTags;
//! All explicit abi tags (i.e. not from namespace).
AbiTagList EmittedAbiTags;
AbiTagState *&LinkHead;
AbiTagState *Parent = nullptr;
void pop() {
assert(LinkHead == this &&
"abi tag link head must point to us on destruction");
if (Parent) {
Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
UsedAbiTags.begin(), UsedAbiTags.end());
Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
EmittedAbiTags.begin(),
EmittedAbiTags.end());
}
LinkHead = Parent;
}
void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
for (const auto &Tag : AbiTags) {
EmittedAbiTags.push_back(Tag);
Out << "B";
Out << Tag.size();
Out << Tag;
}
}
};
AbiTagState *AbiTags = nullptr;
AbiTagState AbiTagsRoot;
llvm::DenseMap<uintptr_t, unsigned> Substitutions;
llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
ASTContext &getASTContext() const { return Context.getASTContext(); }
bool isCompatibleWith(LangOptions::ClangABI Ver) {
return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
}
bool isStd(const NamespaceDecl *NS);
bool isStdNamespace(const DeclContext *DC);
const RecordDecl *GetLocalClassDecl(const Decl *D);
bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
llvm::StringRef Name, bool HasAllocator);
public:
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const NamedDecl *D = nullptr, bool NullOut_ = false)
: Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
AbiTagsRoot(AbiTags) {
// These can't be mangled without a ctor type or dtor type.
assert(!D || (!isa<CXXDestructorDecl>(D) &&
!isa<CXXConstructorDecl>(D)));
}
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const CXXConstructorDecl *D, CXXCtorType Type)
: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
AbiTagsRoot(AbiTags) {}
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
const CXXDestructorDecl *D, CXXDtorType Type)
: Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
AbiTagsRoot(AbiTags) {}
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
bool NormalizeIntegers_)
: Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
: Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
StructorType(Outer.StructorType), SeqID(Outer.SeqID),
FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
Substitutions(Outer.Substitutions),
ModuleSubstitutions(Outer.ModuleSubstitutions) {}
CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
: CXXNameMangler(Outer, (raw_ostream &)Out_) {
NullOut = true;
}
struct WithTemplateDepthOffset { unsigned Offset; };
CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
WithTemplateDepthOffset Offset)
: CXXNameMangler(C, Out) {
TemplateDepthOffset = Offset.Offset;
}
raw_ostream &getStream() { return Out; }
void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
void mangle(GlobalDecl GD);
void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
void mangleNumber(const llvm::APSInt &I);
void mangleNumber(int64_t Number);
void mangleFloat(const llvm::APFloat &F);
void mangleFunctionEncoding(GlobalDecl GD);
void mangleSeqID(unsigned SeqID);
void mangleName(GlobalDecl GD);
void mangleType(QualType T);
void mangleNameOrStandardSubstitution(const NamedDecl *ND);
void mangleLambdaSig(const CXXRecordDecl *Lambda);
void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
private:
bool mangleSubstitution(const NamedDecl *ND);
bool mangleSubstitution(NestedNameSpecifier *NNS);
bool mangleSubstitution(QualType T);
bool mangleSubstitution(TemplateName Template);
bool mangleSubstitution(uintptr_t Ptr);
void mangleExistingSubstitution(TemplateName name);
bool mangleStandardSubstitution(const NamedDecl *ND);
void addSubstitution(const NamedDecl *ND) {
ND = cast<NamedDecl>(ND->getCanonicalDecl());
addSubstitution(reinterpret_cast<uintptr_t>(ND));
}
void addSubstitution(NestedNameSpecifier *NNS) {
NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
addSubstitution(reinterpret_cast<uintptr_t>(NNS));
}
void addSubstitution(QualType T);
void addSubstitution(TemplateName Template);
void addSubstitution(uintptr_t Ptr);
// Destructive copy substitutions from other mangler.
void extendSubstitutions(CXXNameMangler* Other);
void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
bool recursive = false);
void mangleUnresolvedName(NestedNameSpecifier *qualifier,
DeclarationName name,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs,
unsigned KnownArity = UnknownArity);
void mangleFunctionEncodingBareType(const FunctionDecl *FD);
void mangleNameWithAbiTags(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags);
void mangleModuleName(const NamedDecl *ND);
void mangleTemplateName(const TemplateDecl *TD,
ArrayRef<TemplateArgument> Args);
void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags) {
mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
UnknownArity, AdditionalAbiTags);
}
void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
const DeclContext *DC, unsigned KnownArity,
const AbiTagList *AdditionalAbiTags);
void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags);
void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags);
void mangleSourceName(const IdentifierInfo *II);
void mangleRegCallName(const IdentifierInfo *II);
void mangleDeviceStubName(const IdentifierInfo *II);
void mangleSourceNameWithAbiTags(
const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
void mangleLocalName(GlobalDecl GD,
const AbiTagList *AdditionalAbiTags);
void mangleBlockForPrefix(const BlockDecl *Block);
void mangleUnqualifiedBlock(const BlockDecl *Block);
void mangleTemplateParamDecl(const NamedDecl *Decl);
void mangleTemplateParameterList(const TemplateParameterList *Params);
void mangleTypeConstraint(const ConceptDecl *Concept,
ArrayRef<TemplateArgument> Arguments);
void mangleTypeConstraint(const TypeConstraint *Constraint);
void mangleRequiresClause(const Expr *RequiresClause);
void mangleLambda(const CXXRecordDecl *Lambda);
void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
const AbiTagList *AdditionalAbiTags,
bool NoFunction=false);
void mangleNestedName(const TemplateDecl *TD,
ArrayRef<TemplateArgument> Args);
void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
const NamedDecl *PrefixND,
const AbiTagList *AdditionalAbiTags);
void manglePrefix(NestedNameSpecifier *qualifier);
void manglePrefix(const DeclContext *DC, bool NoFunction=false);
void manglePrefix(QualType type);
void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
void mangleTemplatePrefix(TemplateName Template);
const NamedDecl *getClosurePrefix(const Decl *ND);
void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
StringRef Prefix = "");
void mangleOperatorName(DeclarationName Name, unsigned Arity);
void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
void mangleVendorQualifier(StringRef qualifier);
void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
void mangleRefQualifier(RefQualifierKind RefQualifier);
void mangleObjCMethodName(const ObjCMethodDecl *MD);
// Declare manglers for every type class.
#define ABSTRACT_TYPE(CLASS, PARENT)
#define NON_CANONICAL_TYPE(CLASS, PARENT)
#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
#include "clang/AST/TypeNodes.inc"
void mangleType(const TagType*);
void mangleType(TemplateName);
static StringRef getCallingConvQualifierName(CallingConv CC);
void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
void mangleExtFunctionInfo(const FunctionType *T);
void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
const FunctionDecl *FD = nullptr);
void mangleNeonVectorType(const VectorType *T);
void mangleNeonVectorType(const DependentVectorType *T);
void mangleAArch64NeonVectorType(const VectorType *T);
void mangleAArch64NeonVectorType(const DependentVectorType *T);
void mangleAArch64FixedSveVectorType(const VectorType *T);
void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
void mangleRISCVFixedRVVVectorType(const VectorType *T);
void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
void mangleFixedPointLiteral();
void mangleNullPointer(QualType T);
void mangleMemberExprBase(const Expr *base, bool isArrow);
void mangleMemberExpr(const Expr *base, bool isArrow,
NestedNameSpecifier *qualifier,
NamedDecl *firstQualifierLookup,
DeclarationName name,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs,
unsigned knownArity);
void mangleCastExpression(const Expr *E, StringRef CastEncoding);
void mangleInitListElements(const InitListExpr *InitList);
void mangleRequirement(SourceLocation RequiresExprLoc,
const concepts::Requirement *Req);
void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
bool AsTemplateArg = false);
void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
void mangleCXXDtorType(CXXDtorType T);
struct TemplateArgManglingInfo;
void mangleTemplateArgs(TemplateName TN,
const TemplateArgumentLoc *TemplateArgs,
unsigned NumTemplateArgs);
void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
TemplateArgument A);
void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
void mangleTemplateArgExpr(const Expr *E);
void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
bool NeedExactType = false);
void mangleTemplateParameter(unsigned Depth, unsigned Index);
void mangleFunctionParam(const ParmVarDecl *parm);
void writeAbiTags(const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags);
// Returns sorted unique list of ABI tags.
AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
// Returns sorted unique list of ABI tags.
AbiTagList makeVariableTypeTags(const VarDecl *VD);
};
}
NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
if (!StdNamespace) {
StdNamespace = NamespaceDecl::Create(
getASTContext(), getASTContext().getTranslationUnitDecl(),
/*Inline=*/false, SourceLocation(), SourceLocation(),
&getASTContext().Idents.get("std"),
/*PrevDecl=*/nullptr, /*Nested=*/false);
StdNamespace->setImplicit();
}
return StdNamespace;
}
/// Retrieve the declaration context that should be used when mangling the given
/// declaration.
const DeclContext *
ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
// The ABI assumes that lambda closure types that occur within
// default arguments live in the context of the function. However, due to
// the way in which Clang parses and creates function declarations, this is
// not the case: the lambda closure type ends up living in the context
// where the function itself resides, because the function declaration itself
// had not yet been created. Fix the context here.
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
if (RD->isLambda())
if (ParmVarDecl *ContextParam =
dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
return ContextParam->getDeclContext();
}
// Perform the same check for block literals.
if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
if (ParmVarDecl *ContextParam =
dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
return ContextParam->getDeclContext();
}
// On ARM and AArch64, the va_list tag is always mangled as if in the std
// namespace. We do not represent va_list as actually being in the std
// namespace in C because this would result in incorrect debug info in C,
// among other things. It is important for both languages to have the same
// mangling in order for -fsanitize=cfi-icall to work.
if (D == getASTContext().getVaListTagDecl()) {
const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
if (T.isARM() || T.isThumb() || T.isAArch64())
return getStdNamespace();
}
const DeclContext *DC = D->getDeclContext();
if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
isa<OMPDeclareMapperDecl>(DC)) {
return getEffectiveDeclContext(cast<Decl>(DC));
}
if (const auto *VD = dyn_cast<VarDecl>(D))
if (VD->isExternC())
return getASTContext().getTranslationUnitDecl();
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->isExternC())
return getASTContext().getTranslationUnitDecl();
// Member-like constrained friends are mangled as if they were members of
// the enclosing class.
if (FD->isMemberLikeConstrainedFriend() &&
getASTContext().getLangOpts().getClangABICompat() >
LangOptions::ClangABI::Ver17)
return D->getLexicalDeclContext()->getRedeclContext();
}
return DC->getRedeclContext();
}
bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
if (ND && ND->getFormalLinkage() == InternalLinkage &&
!ND->isExternallyVisible() &&
getEffectiveDeclContext(ND)->isFileContext() &&
!ND->isInAnonymousNamespace())
return true;
return false;
}
// Check if this Function Decl needs a unique internal linkage name.
bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
const NamedDecl *ND) {
if (!NeedsUniqueInternalLinkageNames || !ND)
return false;
const auto *FD = dyn_cast<FunctionDecl>(ND);
if (!FD)
return false;
// For C functions without prototypes, return false as their
// names should not be mangled.
if (!FD->getType()->getAs<FunctionProtoType>())
return false;
if (isInternalLinkageDecl(ND))
return true;
return false;
}
bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
LanguageLinkage L = FD->getLanguageLinkage();
// Overloadable functions need mangling.
if (FD->hasAttr<OverloadableAttr>())
return true;
// "main" is not mangled.
if (FD->isMain())
return false;
// The Windows ABI expects that we would never mangle "typical"
// user-defined entry points regardless of visibility or freestanding-ness.
//
// N.B. This is distinct from asking about "main". "main" has a lot of
// special rules associated with it in the standard while these
// user-defined entry points are outside of the purview of the standard.
// For example, there can be only one definition for "main" in a standards
// compliant program; however nothing forbids the existence of wmain and
// WinMain in the same translation unit.
if (FD->isMSVCRTEntryPoint())
return false;
// C++ functions and those whose names are not a simple identifier need
// mangling.
if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
return true;
// C functions are not mangled.
if (L == CLanguageLinkage)
return false;
}
// Otherwise, no mangling is done outside C++ mode.
if (!getASTContext().getLangOpts().CPlusPlus)
return false;
if (const auto *VD = dyn_cast<VarDecl>(D)) {
// Decompositions are mangled.
if (isa<DecompositionDecl>(VD))
return true;
// C variables are not mangled.
if (VD->isExternC())
return false;
// Variables at global scope are not mangled unless they have internal
// linkage or are specializations or are attached to a named module.
const DeclContext *DC = getEffectiveDeclContext(D);
// Check for extern variable declared locally.
if (DC->isFunctionOrMethod() && D->hasLinkage())
while (!DC->isFileContext())
DC = getEffectiveParentContext(DC);
if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
!CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
!isa<VarTemplateSpecializationDecl>(VD) &&
!VD->getOwningModuleForLinkage())
return false;
}
return true;
}
void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
const AbiTagList *AdditionalAbiTags) {
assert(AbiTags && "require AbiTagState");
AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
}
void CXXNameMangler::mangleSourceNameWithAbiTags(
const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
mangleSourceName(ND->getIdentifier());
writeAbiTags(ND, AdditionalAbiTags);
}
void CXXNameMangler::mangle(GlobalDecl GD) {
// <mangled-name> ::= _Z <encoding>
// ::= <data name>
// ::= <special-name>
Out << "_Z";
if (isa<FunctionDecl>(GD.getDecl()))
mangleFunctionEncoding(GD);
else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
BindingDecl>(GD.getDecl()))
mangleName(GD);
else if (const IndirectFieldDecl *IFD =
dyn_cast<IndirectFieldDecl>(GD.getDecl()))
mangleName(IFD->getAnonField());
else
llvm_unreachable("unexpected kind of global decl");
}
void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
// <encoding> ::= <function name> <bare-function-type>
// Don't mangle in the type if this isn't a decl we should typically mangle.
if (!Context.shouldMangleDeclName(FD)) {
mangleName(GD);
return;
}
AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
if (ReturnTypeAbiTags.empty()) {
// There are no tags for return type, the simplest case. Enter the function
// parameter scope before mangling the name, because a template using
// constrained `auto` can have references to its parameters within its
// template argument list:
//
// template<typename T> void f(T x, C<decltype(x)> auto)
// ... is mangled as ...
// template<typename T, C<decltype(param 1)> U> void f(T, U)
FunctionTypeDepthState Saved = FunctionTypeDepth.push();
mangleName(GD);
FunctionTypeDepth.pop(Saved);
mangleFunctionEncodingBareType(FD);
return;
}
// Mangle function name and encoding to temporary buffer.
// We have to output name and encoding to the same mangler to get the same
// substitution as it will be in final mangling.
SmallString<256> FunctionEncodingBuf;
llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
// Output name of the function.
FunctionEncodingMangler.disableDerivedAbiTags();
FunctionTypeDepthState Saved = FunctionTypeDepth.push();
FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
FunctionTypeDepth.pop(Saved);
// Remember length of the function name in the buffer.
size_t EncodingPositionStart = FunctionEncodingStream.str().size();
FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
// Get tags from return type that are not present in function name or
// encoding.
const AbiTagList &UsedAbiTags =
FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
AdditionalAbiTags.erase(
std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
UsedAbiTags.begin(), UsedAbiTags.end(),
AdditionalAbiTags.begin()),
AdditionalAbiTags.end());
// Output name with implicit tags and function encoding from temporary buffer.
Saved = FunctionTypeDepth.push();
mangleNameWithAbiTags(FD, &AdditionalAbiTags);
FunctionTypeDepth.pop(Saved);
Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
// Function encoding could create new substitutions so we have to add
// temp mangled substitutions to main mangler.
extendSubstitutions(&FunctionEncodingMangler);
}
void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
if (FD->hasAttr<EnableIfAttr>()) {
FunctionTypeDepthState Saved = FunctionTypeDepth.push();
Out << "Ua9enable_ifI";
for (AttrVec::const_iterator I = FD->getAttrs().begin(),
E = FD->getAttrs().end();
I != E; ++I) {
EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
if (!EIA)
continue;
if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
// Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
// even though <template-arg> should not include an X/E around
// <expr-primary>.
Out << 'X';
mangleExpression(EIA->getCond());
Out << 'E';
} else {
mangleTemplateArgExpr(EIA->getCond());
}
}
Out << 'E';
FunctionTypeDepth.pop(Saved);
}
// When mangling an inheriting constructor, the bare function type used is
// that of the inherited constructor.
if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
if (auto Inherited = CD->getInheritedConstructor())
FD = Inherited.getConstructor();
// Whether the mangling of a function type includes the return type depends on
// the context and the nature of the function. The rules for deciding whether
// the return type is included are:
//
// 1. Template functions (names or types) have return types encoded, with
// the exceptions listed below.
// 2. Function types not appearing as part of a function name mangling,
// e.g. parameters, pointer types, etc., have return type encoded, with the
// exceptions listed below.
// 3. Non-template function names do not have return types encoded.
//
// The exceptions mentioned in (1) and (2) above, for which the return type is
// never included, are
// 1. Constructors.
// 2. Destructors.
// 3. Conversion operator functions, e.g. operator int.
bool MangleReturnType = false;
if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
isa<CXXConversionDecl>(FD)))
MangleReturnType = true;
// Mangle the type of the primary template.
FD = PrimaryTemplate->getTemplatedDecl();
}
mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
MangleReturnType, FD);
}
/// Return whether a given namespace is the 'std' namespace.
bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
return false;
const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
return II && II->isStr("std");
}
// isStdNamespace - Return whether a given decl context is a toplevel 'std'
// namespace.
bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
if (!DC->isNamespace())
return false;
return isStd(cast<NamespaceDecl>(DC));
}
static const GlobalDecl
isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
// Check if we have a function template.
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
TemplateArgs = FD->getTemplateSpecializationArgs();
return GD.getWithDecl(TD);
}
}
// Check if we have a class template.
if (const ClassTemplateSpecializationDecl *Spec =
dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
TemplateArgs = &Spec->getTemplateArgs();
return GD.getWithDecl(Spec->getSpecializedTemplate());
}
// Check if we have a variable template.
if (const VarTemplateSpecializationDecl *Spec =
dyn_cast<VarTemplateSpecializationDecl>(ND)) {
TemplateArgs = &Spec->getTemplateArgs();
return GD.getWithDecl(Spec->getSpecializedTemplate());
}