1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implements C++ name mangling according to the Itanium C++ ABI,
10 // which is used in GCC 3.2 and newer (and many compilers that are
11 // ABI-compatible with GCC):
13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
15 //===----------------------------------------------------------------------===//
16 #include "clang/AST/Mangle.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
35 using namespace clang;
39 /// Retrieve the declaration context that should be used when mangling the given
41 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
42 // The ABI assumes that lambda closure types that occur within
43 // default arguments live in the context of the function. However, due to
44 // the way in which Clang parses and creates function declarations, this is
45 // not the case: the lambda closure type ends up living in the context
46 // where the function itself resides, because the function declaration itself
47 // had not yet been created. Fix the context here.
48 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
50 if (ParmVarDecl *ContextParam
51 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
52 return ContextParam->getDeclContext();
55 // Perform the same check for block literals.
56 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
59 return ContextParam->getDeclContext();
62 const DeclContext *DC = D->getDeclContext();
63 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
64 isa<OMPDeclareMapperDecl>(DC)) {
65 return getEffectiveDeclContext(cast<Decl>(DC));
68 if (const auto *VD = dyn_cast<VarDecl>(D))
70 return VD->getASTContext().getTranslationUnitDecl();
72 if (const auto *FD = dyn_cast<FunctionDecl>(D))
74 return FD->getASTContext().getTranslationUnitDecl();
76 return DC->getRedeclContext();
79 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
80 return getEffectiveDeclContext(cast<Decl>(DC));
83 static bool isLocalContainerContext(const DeclContext *DC) {
84 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
87 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
88 const DeclContext *DC = getEffectiveDeclContext(D);
89 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
90 if (isLocalContainerContext(DC))
91 return dyn_cast<RecordDecl>(D);
93 DC = getEffectiveDeclContext(D);
98 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
99 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
100 return ftd->getTemplatedDecl();
105 static const NamedDecl *getStructor(const NamedDecl *decl) {
106 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
107 return (fn ? getStructor(fn) : decl);
110 static bool isLambda(const NamedDecl *ND) {
111 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
115 return Record->isLambda();
118 static const unsigned UnknownArity = ~0U;
120 class ItaniumMangleContextImpl : public ItaniumMangleContext {
121 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
122 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
123 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
126 explicit ItaniumMangleContextImpl(ASTContext &Context,
127 DiagnosticsEngine &Diags)
128 : ItaniumMangleContext(Context, Diags) {}
130 /// @name Mangler Entry Points
133 bool shouldMangleCXXName(const NamedDecl *D) override;
134 bool shouldMangleStringLiteral(const StringLiteral *) override {
137 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
138 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
139 raw_ostream &) override;
140 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
141 const ThisAdjustment &ThisAdjustment,
142 raw_ostream &) override;
143 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
144 raw_ostream &) override;
145 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
146 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
147 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
148 const CXXRecordDecl *Type, raw_ostream &) override;
149 void mangleCXXRTTI(QualType T, raw_ostream &) override;
150 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
151 void mangleTypeName(QualType T, raw_ostream &) override;
152 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
153 raw_ostream &) override;
154 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
155 raw_ostream &) override;
157 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
158 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
159 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
160 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
161 void mangleDynamicAtExitDestructor(const VarDecl *D,
162 raw_ostream &Out) override;
163 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164 raw_ostream &Out) override;
165 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166 raw_ostream &Out) override;
167 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169 raw_ostream &) override;
171 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
173 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
175 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
176 // Lambda closure types are already numbered.
180 // Anonymous tags are already numbered.
181 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
182 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
186 // Use the canonical number for externally visible decls.
187 if (ND->isExternallyVisible()) {
188 unsigned discriminator = getASTContext().getManglingNumber(ND);
189 if (discriminator == 1)
191 disc = discriminator - 2;
195 // Make up a reasonable number for internal decls.
196 unsigned &discriminator = Uniquifier[ND];
197 if (!discriminator) {
198 const DeclContext *DC = getEffectiveDeclContext(ND);
199 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
201 if (discriminator == 1)
203 disc = discriminator-2;
209 /// Manage the mangling of a single name.
210 class CXXNameMangler {
211 ItaniumMangleContextImpl &Context;
213 bool NullOut = false;
214 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
215 /// This mode is used when mangler creates another mangler recursively to
216 /// calculate ABI tags for the function return value or the variable type.
217 /// Also it is required to avoid infinite recursion in some cases.
218 bool DisableDerivedAbiTags = false;
220 /// The "structor" is the top-level declaration being mangled, if
221 /// that's not a template specialization; otherwise it's the pattern
222 /// for that specialization.
223 const NamedDecl *Structor;
224 unsigned StructorType;
226 /// The next substitution sequence number.
229 class FunctionTypeDepthState {
232 enum { InResultTypeMask = 1 };
235 FunctionTypeDepthState() : Bits(0) {}
237 /// The number of function types we're inside.
238 unsigned getDepth() const {
242 /// True if we're in the return type of the innermost function type.
243 bool isInResultType() const {
244 return Bits & InResultTypeMask;
247 FunctionTypeDepthState push() {
248 FunctionTypeDepthState tmp = *this;
249 Bits = (Bits & ~InResultTypeMask) + 2;
253 void enterResultType() {
254 Bits |= InResultTypeMask;
257 void leaveResultType() {
258 Bits &= ~InResultTypeMask;
261 void pop(FunctionTypeDepthState saved) {
262 assert(getDepth() == saved.getDepth() + 1);
268 // abi_tag is a gcc attribute, taking one or more strings called "tags".
269 // The goal is to annotate against which version of a library an object was
270 // built and to be able to provide backwards compatibility ("dual abi").
271 // For more information see docs/ItaniumMangleAbiTags.rst.
272 typedef SmallVector<StringRef, 4> AbiTagList;
274 // State to gather all implicit and explicit tags used in a mangled name.
275 // Must always have an instance of this while emitting any name to keep
277 class AbiTagState final {
279 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
285 AbiTagState(const AbiTagState &) = delete;
286 AbiTagState &operator=(const AbiTagState &) = delete;
288 ~AbiTagState() { pop(); }
290 void write(raw_ostream &Out, const NamedDecl *ND,
291 const AbiTagList *AdditionalAbiTags) {
292 ND = cast<NamedDecl>(ND->getCanonicalDecl());
293 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
295 !AdditionalAbiTags &&
296 "only function and variables need a list of additional abi tags");
297 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
298 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
299 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
300 AbiTag->tags().end());
302 // Don't emit abi tags for namespaces.
308 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
309 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
310 AbiTag->tags().end());
311 TagList.insert(TagList.end(), AbiTag->tags().begin(),
312 AbiTag->tags().end());
315 if (AdditionalAbiTags) {
316 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
317 AdditionalAbiTags->end());
318 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
319 AdditionalAbiTags->end());
323 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
325 writeSortedUniqueAbiTags(Out, TagList);
328 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
329 void setUsedAbiTags(const AbiTagList &AbiTags) {
330 UsedAbiTags = AbiTags;
333 const AbiTagList &getEmittedAbiTags() const {
334 return EmittedAbiTags;
337 const AbiTagList &getSortedUniqueUsedAbiTags() {
338 llvm::sort(UsedAbiTags);
339 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
345 //! All abi tags used implicitly or explicitly.
346 AbiTagList UsedAbiTags;
347 //! All explicit abi tags (i.e. not from namespace).
348 AbiTagList EmittedAbiTags;
350 AbiTagState *&LinkHead;
351 AbiTagState *Parent = nullptr;
354 assert(LinkHead == this &&
355 "abi tag link head must point to us on destruction");
357 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
358 UsedAbiTags.begin(), UsedAbiTags.end());
359 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
360 EmittedAbiTags.begin(),
361 EmittedAbiTags.end());
366 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
367 for (const auto &Tag : AbiTags) {
368 EmittedAbiTags.push_back(Tag);
376 AbiTagState *AbiTags = nullptr;
377 AbiTagState AbiTagsRoot;
379 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
380 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
382 ASTContext &getASTContext() const { return Context.getASTContext(); }
385 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
386 const NamedDecl *D = nullptr, bool NullOut_ = false)
387 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
388 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
389 // These can't be mangled without a ctor type or dtor type.
390 assert(!D || (!isa<CXXDestructorDecl>(D) &&
391 !isa<CXXConstructorDecl>(D)));
393 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
394 const CXXConstructorDecl *D, CXXCtorType Type)
395 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
396 SeqID(0), AbiTagsRoot(AbiTags) { }
397 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
398 const CXXDestructorDecl *D, CXXDtorType Type)
399 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
400 SeqID(0), AbiTagsRoot(AbiTags) { }
402 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
403 : Context(Outer.Context), Out(Out_), NullOut(false),
404 Structor(Outer.Structor), StructorType(Outer.StructorType),
405 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
406 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
408 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
409 : Context(Outer.Context), Out(Out_), NullOut(true),
410 Structor(Outer.Structor), StructorType(Outer.StructorType),
411 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
412 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
414 raw_ostream &getStream() { return Out; }
416 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
417 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
419 void mangle(const NamedDecl *D);
420 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
421 void mangleNumber(const llvm::APSInt &I);
422 void mangleNumber(int64_t Number);
423 void mangleFloat(const llvm::APFloat &F);
424 void mangleFunctionEncoding(const FunctionDecl *FD);
425 void mangleSeqID(unsigned SeqID);
426 void mangleName(const NamedDecl *ND);
427 void mangleType(QualType T);
428 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
429 void mangleLambdaSig(const CXXRecordDecl *Lambda);
433 bool mangleSubstitution(const NamedDecl *ND);
434 bool mangleSubstitution(QualType T);
435 bool mangleSubstitution(TemplateName Template);
436 bool mangleSubstitution(uintptr_t Ptr);
438 void mangleExistingSubstitution(TemplateName name);
440 bool mangleStandardSubstitution(const NamedDecl *ND);
442 void addSubstitution(const NamedDecl *ND) {
443 ND = cast<NamedDecl>(ND->getCanonicalDecl());
445 addSubstitution(reinterpret_cast<uintptr_t>(ND));
447 void addSubstitution(QualType T);
448 void addSubstitution(TemplateName Template);
449 void addSubstitution(uintptr_t Ptr);
450 // Destructive copy substitutions from other mangler.
451 void extendSubstitutions(CXXNameMangler* Other);
453 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
454 bool recursive = false);
455 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
456 DeclarationName name,
457 const TemplateArgumentLoc *TemplateArgs,
458 unsigned NumTemplateArgs,
459 unsigned KnownArity = UnknownArity);
461 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
463 void mangleNameWithAbiTags(const NamedDecl *ND,
464 const AbiTagList *AdditionalAbiTags);
465 void mangleModuleName(const Module *M);
466 void mangleModuleNamePrefix(StringRef Name);
467 void mangleTemplateName(const TemplateDecl *TD,
468 const TemplateArgument *TemplateArgs,
469 unsigned NumTemplateArgs);
470 void mangleUnqualifiedName(const NamedDecl *ND,
471 const AbiTagList *AdditionalAbiTags) {
472 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
475 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
477 const AbiTagList *AdditionalAbiTags);
478 void mangleUnscopedName(const NamedDecl *ND,
479 const AbiTagList *AdditionalAbiTags);
480 void mangleUnscopedTemplateName(const TemplateDecl *ND,
481 const AbiTagList *AdditionalAbiTags);
482 void mangleUnscopedTemplateName(TemplateName,
483 const AbiTagList *AdditionalAbiTags);
484 void mangleSourceName(const IdentifierInfo *II);
485 void mangleRegCallName(const IdentifierInfo *II);
486 void mangleSourceNameWithAbiTags(
487 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
488 void mangleLocalName(const Decl *D,
489 const AbiTagList *AdditionalAbiTags);
490 void mangleBlockForPrefix(const BlockDecl *Block);
491 void mangleUnqualifiedBlock(const BlockDecl *Block);
492 void mangleTemplateParamDecl(const NamedDecl *Decl);
493 void mangleLambda(const CXXRecordDecl *Lambda);
494 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
495 const AbiTagList *AdditionalAbiTags,
496 bool NoFunction=false);
497 void mangleNestedName(const TemplateDecl *TD,
498 const TemplateArgument *TemplateArgs,
499 unsigned NumTemplateArgs);
500 void manglePrefix(NestedNameSpecifier *qualifier);
501 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
502 void manglePrefix(QualType type);
503 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
504 void mangleTemplatePrefix(TemplateName Template);
505 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
506 StringRef Prefix = "");
507 void mangleOperatorName(DeclarationName Name, unsigned Arity);
508 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
509 void mangleVendorQualifier(StringRef qualifier);
510 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
511 void mangleRefQualifier(RefQualifierKind RefQualifier);
513 void mangleObjCMethodName(const ObjCMethodDecl *MD);
515 // Declare manglers for every type class.
516 #define ABSTRACT_TYPE(CLASS, PARENT)
517 #define NON_CANONICAL_TYPE(CLASS, PARENT)
518 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
519 #include "clang/AST/TypeNodes.inc"
521 void mangleType(const TagType*);
522 void mangleType(TemplateName);
523 static StringRef getCallingConvQualifierName(CallingConv CC);
524 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
525 void mangleExtFunctionInfo(const FunctionType *T);
526 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
527 const FunctionDecl *FD = nullptr);
528 void mangleNeonVectorType(const VectorType *T);
529 void mangleNeonVectorType(const DependentVectorType *T);
530 void mangleAArch64NeonVectorType(const VectorType *T);
531 void mangleAArch64NeonVectorType(const DependentVectorType *T);
533 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
534 void mangleMemberExprBase(const Expr *base, bool isArrow);
535 void mangleMemberExpr(const Expr *base, bool isArrow,
536 NestedNameSpecifier *qualifier,
537 NamedDecl *firstQualifierLookup,
538 DeclarationName name,
539 const TemplateArgumentLoc *TemplateArgs,
540 unsigned NumTemplateArgs,
541 unsigned knownArity);
542 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
543 void mangleInitListElements(const InitListExpr *InitList);
544 void mangleDeclRefExpr(const NamedDecl *D);
545 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
546 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
547 void mangleCXXDtorType(CXXDtorType T);
549 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
550 unsigned NumTemplateArgs);
551 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
552 unsigned NumTemplateArgs);
553 void mangleTemplateArgs(const TemplateArgumentList &AL);
554 void mangleTemplateArg(TemplateArgument A);
556 void mangleTemplateParameter(unsigned Depth, unsigned Index);
558 void mangleFunctionParam(const ParmVarDecl *parm);
560 void writeAbiTags(const NamedDecl *ND,
561 const AbiTagList *AdditionalAbiTags);
563 // Returns sorted unique list of ABI tags.
564 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
565 // Returns sorted unique list of ABI tags.
566 AbiTagList makeVariableTypeTags(const VarDecl *VD);
571 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
572 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
574 LanguageLinkage L = FD->getLanguageLinkage();
575 // Overloadable functions need mangling.
576 if (FD->hasAttr<OverloadableAttr>())
579 // "main" is not mangled.
583 // The Windows ABI expects that we would never mangle "typical"
584 // user-defined entry points regardless of visibility or freestanding-ness.
586 // N.B. This is distinct from asking about "main". "main" has a lot of
587 // special rules associated with it in the standard while these
588 // user-defined entry points are outside of the purview of the standard.
589 // For example, there can be only one definition for "main" in a standards
590 // compliant program; however nothing forbids the existence of wmain and
591 // WinMain in the same translation unit.
592 if (FD->isMSVCRTEntryPoint())
595 // C++ functions and those whose names are not a simple identifier need
597 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
600 // C functions are not mangled.
601 if (L == CLanguageLinkage)
605 // Otherwise, no mangling is done outside C++ mode.
606 if (!getASTContext().getLangOpts().CPlusPlus)
609 const VarDecl *VD = dyn_cast<VarDecl>(D);
610 if (VD && !isa<DecompositionDecl>(D)) {
611 // C variables are not mangled.
615 // Variables at global scope with non-internal linkage are not mangled
616 const DeclContext *DC = getEffectiveDeclContext(D);
617 // Check for extern variable declared locally.
618 if (DC->isFunctionOrMethod() && D->hasLinkage())
619 while (!DC->isNamespace() && !DC->isTranslationUnit())
620 DC = getEffectiveParentContext(DC);
621 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
622 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
623 !isa<VarTemplateSpecializationDecl>(D))
630 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
631 const AbiTagList *AdditionalAbiTags) {
632 assert(AbiTags && "require AbiTagState");
633 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
636 void CXXNameMangler::mangleSourceNameWithAbiTags(
637 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
638 mangleSourceName(ND->getIdentifier());
639 writeAbiTags(ND, AdditionalAbiTags);
642 void CXXNameMangler::mangle(const NamedDecl *D) {
643 // <mangled-name> ::= _Z <encoding>
645 // ::= <special-name>
647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
648 mangleFunctionEncoding(FD);
649 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
651 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
652 mangleName(IFD->getAnonField());
654 mangleName(cast<FieldDecl>(D));
657 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
658 // <encoding> ::= <function name> <bare-function-type>
660 // Don't mangle in the type if this isn't a decl we should typically mangle.
661 if (!Context.shouldMangleDeclName(FD)) {
666 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
667 if (ReturnTypeAbiTags.empty()) {
668 // There are no tags for return type, the simplest case.
670 mangleFunctionEncodingBareType(FD);
674 // Mangle function name and encoding to temporary buffer.
675 // We have to output name and encoding to the same mangler to get the same
676 // substitution as it will be in final mangling.
677 SmallString<256> FunctionEncodingBuf;
678 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
679 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
680 // Output name of the function.
681 FunctionEncodingMangler.disableDerivedAbiTags();
682 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
684 // Remember length of the function name in the buffer.
685 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
686 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
688 // Get tags from return type that are not present in function name or
690 const AbiTagList &UsedAbiTags =
691 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
692 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
693 AdditionalAbiTags.erase(
694 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
695 UsedAbiTags.begin(), UsedAbiTags.end(),
696 AdditionalAbiTags.begin()),
697 AdditionalAbiTags.end());
699 // Output name with implicit tags and function encoding from temporary buffer.
700 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
701 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
703 // Function encoding could create new substitutions so we have to add
704 // temp mangled substitutions to main mangler.
705 extendSubstitutions(&FunctionEncodingMangler);
708 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
709 if (FD->hasAttr<EnableIfAttr>()) {
710 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
711 Out << "Ua9enable_ifI";
712 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
713 E = FD->getAttrs().end();
715 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
719 mangleExpression(EIA->getCond());
723 FunctionTypeDepth.pop(Saved);
726 // When mangling an inheriting constructor, the bare function type used is
727 // that of the inherited constructor.
728 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
729 if (auto Inherited = CD->getInheritedConstructor())
730 FD = Inherited.getConstructor();
732 // Whether the mangling of a function type includes the return type depends on
733 // the context and the nature of the function. The rules for deciding whether
734 // the return type is included are:
736 // 1. Template functions (names or types) have return types encoded, with
737 // the exceptions listed below.
738 // 2. Function types not appearing as part of a function name mangling,
739 // e.g. parameters, pointer types, etc., have return type encoded, with the
740 // exceptions listed below.
741 // 3. Non-template function names do not have return types encoded.
743 // The exceptions mentioned in (1) and (2) above, for which the return type is
744 // never included, are
747 // 3. Conversion operator functions, e.g. operator int.
748 bool MangleReturnType = false;
749 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
750 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
751 isa<CXXConversionDecl>(FD)))
752 MangleReturnType = true;
754 // Mangle the type of the primary template.
755 FD = PrimaryTemplate->getTemplatedDecl();
758 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
759 MangleReturnType, FD);
762 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
763 while (isa<LinkageSpecDecl>(DC)) {
764 DC = getEffectiveParentContext(DC);
770 /// Return whether a given namespace is the 'std' namespace.
771 static bool isStd(const NamespaceDecl *NS) {
772 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
773 ->isTranslationUnit())
776 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
777 return II && II->isStr("std");
780 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
782 static bool isStdNamespace(const DeclContext *DC) {
783 if (!DC->isNamespace())
786 return isStd(cast<NamespaceDecl>(DC));
789 static const TemplateDecl *
790 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
791 // Check if we have a function template.
792 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
793 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
794 TemplateArgs = FD->getTemplateSpecializationArgs();
799 // Check if we have a class template.
800 if (const ClassTemplateSpecializationDecl *Spec =
801 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
802 TemplateArgs = &Spec->getTemplateArgs();
803 return Spec->getSpecializedTemplate();
806 // Check if we have a variable template.
807 if (const VarTemplateSpecializationDecl *Spec =
808 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
809 TemplateArgs = &Spec->getTemplateArgs();
810 return Spec->getSpecializedTemplate();
816 void CXXNameMangler::mangleName(const NamedDecl *ND) {
817 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
818 // Variables should have implicit tags from its type.
819 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
820 if (VariableTypeAbiTags.empty()) {
821 // Simple case no variable type tags.
822 mangleNameWithAbiTags(VD, nullptr);
826 // Mangle variable name to null stream to collect tags.
827 llvm::raw_null_ostream NullOutStream;
828 CXXNameMangler VariableNameMangler(*this, NullOutStream);
829 VariableNameMangler.disableDerivedAbiTags();
830 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
832 // Get tags from variable type that are not present in its name.
833 const AbiTagList &UsedAbiTags =
834 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
835 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
836 AdditionalAbiTags.erase(
837 std::set_difference(VariableTypeAbiTags.begin(),
838 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
839 UsedAbiTags.end(), AdditionalAbiTags.begin()),
840 AdditionalAbiTags.end());
842 // Output name with implicit tags.
843 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
845 mangleNameWithAbiTags(ND, nullptr);
849 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
850 const AbiTagList *AdditionalAbiTags) {
851 // <name> ::= [<module-name>] <nested-name>
852 // ::= [<module-name>] <unscoped-name>
853 // ::= [<module-name>] <unscoped-template-name> <template-args>
856 const DeclContext *DC = getEffectiveDeclContext(ND);
858 // If this is an extern variable declared locally, the relevant DeclContext
859 // is that of the containing namespace, or the translation unit.
860 // FIXME: This is a hack; extern variables declared locally should have
861 // a proper semantic declaration context!
862 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
863 while (!DC->isNamespace() && !DC->isTranslationUnit())
864 DC = getEffectiveParentContext(DC);
865 else if (GetLocalClassDecl(ND)) {
866 mangleLocalName(ND, AdditionalAbiTags);
870 DC = IgnoreLinkageSpecDecls(DC);
872 if (isLocalContainerContext(DC)) {
873 mangleLocalName(ND, AdditionalAbiTags);
877 // Do not mangle the owning module for an external linkage declaration.
878 // This enables backwards-compatibility with non-modular code, and is
879 // a valid choice since conflicts are not permitted by C++ Modules TS
880 // [basic.def.odr]/6.2.
881 if (!ND->hasExternalFormalLinkage())
882 if (Module *M = ND->getOwningModuleForLinkage())
885 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
886 // Check if we have a template.
887 const TemplateArgumentList *TemplateArgs = nullptr;
888 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
889 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
890 mangleTemplateArgs(*TemplateArgs);
894 mangleUnscopedName(ND, AdditionalAbiTags);
898 mangleNestedName(ND, DC, AdditionalAbiTags);
901 void CXXNameMangler::mangleModuleName(const Module *M) {
902 // Implement the C++ Modules TS name mangling proposal; see
903 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
905 // <module-name> ::= W <unscoped-name>+ E
906 // ::= W <module-subst> <unscoped-name>* E
908 mangleModuleNamePrefix(M->Name);
912 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
913 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
914 // ::= W <seq-id - 10> _ # otherwise
915 auto It = ModuleSubstitutions.find(Name);
916 if (It != ModuleSubstitutions.end()) {
918 Out << '_' << static_cast<char>('0' + It->second);
920 Out << 'W' << (It->second - 10) << '_';
924 // FIXME: Preserve hierarchy in module names rather than flattening
925 // them to strings; use Module*s as substitution keys.
926 auto Parts = Name.rsplit('.');
927 if (Parts.second.empty())
928 Parts.second = Parts.first;
930 mangleModuleNamePrefix(Parts.first);
932 Out << Parts.second.size() << Parts.second;
933 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
936 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
937 const TemplateArgument *TemplateArgs,
938 unsigned NumTemplateArgs) {
939 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
941 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
942 mangleUnscopedTemplateName(TD, nullptr);
943 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
945 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
949 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
950 const AbiTagList *AdditionalAbiTags) {
951 // <unscoped-name> ::= <unqualified-name>
952 // ::= St <unqualified-name> # ::std::
954 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
957 mangleUnqualifiedName(ND, AdditionalAbiTags);
960 void CXXNameMangler::mangleUnscopedTemplateName(
961 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
962 // <unscoped-template-name> ::= <unscoped-name>
963 // ::= <substitution>
964 if (mangleSubstitution(ND))
967 // <template-template-param> ::= <template-param>
968 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
969 assert(!AdditionalAbiTags &&
970 "template template param cannot have abi tags");
971 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
972 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
973 mangleUnscopedName(ND, AdditionalAbiTags);
975 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
981 void CXXNameMangler::mangleUnscopedTemplateName(
982 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
983 // <unscoped-template-name> ::= <unscoped-name>
984 // ::= <substitution>
985 if (TemplateDecl *TD = Template.getAsTemplateDecl())
986 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
988 if (mangleSubstitution(Template))
991 assert(!AdditionalAbiTags &&
992 "dependent template name cannot have abi tags");
994 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
995 assert(Dependent && "Not a dependent template name?");
996 if (const IdentifierInfo *Id = Dependent->getIdentifier())
997 mangleSourceName(Id);
999 mangleOperatorName(Dependent->getOperator(), UnknownArity);
1001 addSubstitution(Template);
1004 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1006 // Floating-point literals are encoded using a fixed-length
1007 // lowercase hexadecimal string corresponding to the internal
1008 // representation (IEEE on Itanium), high-order bytes first,
1009 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1011 // The 'without leading zeroes' thing seems to be an editorial
1012 // mistake; see the discussion on cxx-abi-dev beginning on
1015 // Our requirements here are just barely weird enough to justify
1016 // using a custom algorithm instead of post-processing APInt::toString().
1018 llvm::APInt valueBits = f.bitcastToAPInt();
1019 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1020 assert(numCharacters != 0);
1022 // Allocate a buffer of the right number of characters.
1023 SmallVector<char, 20> buffer(numCharacters);
1025 // Fill the buffer left-to-right.
1026 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1027 // The bit-index of the next hex digit.
1028 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1030 // Project out 4 bits starting at 'digitIndex'.
1031 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1032 hexDigit >>= (digitBitIndex % 64);
1035 // Map that over to a lowercase hex digit.
1036 static const char charForHex[16] = {
1037 '0', '1', '2', '3', '4', '5', '6', '7',
1038 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1040 buffer[stringIndex] = charForHex[hexDigit];
1043 Out.write(buffer.data(), numCharacters);
1046 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1047 if (Value.isSigned() && Value.isNegative()) {
1049 Value.abs().print(Out, /*signed*/ false);
1051 Value.print(Out, /*signed*/ false);
1055 void CXXNameMangler::mangleNumber(int64_t Number) {
1056 // <number> ::= [n] <non-negative decimal integer>
1065 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1066 // <call-offset> ::= h <nv-offset> _
1067 // ::= v <v-offset> _
1068 // <nv-offset> ::= <offset number> # non-virtual base override
1069 // <v-offset> ::= <offset number> _ <virtual offset number>
1070 // # virtual base override, with vcall offset
1073 mangleNumber(NonVirtual);
1079 mangleNumber(NonVirtual);
1081 mangleNumber(Virtual);
1085 void CXXNameMangler::manglePrefix(QualType type) {
1086 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1087 if (!mangleSubstitution(QualType(TST, 0))) {
1088 mangleTemplatePrefix(TST->getTemplateName());
1090 // FIXME: GCC does not appear to mangle the template arguments when
1091 // the template in question is a dependent template name. Should we
1092 // emulate that badness?
1093 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1094 addSubstitution(QualType(TST, 0));
1096 } else if (const auto *DTST =
1097 type->getAs<DependentTemplateSpecializationType>()) {
1098 if (!mangleSubstitution(QualType(DTST, 0))) {
1099 TemplateName Template = getASTContext().getDependentTemplateName(
1100 DTST->getQualifier(), DTST->getIdentifier());
1101 mangleTemplatePrefix(Template);
1103 // FIXME: GCC does not appear to mangle the template arguments when
1104 // the template in question is a dependent template name. Should we
1105 // emulate that badness?
1106 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1107 addSubstitution(QualType(DTST, 0));
1110 // We use the QualType mangle type variant here because it handles
1116 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1118 /// \param recursive - true if this is being called recursively,
1119 /// i.e. if there is more prefix "to the right".
1120 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1124 // <unresolved-name> ::= [gs] <base-unresolved-name>
1126 // T::x / decltype(p)::x
1127 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1129 // T::N::x /decltype(p)::N::x
1130 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1131 // <base-unresolved-name>
1133 // A::x, N::y, A<T>::z; "gs" means leading "::"
1134 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1135 // <base-unresolved-name>
1137 switch (qualifier->getKind()) {
1138 case NestedNameSpecifier::Global:
1141 // We want an 'sr' unless this is the entire NNS.
1145 // We never want an 'E' here.
1148 case NestedNameSpecifier::Super:
1149 llvm_unreachable("Can't mangle __super specifier");
1151 case NestedNameSpecifier::Namespace:
1152 if (qualifier->getPrefix())
1153 mangleUnresolvedPrefix(qualifier->getPrefix(),
1154 /*recursive*/ true);
1157 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1159 case NestedNameSpecifier::NamespaceAlias:
1160 if (qualifier->getPrefix())
1161 mangleUnresolvedPrefix(qualifier->getPrefix(),
1162 /*recursive*/ true);
1165 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1168 case NestedNameSpecifier::TypeSpec:
1169 case NestedNameSpecifier::TypeSpecWithTemplate: {
1170 const Type *type = qualifier->getAsType();
1172 // We only want to use an unresolved-type encoding if this is one of:
1174 // - a template type parameter
1175 // - a template template parameter with arguments
1176 // In all of these cases, we should have no prefix.
1177 if (qualifier->getPrefix()) {
1178 mangleUnresolvedPrefix(qualifier->getPrefix(),
1179 /*recursive*/ true);
1181 // Otherwise, all the cases want this.
1185 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1191 case NestedNameSpecifier::Identifier:
1192 // Member expressions can have these without prefixes.
1193 if (qualifier->getPrefix())
1194 mangleUnresolvedPrefix(qualifier->getPrefix(),
1195 /*recursive*/ true);
1199 mangleSourceName(qualifier->getAsIdentifier());
1200 // An Identifier has no type information, so we can't emit abi tags for it.
1204 // If this was the innermost part of the NNS, and we fell out to
1205 // here, append an 'E'.
1210 /// Mangle an unresolved-name, which is generally used for names which
1211 /// weren't resolved to specific entities.
1212 void CXXNameMangler::mangleUnresolvedName(
1213 NestedNameSpecifier *qualifier, DeclarationName name,
1214 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1215 unsigned knownArity) {
1216 if (qualifier) mangleUnresolvedPrefix(qualifier);
1217 switch (name.getNameKind()) {
1218 // <base-unresolved-name> ::= <simple-id>
1219 case DeclarationName::Identifier:
1220 mangleSourceName(name.getAsIdentifierInfo());
1222 // <base-unresolved-name> ::= dn <destructor-name>
1223 case DeclarationName::CXXDestructorName:
1225 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1227 // <base-unresolved-name> ::= on <operator-name>
1228 case DeclarationName::CXXConversionFunctionName:
1229 case DeclarationName::CXXLiteralOperatorName:
1230 case DeclarationName::CXXOperatorName:
1232 mangleOperatorName(name, knownArity);
1234 case DeclarationName::CXXConstructorName:
1235 llvm_unreachable("Can't mangle a constructor name!");
1236 case DeclarationName::CXXUsingDirective:
1237 llvm_unreachable("Can't mangle a using directive name!");
1238 case DeclarationName::CXXDeductionGuideName:
1239 llvm_unreachable("Can't mangle a deduction guide name!");
1240 case DeclarationName::ObjCMultiArgSelector:
1241 case DeclarationName::ObjCOneArgSelector:
1242 case DeclarationName::ObjCZeroArgSelector:
1243 llvm_unreachable("Can't mangle Objective-C selector names here!");
1246 // The <simple-id> and on <operator-name> productions end in an optional
1249 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1252 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1253 DeclarationName Name,
1254 unsigned KnownArity,
1255 const AbiTagList *AdditionalAbiTags) {
1256 unsigned Arity = KnownArity;
1257 // <unqualified-name> ::= <operator-name>
1258 // ::= <ctor-dtor-name>
1259 // ::= <source-name>
1260 switch (Name.getNameKind()) {
1261 case DeclarationName::Identifier: {
1262 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1264 // We mangle decomposition declarations as the names of their bindings.
1265 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1266 // FIXME: Non-standard mangling for decomposition declarations:
1268 // <unqualified-name> ::= DC <source-name>* E
1270 // These can never be referenced across translation units, so we do
1271 // not need a cross-vendor mangling for anything other than demanglers.
1272 // Proposed on cxx-abi-dev on 2016-08-12
1274 for (auto *BD : DD->bindings())
1275 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1277 writeAbiTags(ND, AdditionalAbiTags);
1282 // Match GCC's naming convention for internal linkage symbols, for
1283 // symbols that are not actually visible outside of this TU. GCC
1284 // distinguishes between internal and external linkage symbols in
1285 // its mangling, to support cases like this that were valid C++ prior
1288 // void test() { extern void foo(); }
1289 // static void foo();
1291 // Don't bother with the L marker for names in anonymous namespaces; the
1292 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1293 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1294 // implying internal linkage.
1295 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1296 !ND->isExternallyVisible() &&
1297 getEffectiveDeclContext(ND)->isFileContext() &&
1298 !ND->isInAnonymousNamespace())
1301 auto *FD = dyn_cast<FunctionDecl>(ND);
1302 bool IsRegCall = FD &&
1303 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1304 clang::CC_X86RegCall;
1306 mangleRegCallName(II);
1308 mangleSourceName(II);
1310 writeAbiTags(ND, AdditionalAbiTags);
1314 // Otherwise, an anonymous entity. We must have a declaration.
1315 assert(ND && "mangling empty name without declaration");
1317 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1318 if (NS->isAnonymousNamespace()) {
1319 // This is how gcc mangles these names.
1320 Out << "12_GLOBAL__N_1";
1325 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1326 // We must have an anonymous union or struct declaration.
1327 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1329 // Itanium C++ ABI 5.1.2:
1331 // For the purposes of mangling, the name of an anonymous union is
1332 // considered to be the name of the first named data member found by a
1333 // pre-order, depth-first, declaration-order walk of the data members of
1334 // the anonymous union. If there is no such data member (i.e., if all of
1335 // the data members in the union are unnamed), then there is no way for
1336 // a program to refer to the anonymous union, and there is therefore no
1337 // need to mangle its name.
1338 assert(RD->isAnonymousStructOrUnion()
1339 && "Expected anonymous struct or union!");
1340 const FieldDecl *FD = RD->findFirstNamedDataMember();
1342 // It's actually possible for various reasons for us to get here
1343 // with an empty anonymous struct / union. Fortunately, it
1344 // doesn't really matter what name we generate.
1346 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1348 mangleSourceName(FD->getIdentifier());
1349 // Not emitting abi tags: internal name anyway.
1353 // Class extensions have no name as a category, and it's possible
1354 // for them to be the semantic parent of certain declarations
1355 // (primarily, tag decls defined within declarations). Such
1356 // declarations will always have internal linkage, so the name
1357 // doesn't really matter, but we shouldn't crash on them. For
1358 // safety, just handle all ObjC containers here.
1359 if (isa<ObjCContainerDecl>(ND))
1362 // We must have an anonymous struct.
1363 const TagDecl *TD = cast<TagDecl>(ND);
1364 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1365 assert(TD->getDeclContext() == D->getDeclContext() &&
1366 "Typedef should not be in another decl context!");
1367 assert(D->getDeclName().getAsIdentifierInfo() &&
1368 "Typedef was not named!");
1369 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1370 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1371 // Explicit abi tags are still possible; take from underlying type, not
1373 writeAbiTags(TD, nullptr);
1377 // <unnamed-type-name> ::= <closure-type-name>
1379 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1380 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1381 // # Parameter types or 'v' for 'void'.
1382 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1383 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1384 assert(!AdditionalAbiTags &&
1385 "Lambda type cannot have additional abi tags");
1386 mangleLambda(Record);
1391 if (TD->isExternallyVisible()) {
1392 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1394 if (UnnamedMangle > 1)
1395 Out << UnnamedMangle - 2;
1397 writeAbiTags(TD, AdditionalAbiTags);
1401 // Get a unique id for the anonymous struct. If it is not a real output
1402 // ID doesn't matter so use fake one.
1403 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1405 // Mangle it as a source name in the form
1407 // where n is the length of the string.
1410 Str += llvm::utostr(AnonStructId);
1417 case DeclarationName::ObjCZeroArgSelector:
1418 case DeclarationName::ObjCOneArgSelector:
1419 case DeclarationName::ObjCMultiArgSelector:
1420 llvm_unreachable("Can't mangle Objective-C selector names here!");
1422 case DeclarationName::CXXConstructorName: {
1423 const CXXRecordDecl *InheritedFrom = nullptr;
1424 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1425 if (auto Inherited =
1426 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1427 InheritedFrom = Inherited.getConstructor()->getParent();
1428 InheritedTemplateArgs =
1429 Inherited.getConstructor()->getTemplateSpecializationArgs();
1433 // If the named decl is the C++ constructor we're mangling, use the type
1435 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1437 // Otherwise, use the complete constructor name. This is relevant if a
1438 // class with a constructor is declared within a constructor.
1439 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1441 // FIXME: The template arguments are part of the enclosing prefix or
1442 // nested-name, but it's more convenient to mangle them here.
1443 if (InheritedTemplateArgs)
1444 mangleTemplateArgs(*InheritedTemplateArgs);
1446 writeAbiTags(ND, AdditionalAbiTags);
1450 case DeclarationName::CXXDestructorName:
1452 // If the named decl is the C++ destructor we're mangling, use the type we
1454 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1456 // Otherwise, use the complete destructor name. This is relevant if a
1457 // class with a destructor is declared within a destructor.
1458 mangleCXXDtorType(Dtor_Complete);
1459 writeAbiTags(ND, AdditionalAbiTags);
1462 case DeclarationName::CXXOperatorName:
1463 if (ND && Arity == UnknownArity) {
1464 Arity = cast<FunctionDecl>(ND)->getNumParams();
1466 // If we have a member function, we need to include the 'this' pointer.
1467 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1468 if (!MD->isStatic())
1472 case DeclarationName::CXXConversionFunctionName:
1473 case DeclarationName::CXXLiteralOperatorName:
1474 mangleOperatorName(Name, Arity);
1475 writeAbiTags(ND, AdditionalAbiTags);
1478 case DeclarationName::CXXDeductionGuideName:
1479 llvm_unreachable("Can't mangle a deduction guide name!");
1481 case DeclarationName::CXXUsingDirective:
1482 llvm_unreachable("Can't mangle a using directive name!");
1486 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1487 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1488 // <number> ::= [n] <non-negative decimal integer>
1489 // <identifier> ::= <unqualified source code identifier>
1490 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1494 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1495 // <source-name> ::= <positive length number> <identifier>
1496 // <number> ::= [n] <non-negative decimal integer>
1497 // <identifier> ::= <unqualified source code identifier>
1498 Out << II->getLength() << II->getName();
1501 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1502 const DeclContext *DC,
1503 const AbiTagList *AdditionalAbiTags,
1506 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1507 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1508 // <template-args> E
1511 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1512 Qualifiers MethodQuals = Method->getMethodQualifiers();
1513 // We do not consider restrict a distinguishing attribute for overloading
1514 // purposes so we must not mangle it.
1515 MethodQuals.removeRestrict();
1516 mangleQualifiers(MethodQuals);
1517 mangleRefQualifier(Method->getRefQualifier());
1520 // Check if we have a template.
1521 const TemplateArgumentList *TemplateArgs = nullptr;
1522 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1523 mangleTemplatePrefix(TD, NoFunction);
1524 mangleTemplateArgs(*TemplateArgs);
1527 manglePrefix(DC, NoFunction);
1528 mangleUnqualifiedName(ND, AdditionalAbiTags);
1533 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1534 const TemplateArgument *TemplateArgs,
1535 unsigned NumTemplateArgs) {
1536 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1540 mangleTemplatePrefix(TD);
1541 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1546 void CXXNameMangler::mangleLocalName(const Decl *D,
1547 const AbiTagList *AdditionalAbiTags) {
1548 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1549 // := Z <function encoding> E s [<discriminator>]
1550 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1552 // <discriminator> := _ <non-negative number>
1553 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1554 const RecordDecl *RD = GetLocalClassDecl(D);
1555 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1560 AbiTagState LocalAbiTags(AbiTags);
1562 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1563 mangleObjCMethodName(MD);
1564 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1565 mangleBlockForPrefix(BD);
1567 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1569 // Implicit ABI tags (from namespace) are not available in the following
1570 // entity; reset to actually emitted tags, which are available.
1571 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1576 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1577 // be a bug that is fixed in trunk.
1580 // The parameter number is omitted for the last parameter, 0 for the
1581 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1582 // <entity name> will of course contain a <closure-type-name>: Its
1583 // numbering will be local to the particular argument in which it appears
1584 // -- other default arguments do not affect its encoding.
1585 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1586 if (CXXRD && CXXRD->isLambda()) {
1587 if (const ParmVarDecl *Parm
1588 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1589 if (const FunctionDecl *Func
1590 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1592 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1594 mangleNumber(Num - 2);
1600 // Mangle the name relative to the closest enclosing function.
1601 // equality ok because RD derived from ND above
1603 mangleUnqualifiedName(RD, AdditionalAbiTags);
1604 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1605 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1606 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1607 mangleUnqualifiedBlock(BD);
1609 const NamedDecl *ND = cast<NamedDecl>(D);
1610 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1611 true /*NoFunction*/);
1613 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1614 // Mangle a block in a default parameter; see above explanation for
1616 if (const ParmVarDecl *Parm
1617 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1618 if (const FunctionDecl *Func
1619 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1621 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1623 mangleNumber(Num - 2);
1628 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1629 mangleUnqualifiedBlock(BD);
1631 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1634 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1636 if (Context.getNextDiscriminator(ND, disc)) {
1640 Out << "__" << disc << '_';
1645 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1646 if (GetLocalClassDecl(Block)) {
1647 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1650 const DeclContext *DC = getEffectiveDeclContext(Block);
1651 if (isLocalContainerContext(DC)) {
1652 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1655 manglePrefix(getEffectiveDeclContext(Block));
1656 mangleUnqualifiedBlock(Block);
1659 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1660 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1661 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1662 Context->getDeclContext()->isRecord()) {
1663 const auto *ND = cast<NamedDecl>(Context);
1664 if (ND->getIdentifier()) {
1665 mangleSourceNameWithAbiTags(ND);
1671 // If we have a block mangling number, use it.
1672 unsigned Number = Block->getBlockManglingNumber();
1673 // Otherwise, just make up a number. It doesn't matter what it is because
1674 // the symbol in question isn't externally visible.
1676 Number = Context.getBlockId(Block, false);
1678 // Stored mangling numbers are 1-based.
1687 // <template-param-decl>
1688 // ::= Ty # template type parameter
1689 // ::= Tn <type> # template non-type parameter
1690 // ::= Tt <template-param-decl>* E # template template parameter
1691 // ::= Tp <template-param-decl> # template parameter pack
1692 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1693 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1694 if (Ty->isParameterPack())
1697 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1698 if (Tn->isExpandedParameterPack()) {
1699 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1701 mangleType(Tn->getExpansionType(I));
1704 QualType T = Tn->getType();
1705 if (Tn->isParameterPack()) {
1707 if (auto *PackExpansion = T->getAs<PackExpansionType>())
1708 T = PackExpansion->getPattern();
1713 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1714 if (Tt->isExpandedParameterPack()) {
1715 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1718 for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1719 mangleTemplateParamDecl(Param);
1723 if (Tt->isParameterPack())
1726 for (auto *Param : *Tt->getTemplateParameters())
1727 mangleTemplateParamDecl(Param);
1733 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1734 // If the context of a closure type is an initializer for a class member
1735 // (static or nonstatic), it is encoded in a qualified name with a final
1736 // <prefix> of the form:
1738 // <data-member-prefix> := <member source-name> M
1740 // Technically, the data-member-prefix is part of the <prefix>. However,
1741 // since a closure type will always be mangled with a prefix, it's easier
1742 // to emit that last part of the prefix here.
1743 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1744 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1745 !isa<ParmVarDecl>(Context)) {
1746 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1747 // reasonable mangling here.
1748 if (const IdentifierInfo *Name
1749 = cast<NamedDecl>(Context)->getIdentifier()) {
1750 mangleSourceName(Name);
1751 const TemplateArgumentList *TemplateArgs = nullptr;
1752 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1753 mangleTemplateArgs(*TemplateArgs);
1760 mangleLambdaSig(Lambda);
1763 // The number is omitted for the first closure type with a given
1764 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1765 // (in lexical order) with that same <lambda-sig> and context.
1767 // The AST keeps track of the number for us.
1768 unsigned Number = Lambda->getLambdaManglingNumber();
1769 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1771 mangleNumber(Number - 2);
1775 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
1776 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1777 mangleTemplateParamDecl(D);
1778 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1779 getAs<FunctionProtoType>();
1780 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1781 Lambda->getLambdaStaticInvoker());
1784 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1785 switch (qualifier->getKind()) {
1786 case NestedNameSpecifier::Global:
1790 case NestedNameSpecifier::Super:
1791 llvm_unreachable("Can't mangle __super specifier");
1793 case NestedNameSpecifier::Namespace:
1794 mangleName(qualifier->getAsNamespace());
1797 case NestedNameSpecifier::NamespaceAlias:
1798 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1801 case NestedNameSpecifier::TypeSpec:
1802 case NestedNameSpecifier::TypeSpecWithTemplate:
1803 manglePrefix(QualType(qualifier->getAsType(), 0));
1806 case NestedNameSpecifier::Identifier:
1807 // Member expressions can have these without prefixes, but that
1808 // should end up in mangleUnresolvedPrefix instead.
1809 assert(qualifier->getPrefix());
1810 manglePrefix(qualifier->getPrefix());
1812 mangleSourceName(qualifier->getAsIdentifier());
1816 llvm_unreachable("unexpected nested name specifier");
1819 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1820 // <prefix> ::= <prefix> <unqualified-name>
1821 // ::= <template-prefix> <template-args>
1822 // ::= <template-param>
1824 // ::= <substitution>
1826 DC = IgnoreLinkageSpecDecls(DC);
1828 if (DC->isTranslationUnit())
1831 if (NoFunction && isLocalContainerContext(DC))
1834 assert(!isLocalContainerContext(DC));
1836 const NamedDecl *ND = cast<NamedDecl>(DC);
1837 if (mangleSubstitution(ND))
1840 // Check if we have a template.
1841 const TemplateArgumentList *TemplateArgs = nullptr;
1842 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1843 mangleTemplatePrefix(TD);
1844 mangleTemplateArgs(*TemplateArgs);
1846 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1847 mangleUnqualifiedName(ND, nullptr);
1850 addSubstitution(ND);
1853 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1854 // <template-prefix> ::= <prefix> <template unqualified-name>
1855 // ::= <template-param>
1856 // ::= <substitution>
1857 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1858 return mangleTemplatePrefix(TD);
1860 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1861 manglePrefix(Qualified->getQualifier());
1863 if (OverloadedTemplateStorage *Overloaded
1864 = Template.getAsOverloadedTemplate()) {
1865 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1866 UnknownArity, nullptr);
1870 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1871 assert(Dependent && "Unknown template name kind?");
1872 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1873 manglePrefix(Qualifier);
1874 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1877 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1879 // <template-prefix> ::= <prefix> <template unqualified-name>
1880 // ::= <template-param>
1881 // ::= <substitution>
1882 // <template-template-param> ::= <template-param>
1885 if (mangleSubstitution(ND))
1888 // <template-template-param> ::= <template-param>
1889 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1890 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1892 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1893 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
1894 mangleUnqualifiedName(ND, nullptr);
1896 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1899 addSubstitution(ND);
1902 /// Mangles a template name under the production <type>. Required for
1903 /// template template arguments.
1904 /// <type> ::= <class-enum-type>
1905 /// ::= <template-param>
1906 /// ::= <substitution>
1907 void CXXNameMangler::mangleType(TemplateName TN) {
1908 if (mangleSubstitution(TN))
1911 TemplateDecl *TD = nullptr;
1913 switch (TN.getKind()) {
1914 case TemplateName::QualifiedTemplate:
1915 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1918 case TemplateName::Template:
1919 TD = TN.getAsTemplateDecl();
1923 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
1924 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1929 case TemplateName::OverloadedTemplate:
1930 case TemplateName::AssumedTemplate:
1931 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1933 case TemplateName::DependentTemplate: {
1934 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1935 assert(Dependent->isIdentifier());
1937 // <class-enum-type> ::= <name>
1938 // <name> ::= <nested-name>
1939 mangleUnresolvedPrefix(Dependent->getQualifier());
1940 mangleSourceName(Dependent->getIdentifier());
1944 case TemplateName::SubstTemplateTemplateParm: {
1945 // Substituted template parameters are mangled as the substituted
1946 // template. This will check for the substitution twice, which is
1947 // fine, but we have to return early so that we don't try to *add*
1948 // the substitution twice.
1949 SubstTemplateTemplateParmStorage *subst
1950 = TN.getAsSubstTemplateTemplateParm();
1951 mangleType(subst->getReplacement());
1955 case TemplateName::SubstTemplateTemplateParmPack: {
1956 // FIXME: not clear how to mangle this!
1957 // template <template <class> class T...> class A {
1958 // template <template <class> class U...> void foo(B<T,U> x...);
1960 Out << "_SUBSTPACK_";
1965 addSubstitution(TN);
1968 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1970 // Only certain other types are valid as prefixes; enumerate them.
1971 switch (Ty->getTypeClass()) {
1974 case Type::Adjusted:
1977 case Type::BlockPointer:
1978 case Type::LValueReference:
1979 case Type::RValueReference:
1980 case Type::MemberPointer:
1981 case Type::ConstantArray:
1982 case Type::IncompleteArray:
1983 case Type::VariableArray:
1984 case Type::DependentSizedArray:
1985 case Type::DependentAddressSpace:
1986 case Type::DependentVector:
1987 case Type::DependentSizedExtVector:
1989 case Type::ExtVector:
1990 case Type::FunctionProto:
1991 case Type::FunctionNoProto:
1993 case Type::Attributed:
1995 case Type::DeducedTemplateSpecialization:
1996 case Type::PackExpansion:
1997 case Type::ObjCObject:
1998 case Type::ObjCInterface:
1999 case Type::ObjCObjectPointer:
2000 case Type::ObjCTypeParam:
2003 case Type::MacroQualified:
2004 llvm_unreachable("type is illegal as a nested name specifier");
2006 case Type::SubstTemplateTypeParmPack:
2007 // FIXME: not clear how to mangle this!
2008 // template <class T...> class A {
2009 // template <class U...> void foo(decltype(T::foo(U())) x...);
2011 Out << "_SUBSTPACK_";
2014 // <unresolved-type> ::= <template-param>
2016 // ::= <template-template-param> <template-args>
2017 // (this last is not official yet)
2018 case Type::TypeOfExpr:
2020 case Type::Decltype:
2021 case Type::TemplateTypeParm:
2022 case Type::UnaryTransform:
2023 case Type::SubstTemplateTypeParm:
2025 // Some callers want a prefix before the mangled type.
2028 // This seems to do everything we want. It's not really
2029 // sanctioned for a substituted template parameter, though.
2032 // We never want to print 'E' directly after an unresolved-type,
2033 // so we return directly.
2037 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2040 case Type::UnresolvedUsing:
2041 mangleSourceNameWithAbiTags(
2042 cast<UnresolvedUsingType>(Ty)->getDecl());
2047 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2050 case Type::TemplateSpecialization: {
2051 const TemplateSpecializationType *TST =
2052 cast<TemplateSpecializationType>(Ty);
2053 TemplateName TN = TST->getTemplateName();
2054 switch (TN.getKind()) {
2055 case TemplateName::Template:
2056 case TemplateName::QualifiedTemplate: {
2057 TemplateDecl *TD = TN.getAsTemplateDecl();
2059 // If the base is a template template parameter, this is an
2061 assert(TD && "no template for template specialization type");
2062 if (isa<TemplateTemplateParmDecl>(TD))
2063 goto unresolvedType;
2065 mangleSourceNameWithAbiTags(TD);
2069 case TemplateName::OverloadedTemplate:
2070 case TemplateName::AssumedTemplate:
2071 case TemplateName::DependentTemplate:
2072 llvm_unreachable("invalid base for a template specialization type");
2074 case TemplateName::SubstTemplateTemplateParm: {
2075 SubstTemplateTemplateParmStorage *subst =
2076 TN.getAsSubstTemplateTemplateParm();
2077 mangleExistingSubstitution(subst->getReplacement());
2081 case TemplateName::SubstTemplateTemplateParmPack: {
2082 // FIXME: not clear how to mangle this!
2083 // template <template <class U> class T...> class A {
2084 // template <class U...> void foo(decltype(T<U>::foo) x...);
2086 Out << "_SUBSTPACK_";
2091 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
2095 case Type::InjectedClassName:
2096 mangleSourceNameWithAbiTags(
2097 cast<InjectedClassNameType>(Ty)->getDecl());
2100 case Type::DependentName:
2101 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2104 case Type::DependentTemplateSpecialization: {
2105 const DependentTemplateSpecializationType *DTST =
2106 cast<DependentTemplateSpecializationType>(Ty);
2107 mangleSourceName(DTST->getIdentifier());
2108 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2112 case Type::Elaborated:
2113 return mangleUnresolvedTypeOrSimpleId(
2114 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2120 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2121 switch (Name.getNameKind()) {
2122 case DeclarationName::CXXConstructorName:
2123 case DeclarationName::CXXDestructorName:
2124 case DeclarationName::CXXDeductionGuideName:
2125 case DeclarationName::CXXUsingDirective:
2126 case DeclarationName::Identifier:
2127 case DeclarationName::ObjCMultiArgSelector:
2128 case DeclarationName::ObjCOneArgSelector:
2129 case DeclarationName::ObjCZeroArgSelector:
2130 llvm_unreachable("Not an operator name");
2132 case DeclarationName::CXXConversionFunctionName:
2133 // <operator-name> ::= cv <type> # (cast)
2135 mangleType(Name.getCXXNameType());
2138 case DeclarationName::CXXLiteralOperatorName:
2140 mangleSourceName(Name.getCXXLiteralIdentifier());
2143 case DeclarationName::CXXOperatorName:
2144 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2150 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2152 // <operator-name> ::= nw # new
2153 case OO_New: Out << "nw"; break;
2155 case OO_Array_New: Out << "na"; break;
2157 case OO_Delete: Out << "dl"; break;
2158 // ::= da # delete[]
2159 case OO_Array_Delete: Out << "da"; break;
2160 // ::= ps # + (unary)
2161 // ::= pl # + (binary or unknown)
2163 Out << (Arity == 1? "ps" : "pl"); break;
2164 // ::= ng # - (unary)
2165 // ::= mi # - (binary or unknown)
2167 Out << (Arity == 1? "ng" : "mi"); break;
2168 // ::= ad # & (unary)
2169 // ::= an # & (binary or unknown)
2171 Out << (Arity == 1? "ad" : "an"); break;
2172 // ::= de # * (unary)
2173 // ::= ml # * (binary or unknown)
2175 // Use binary when unknown.
2176 Out << (Arity == 1? "de" : "ml"); break;
2178 case OO_Tilde: Out << "co"; break;
2180 case OO_Slash: Out << "dv"; break;
2182 case OO_Percent: Out << "rm"; break;
2184 case OO_Pipe: Out << "or"; break;
2186 case OO_Caret: Out << "eo"; break;
2188 case OO_Equal: Out << "aS"; break;
2190 case OO_PlusEqual: Out << "pL"; break;
2192 case OO_MinusEqual: Out << "mI"; break;
2194 case OO_StarEqual: Out << "mL"; break;
2196 case OO_SlashEqual: Out << "dV"; break;
2198 case OO_PercentEqual: Out << "rM"; break;
2200 case OO_AmpEqual: Out << "aN"; break;
2202 case OO_PipeEqual: Out << "oR"; break;
2204 case OO_CaretEqual: Out << "eO"; break;
2206 case OO_LessLess: Out << "ls"; break;
2208 case OO_GreaterGreater: Out << "rs"; break;
2210 case OO_LessLessEqual: Out << "lS"; break;
2212 case OO_GreaterGreaterEqual: Out << "rS"; break;
2214 case OO_EqualEqual: Out << "eq"; break;
2216 case OO_ExclaimEqual: Out << "ne"; break;
2218 case OO_Less: Out << "lt"; break;
2220 case OO_Greater: Out << "gt"; break;
2222 case OO_LessEqual: Out << "le"; break;
2224 case OO_GreaterEqual: Out << "ge"; break;
2226 case OO_Exclaim: Out << "nt"; break;
2228 case OO_AmpAmp: Out << "aa"; break;
2230 case OO_PipePipe: Out << "oo"; break;
2232 case OO_PlusPlus: Out << "pp"; break;
2234 case OO_MinusMinus: Out << "mm"; break;
2236 case OO_Comma: Out << "cm"; break;
2238 case OO_ArrowStar: Out << "pm"; break;
2240 case OO_Arrow: Out << "pt"; break;
2242 case OO_Call: Out << "cl"; break;
2244 case OO_Subscript: Out << "ix"; break;
2247 // The conditional operator can't be overloaded, but we still handle it when
2248 // mangling expressions.
2249 case OO_Conditional: Out << "qu"; break;
2250 // Proposal on cxx-abi-dev, 2015-10-21.
2251 // ::= aw # co_await
2252 case OO_Coawait: Out << "aw"; break;
2253 // Proposed in cxx-abi github issue 43.
2255 case OO_Spaceship: Out << "ss"; break;
2258 case NUM_OVERLOADED_OPERATORS:
2259 llvm_unreachable("Not an overloaded operator");
2263 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2264 // Vendor qualifiers come first and if they are order-insensitive they must
2265 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2267 // <type> ::= U <addrspace-expr>
2270 mangleExpression(DAST->getAddrSpaceExpr());
2274 // Address space qualifiers start with an ordinary letter.
2275 if (Quals.hasAddressSpace()) {
2276 // Address space extension:
2278 // <type> ::= U <target-addrspace>
2279 // <type> ::= U <OpenCL-addrspace>
2280 // <type> ::= U <CUDA-addrspace>
2282 SmallString<64> ASString;
2283 LangAS AS = Quals.getAddressSpace();
2285 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2286 // <target-addrspace> ::= "AS" <address-space-number>
2287 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2289 ASString = "AS" + llvm::utostr(TargetAS);
2292 default: llvm_unreachable("Not a language specific address space");
2293 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2294 // "private"| "generic" ]
2295 case LangAS::opencl_global: ASString = "CLglobal"; break;
2296 case LangAS::opencl_local: ASString = "CLlocal"; break;
2297 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2298 case LangAS::opencl_private: ASString = "CLprivate"; break;
2299 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
2300 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2301 case LangAS::cuda_device: ASString = "CUdevice"; break;
2302 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2303 case LangAS::cuda_shared: ASString = "CUshared"; break;
2306 if (!ASString.empty())
2307 mangleVendorQualifier(ASString);
2310 // The ARC ownership qualifiers start with underscores.
2311 // Objective-C ARC Extension:
2313 // <type> ::= U "__strong"
2314 // <type> ::= U "__weak"
2315 // <type> ::= U "__autoreleasing"
2317 // Note: we emit __weak first to preserve the order as
2318 // required by the Itanium ABI.
2319 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2320 mangleVendorQualifier("__weak");
2322 // __unaligned (from -fms-extensions)
2323 if (Quals.hasUnaligned())
2324 mangleVendorQualifier("__unaligned");
2326 // Remaining ARC ownership qualifiers.
2327 switch (Quals.getObjCLifetime()) {
2328 case Qualifiers::OCL_None:
2331 case Qualifiers::OCL_Weak:
2332 // Do nothing as we already handled this case above.
2335 case Qualifiers::OCL_Strong:
2336 mangleVendorQualifier("__strong");
2339 case Qualifiers::OCL_Autoreleasing:
2340 mangleVendorQualifier("__autoreleasing");
2343 case Qualifiers::OCL_ExplicitNone:
2344 // The __unsafe_unretained qualifier is *not* mangled, so that
2345 // __unsafe_unretained types in ARC produce the same manglings as the
2346 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2347 // better ABI compatibility.
2349 // It's safe to do this because unqualified 'id' won't show up
2350 // in any type signatures that need to be mangled.
2354 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2355 if (Quals.hasRestrict())
2357 if (Quals.hasVolatile())
2359 if (Quals.hasConst())
2363 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2364 Out << 'U' << name.size() << name;
2367 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2368 // <ref-qualifier> ::= R # lvalue reference
2369 // ::= O # rvalue-reference
2370 switch (RefQualifier) {
2384 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2385 Context.mangleObjCMethodName(MD, Out);
2388 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2392 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2394 if (Ty->isOpenCLSpecificType())
2396 if (Ty->isBuiltinType())
2398 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2399 // substitution candidates.
2400 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2406 void CXXNameMangler::mangleType(QualType T) {
2407 // If our type is instantiation-dependent but not dependent, we mangle
2408 // it as it was written in the source, removing any top-level sugar.
2409 // Otherwise, use the canonical type.
2411 // FIXME: This is an approximation of the instantiation-dependent name
2412 // mangling rules, since we should really be using the type as written and
2413 // augmented via semantic analysis (i.e., with implicit conversions and
2414 // default template arguments) for any instantiation-dependent type.
2415 // Unfortunately, that requires several changes to our AST:
2416 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2417 // uniqued, so that we can handle substitutions properly
2418 // - Default template arguments will need to be represented in the
2419 // TemplateSpecializationType, since they need to be mangled even though
2420 // they aren't written.
2421 // - Conversions on non-type template arguments need to be expressed, since
2422 // they can affect the mangling of sizeof/alignof.
2424 // FIXME: This is wrong when mapping to the canonical type for a dependent
2425 // type discards instantiation-dependent portions of the type, such as for:
2427 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2428 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2430 // It's also wrong in the opposite direction when instantiation-dependent,
2431 // canonically-equivalent types differ in some irrelevant portion of inner
2432 // type sugar. In such cases, we fail to form correct substitutions, eg:
2434 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2436 // We should instead canonicalize the non-instantiation-dependent parts,
2437 // regardless of whether the type as a whole is dependent or instantiation
2439 if (!T->isInstantiationDependentType() || T->isDependentType())
2440 T = T.getCanonicalType();
2442 // Desugar any types that are purely sugar.
2444 // Don't desugar through template specialization types that aren't
2445 // type aliases. We need to mangle the template arguments as written.
2446 if (const TemplateSpecializationType *TST
2447 = dyn_cast<TemplateSpecializationType>(T))
2448 if (!TST->isTypeAlias())
2452 = T.getSingleStepDesugaredType(Context.getASTContext());
2459 SplitQualType split = T.split();
2460 Qualifiers quals = split.Quals;
2461 const Type *ty = split.Ty;
2463 bool isSubstitutable =
2464 isTypeSubstitutable(quals, ty, Context.getASTContext());
2465 if (isSubstitutable && mangleSubstitution(T))
2468 // If we're mangling a qualified array type, push the qualifiers to
2469 // the element type.
2470 if (quals && isa<ArrayType>(T)) {
2471 ty = Context.getASTContext().getAsArrayType(T);
2472 quals = Qualifiers();
2474 // Note that we don't update T: we want to add the
2475 // substitution at the original type.
2478 if (quals || ty->isDependentAddressSpaceType()) {
2479 if (const DependentAddressSpaceType *DAST =
2480 dyn_cast<DependentAddressSpaceType>(ty)) {
2481 SplitQualType splitDAST = DAST->getPointeeType().split();
2482 mangleQualifiers(splitDAST.Quals, DAST);
2483 mangleType(QualType(splitDAST.Ty, 0));
2485 mangleQualifiers(quals);
2487 // Recurse: even if the qualified type isn't yet substitutable,
2488 // the unqualified type might be.
2489 mangleType(QualType(ty, 0));
2492 switch (ty->getTypeClass()) {
2493 #define ABSTRACT_TYPE(CLASS, PARENT)
2494 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2496 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2498 #define TYPE(CLASS, PARENT) \
2500 mangleType(static_cast<const CLASS##Type*>(ty)); \
2502 #include "clang/AST/TypeNodes.inc"
2506 // Add the substitution.
2507 if (isSubstitutable)
2511 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2512 if (!mangleStandardSubstitution(ND))
2516 void CXXNameMangler::mangleType(const BuiltinType *T) {
2517 // <type> ::= <builtin-type>
2518 // <builtin-type> ::= v # void
2522 // ::= a # signed char
2523 // ::= h # unsigned char
2525 // ::= t # unsigned short
2527 // ::= j # unsigned int
2529 // ::= m # unsigned long
2530 // ::= x # long long, __int64
2531 // ::= y # unsigned long long, __int64
2533 // ::= o # unsigned __int128
2536 // ::= e # long double, __float80
2537 // ::= g # __float128
2538 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2539 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2540 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2541 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2542 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2543 // ::= Di # char32_t
2544 // ::= Ds # char16_t
2545 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2546 // ::= u <source-name> # vendor extended type
2547 std::string type_name;
2548 switch (T->getKind()) {
2549 case BuiltinType::Void:
2552 case BuiltinType::Bool:
2555 case BuiltinType::Char_U:
2556 case BuiltinType::Char_S:
2559 case BuiltinType::UChar:
2562 case BuiltinType::UShort:
2565 case BuiltinType::UInt:
2568 case BuiltinType::ULong:
2571 case BuiltinType::ULongLong:
2574 case BuiltinType::UInt128:
2577 case BuiltinType::SChar:
2580 case BuiltinType::WChar_S:
2581 case BuiltinType::WChar_U:
2584 case BuiltinType::Char8:
2587 case BuiltinType::Char16:
2590 case BuiltinType::Char32:
2593 case BuiltinType::Short:
2596 case BuiltinType::Int:
2599 case BuiltinType::Long:
2602 case BuiltinType::LongLong:
2605 case BuiltinType::Int128:
2608 case BuiltinType::Float16:
2611 case BuiltinType::ShortAccum:
2612 case BuiltinType::Accum:
2613 case BuiltinType::LongAccum:
2614 case BuiltinType::UShortAccum:
2615 case BuiltinType::UAccum:
2616 case BuiltinType::ULongAccum:
2617 case BuiltinType::ShortFract:
2618 case BuiltinType::Fract:
2619 case BuiltinType::LongFract:
2620 case BuiltinType::UShortFract:
2621 case BuiltinType::UFract:
2622 case BuiltinType::ULongFract:
2623 case BuiltinType::SatShortAccum:
2624 case BuiltinType::SatAccum:
2625 case BuiltinType::SatLongAccum:
2626 case BuiltinType::SatUShortAccum:
2627 case BuiltinType::SatUAccum:
2628 case BuiltinType::SatULongAccum:
2629 case BuiltinType::SatShortFract:
2630 case BuiltinType::SatFract:
2631 case BuiltinType::SatLongFract:
2632 case BuiltinType::SatUShortFract:
2633 case BuiltinType::SatUFract:
2634 case BuiltinType::SatULongFract:
2635 llvm_unreachable("Fixed point types are disabled for c++");
2636 case BuiltinType::Half:
2639 case BuiltinType::Float:
2642 case BuiltinType::Double:
2645 case BuiltinType::LongDouble: {
2646 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2647 getASTContext().getLangOpts().OpenMPIsDevice
2648 ? getASTContext().getAuxTargetInfo()
2649 : &getASTContext().getTargetInfo();
2650 Out << TI->getLongDoubleMangling();
2653 case BuiltinType::Float128: {
2654 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2655 getASTContext().getLangOpts().OpenMPIsDevice
2656 ? getASTContext().getAuxTargetInfo()
2657 : &getASTContext().getTargetInfo();
2658 Out << TI->getFloat128Mangling();
2661 case BuiltinType::NullPtr:
2665 #define BUILTIN_TYPE(Id, SingletonId)
2666 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2667 case BuiltinType::Id:
2668 #include "clang/AST/BuiltinTypes.def"
2669 case BuiltinType::Dependent:
2671 llvm_unreachable("mangling a placeholder type");
2673 case BuiltinType::ObjCId:
2674 Out << "11objc_object";
2676 case BuiltinType::ObjCClass:
2677 Out << "10objc_class";
2679 case BuiltinType::ObjCSel:
2680 Out << "13objc_selector";
2682 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2683 case BuiltinType::Id: \
2684 type_name = "ocl_" #ImgType "_" #Suffix; \
2685 Out << type_name.size() << type_name; \
2687 #include "clang/Basic/OpenCLImageTypes.def"
2688 case BuiltinType::OCLSampler:
2689 Out << "11ocl_sampler";
2691 case BuiltinType::OCLEvent:
2692 Out << "9ocl_event";
2694 case BuiltinType::OCLClkEvent:
2695 Out << "12ocl_clkevent";
2697 case BuiltinType::OCLQueue:
2698 Out << "9ocl_queue";
2700 case BuiltinType::OCLReserveID:
2701 Out << "13ocl_reserveid";
2703 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2704 case BuiltinType::Id: \
2705 type_name = "ocl_" #ExtType; \
2706 Out << type_name.size() << type_name; \
2708 #include "clang/Basic/OpenCLExtensionTypes.def"
2709 // The SVE types are effectively target-specific. The mangling scheme
2710 // is defined in the appendices to the Procedure Call Standard for the
2711 // Arm Architecture.
2712 #define SVE_TYPE(Name, Id, SingletonId) \
2713 case BuiltinType::Id: \
2715 Out << 'u' << type_name.size() << type_name; \
2717 #include "clang/Basic/AArch64SVEACLETypes.def"
2721 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2726 case CC_X86VectorCall:
2731 case CC_AArch64VectorCall:
2732 case CC_IntelOclBicc:
2733 case CC_SpirFunction:
2734 case CC_OpenCLKernel:
2735 case CC_PreserveMost:
2736 case CC_PreserveAll:
2737 // FIXME: we should be mangling all of the above.
2740 case CC_X86ThisCall:
2741 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2742 // used explicitly. At this point, we don't have that much information in
2743 // the AST, since clang tends to bake the convention into the canonical
2744 // function type. thiscall only rarely used explicitly, so don't mangle it
2750 case CC_X86FastCall:
2759 llvm_unreachable("bad calling convention");
2762 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2764 if (T->getExtInfo() == FunctionType::ExtInfo())
2767 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2768 // This will get more complicated in the future if we mangle other
2769 // things here; but for now, since we mangle ns_returns_retained as
2770 // a qualifier on the result type, we can get away with this:
2771 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2772 if (!CCQualifier.empty())
2773 mangleVendorQualifier(CCQualifier);
2780 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2781 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2783 // Note that these are *not* substitution candidates. Demanglers might
2784 // have trouble with this if the parameter type is fully substituted.
2786 switch (PI.getABI()) {
2787 case ParameterABI::Ordinary:
2790 // All of these start with "swift", so they come before "ns_consumed".
2791 case ParameterABI::SwiftContext:
2792 case ParameterABI::SwiftErrorResult:
2793 case ParameterABI::SwiftIndirectResult:
2794 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2798 if (PI.isConsumed())
2799 mangleVendorQualifier("ns_consumed");
2801 if (PI.isNoEscape())
2802 mangleVendorQualifier("noescape");
2805 // <type> ::= <function-type>
2806 // <function-type> ::= [<CV-qualifiers>] F [Y]
2807 // <bare-function-type> [<ref-qualifier>] E
2808 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2809 mangleExtFunctionInfo(T);
2811 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2812 // e.g. "const" in "int (A::*)() const".
2813 mangleQualifiers(T->getMethodQuals());
2815 // Mangle instantiation-dependent exception-specification, if present,
2816 // per cxx-abi-dev proposal on 2016-10-11.
2817 if (T->hasInstantiationDependentExceptionSpec()) {
2818 if (isComputedNoexcept(T->getExceptionSpecType())) {
2820 mangleExpression(T->getNoexceptExpr());
2823 assert(T->getExceptionSpecType() == EST_Dynamic);
2825 for (auto ExceptTy : T->exceptions())
2826 mangleType(ExceptTy);
2829 } else if (T->isNothrow()) {
2835 // FIXME: We don't have enough information in the AST to produce the 'Y'
2836 // encoding for extern "C" function types.
2837 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2839 // Mangle the ref-qualifier, if present.
2840 mangleRefQualifier(T->getRefQualifier());
2845 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2846 // Function types without prototypes can arise when mangling a function type
2847 // within an overloadable function in C. We mangle these as the absence of any
2848 // parameter types (not even an empty parameter list).
2851 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2853 FunctionTypeDepth.enterResultType();
2854 mangleType(T->getReturnType());
2855 FunctionTypeDepth.leaveResultType();
2857 FunctionTypeDepth.pop(saved);
2861 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2862 bool MangleReturnType,
2863 const FunctionDecl *FD) {
2864 // Record that we're in a function type. See mangleFunctionParam
2865 // for details on what we're trying to achieve here.
2866 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2868 // <bare-function-type> ::= <signature type>+
2869 if (MangleReturnType) {
2870 FunctionTypeDepth.enterResultType();
2872 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2873 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2874 mangleVendorQualifier("ns_returns_retained");
2876 // Mangle the return type without any direct ARC ownership qualifiers.
2877 QualType ReturnTy = Proto->getReturnType();
2878 if (ReturnTy.getObjCLifetime()) {
2879 auto SplitReturnTy = ReturnTy.split();
2880 SplitReturnTy.Quals.removeObjCLifetime();
2881 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2883 mangleType(ReturnTy);
2885 FunctionTypeDepth.leaveResultType();
2888 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2889 // <builtin-type> ::= v # void
2892 FunctionTypeDepth.pop(saved);
2896 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2897 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2898 // Mangle extended parameter info as order-sensitive qualifiers here.
2899 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2900 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2904 QualType ParamTy = Proto->getParamType(I);
2905 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2908 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2909 // Attr can only take 1 character, so we can hardcode the length below.
2910 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2911 if (Attr->isDynamic())
2912 Out << "U25pass_dynamic_object_size" << Attr->getType();
2914 Out << "U17pass_object_size" << Attr->getType();
2919 FunctionTypeDepth.pop(saved);
2921 // <builtin-type> ::= z # ellipsis
2922 if (Proto->isVariadic())
2926 // <type> ::= <class-enum-type>
2927 // <class-enum-type> ::= <name>
2928 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2929 mangleName(T->getDecl());
2932 // <type> ::= <class-enum-type>
2933 // <class-enum-type> ::= <name>
2934 void CXXNameMangler::mangleType(const EnumType *T) {
2935 mangleType(static_cast<const TagType*>(T));
2937 void CXXNameMangler::mangleType(const RecordType *T) {
2938 mangleType(static_cast<const TagType*>(T));
2940 void CXXNameMangler::mangleType(const TagType *T) {
2941 mangleName(T->getDecl());
2944 // <type> ::= <array-type>
2945 // <array-type> ::= A <positive dimension number> _ <element type>
2946 // ::= A [<dimension expression>] _ <element type>
2947 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2948 Out << 'A' << T->getSize() << '_';
2949 mangleType(T->getElementType());
2951 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2953 // decayed vla types (size 0) will just be skipped.
2954 if (T->getSizeExpr())
2955 mangleExpression(T->getSizeExpr());
2957 mangleType(T->getElementType());
2959 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2961 mangleExpression(T->getSizeExpr());
2963 mangleType(T->getElementType());
2965 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2967 mangleType(T->getElementType());
2970 // <type> ::= <pointer-to-member-type>
2971 // <pointer-to-member-type> ::= M <class type> <member type>
2972 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2974 mangleType(QualType(T->getClass(), 0));
2975 QualType PointeeType = T->getPointeeType();
2976 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2979 // Itanium C++ ABI 5.1.8:
2981 // The type of a non-static member function is considered to be different,
2982 // for the purposes of substitution, from the type of a namespace-scope or
2983 // static member function whose type appears similar. The types of two
2984 // non-static member functions are considered to be different, for the
2985 // purposes of substitution, if the functions are members of different
2986 // classes. In other words, for the purposes of substitution, the class of
2987 // which the function is a member is considered part of the type of
2990 // Given that we already substitute member function pointers as a
2991 // whole, the net effect of this rule is just to unconditionally
2992 // suppress substitution on the function type in a member pointer.
2993 // We increment the SeqID here to emulate adding an entry to the
2994 // substitution table.
2997 mangleType(PointeeType);
3000 // <type> ::= <template-param>
3001 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3002 mangleTemplateParameter(T->getDepth(), T->getIndex());
3005 // <type> ::= <template-param>
3006 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3007 // FIXME: not clear how to mangle this!
3008 // template <class T...> class A {
3009 // template <class U...> void foo(T(*)(U) x...);
3011 Out << "_SUBSTPACK_";
3014 // <type> ::= P <type> # pointer-to
3015 void CXXNameMangler::mangleType(const PointerType *T) {
3017 mangleType(T->getPointeeType());
3019 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3021 mangleType(T->getPointeeType());
3024 // <type> ::= R <type> # reference-to
3025 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3027 mangleType(T->getPointeeType());
3030 // <type> ::= O <type> # rvalue reference-to (C++0x)
3031 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3033 mangleType(T->getPointeeType());
3036 // <type> ::= C <type> # complex pair (C 2000)
3037 void CXXNameMangler::mangleType(const ComplexType *T) {
3039 mangleType(T->getElementType());
3042 // ARM's ABI for Neon vector types specifies that they should be mangled as
3043 // if they are structs (to match ARM's initial implementation). The
3044 // vector type must be one of the special types predefined by ARM.
3045 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3046 QualType EltType = T->getElementType();
3047 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3048 const char *EltName = nullptr;
3049 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3050 switch (cast<BuiltinType>(EltType)->getKind()) {
3051 case BuiltinType::SChar:
3052 case BuiltinType::UChar:
3053 EltName = "poly8_t";
3055 case BuiltinType::Short:
3056 case BuiltinType::UShort:
3057 EltName = "poly16_t";
3059 case BuiltinType::ULongLong:
3060 EltName = "poly64_t";
3062 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3065 switch (cast<BuiltinType>(EltType)->getKind()) {
3066 case BuiltinType::SChar: EltName = "int8_t"; break;
3067 case BuiltinType::UChar: EltName = "uint8_t"; break;
3068 case BuiltinType::Short: EltName = "int16_t"; break;
3069 case BuiltinType::UShort: EltName = "uint16_t"; break;
3070 case BuiltinType::Int: EltName = "int32_t"; break;
3071 case BuiltinType::UInt: EltName = "uint32_t"; break;
3072 case BuiltinType::LongLong: EltName = "int64_t"; break;
3073 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3074 case BuiltinType::Double: EltName = "float64_t"; break;
3075 case BuiltinType::Float: EltName = "float32_t"; break;
3076 case BuiltinType::Half: EltName = "float16_t";break;
3078 llvm_unreachable("unexpected Neon vector element type");
3081 const char *BaseName = nullptr;
3082 unsigned BitSize = (T->getNumElements() *
3083 getASTContext().getTypeSize(EltType));
3085 BaseName = "__simd64_";
3087 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3088 BaseName = "__simd128_";
3090 Out << strlen(BaseName) + strlen(EltName);
3091 Out << BaseName << EltName;
3094 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3095 DiagnosticsEngine &Diags = Context.getDiags();
3096 unsigned DiagID = Diags.getCustomDiagID(
3097 DiagnosticsEngine::Error,
3098 "cannot mangle this dependent neon vector type yet");
3099 Diags.Report(T->getAttributeLoc(), DiagID);
3102 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3103 switch (EltType->getKind()) {
3104 case BuiltinType::SChar:
3106 case BuiltinType::Short:
3108 case BuiltinType::Int:
3110 case BuiltinType::Long:
3111 case BuiltinType::LongLong:
3113 case BuiltinType::UChar:
3115 case BuiltinType::UShort:
3117 case BuiltinType::UInt:
3119 case BuiltinType::ULong:
3120 case BuiltinType::ULongLong:
3122 case BuiltinType::Half:
3124 case BuiltinType::Float:
3126 case BuiltinType::Double:
3129 llvm_unreachable("Unexpected vector element base type");
3133 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3134 // the equivalent internal name. The vector type must be one of the special
3135 // types predefined by ARM.
3136 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3137 QualType EltType = T->getElementType();
3138 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3140 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3141 (void)BitSize; // Silence warning.
3143 assert((BitSize == 64 || BitSize == 128) &&
3144 "Neon vector type not 64 or 128 bits");
3147 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3148 switch (cast<BuiltinType>(EltType)->getKind()) {
3149 case BuiltinType::UChar:
3152 case BuiltinType::UShort:
3155 case BuiltinType::ULong:
3156 case BuiltinType::ULongLong:
3160 llvm_unreachable("unexpected Neon polynomial vector element type");
3163 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3165 std::string TypeName =
3166 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3167 Out << TypeName.length() << TypeName;
3169 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3170 DiagnosticsEngine &Diags = Context.getDiags();
3171 unsigned DiagID = Diags.getCustomDiagID(
3172 DiagnosticsEngine::Error,
3173 "cannot mangle this dependent neon vector type yet");
3174 Diags.Report(T->getAttributeLoc(), DiagID);
3177 // GNU extension: vector types
3178 // <type> ::= <vector-type>
3179 // <vector-type> ::= Dv <positive dimension number> _
3180 // <extended element type>
3181 // ::= Dv [<dimension expression>] _ <element type>
3182 // <extended element type> ::= <element type>
3183 // ::= p # AltiVec vector pixel
3184 // ::= b # Altivec vector bool
3185 void CXXNameMangler::mangleType(const VectorType *T) {
3186 if ((T->getVectorKind() == VectorType::NeonVector ||
3187 T->getVectorKind() == VectorType::NeonPolyVector)) {
3188 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3189 llvm::Triple::ArchType Arch =
3190 getASTContext().getTargetInfo().getTriple().getArch();
3191 if ((Arch == llvm::Triple::aarch64 ||
3192 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3193 mangleAArch64NeonVectorType(T);
3195 mangleNeonVectorType(T);
3198 Out << "Dv" << T->getNumElements() << '_';
3199 if (T->getVectorKind() == VectorType::AltiVecPixel)
3201 else if (T->getVectorKind() == VectorType::AltiVecBool)
3204 mangleType(T->getElementType());
3207 void CXXNameMangler::mangleType(const DependentVectorType *T) {
3208 if ((T->getVectorKind() == VectorType::NeonVector ||
3209 T->getVectorKind() == VectorType::NeonPolyVector)) {
3210 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3211 llvm::Triple::ArchType Arch =
3212 getASTContext().getTargetInfo().getTriple().getArch();
3213 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3214 !Target.isOSDarwin())
3215 mangleAArch64NeonVectorType(T);
3217 mangleNeonVectorType(T);
3222 mangleExpression(T->getSizeExpr());
3224 if (T->getVectorKind() == VectorType::AltiVecPixel)
3226 else if (T->getVectorKind() == VectorType::AltiVecBool)
3229 mangleType(T->getElementType());
3232 void CXXNameMangler::mangleType(const ExtVectorType *T) {
3233 mangleType(static_cast<const VectorType*>(T));
3235 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3237 mangleExpression(T->getSizeExpr());
3239 mangleType(T->getElementType());
3242 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3243 SplitQualType split = T->getPointeeType().split();
3244 mangleQualifiers(split.Quals, T);
3245 mangleType(QualType(split.Ty, 0));
3248 void CXXNameMangler::mangleType(const PackExpansionType *T) {
3249 // <type> ::= Dp <type> # pack expansion (C++0x)
3251 mangleType(T->getPattern());
3254 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3255 mangleSourceName(T->getDecl()->getIdentifier());
3258 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3259 // Treat __kindof as a vendor extended type qualifier.
3260 if (T->isKindOfType())
3261 Out << "U8__kindof";
3263 if (!T->qual_empty()) {
3264 // Mangle protocol qualifiers.
3265 SmallString<64> QualStr;
3266 llvm::raw_svector_ostream QualOS(QualStr);
3267 QualOS << "objcproto";
3268 for (const auto *I : T->quals()) {
3269 StringRef name = I->getName();
3270 QualOS << name.size() << name;
3272 Out << 'U' << QualStr.size() << QualStr;
3275 mangleType(T->getBaseType());
3277 if (T->isSpecialized()) {
3278 // Mangle type arguments as I <type>+ E
3280 for (auto typeArg : T->getTypeArgs())
3281 mangleType(typeArg);
3286 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3287 Out << "U13block_pointer";
3288 mangleType(T->getPointeeType());
3291 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3292 // Mangle injected class name types as if the user had written the
3293 // specialization out fully. It may not actually be possible to see
3294 // this mangling, though.
3295 mangleType(T->getInjectedSpecializationType());
3298 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3299 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3300 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3302 if (mangleSubstitution(QualType(T, 0)))
3305 mangleTemplatePrefix(T->getTemplateName());
3307 // FIXME: GCC does not appear to mangle the template arguments when
3308 // the template in question is a dependent template name. Should we
3309 // emulate that badness?
3310 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3311 addSubstitution(QualType(T, 0));
3315 void CXXNameMangler::mangleType(const DependentNameType *T) {
3316 // Proposal by cxx-abi-dev, 2014-03-26
3317 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3318 // # dependent elaborated type specifier using
3320 // ::= Ts <name> # dependent elaborated type specifier using
3321 // # 'struct' or 'class'
3322 // ::= Tu <name> # dependent elaborated type specifier using
3324 // ::= Te <name> # dependent elaborated type specifier using
3326 switch (T->getKeyword()) {
3342 // Typename types are always nested
3344 manglePrefix(T->getQualifier());
3345 mangleSourceName(T->getIdentifier());
3349 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3350 // Dependently-scoped template types are nested if they have a prefix.
3353 // TODO: avoid making this TemplateName.
3354 TemplateName Prefix =
3355 getASTContext().getDependentTemplateName(T->getQualifier(),
3356 T->getIdentifier());
3357 mangleTemplatePrefix(Prefix);
3359 // FIXME: GCC does not appear to mangle the template arguments when
3360 // the template in question is a dependent template name. Should we
3361 // emulate that badness?
3362 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3366 void CXXNameMangler::mangleType(const TypeOfType *T) {
3367 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3368 // "extension with parameters" mangling.
3372 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3373 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3374 // "extension with parameters" mangling.
3378 void CXXNameMangler::mangleType(const DecltypeType *T) {
3379 Expr *E = T->getUnderlyingExpr();
3381 // type ::= Dt <expression> E # decltype of an id-expression
3382 // # or class member access
3383 // ::= DT <expression> E # decltype of an expression
3385 // This purports to be an exhaustive list of id-expressions and
3386 // class member accesses. Note that we do not ignore parentheses;
3387 // parentheses change the semantics of decltype for these
3388 // expressions (and cause the mangler to use the other form).
3389 if (isa<DeclRefExpr>(E) ||
3390 isa<MemberExpr>(E) ||
3391 isa<UnresolvedLookupExpr>(E) ||
3392 isa<DependentScopeDeclRefExpr>(E) ||
3393 isa<CXXDependentScopeMemberExpr>(E) ||
3394 isa<UnresolvedMemberExpr>(E))
3398 mangleExpression(E);
3402 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3403 // If this is dependent, we need to record that. If not, we simply
3404 // mangle it as the underlying type since they are equivalent.
3405 if (T->isDependentType()) {
3408 switch (T->getUTTKind()) {
3409 case UnaryTransformType::EnumUnderlyingType:
3415 mangleType(T->getBaseType());
3418 void CXXNameMangler::mangleType(const AutoType *T) {
3419 assert(T->getDeducedType().isNull() &&
3420 "Deduced AutoType shouldn't be handled here!");
3421 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3422 "shouldn't need to mangle __auto_type!");
3423 // <builtin-type> ::= Da # auto
3424 // ::= Dc # decltype(auto)
3425 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3428 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3429 // FIXME: This is not the right mangling. We also need to include a scope
3430 // here in some cases.
3431 QualType D = T->getDeducedType();
3433 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3438 void CXXNameMangler::mangleType(const AtomicType *T) {
3439 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3440 // (Until there's a standardized mangling...)
3442 mangleType(T->getValueType());
3445 void CXXNameMangler::mangleType(const PipeType *T) {
3446 // Pipe type mangling rules are described in SPIR 2.0 specification
3447 // A.1 Data types and A.3 Summary of changes
3448 // <type> ::= 8ocl_pipe
3452 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3453 const llvm::APSInt &Value) {
3454 // <expr-primary> ::= L <type> <value number> E # integer literal
3458 if (T->isBooleanType()) {
3459 // Boolean values are encoded as 0/1.
3460 Out << (Value.getBoolValue() ? '1' : '0');
3462 mangleNumber(Value);
3468 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3469 // Ignore member expressions involving anonymous unions.
3470 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3471 if (!RT->getDecl()->isAnonymousStructOrUnion())
3473 const auto *ME = dyn_cast<MemberExpr>(Base);
3476 Base = ME->getBase();
3477 IsArrow = ME->isArrow();
3480 if (Base->isImplicitCXXThis()) {
3481 // Note: GCC mangles member expressions to the implicit 'this' as
3482 // *this., whereas we represent them as this->. The Itanium C++ ABI
3483 // does not specify anything here, so we follow GCC.
3486 Out << (IsArrow ? "pt" : "dt");
3487 mangleExpression(Base);
3491 /// Mangles a member expression.
3492 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3494 NestedNameSpecifier *qualifier,
3495 NamedDecl *firstQualifierLookup,
3496 DeclarationName member,
3497 const TemplateArgumentLoc *TemplateArgs,
3498 unsigned NumTemplateArgs,
3500 // <expression> ::= dt <expression> <unresolved-name>
3501 // ::= pt <expression> <unresolved-name>
3503 mangleMemberExprBase(base, isArrow);
3504 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3507 /// Look at the callee of the given call expression and determine if
3508 /// it's a parenthesized id-expression which would have triggered ADL
3510 static bool isParenthesizedADLCallee(const CallExpr *call) {
3511 const Expr *callee = call->getCallee();
3512 const Expr *fn = callee->IgnoreParens();
3514 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3515 // too, but for those to appear in the callee, it would have to be
3517 if (callee == fn) return false;
3519 // Must be an unresolved lookup.
3520 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3521 if (!lookup) return false;
3523 assert(!lookup->requiresADL());
3525 // Must be an unqualified lookup.
3526 if (lookup->getQualifier()) return false;
3528 // Must not have found a class member. Note that if one is a class
3529 // member, they're all class members.
3530 if (lookup->getNumDecls() > 0 &&
3531 (*lookup->decls_begin())->isCXXClassMember())
3534 // Otherwise, ADL would have been triggered.
3538 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3539 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3540 Out << CastEncoding;
3541 mangleType(ECE->getType());
3542 mangleExpression(ECE->getSubExpr());
3545 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3546 if (auto *Syntactic = InitList->getSyntacticForm())
3547 InitList = Syntactic;
3548 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3549 mangleExpression(InitList->getInit(i));
3552 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) {
3553 switch (D->getKind()) {
3555 // <expr-primary> ::= L <mangled-name> E # external name
3562 mangleFunctionParam(cast<ParmVarDecl>(D));
3565 case Decl::EnumConstant: {
3566 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3567 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3571 case Decl::NonTypeTemplateParm:
3572 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3573 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
3578 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3579 // <expression> ::= <unary operator-name> <expression>
3580 // ::= <binary operator-name> <expression> <expression>
3581 // ::= <trinary operator-name> <expression> <expression> <expression>
3582 // ::= cv <type> expression # conversion with one argument
3583 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3584 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3585 // ::= sc <type> <expression> # static_cast<type> (expression)
3586 // ::= cc <type> <expression> # const_cast<type> (expression)
3587 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3588 // ::= st <type> # sizeof (a type)
3589 // ::= at <type> # alignof (a type)
3590 // ::= <template-param>
3591 // ::= <function-param>
3592 // ::= sr <type> <unqualified-name> # dependent name
3593 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3594 // ::= ds <expression> <expression> # expr.*expr
3595 // ::= sZ <template-param> # size of a parameter pack
3596 // ::= sZ <function-param> # size of a function parameter pack
3597 // ::= <expr-primary>
3598 // <expr-primary> ::= L <type> <value number> E # integer literal
3599 // ::= L <type <value float> E # floating literal
3600 // ::= L <mangled-name> E # external name
3601 // ::= fpT # 'this' expression
3602 QualType ImplicitlyConvertedToType;
3605 switch (E->getStmtClass()) {
3606 case Expr::NoStmtClass:
3607 #define ABSTRACT_STMT(Type)
3608 #define EXPR(Type, Base)
3609 #define STMT(Type, Base) \
3610 case Expr::Type##Class:
3611 #include "clang/AST/StmtNodes.inc"
3614 // These all can only appear in local or variable-initialization
3615 // contexts and so should never appear in a mangling.
3616 case Expr::AddrLabelExprClass:
3617 case Expr::DesignatedInitUpdateExprClass:
3618 case Expr::ImplicitValueInitExprClass:
3619 case Expr::ArrayInitLoopExprClass:
3620 case Expr::ArrayInitIndexExprClass:
3621 case Expr::NoInitExprClass:
3622 case Expr::ParenListExprClass:
3623 case Expr::LambdaExprClass:
3624 case Expr::MSPropertyRefExprClass:
3625 case Expr::MSPropertySubscriptExprClass:
3626 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3627 case Expr::OMPArraySectionExprClass:
3628 case Expr::CXXInheritedCtorInitExprClass:
3629 llvm_unreachable("unexpected statement kind");
3631 case Expr::ConstantExprClass:
3632 E = cast<ConstantExpr>(E)->getSubExpr();
3635 // FIXME: invent manglings for all these.
3636 case Expr::BlockExprClass:
3637 case Expr::ChooseExprClass:
3638 case Expr::CompoundLiteralExprClass:
3639 case Expr::ExtVectorElementExprClass:
3640 case Expr::GenericSelectionExprClass:
3641 case Expr::ObjCEncodeExprClass:
3642 case Expr::ObjCIsaExprClass:
3643 case Expr::ObjCIvarRefExprClass:
3644 case Expr::ObjCMessageExprClass:
3645 case Expr::ObjCPropertyRefExprClass:
3646 case Expr::ObjCProtocolExprClass:
3647 case Expr::ObjCSelectorExprClass:
3648 case Expr::ObjCStringLiteralClass:
3649 case Expr::ObjCBoxedExprClass:
3650 case Expr::ObjCArrayLiteralClass:
3651 case Expr::ObjCDictionaryLiteralClass:
3652 case Expr::ObjCSubscriptRefExprClass:
3653 case Expr::ObjCIndirectCopyRestoreExprClass:
3654 case Expr::ObjCAvailabilityCheckExprClass:
3655 case Expr::OffsetOfExprClass:
3656 case Expr::PredefinedExprClass:
3657 case Expr::ShuffleVectorExprClass:
3658 case Expr::ConvertVectorExprClass:
3659 case Expr::StmtExprClass:
3660 case Expr::TypeTraitExprClass:
3661 case Expr::ArrayTypeTraitExprClass:
3662 case Expr::ExpressionTraitExprClass:
3663 case Expr::VAArgExprClass:
3664 case Expr::CUDAKernelCallExprClass:
3665 case Expr::AsTypeExprClass:
3666 case Expr::PseudoObjectExprClass:
3667 case Expr::AtomicExprClass:
3668 case Expr::SourceLocExprClass:
3669 case Expr::FixedPointLiteralClass:
3670 case Expr::BuiltinBitCastExprClass:
3673 // As bad as this diagnostic is, it's better than crashing.
3674 DiagnosticsEngine &Diags = Context.getDiags();
3675 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3676 "cannot yet mangle expression type %0");
3677 Diags.Report(E->getExprLoc(), DiagID)
3678 << E->getStmtClassName() << E->getSourceRange();
3683 case Expr::CXXUuidofExprClass: {
3684 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3685 if (UE->isTypeOperand()) {
3686 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3687 Out << "u8__uuidoft";
3690 Expr *UuidExp = UE->getExprOperand();
3691 Out << "u8__uuidofz";
3692 mangleExpression(UuidExp, Arity);
3697 // Even gcc-4.5 doesn't mangle this.
3698 case Expr::BinaryConditionalOperatorClass: {
3699 DiagnosticsEngine &Diags = Context.getDiags();
3701 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3702 "?: operator with omitted middle operand cannot be mangled");
3703 Diags.Report(E->getExprLoc(), DiagID)
3704 << E->getStmtClassName() << E->getSourceRange();
3708 // These are used for internal purposes and cannot be meaningfully mangled.
3709 case Expr::OpaqueValueExprClass:
3710 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3712 case Expr::InitListExprClass: {
3714 mangleInitListElements(cast<InitListExpr>(E));
3719 case Expr::DesignatedInitExprClass: {
3720 auto *DIE = cast<DesignatedInitExpr>(E);
3721 for (const auto &Designator : DIE->designators()) {
3722 if (Designator.isFieldDesignator()) {
3724 mangleSourceName(Designator.getFieldName());
3725 } else if (Designator.isArrayDesignator()) {
3727 mangleExpression(DIE->getArrayIndex(Designator));
3729 assert(Designator.isArrayRangeDesignator() &&
3730 "unknown designator kind");
3732 mangleExpression(DIE->getArrayRangeStart(Designator));
3733 mangleExpression(DIE->getArrayRangeEnd(Designator));
3736 mangleExpression(DIE->getInit());
3740 case Expr::CXXDefaultArgExprClass:
3741 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3744 case Expr::CXXDefaultInitExprClass:
3745 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3748 case Expr::CXXStdInitializerListExprClass:
3749 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3752 case Expr::SubstNonTypeTemplateParmExprClass:
3753 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3757 case Expr::UserDefinedLiteralClass:
3758 // We follow g++'s approach of mangling a UDL as a call to the literal
3760 case Expr::CXXMemberCallExprClass: // fallthrough
3761 case Expr::CallExprClass: {
3762 const CallExpr *CE = cast<CallExpr>(E);
3764 // <expression> ::= cp <simple-id> <expression>* E
3765 // We use this mangling only when the call would use ADL except
3766 // for being parenthesized. Per discussion with David
3767 // Vandervoorde, 2011.04.25.
3768 if (isParenthesizedADLCallee(CE)) {
3770 // The callee here is a parenthesized UnresolvedLookupExpr with
3771 // no qualifier and should always get mangled as a <simple-id>
3774 // <expression> ::= cl <expression>* E
3779 unsigned CallArity = CE->getNumArgs();
3780 for (const Expr *Arg : CE->arguments())
3781 if (isa<PackExpansionExpr>(Arg))
3782 CallArity = UnknownArity;
3784 mangleExpression(CE->getCallee(), CallArity);
3785 for (const Expr *Arg : CE->arguments())
3786 mangleExpression(Arg);
3791 case Expr::CXXNewExprClass: {
3792 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3793 if (New->isGlobalNew()) Out << "gs";
3794 Out << (New->isArray() ? "na" : "nw");
3795 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3796 E = New->placement_arg_end(); I != E; ++I)
3797 mangleExpression(*I);
3799 mangleType(New->getAllocatedType());
3800 if (New->hasInitializer()) {
3801 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3805 const Expr *Init = New->getInitializer();
3806 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3807 // Directly inline the initializers.
3808 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3811 mangleExpression(*I);
3812 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3813 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3814 mangleExpression(PLE->getExpr(i));
3815 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3816 isa<InitListExpr>(Init)) {
3817 // Only take InitListExprs apart for list-initialization.
3818 mangleInitListElements(cast<InitListExpr>(Init));
3820 mangleExpression(Init);
3826 case Expr::CXXPseudoDestructorExprClass: {
3827 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3828 if (const Expr *Base = PDE->getBase())
3829 mangleMemberExprBase(Base, PDE->isArrow());
3830 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3831 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3833 mangleUnresolvedPrefix(Qualifier,
3834 /*recursive=*/true);
3835 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3839 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3842 } else if (Qualifier) {
3843 mangleUnresolvedPrefix(Qualifier);
3845 // <base-unresolved-name> ::= dn <destructor-name>
3847 QualType DestroyedType = PDE->getDestroyedType();
3848 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3852 case Expr::MemberExprClass: {
3853 const MemberExpr *ME = cast<MemberExpr>(E);
3854 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3855 ME->getQualifier(), nullptr,
3856 ME->getMemberDecl()->getDeclName(),
3857 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3862 case Expr::UnresolvedMemberExprClass: {
3863 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3864 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3865 ME->isArrow(), ME->getQualifier(), nullptr,
3866 ME->getMemberName(),
3867 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3872 case Expr::CXXDependentScopeMemberExprClass: {
3873 const CXXDependentScopeMemberExpr *ME
3874 = cast<CXXDependentScopeMemberExpr>(E);
3875 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3876 ME->isArrow(), ME->getQualifier(),
3877 ME->getFirstQualifierFoundInScope(),
3879 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3884 case Expr::UnresolvedLookupExprClass: {
3885 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3886 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3887 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3892 case Expr::CXXUnresolvedConstructExprClass: {
3893 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3894 unsigned N = CE->arg_size();
3896 if (CE->isListInitialization()) {
3897 assert(N == 1 && "unexpected form for list initialization");
3898 auto *IL = cast<InitListExpr>(CE->getArg(0));
3900 mangleType(CE->getType());
3901 mangleInitListElements(IL);
3907 mangleType(CE->getType());
3908 if (N != 1) Out << '_';
3909 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3910 if (N != 1) Out << 'E';
3914 case Expr::CXXConstructExprClass: {
3915 const auto *CE = cast<CXXConstructExpr>(E);
3916 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3918 CE->getNumArgs() >= 1 &&
3919 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3920 "implicit CXXConstructExpr must have one argument");
3921 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3924 for (auto *E : CE->arguments())
3925 mangleExpression(E);
3930 case Expr::CXXTemporaryObjectExprClass: {
3931 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3932 unsigned N = CE->getNumArgs();
3933 bool List = CE->isListInitialization();
3939 mangleType(CE->getType());
3940 if (!List && N != 1)
3942 if (CE->isStdInitListInitialization()) {
3943 // We implicitly created a std::initializer_list<T> for the first argument
3944 // of a constructor of type U in an expression of the form U{a, b, c}.
3945 // Strip all the semantic gunk off the initializer list.
3947 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3948 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3949 mangleInitListElements(ILE);
3951 for (auto *E : CE->arguments())
3952 mangleExpression(E);
3959 case Expr::CXXScalarValueInitExprClass:
3961 mangleType(E->getType());
3965 case Expr::CXXNoexceptExprClass:
3967 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3970 case Expr::UnaryExprOrTypeTraitExprClass: {
3971 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3973 if (!SAE->isInstantiationDependent()) {
3975 // If the operand of a sizeof or alignof operator is not
3976 // instantiation-dependent it is encoded as an integer literal
3977 // reflecting the result of the operator.
3979 // If the result of the operator is implicitly converted to a known
3980 // integer type, that type is used for the literal; otherwise, the type
3981 // of std::size_t or std::ptrdiff_t is used.
3982 QualType T = (ImplicitlyConvertedToType.isNull() ||
3983 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3984 : ImplicitlyConvertedToType;
3985 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3986 mangleIntegerLiteral(T, V);
3990 switch(SAE->getKind()) {
3994 case UETT_PreferredAlignOf:
3998 case UETT_VecStep: {
3999 DiagnosticsEngine &Diags = Context.getDiags();
4000 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4001 "cannot yet mangle vec_step expression");
4002 Diags.Report(DiagID);
4005 case UETT_OpenMPRequiredSimdAlign: {
4006 DiagnosticsEngine &Diags = Context.getDiags();
4007 unsigned DiagID = Diags.getCustomDiagID(
4008 DiagnosticsEngine::Error,
4009 "cannot yet mangle __builtin_omp_required_simd_align expression");
4010 Diags.Report(DiagID);
4014 if (SAE->isArgumentType()) {
4016 mangleType(SAE->getArgumentType());
4019 mangleExpression(SAE->getArgumentExpr());
4024 case Expr::CXXThrowExprClass: {
4025 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4026 // <expression> ::= tw <expression> # throw expression
4028 if (TE->getSubExpr()) {
4030 mangleExpression(TE->getSubExpr());
4037 case Expr::CXXTypeidExprClass: {
4038 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4039 // <expression> ::= ti <type> # typeid (type)
4040 // ::= te <expression> # typeid (expression)
4041 if (TIE->isTypeOperand()) {
4043 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4046 mangleExpression(TIE->getExprOperand());
4051 case Expr::CXXDeleteExprClass: {
4052 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4053 // <expression> ::= [gs] dl <expression> # [::] delete expr
4054 // ::= [gs] da <expression> # [::] delete [] expr
4055 if (DE->isGlobalDelete()) Out << "gs";
4056 Out << (DE->isArrayForm() ? "da" : "dl");
4057 mangleExpression(DE->getArgument());
4061 case Expr::UnaryOperatorClass: {
4062 const UnaryOperator *UO = cast<UnaryOperator>(E);
4063 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4065 mangleExpression(UO->getSubExpr());
4069 case Expr::ArraySubscriptExprClass: {
4070 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4072 // Array subscript is treated as a syntactically weird form of
4075 mangleExpression(AE->getLHS());
4076 mangleExpression(AE->getRHS());
4080 case Expr::CompoundAssignOperatorClass: // fallthrough
4081 case Expr::BinaryOperatorClass: {
4082 const BinaryOperator *BO = cast<BinaryOperator>(E);
4083 if (BO->getOpcode() == BO_PtrMemD)
4086 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4088 mangleExpression(BO->getLHS());
4089 mangleExpression(BO->getRHS());
4093 case Expr::CXXRewrittenBinaryOperatorClass: {
4094 // The mangled form represents the original syntax.
4095 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
4096 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4097 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4099 mangleExpression(Decomposed.LHS);
4100 mangleExpression(Decomposed.RHS);
4104 case Expr::ConditionalOperatorClass: {
4105 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4106 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4107 mangleExpression(CO->getCond());
4108 mangleExpression(CO->getLHS(), Arity);
4109 mangleExpression(CO->getRHS(), Arity);
4113 case Expr::ImplicitCastExprClass: {
4114 ImplicitlyConvertedToType = E->getType();
4115 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4119 case Expr::ObjCBridgedCastExprClass: {
4120 // Mangle ownership casts as a vendor extended operator __bridge,
4121 // __bridge_transfer, or __bridge_retain.
4122 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4123 Out << "v1U" << Kind.size() << Kind;
4125 // Fall through to mangle the cast itself.
4128 case Expr::CStyleCastExprClass:
4129 mangleCastExpression(E, "cv");
4132 case Expr::CXXFunctionalCastExprClass: {
4133 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4134 // FIXME: Add isImplicit to CXXConstructExpr.
4135 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4136 if (CCE->getParenOrBraceRange().isInvalid())
4137 Sub = CCE->getArg(0)->IgnoreImplicit();
4138 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4139 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4140 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4142 mangleType(E->getType());
4143 mangleInitListElements(IL);
4146 mangleCastExpression(E, "cv");
4151 case Expr::CXXStaticCastExprClass:
4152 mangleCastExpression(E, "sc");
4154 case Expr::CXXDynamicCastExprClass:
4155 mangleCastExpression(E, "dc");
4157 case Expr::CXXReinterpretCastExprClass:
4158 mangleCastExpression(E, "rc");
4160 case Expr::CXXConstCastExprClass:
4161 mangleCastExpression(E, "cc");
4164 case Expr::CXXOperatorCallExprClass: {
4165 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4166 unsigned NumArgs = CE->getNumArgs();
4167 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4168 // (the enclosing MemberExpr covers the syntactic portion).
4169 if (CE->getOperator() != OO_Arrow)
4170 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4171 // Mangle the arguments.
4172 for (unsigned i = 0; i != NumArgs; ++i)
4173 mangleExpression(CE->getArg(i));
4177 case Expr::ParenExprClass:
4178 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4182 case Expr::ConceptSpecializationExprClass: {
4183 // <expr-primary> ::= L <mangled-name> E # external name
4185 auto *CSE = cast<ConceptSpecializationExpr>(E);
4186 mangleTemplateName(CSE->getNamedConcept(),
4187 CSE->getTemplateArguments().data(),
4188 CSE->getTemplateArguments().size());
4193 case Expr::DeclRefExprClass:
4194 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4197 case Expr::SubstNonTypeTemplateParmPackExprClass:
4198 // FIXME: not clear how to mangle this!
4199 // template <unsigned N...> class A {
4200 // template <class U...> void foo(U (&x)[N]...);
4202 Out << "_SUBSTPACK_";
4205 case Expr::FunctionParmPackExprClass: {
4206 // FIXME: not clear how to mangle this!
4207 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4208 Out << "v110_SUBSTPACK";
4209 mangleDeclRefExpr(FPPE->getParameterPack());
4213 case Expr::DependentScopeDeclRefExprClass: {
4214 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4215 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4216 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4221 case Expr::CXXBindTemporaryExprClass:
4222 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4225 case Expr::ExprWithCleanupsClass:
4226 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4229 case Expr::FloatingLiteralClass: {
4230 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4232 mangleType(FL->getType());
4233 mangleFloat(FL->getValue());
4238 case Expr::CharacterLiteralClass:
4240 mangleType(E->getType());
4241 Out << cast<CharacterLiteral>(E)->getValue();
4245 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4246 case Expr::ObjCBoolLiteralExprClass:
4248 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4252 case Expr::CXXBoolLiteralExprClass:
4254 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4258 case Expr::IntegerLiteralClass: {
4259 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4260 if (E->getType()->isSignedIntegerType())
4261 Value.setIsSigned(true);
4262 mangleIntegerLiteral(E->getType(), Value);
4266 case Expr::ImaginaryLiteralClass: {
4267 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4268 // Mangle as if a complex literal.
4269 // Proposal from David Vandevoorde, 2010.06.30.
4271 mangleType(E->getType());
4272 if (const FloatingLiteral *Imag =
4273 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4274 // Mangle a floating-point zero of the appropriate type.
4275 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4277 mangleFloat(Imag->getValue());
4280 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4281 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4282 Value.setIsSigned(true);
4283 mangleNumber(Value);
4289 case Expr::StringLiteralClass: {
4290 // Revised proposal from David Vandervoorde, 2010.07.15.
4292 assert(isa<ConstantArrayType>(E->getType()));
4293 mangleType(E->getType());
4298 case Expr::GNUNullExprClass:
4299 // Mangle as if an integer literal 0.
4301 mangleType(E->getType());
4305 case Expr::CXXNullPtrLiteralExprClass: {
4310 case Expr::PackExpansionExprClass:
4312 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4315 case Expr::SizeOfPackExprClass: {
4316 auto *SPE = cast<SizeOfPackExpr>(E);
4317 if (SPE->isPartiallySubstituted()) {
4319 for (const auto &A : SPE->getPartialArguments())
4320 mangleTemplateArg(A);
4326 const NamedDecl *Pack = SPE->getPack();
4327 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4328 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
4329 else if (const NonTypeTemplateParmDecl *NTTP
4330 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4331 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
4332 else if (const TemplateTemplateParmDecl *TempTP
4333 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4334 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
4336 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4340 case Expr::MaterializeTemporaryExprClass: {
4341 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4345 case Expr::CXXFoldExprClass: {
4346 auto *FE = cast<CXXFoldExpr>(E);
4347 if (FE->isLeftFold())
4348 Out << (FE->getInit() ? "fL" : "fl");
4350 Out << (FE->getInit() ? "fR" : "fr");
4352 if (FE->getOperator() == BO_PtrMemD)
4356 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4360 mangleExpression(FE->getLHS());
4362 mangleExpression(FE->getRHS());
4366 case Expr::CXXThisExprClass:
4370 case Expr::CoawaitExprClass:
4371 // FIXME: Propose a non-vendor mangling.
4372 Out << "v18co_await";
4373 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4376 case Expr::DependentCoawaitExprClass:
4377 // FIXME: Propose a non-vendor mangling.
4378 Out << "v18co_await";
4379 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4382 case Expr::CoyieldExprClass:
4383 // FIXME: Propose a non-vendor mangling.
4384 Out << "v18co_yield";
4385 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4390 /// Mangle an expression which refers to a parameter variable.
4392 /// <expression> ::= <function-param>
4393 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4394 /// <function-param> ::= fp <top-level CV-qualifiers>
4395 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4396 /// <function-param> ::= fL <L-1 non-negative number>
4397 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4398 /// <function-param> ::= fL <L-1 non-negative number>
4399 /// p <top-level CV-qualifiers>
4400 /// <I-1 non-negative number> _ # L > 0, I > 0
4402 /// L is the nesting depth of the parameter, defined as 1 if the
4403 /// parameter comes from the innermost function prototype scope
4404 /// enclosing the current context, 2 if from the next enclosing
4405 /// function prototype scope, and so on, with one special case: if
4406 /// we've processed the full parameter clause for the innermost
4407 /// function type, then L is one less. This definition conveniently
4408 /// makes it irrelevant whether a function's result type was written
4409 /// trailing or leading, but is otherwise overly complicated; the
4410 /// numbering was first designed without considering references to
4411 /// parameter in locations other than return types, and then the
4412 /// mangling had to be generalized without changing the existing
4415 /// I is the zero-based index of the parameter within its parameter
4416 /// declaration clause. Note that the original ABI document describes
4417 /// this using 1-based ordinals.
4418 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4419 unsigned parmDepth = parm->getFunctionScopeDepth();
4420 unsigned parmIndex = parm->getFunctionScopeIndex();
4423 // parmDepth does not include the declaring function prototype.
4424 // FunctionTypeDepth does account for that.
4425 assert(parmDepth < FunctionTypeDepth.getDepth());
4426 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4427 if (FunctionTypeDepth.isInResultType())
4430 if (nestingDepth == 0) {
4433 Out << "fL" << (nestingDepth - 1) << 'p';
4436 // Top-level qualifiers. We don't have to worry about arrays here,
4437 // because parameters declared as arrays should already have been
4438 // transformed to have pointer type. FIXME: apparently these don't
4439 // get mangled if used as an rvalue of a known non-class type?
4440 assert(!parm->getType()->isArrayType()
4441 && "parameter's type is still an array type?");
4443 if (const DependentAddressSpaceType *DAST =
4444 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4445 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4447 mangleQualifiers(parm->getType().getQualifiers());
4451 if (parmIndex != 0) {
4452 Out << (parmIndex - 1);
4457 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4458 const CXXRecordDecl *InheritedFrom) {
4459 // <ctor-dtor-name> ::= C1 # complete object constructor
4460 // ::= C2 # base object constructor
4461 // ::= CI1 <type> # complete inheriting constructor
4462 // ::= CI2 <type> # base inheriting constructor
4464 // In addition, C5 is a comdat name with C1 and C2 in it.
4478 case Ctor_DefaultClosure:
4479 case Ctor_CopyingClosure:
4480 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4483 mangleName(InheritedFrom);
4486 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4487 // <ctor-dtor-name> ::= D0 # deleting destructor
4488 // ::= D1 # complete object destructor
4489 // ::= D2 # base object destructor
4491 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4508 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4509 unsigned NumTemplateArgs) {
4510 // <template-args> ::= I <template-arg>+ E
4512 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4513 mangleTemplateArg(TemplateArgs[i].getArgument());
4517 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4518 // <template-args> ::= I <template-arg>+ E
4520 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4521 mangleTemplateArg(AL[i]);
4525 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4526 unsigned NumTemplateArgs) {
4527 // <template-args> ::= I <template-arg>+ E
4529 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4530 mangleTemplateArg(TemplateArgs[i]);
4534 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4535 // <template-arg> ::= <type> # type or template
4536 // ::= X <expression> E # expression
4537 // ::= <expr-primary> # simple expressions
4538 // ::= J <template-arg>* E # argument pack
4539 if (!A.isInstantiationDependent() || A.isDependent())
4540 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4542 switch (A.getKind()) {
4543 case TemplateArgument::Null:
4544 llvm_unreachable("Cannot mangle NULL template argument");
4546 case TemplateArgument::Type:
4547 mangleType(A.getAsType());
4549 case TemplateArgument::Template:
4550 // This is mangled as <type>.
4551 mangleType(A.getAsTemplate());
4553 case TemplateArgument::TemplateExpansion:
4554 // <type> ::= Dp <type> # pack expansion (C++0x)
4556 mangleType(A.getAsTemplateOrTemplatePattern());
4558 case TemplateArgument::Expression: {
4559 // It's possible to end up with a DeclRefExpr here in certain
4560 // dependent cases, in which case we should mangle as a
4562 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts();
4563 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4564 const ValueDecl *D = DRE->getDecl();
4565 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4574 mangleExpression(E);
4578 case TemplateArgument::Integral:
4579 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4581 case TemplateArgument::Declaration: {
4582 // <expr-primary> ::= L <mangled-name> E # external name
4583 // Clang produces AST's where pointer-to-member-function expressions
4584 // and pointer-to-function expressions are represented as a declaration not
4585 // an expression. We compensate for it here to produce the correct mangling.
4586 ValueDecl *D = A.getAsDecl();
4587 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4588 if (compensateMangling) {
4590 mangleOperatorName(OO_Amp, 1);
4594 // References to external entities use the mangled name; if the name would
4595 // not normally be mangled then mangle it as unqualified.
4599 if (compensateMangling)
4604 case TemplateArgument::NullPtr: {
4605 // <expr-primary> ::= L <type> 0 E
4607 mangleType(A.getNullPtrType());
4611 case TemplateArgument::Pack: {
4612 // <template-arg> ::= J <template-arg>* E
4614 for (const auto &P : A.pack_elements())
4615 mangleTemplateArg(P);
4621 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
4622 // <template-param> ::= T_ # first template parameter
4623 // ::= T <parameter-2 non-negative number> _
4624 // ::= TL <L-1 non-negative number> __
4625 // ::= TL <L-1 non-negative number> _
4626 // <parameter-2 non-negative number> _
4628 // The latter two manglings are from a proposal here:
4629 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
4632 Out << 'L' << (Depth - 1) << '_';
4638 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4641 else if (SeqID > 1) {
4644 // <seq-id> is encoded in base-36, using digits and upper case letters.
4645 char Buffer[7]; // log(2**32) / log(36) ~= 7
4646 MutableArrayRef<char> BufferRef(Buffer);
4647 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4649 for (; SeqID != 0; SeqID /= 36) {
4650 unsigned C = SeqID % 36;
4651 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4654 Out.write(I.base(), I - BufferRef.rbegin());
4659 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4660 bool result = mangleSubstitution(tname);
4661 assert(result && "no existing substitution for template name");
4665 // <substitution> ::= S <seq-id> _
4667 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4668 // Try one of the standard substitutions first.
4669 if (mangleStandardSubstitution(ND))
4672 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4673 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4676 /// Determine whether the given type has any qualifiers that are relevant for
4678 static bool hasMangledSubstitutionQualifiers(QualType T) {
4679 Qualifiers Qs = T.getQualifiers();
4680 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
4683 bool CXXNameMangler::mangleSubstitution(QualType T) {
4684 if (!hasMangledSubstitutionQualifiers(T)) {
4685 if (const RecordType *RT = T->getAs<RecordType>())
4686 return mangleSubstitution(RT->getDecl());
4689 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4691 return mangleSubstitution(TypePtr);
4694 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4695 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4696 return mangleSubstitution(TD);
4698 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4699 return mangleSubstitution(
4700 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4703 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4704 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4705 if (I == Substitutions.end())
4708 unsigned SeqID = I->second;
4715 static bool isCharType(QualType T) {
4719 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4720 T->isSpecificBuiltinType(BuiltinType::Char_U);
4723 /// Returns whether a given type is a template specialization of a given name
4724 /// with a single argument of type char.
4725 static bool isCharSpecialization(QualType T, const char *Name) {
4729 const RecordType *RT = T->getAs<RecordType>();
4733 const ClassTemplateSpecializationDecl *SD =
4734 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4738 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4741 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4742 if (TemplateArgs.size() != 1)
4745 if (!isCharType(TemplateArgs[0].getAsType()))
4748 return SD->getIdentifier()->getName() == Name;
4751 template <std::size_t StrLen>
4752 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4753 const char (&Str)[StrLen]) {
4754 if (!SD->getIdentifier()->isStr(Str))
4757 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4758 if (TemplateArgs.size() != 2)
4761 if (!isCharType(TemplateArgs[0].getAsType()))
4764 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4770 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4771 // <substitution> ::= St # ::std::
4772 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4779 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4780 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4783 // <substitution> ::= Sa # ::std::allocator
4784 if (TD->getIdentifier()->isStr("allocator")) {
4789 // <<substitution> ::= Sb # ::std::basic_string
4790 if (TD->getIdentifier()->isStr("basic_string")) {
4796 if (const ClassTemplateSpecializationDecl *SD =
4797 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4798 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4801 // <substitution> ::= Ss # ::std::basic_string<char,
4802 // ::std::char_traits<char>,
4803 // ::std::allocator<char> >
4804 if (SD->getIdentifier()->isStr("basic_string")) {
4805 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4807 if (TemplateArgs.size() != 3)
4810 if (!isCharType(TemplateArgs[0].getAsType()))
4813 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4816 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4823 // <substitution> ::= Si # ::std::basic_istream<char,
4824 // ::std::char_traits<char> >
4825 if (isStreamCharSpecialization(SD, "basic_istream")) {
4830 // <substitution> ::= So # ::std::basic_ostream<char,
4831 // ::std::char_traits<char> >
4832 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4837 // <substitution> ::= Sd # ::std::basic_iostream<char,
4838 // ::std::char_traits<char> >
4839 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4847 void CXXNameMangler::addSubstitution(QualType T) {
4848 if (!hasMangledSubstitutionQualifiers(T)) {
4849 if (const RecordType *RT = T->getAs<RecordType>()) {
4850 addSubstitution(RT->getDecl());
4855 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4856 addSubstitution(TypePtr);
4859 void CXXNameMangler::addSubstitution(TemplateName Template) {
4860 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4861 return addSubstitution(TD);
4863 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4864 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4867 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4868 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4869 Substitutions[Ptr] = SeqID++;
4872 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4873 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4874 if (Other->SeqID > SeqID) {
4875 Substitutions.swap(Other->Substitutions);
4876 SeqID = Other->SeqID;
4880 CXXNameMangler::AbiTagList
4881 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4882 // When derived abi tags are disabled there is no need to make any list.
4883 if (DisableDerivedAbiTags)
4884 return AbiTagList();
4886 llvm::raw_null_ostream NullOutStream;
4887 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4888 TrackReturnTypeTags.disableDerivedAbiTags();
4890 const FunctionProtoType *Proto =
4891 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4892 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
4893 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4894 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4895 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4896 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
4898 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4901 CXXNameMangler::AbiTagList
4902 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4903 // When derived abi tags are disabled there is no need to make any list.
4904 if (DisableDerivedAbiTags)
4905 return AbiTagList();
4907 llvm::raw_null_ostream NullOutStream;
4908 CXXNameMangler TrackVariableType(*this, NullOutStream);
4909 TrackVariableType.disableDerivedAbiTags();
4911 TrackVariableType.mangleType(VD->getType());
4913 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4916 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4917 const VarDecl *VD) {
4918 llvm::raw_null_ostream NullOutStream;
4919 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4920 TrackAbiTags.mangle(VD);
4921 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4926 /// Mangles the name of the declaration D and emits that name to the given
4929 /// If the declaration D requires a mangled name, this routine will emit that
4930 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4931 /// and this routine will return false. In this case, the caller should just
4932 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4934 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4936 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4937 "Invalid mangleName() call, argument is not a variable or function!");
4938 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4939 "Invalid mangleName() call on 'structor decl!");
4941 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4942 getASTContext().getSourceManager(),
4943 "Mangling declaration");
4945 CXXNameMangler Mangler(*this, Out, D);
4949 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4952 CXXNameMangler Mangler(*this, Out, D, Type);
4956 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4959 CXXNameMangler Mangler(*this, Out, D, Type);
4963 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4965 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4969 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4971 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4975 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4976 const ThunkInfo &Thunk,
4978 // <special-name> ::= T <call-offset> <base encoding>
4979 // # base is the nominal target function of thunk
4980 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4981 // # base is the nominal target function of thunk
4982 // # first call-offset is 'this' adjustment
4983 // # second call-offset is result adjustment
4985 assert(!isa<CXXDestructorDecl>(MD) &&
4986 "Use mangleCXXDtor for destructor decls!");
4987 CXXNameMangler Mangler(*this, Out);
4988 Mangler.getStream() << "_ZT";
4989 if (!Thunk.Return.isEmpty())
4990 Mangler.getStream() << 'c';
4992 // Mangle the 'this' pointer adjustment.
4993 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4994 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4996 // Mangle the return pointer adjustment if there is one.
4997 if (!Thunk.Return.isEmpty())
4998 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4999 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
5001 Mangler.mangleFunctionEncoding(MD);
5004 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
5005 const CXXDestructorDecl *DD, CXXDtorType Type,
5006 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
5007 // <special-name> ::= T <call-offset> <base encoding>
5008 // # base is the nominal target function of thunk
5009 CXXNameMangler Mangler(*this, Out, DD, Type);
5010 Mangler.getStream() << "_ZT";
5012 // Mangle the 'this' pointer adjustment.
5013 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
5014 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
5016 Mangler.mangleFunctionEncoding(DD);
5019 /// Returns the mangled name for a guard variable for the passed in VarDecl.
5020 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
5022 // <special-name> ::= GV <object name> # Guard variable for one-time
5024 CXXNameMangler Mangler(*this, Out);
5025 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
5026 // be a bug that is fixed in trunk.
5027 Mangler.getStream() << "_ZGV";
5028 Mangler.mangleName(D);
5031 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
5033 // These symbols are internal in the Itanium ABI, so the names don't matter.
5034 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
5035 // avoid duplicate symbols.
5036 Out << "__cxx_global_var_init";
5039 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
5041 // Prefix the mangling of D with __dtor_.
5042 CXXNameMangler Mangler(*this, Out);
5043 Mangler.getStream() << "__dtor_";
5044 if (shouldMangleDeclName(D))
5047 Mangler.getStream() << D->getName();
5050 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
5051 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5052 CXXNameMangler Mangler(*this, Out);
5053 Mangler.getStream() << "__filt_";
5054 if (shouldMangleDeclName(EnclosingDecl))
5055 Mangler.mangle(EnclosingDecl);
5057 Mangler.getStream() << EnclosingDecl->getName();
5060 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
5061 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5062 CXXNameMangler Mangler(*this, Out);
5063 Mangler.getStream() << "__fin_";
5064 if (shouldMangleDeclName(EnclosingDecl))
5065 Mangler.mangle(EnclosingDecl);
5067 Mangler.getStream() << EnclosingDecl->getName();
5070 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
5072 // <special-name> ::= TH <object name>
5073 CXXNameMangler Mangler(*this, Out);
5074 Mangler.getStream() << "_ZTH";
5075 Mangler.mangleName(D);
5079 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
5081 // <special-name> ::= TW <object name>
5082 CXXNameMangler Mangler(*this, Out);
5083 Mangler.getStream() << "_ZTW";
5084 Mangler.mangleName(D);
5087 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
5088 unsigned ManglingNumber,
5090 // We match the GCC mangling here.
5091 // <special-name> ::= GR <object name>
5092 CXXNameMangler Mangler(*this, Out);
5093 Mangler.getStream() << "_ZGR";
5094 Mangler.mangleName(D);
5095 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
5096 Mangler.mangleSeqID(ManglingNumber - 1);
5099 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5101 // <special-name> ::= TV <type> # virtual table
5102 CXXNameMangler Mangler(*this, Out);
5103 Mangler.getStream() << "_ZTV";
5104 Mangler.mangleNameOrStandardSubstitution(RD);
5107 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5109 // <special-name> ::= TT <type> # VTT structure
5110 CXXNameMangler Mangler(*this, Out);
5111 Mangler.getStream() << "_ZTT";
5112 Mangler.mangleNameOrStandardSubstitution(RD);
5115 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5117 const CXXRecordDecl *Type,
5119 // <special-name> ::= TC <type> <offset number> _ <base type>
5120 CXXNameMangler Mangler(*this, Out);
5121 Mangler.getStream() << "_ZTC";
5122 Mangler.mangleNameOrStandardSubstitution(RD);
5123 Mangler.getStream() << Offset;
5124 Mangler.getStream() << '_';
5125 Mangler.mangleNameOrStandardSubstitution(Type);
5128 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
5129 // <special-name> ::= TI <type> # typeinfo structure
5130 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5131 CXXNameMangler Mangler(*this, Out);
5132 Mangler.getStream() << "_ZTI";
5133 Mangler.mangleType(Ty);
5136 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5138 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5139 CXXNameMangler Mangler(*this, Out);
5140 Mangler.getStream() << "_ZTS";
5141 Mangler.mangleType(Ty);
5144 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5145 mangleCXXRTTIName(Ty, Out);
5148 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5149 llvm_unreachable("Can't mangle string literals");
5152 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
5154 CXXNameMangler Mangler(*this, Out);
5155 Mangler.mangleLambdaSig(Lambda);
5158 ItaniumMangleContext *
5159 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5160 return new ItaniumMangleContextImpl(Context, Diags);