1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
14 // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
36 #define MANGLE_CHECKER 0
42 using namespace clang;
46 /// Retrieve the declaration context that should be used when mangling the given
48 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49 // The ABI assumes that lambda closure types that occur within
50 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
52 // not the case: the lambda closure type ends up living in the context
53 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
69 const DeclContext *DC = D->getDeclContext();
70 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
74 if (const auto *VD = dyn_cast<VarDecl>(D))
76 return VD->getASTContext().getTranslationUnitDecl();
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
80 return FD->getASTContext().getTranslationUnitDecl();
82 return DC->getRedeclContext();
85 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
89 static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
93 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
94 const DeclContext *DC = getEffectiveDeclContext(D);
95 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
96 if (isLocalContainerContext(DC))
97 return dyn_cast<RecordDecl>(D);
99 DC = getEffectiveDeclContext(D);
104 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
111 static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
116 static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
121 return Record->isLambda();
124 static const unsigned UnknownArity = ~0U;
126 class ItaniumMangleContextImpl : public ItaniumMangleContext {
127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
136 /// @name Mangler Entry Points
139 bool shouldMangleCXXName(const NamedDecl *D) override;
140 bool shouldMangleStringLiteral(const StringLiteral *) override {
143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
148 raw_ostream &) override;
149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
159 raw_ostream &) override;
160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
161 raw_ostream &) override;
163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180 // Lambda closure types are already numbered.
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
195 disc = discriminator - 2;
199 // Make up a reasonable number for internal decls.
200 unsigned &discriminator = Uniquifier[ND];
201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
205 if (discriminator == 1)
207 disc = discriminator-2;
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215 ItaniumMangleContextImpl &Context;
217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType;
230 /// The next substitution sequence number.
233 class FunctionTypeDepthState {
236 enum { InResultTypeMask = 1 };
239 FunctionTypeDepthState() : Bits(0) {}
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
257 void enterResultType() {
258 Bits |= InResultTypeMask;
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
281 class AbiTagState final {
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
292 ~AbiTagState() { pop(); }
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
299 !AdditionalAbiTags &&
300 "only function and variables need a list of additional abi tags");
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
306 // Don't emit abi tags for namespaces.
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
326 std::sort(TagList.begin(), TagList.end());
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
329 writeSortedUniqueAbiTags(Out, TagList);
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
385 ASTContext &getASTContext() const { return Context.getASTContext(); }
388 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
389 const NamedDecl *D = nullptr, bool NullOut_ = false)
390 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
391 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
392 // These can't be mangled without a ctor type or dtor type.
393 assert(!D || (!isa<CXXDestructorDecl>(D) &&
394 !isa<CXXConstructorDecl>(D)));
396 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
397 const CXXConstructorDecl *D, CXXCtorType Type)
398 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
399 SeqID(0), AbiTagsRoot(AbiTags) { }
400 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
401 const CXXDestructorDecl *D, CXXDtorType Type)
402 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
403 SeqID(0), AbiTagsRoot(AbiTags) { }
405 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
406 : Context(Outer.Context), Out(Out_), NullOut(false),
407 Structor(Outer.Structor), StructorType(Outer.StructorType),
408 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
409 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
411 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
412 : Context(Outer.Context), Out(Out_), NullOut(true),
413 Structor(Outer.Structor), StructorType(Outer.StructorType),
414 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
415 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
419 if (Out.str()[0] == '\01')
423 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
424 assert(status == 0 && "Could not demangle mangled name!");
428 raw_ostream &getStream() { return Out; }
430 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
431 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
433 void mangle(const NamedDecl *D);
434 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
435 void mangleNumber(const llvm::APSInt &I);
436 void mangleNumber(int64_t Number);
437 void mangleFloat(const llvm::APFloat &F);
438 void mangleFunctionEncoding(const FunctionDecl *FD);
439 void mangleSeqID(unsigned SeqID);
440 void mangleName(const NamedDecl *ND);
441 void mangleType(QualType T);
442 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
446 bool mangleSubstitution(const NamedDecl *ND);
447 bool mangleSubstitution(QualType T);
448 bool mangleSubstitution(TemplateName Template);
449 bool mangleSubstitution(uintptr_t Ptr);
451 void mangleExistingSubstitution(TemplateName name);
453 bool mangleStandardSubstitution(const NamedDecl *ND);
455 void addSubstitution(const NamedDecl *ND) {
456 ND = cast<NamedDecl>(ND->getCanonicalDecl());
458 addSubstitution(reinterpret_cast<uintptr_t>(ND));
460 void addSubstitution(QualType T);
461 void addSubstitution(TemplateName Template);
462 void addSubstitution(uintptr_t Ptr);
463 // Destructive copy substitutions from other mangler.
464 void extendSubstitutions(CXXNameMangler* Other);
466 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
467 bool recursive = false);
468 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
469 DeclarationName name,
470 const TemplateArgumentLoc *TemplateArgs,
471 unsigned NumTemplateArgs,
472 unsigned KnownArity = UnknownArity);
474 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
476 void mangleNameWithAbiTags(const NamedDecl *ND,
477 const AbiTagList *AdditionalAbiTags);
478 void mangleTemplateName(const TemplateDecl *TD,
479 const TemplateArgument *TemplateArgs,
480 unsigned NumTemplateArgs);
481 void mangleUnqualifiedName(const NamedDecl *ND,
482 const AbiTagList *AdditionalAbiTags) {
483 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
486 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
488 const AbiTagList *AdditionalAbiTags);
489 void mangleUnscopedName(const NamedDecl *ND,
490 const AbiTagList *AdditionalAbiTags);
491 void mangleUnscopedTemplateName(const TemplateDecl *ND,
492 const AbiTagList *AdditionalAbiTags);
493 void mangleUnscopedTemplateName(TemplateName,
494 const AbiTagList *AdditionalAbiTags);
495 void mangleSourceName(const IdentifierInfo *II);
496 void mangleRegCallName(const IdentifierInfo *II);
497 void mangleSourceNameWithAbiTags(
498 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
499 void mangleLocalName(const Decl *D,
500 const AbiTagList *AdditionalAbiTags);
501 void mangleBlockForPrefix(const BlockDecl *Block);
502 void mangleUnqualifiedBlock(const BlockDecl *Block);
503 void mangleLambda(const CXXRecordDecl *Lambda);
504 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
505 const AbiTagList *AdditionalAbiTags,
506 bool NoFunction=false);
507 void mangleNestedName(const TemplateDecl *TD,
508 const TemplateArgument *TemplateArgs,
509 unsigned NumTemplateArgs);
510 void manglePrefix(NestedNameSpecifier *qualifier);
511 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
512 void manglePrefix(QualType type);
513 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
514 void mangleTemplatePrefix(TemplateName Template);
515 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
516 StringRef Prefix = "");
517 void mangleOperatorName(DeclarationName Name, unsigned Arity);
518 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
519 void mangleVendorQualifier(StringRef qualifier);
520 void mangleQualifiers(Qualifiers Quals);
521 void mangleRefQualifier(RefQualifierKind RefQualifier);
523 void mangleObjCMethodName(const ObjCMethodDecl *MD);
525 // Declare manglers for every type class.
526 #define ABSTRACT_TYPE(CLASS, PARENT)
527 #define NON_CANONICAL_TYPE(CLASS, PARENT)
528 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
529 #include "clang/AST/TypeNodes.def"
531 void mangleType(const TagType*);
532 void mangleType(TemplateName);
533 static StringRef getCallingConvQualifierName(CallingConv CC);
534 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
535 void mangleExtFunctionInfo(const FunctionType *T);
536 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
537 const FunctionDecl *FD = nullptr);
538 void mangleNeonVectorType(const VectorType *T);
539 void mangleAArch64NeonVectorType(const VectorType *T);
541 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
542 void mangleMemberExprBase(const Expr *base, bool isArrow);
543 void mangleMemberExpr(const Expr *base, bool isArrow,
544 NestedNameSpecifier *qualifier,
545 NamedDecl *firstQualifierLookup,
546 DeclarationName name,
547 const TemplateArgumentLoc *TemplateArgs,
548 unsigned NumTemplateArgs,
549 unsigned knownArity);
550 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
551 void mangleInitListElements(const InitListExpr *InitList);
552 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
553 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
554 void mangleCXXDtorType(CXXDtorType T);
556 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
557 unsigned NumTemplateArgs);
558 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
559 unsigned NumTemplateArgs);
560 void mangleTemplateArgs(const TemplateArgumentList &AL);
561 void mangleTemplateArg(TemplateArgument A);
563 void mangleTemplateParameter(unsigned Index);
565 void mangleFunctionParam(const ParmVarDecl *parm);
567 void writeAbiTags(const NamedDecl *ND,
568 const AbiTagList *AdditionalAbiTags);
570 // Returns sorted unique list of ABI tags.
571 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
572 // Returns sorted unique list of ABI tags.
573 AbiTagList makeVariableTypeTags(const VarDecl *VD);
578 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
579 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
581 LanguageLinkage L = FD->getLanguageLinkage();
582 // Overloadable functions need mangling.
583 if (FD->hasAttr<OverloadableAttr>())
586 // "main" is not mangled.
590 // C++ functions and those whose names are not a simple identifier need
592 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
595 // C functions are not mangled.
596 if (L == CLanguageLinkage)
600 // Otherwise, no mangling is done outside C++ mode.
601 if (!getASTContext().getLangOpts().CPlusPlus)
604 const VarDecl *VD = dyn_cast<VarDecl>(D);
605 if (VD && !isa<DecompositionDecl>(D)) {
606 // C variables are not mangled.
610 // Variables at global scope with non-internal linkage are not mangled
611 const DeclContext *DC = getEffectiveDeclContext(D);
612 // Check for extern variable declared locally.
613 if (DC->isFunctionOrMethod() && D->hasLinkage())
614 while (!DC->isNamespace() && !DC->isTranslationUnit())
615 DC = getEffectiveParentContext(DC);
616 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
617 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
618 !isa<VarTemplateSpecializationDecl>(D))
625 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
626 const AbiTagList *AdditionalAbiTags) {
627 assert(AbiTags && "require AbiTagState");
628 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
631 void CXXNameMangler::mangleSourceNameWithAbiTags(
632 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
633 mangleSourceName(ND->getIdentifier());
634 writeAbiTags(ND, AdditionalAbiTags);
637 void CXXNameMangler::mangle(const NamedDecl *D) {
638 // <mangled-name> ::= _Z <encoding>
640 // ::= <special-name>
642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
643 mangleFunctionEncoding(FD);
644 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
646 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
647 mangleName(IFD->getAnonField());
649 mangleName(cast<FieldDecl>(D));
652 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
653 // <encoding> ::= <function name> <bare-function-type>
655 // Don't mangle in the type if this isn't a decl we should typically mangle.
656 if (!Context.shouldMangleDeclName(FD)) {
661 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
662 if (ReturnTypeAbiTags.empty()) {
663 // There are no tags for return type, the simplest case.
665 mangleFunctionEncodingBareType(FD);
669 // Mangle function name and encoding to temporary buffer.
670 // We have to output name and encoding to the same mangler to get the same
671 // substitution as it will be in final mangling.
672 SmallString<256> FunctionEncodingBuf;
673 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
674 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
675 // Output name of the function.
676 FunctionEncodingMangler.disableDerivedAbiTags();
677 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
679 // Remember length of the function name in the buffer.
680 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
681 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
683 // Get tags from return type that are not present in function name or
685 const AbiTagList &UsedAbiTags =
686 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
687 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
688 AdditionalAbiTags.erase(
689 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
690 UsedAbiTags.begin(), UsedAbiTags.end(),
691 AdditionalAbiTags.begin()),
692 AdditionalAbiTags.end());
694 // Output name with implicit tags and function encoding from temporary buffer.
695 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
696 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
698 // Function encoding could create new substitutions so we have to add
699 // temp mangled substitutions to main mangler.
700 extendSubstitutions(&FunctionEncodingMangler);
703 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
704 if (FD->hasAttr<EnableIfAttr>()) {
705 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
706 Out << "Ua9enable_ifI";
707 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
709 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
710 E = FD->getAttrs().rend();
712 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
716 mangleExpression(EIA->getCond());
720 FunctionTypeDepth.pop(Saved);
723 // When mangling an inheriting constructor, the bare function type used is
724 // that of the inherited constructor.
725 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
726 if (auto Inherited = CD->getInheritedConstructor())
727 FD = Inherited.getConstructor();
729 // Whether the mangling of a function type includes the return type depends on
730 // the context and the nature of the function. The rules for deciding whether
731 // the return type is included are:
733 // 1. Template functions (names or types) have return types encoded, with
734 // the exceptions listed below.
735 // 2. Function types not appearing as part of a function name mangling,
736 // e.g. parameters, pointer types, etc., have return type encoded, with the
737 // exceptions listed below.
738 // 3. Non-template function names do not have return types encoded.
740 // The exceptions mentioned in (1) and (2) above, for which the return type is
741 // never included, are
744 // 3. Conversion operator functions, e.g. operator int.
745 bool MangleReturnType = false;
746 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
747 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
748 isa<CXXConversionDecl>(FD)))
749 MangleReturnType = true;
751 // Mangle the type of the primary template.
752 FD = PrimaryTemplate->getTemplatedDecl();
755 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
756 MangleReturnType, FD);
759 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
760 while (isa<LinkageSpecDecl>(DC)) {
761 DC = getEffectiveParentContext(DC);
767 /// Return whether a given namespace is the 'std' namespace.
768 static bool isStd(const NamespaceDecl *NS) {
769 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
770 ->isTranslationUnit())
773 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
774 return II && II->isStr("std");
777 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
779 static bool isStdNamespace(const DeclContext *DC) {
780 if (!DC->isNamespace())
783 return isStd(cast<NamespaceDecl>(DC));
786 static const TemplateDecl *
787 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
788 // Check if we have a function template.
789 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
790 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
791 TemplateArgs = FD->getTemplateSpecializationArgs();
796 // Check if we have a class template.
797 if (const ClassTemplateSpecializationDecl *Spec =
798 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
799 TemplateArgs = &Spec->getTemplateArgs();
800 return Spec->getSpecializedTemplate();
803 // Check if we have a variable template.
804 if (const VarTemplateSpecializationDecl *Spec =
805 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
806 TemplateArgs = &Spec->getTemplateArgs();
807 return Spec->getSpecializedTemplate();
813 void CXXNameMangler::mangleName(const NamedDecl *ND) {
814 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
815 // Variables should have implicit tags from its type.
816 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
817 if (VariableTypeAbiTags.empty()) {
818 // Simple case no variable type tags.
819 mangleNameWithAbiTags(VD, nullptr);
823 // Mangle variable name to null stream to collect tags.
824 llvm::raw_null_ostream NullOutStream;
825 CXXNameMangler VariableNameMangler(*this, NullOutStream);
826 VariableNameMangler.disableDerivedAbiTags();
827 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
829 // Get tags from variable type that are not present in its name.
830 const AbiTagList &UsedAbiTags =
831 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
832 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
833 AdditionalAbiTags.erase(
834 std::set_difference(VariableTypeAbiTags.begin(),
835 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
836 UsedAbiTags.end(), AdditionalAbiTags.begin()),
837 AdditionalAbiTags.end());
839 // Output name with implicit tags.
840 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
842 mangleNameWithAbiTags(ND, nullptr);
846 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
847 const AbiTagList *AdditionalAbiTags) {
848 // <name> ::= <nested-name>
849 // ::= <unscoped-name>
850 // ::= <unscoped-template-name> <template-args>
853 const DeclContext *DC = getEffectiveDeclContext(ND);
855 // If this is an extern variable declared locally, the relevant DeclContext
856 // is that of the containing namespace, or the translation unit.
857 // FIXME: This is a hack; extern variables declared locally should have
858 // a proper semantic declaration context!
859 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
860 while (!DC->isNamespace() && !DC->isTranslationUnit())
861 DC = getEffectiveParentContext(DC);
862 else if (GetLocalClassDecl(ND)) {
863 mangleLocalName(ND, AdditionalAbiTags);
867 DC = IgnoreLinkageSpecDecls(DC);
869 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
870 // Check if we have a template.
871 const TemplateArgumentList *TemplateArgs = nullptr;
872 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
873 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
874 mangleTemplateArgs(*TemplateArgs);
878 mangleUnscopedName(ND, AdditionalAbiTags);
882 if (isLocalContainerContext(DC)) {
883 mangleLocalName(ND, AdditionalAbiTags);
887 mangleNestedName(ND, DC, AdditionalAbiTags);
890 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
891 const TemplateArgument *TemplateArgs,
892 unsigned NumTemplateArgs) {
893 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
895 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
896 mangleUnscopedTemplateName(TD, nullptr);
897 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
899 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
903 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
904 const AbiTagList *AdditionalAbiTags) {
905 // <unscoped-name> ::= <unqualified-name>
906 // ::= St <unqualified-name> # ::std::
908 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
911 mangleUnqualifiedName(ND, AdditionalAbiTags);
914 void CXXNameMangler::mangleUnscopedTemplateName(
915 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
916 // <unscoped-template-name> ::= <unscoped-name>
917 // ::= <substitution>
918 if (mangleSubstitution(ND))
921 // <template-template-param> ::= <template-param>
922 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
923 assert(!AdditionalAbiTags &&
924 "template template param cannot have abi tags");
925 mangleTemplateParameter(TTP->getIndex());
926 } else if (isa<BuiltinTemplateDecl>(ND)) {
927 mangleUnscopedName(ND, AdditionalAbiTags);
929 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
935 void CXXNameMangler::mangleUnscopedTemplateName(
936 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
937 // <unscoped-template-name> ::= <unscoped-name>
938 // ::= <substitution>
939 if (TemplateDecl *TD = Template.getAsTemplateDecl())
940 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
942 if (mangleSubstitution(Template))
945 assert(!AdditionalAbiTags &&
946 "dependent template name cannot have abi tags");
948 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
949 assert(Dependent && "Not a dependent template name?");
950 if (const IdentifierInfo *Id = Dependent->getIdentifier())
951 mangleSourceName(Id);
953 mangleOperatorName(Dependent->getOperator(), UnknownArity);
955 addSubstitution(Template);
958 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
960 // Floating-point literals are encoded using a fixed-length
961 // lowercase hexadecimal string corresponding to the internal
962 // representation (IEEE on Itanium), high-order bytes first,
963 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
965 // The 'without leading zeroes' thing seems to be an editorial
966 // mistake; see the discussion on cxx-abi-dev beginning on
969 // Our requirements here are just barely weird enough to justify
970 // using a custom algorithm instead of post-processing APInt::toString().
972 llvm::APInt valueBits = f.bitcastToAPInt();
973 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
974 assert(numCharacters != 0);
976 // Allocate a buffer of the right number of characters.
977 SmallVector<char, 20> buffer(numCharacters);
979 // Fill the buffer left-to-right.
980 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
981 // The bit-index of the next hex digit.
982 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
984 // Project out 4 bits starting at 'digitIndex'.
985 llvm::integerPart hexDigit
986 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
987 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
990 // Map that over to a lowercase hex digit.
991 static const char charForHex[16] = {
992 '0', '1', '2', '3', '4', '5', '6', '7',
993 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
995 buffer[stringIndex] = charForHex[hexDigit];
998 Out.write(buffer.data(), numCharacters);
1001 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1002 if (Value.isSigned() && Value.isNegative()) {
1004 Value.abs().print(Out, /*signed*/ false);
1006 Value.print(Out, /*signed*/ false);
1010 void CXXNameMangler::mangleNumber(int64_t Number) {
1011 // <number> ::= [n] <non-negative decimal integer>
1020 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1021 // <call-offset> ::= h <nv-offset> _
1022 // ::= v <v-offset> _
1023 // <nv-offset> ::= <offset number> # non-virtual base override
1024 // <v-offset> ::= <offset number> _ <virtual offset number>
1025 // # virtual base override, with vcall offset
1028 mangleNumber(NonVirtual);
1034 mangleNumber(NonVirtual);
1036 mangleNumber(Virtual);
1040 void CXXNameMangler::manglePrefix(QualType type) {
1041 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1042 if (!mangleSubstitution(QualType(TST, 0))) {
1043 mangleTemplatePrefix(TST->getTemplateName());
1045 // FIXME: GCC does not appear to mangle the template arguments when
1046 // the template in question is a dependent template name. Should we
1047 // emulate that badness?
1048 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1049 addSubstitution(QualType(TST, 0));
1051 } else if (const auto *DTST =
1052 type->getAs<DependentTemplateSpecializationType>()) {
1053 if (!mangleSubstitution(QualType(DTST, 0))) {
1054 TemplateName Template = getASTContext().getDependentTemplateName(
1055 DTST->getQualifier(), DTST->getIdentifier());
1056 mangleTemplatePrefix(Template);
1058 // FIXME: GCC does not appear to mangle the template arguments when
1059 // the template in question is a dependent template name. Should we
1060 // emulate that badness?
1061 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1062 addSubstitution(QualType(DTST, 0));
1065 // We use the QualType mangle type variant here because it handles
1071 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1073 /// \param recursive - true if this is being called recursively,
1074 /// i.e. if there is more prefix "to the right".
1075 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1079 // <unresolved-name> ::= [gs] <base-unresolved-name>
1081 // T::x / decltype(p)::x
1082 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1084 // T::N::x /decltype(p)::N::x
1085 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1086 // <base-unresolved-name>
1088 // A::x, N::y, A<T>::z; "gs" means leading "::"
1089 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1090 // <base-unresolved-name>
1092 switch (qualifier->getKind()) {
1093 case NestedNameSpecifier::Global:
1096 // We want an 'sr' unless this is the entire NNS.
1100 // We never want an 'E' here.
1103 case NestedNameSpecifier::Super:
1104 llvm_unreachable("Can't mangle __super specifier");
1106 case NestedNameSpecifier::Namespace:
1107 if (qualifier->getPrefix())
1108 mangleUnresolvedPrefix(qualifier->getPrefix(),
1109 /*recursive*/ true);
1112 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1114 case NestedNameSpecifier::NamespaceAlias:
1115 if (qualifier->getPrefix())
1116 mangleUnresolvedPrefix(qualifier->getPrefix(),
1117 /*recursive*/ true);
1120 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1123 case NestedNameSpecifier::TypeSpec:
1124 case NestedNameSpecifier::TypeSpecWithTemplate: {
1125 const Type *type = qualifier->getAsType();
1127 // We only want to use an unresolved-type encoding if this is one of:
1129 // - a template type parameter
1130 // - a template template parameter with arguments
1131 // In all of these cases, we should have no prefix.
1132 if (qualifier->getPrefix()) {
1133 mangleUnresolvedPrefix(qualifier->getPrefix(),
1134 /*recursive*/ true);
1136 // Otherwise, all the cases want this.
1140 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1146 case NestedNameSpecifier::Identifier:
1147 // Member expressions can have these without prefixes.
1148 if (qualifier->getPrefix())
1149 mangleUnresolvedPrefix(qualifier->getPrefix(),
1150 /*recursive*/ true);
1154 mangleSourceName(qualifier->getAsIdentifier());
1155 // An Identifier has no type information, so we can't emit abi tags for it.
1159 // If this was the innermost part of the NNS, and we fell out to
1160 // here, append an 'E'.
1165 /// Mangle an unresolved-name, which is generally used for names which
1166 /// weren't resolved to specific entities.
1167 void CXXNameMangler::mangleUnresolvedName(
1168 NestedNameSpecifier *qualifier, DeclarationName name,
1169 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1170 unsigned knownArity) {
1171 if (qualifier) mangleUnresolvedPrefix(qualifier);
1172 switch (name.getNameKind()) {
1173 // <base-unresolved-name> ::= <simple-id>
1174 case DeclarationName::Identifier:
1175 mangleSourceName(name.getAsIdentifierInfo());
1177 // <base-unresolved-name> ::= dn <destructor-name>
1178 case DeclarationName::CXXDestructorName:
1180 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1182 // <base-unresolved-name> ::= on <operator-name>
1183 case DeclarationName::CXXConversionFunctionName:
1184 case DeclarationName::CXXLiteralOperatorName:
1185 case DeclarationName::CXXOperatorName:
1187 mangleOperatorName(name, knownArity);
1189 case DeclarationName::CXXConstructorName:
1190 llvm_unreachable("Can't mangle a constructor name!");
1191 case DeclarationName::CXXUsingDirective:
1192 llvm_unreachable("Can't mangle a using directive name!");
1193 case DeclarationName::ObjCMultiArgSelector:
1194 case DeclarationName::ObjCOneArgSelector:
1195 case DeclarationName::ObjCZeroArgSelector:
1196 llvm_unreachable("Can't mangle Objective-C selector names here!");
1199 // The <simple-id> and on <operator-name> productions end in an optional
1202 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1205 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1206 DeclarationName Name,
1207 unsigned KnownArity,
1208 const AbiTagList *AdditionalAbiTags) {
1209 unsigned Arity = KnownArity;
1210 // <unqualified-name> ::= <operator-name>
1211 // ::= <ctor-dtor-name>
1212 // ::= <source-name>
1213 switch (Name.getNameKind()) {
1214 case DeclarationName::Identifier: {
1215 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1217 // We mangle decomposition declarations as the names of their bindings.
1218 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1219 // FIXME: Non-standard mangling for decomposition declarations:
1221 // <unqualified-name> ::= DC <source-name>* E
1223 // These can never be referenced across translation units, so we do
1224 // not need a cross-vendor mangling for anything other than demanglers.
1225 // Proposed on cxx-abi-dev on 2016-08-12
1227 for (auto *BD : DD->bindings())
1228 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1230 writeAbiTags(ND, AdditionalAbiTags);
1235 // We must avoid conflicts between internally- and externally-
1236 // linked variable and function declaration names in the same TU:
1237 // void test() { extern void foo(); }
1238 // static void foo();
1239 // This naming convention is the same as that followed by GCC,
1240 // though it shouldn't actually matter.
1241 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1242 getEffectiveDeclContext(ND)->isFileContext())
1245 auto *FD = dyn_cast<FunctionDecl>(ND);
1246 bool IsRegCall = FD &&
1247 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1248 clang::CC_X86RegCall;
1250 mangleRegCallName(II);
1252 mangleSourceName(II);
1254 writeAbiTags(ND, AdditionalAbiTags);
1258 // Otherwise, an anonymous entity. We must have a declaration.
1259 assert(ND && "mangling empty name without declaration");
1261 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1262 if (NS->isAnonymousNamespace()) {
1263 // This is how gcc mangles these names.
1264 Out << "12_GLOBAL__N_1";
1269 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1270 // We must have an anonymous union or struct declaration.
1271 const RecordDecl *RD =
1272 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1274 // Itanium C++ ABI 5.1.2:
1276 // For the purposes of mangling, the name of an anonymous union is
1277 // considered to be the name of the first named data member found by a
1278 // pre-order, depth-first, declaration-order walk of the data members of
1279 // the anonymous union. If there is no such data member (i.e., if all of
1280 // the data members in the union are unnamed), then there is no way for
1281 // a program to refer to the anonymous union, and there is therefore no
1282 // need to mangle its name.
1283 assert(RD->isAnonymousStructOrUnion()
1284 && "Expected anonymous struct or union!");
1285 const FieldDecl *FD = RD->findFirstNamedDataMember();
1287 // It's actually possible for various reasons for us to get here
1288 // with an empty anonymous struct / union. Fortunately, it
1289 // doesn't really matter what name we generate.
1291 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1293 mangleSourceName(FD->getIdentifier());
1294 // Not emitting abi tags: internal name anyway.
1298 // Class extensions have no name as a category, and it's possible
1299 // for them to be the semantic parent of certain declarations
1300 // (primarily, tag decls defined within declarations). Such
1301 // declarations will always have internal linkage, so the name
1302 // doesn't really matter, but we shouldn't crash on them. For
1303 // safety, just handle all ObjC containers here.
1304 if (isa<ObjCContainerDecl>(ND))
1307 // We must have an anonymous struct.
1308 const TagDecl *TD = cast<TagDecl>(ND);
1309 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1310 assert(TD->getDeclContext() == D->getDeclContext() &&
1311 "Typedef should not be in another decl context!");
1312 assert(D->getDeclName().getAsIdentifierInfo() &&
1313 "Typedef was not named!");
1314 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1315 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1316 // Explicit abi tags are still possible; take from underlying type, not
1318 writeAbiTags(TD, nullptr);
1322 // <unnamed-type-name> ::= <closure-type-name>
1324 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1325 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1326 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1327 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1328 assert(!AdditionalAbiTags &&
1329 "Lambda type cannot have additional abi tags");
1330 mangleLambda(Record);
1335 if (TD->isExternallyVisible()) {
1336 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1338 if (UnnamedMangle > 1)
1339 Out << UnnamedMangle - 2;
1341 writeAbiTags(TD, AdditionalAbiTags);
1345 // Get a unique id for the anonymous struct. If it is not a real output
1346 // ID doesn't matter so use fake one.
1347 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1349 // Mangle it as a source name in the form
1351 // where n is the length of the string.
1354 Str += llvm::utostr(AnonStructId);
1361 case DeclarationName::ObjCZeroArgSelector:
1362 case DeclarationName::ObjCOneArgSelector:
1363 case DeclarationName::ObjCMultiArgSelector:
1364 llvm_unreachable("Can't mangle Objective-C selector names here!");
1366 case DeclarationName::CXXConstructorName: {
1367 const CXXRecordDecl *InheritedFrom = nullptr;
1368 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1369 if (auto Inherited =
1370 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1371 InheritedFrom = Inherited.getConstructor()->getParent();
1372 InheritedTemplateArgs =
1373 Inherited.getConstructor()->getTemplateSpecializationArgs();
1377 // If the named decl is the C++ constructor we're mangling, use the type
1379 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1381 // Otherwise, use the complete constructor name. This is relevant if a
1382 // class with a constructor is declared within a constructor.
1383 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1385 // FIXME: The template arguments are part of the enclosing prefix or
1386 // nested-name, but it's more convenient to mangle them here.
1387 if (InheritedTemplateArgs)
1388 mangleTemplateArgs(*InheritedTemplateArgs);
1390 writeAbiTags(ND, AdditionalAbiTags);
1394 case DeclarationName::CXXDestructorName:
1396 // If the named decl is the C++ destructor we're mangling, use the type we
1398 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1400 // Otherwise, use the complete destructor name. This is relevant if a
1401 // class with a destructor is declared within a destructor.
1402 mangleCXXDtorType(Dtor_Complete);
1403 writeAbiTags(ND, AdditionalAbiTags);
1406 case DeclarationName::CXXOperatorName:
1407 if (ND && Arity == UnknownArity) {
1408 Arity = cast<FunctionDecl>(ND)->getNumParams();
1410 // If we have a member function, we need to include the 'this' pointer.
1411 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1412 if (!MD->isStatic())
1416 case DeclarationName::CXXConversionFunctionName:
1417 case DeclarationName::CXXLiteralOperatorName:
1418 mangleOperatorName(Name, Arity);
1419 writeAbiTags(ND, AdditionalAbiTags);
1422 case DeclarationName::CXXUsingDirective:
1423 llvm_unreachable("Can't mangle a using directive name!");
1427 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1428 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1429 // <number> ::= [n] <non-negative decimal integer>
1430 // <identifier> ::= <unqualified source code identifier>
1431 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1435 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1436 // <source-name> ::= <positive length number> <identifier>
1437 // <number> ::= [n] <non-negative decimal integer>
1438 // <identifier> ::= <unqualified source code identifier>
1439 Out << II->getLength() << II->getName();
1442 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1443 const DeclContext *DC,
1444 const AbiTagList *AdditionalAbiTags,
1447 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1448 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1449 // <template-args> E
1452 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1453 Qualifiers MethodQuals =
1454 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1455 // We do not consider restrict a distinguishing attribute for overloading
1456 // purposes so we must not mangle it.
1457 MethodQuals.removeRestrict();
1458 mangleQualifiers(MethodQuals);
1459 mangleRefQualifier(Method->getRefQualifier());
1462 // Check if we have a template.
1463 const TemplateArgumentList *TemplateArgs = nullptr;
1464 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1465 mangleTemplatePrefix(TD, NoFunction);
1466 mangleTemplateArgs(*TemplateArgs);
1469 manglePrefix(DC, NoFunction);
1470 mangleUnqualifiedName(ND, AdditionalAbiTags);
1475 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1476 const TemplateArgument *TemplateArgs,
1477 unsigned NumTemplateArgs) {
1478 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1482 mangleTemplatePrefix(TD);
1483 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1488 void CXXNameMangler::mangleLocalName(const Decl *D,
1489 const AbiTagList *AdditionalAbiTags) {
1490 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1491 // := Z <function encoding> E s [<discriminator>]
1492 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1494 // <discriminator> := _ <non-negative number>
1495 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1496 const RecordDecl *RD = GetLocalClassDecl(D);
1497 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1502 AbiTagState LocalAbiTags(AbiTags);
1504 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1505 mangleObjCMethodName(MD);
1506 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1507 mangleBlockForPrefix(BD);
1509 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1511 // Implicit ABI tags (from namespace) are not available in the following
1512 // entity; reset to actually emitted tags, which are available.
1513 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1518 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1519 // be a bug that is fixed in trunk.
1522 // The parameter number is omitted for the last parameter, 0 for the
1523 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1524 // <entity name> will of course contain a <closure-type-name>: Its
1525 // numbering will be local to the particular argument in which it appears
1526 // -- other default arguments do not affect its encoding.
1527 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1528 if (CXXRD && CXXRD->isLambda()) {
1529 if (const ParmVarDecl *Parm
1530 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1531 if (const FunctionDecl *Func
1532 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1534 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1536 mangleNumber(Num - 2);
1542 // Mangle the name relative to the closest enclosing function.
1543 // equality ok because RD derived from ND above
1545 mangleUnqualifiedName(RD, AdditionalAbiTags);
1546 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1547 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1548 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1549 mangleUnqualifiedBlock(BD);
1551 const NamedDecl *ND = cast<NamedDecl>(D);
1552 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1553 true /*NoFunction*/);
1555 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1556 // Mangle a block in a default parameter; see above explanation for
1558 if (const ParmVarDecl *Parm
1559 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1560 if (const FunctionDecl *Func
1561 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1563 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1565 mangleNumber(Num - 2);
1570 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1571 mangleUnqualifiedBlock(BD);
1573 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1576 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1578 if (Context.getNextDiscriminator(ND, disc)) {
1582 Out << "__" << disc << '_';
1587 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1588 if (GetLocalClassDecl(Block)) {
1589 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1592 const DeclContext *DC = getEffectiveDeclContext(Block);
1593 if (isLocalContainerContext(DC)) {
1594 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1597 manglePrefix(getEffectiveDeclContext(Block));
1598 mangleUnqualifiedBlock(Block);
1601 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1602 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1603 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1604 Context->getDeclContext()->isRecord()) {
1605 const auto *ND = cast<NamedDecl>(Context);
1606 if (ND->getIdentifier()) {
1607 mangleSourceNameWithAbiTags(ND);
1613 // If we have a block mangling number, use it.
1614 unsigned Number = Block->getBlockManglingNumber();
1615 // Otherwise, just make up a number. It doesn't matter what it is because
1616 // the symbol in question isn't externally visible.
1618 Number = Context.getBlockId(Block, false);
1625 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1626 // If the context of a closure type is an initializer for a class member
1627 // (static or nonstatic), it is encoded in a qualified name with a final
1628 // <prefix> of the form:
1630 // <data-member-prefix> := <member source-name> M
1632 // Technically, the data-member-prefix is part of the <prefix>. However,
1633 // since a closure type will always be mangled with a prefix, it's easier
1634 // to emit that last part of the prefix here.
1635 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1636 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1637 Context->getDeclContext()->isRecord()) {
1638 if (const IdentifierInfo *Name
1639 = cast<NamedDecl>(Context)->getIdentifier()) {
1640 mangleSourceName(Name);
1647 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1648 getAs<FunctionProtoType>();
1649 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1650 Lambda->getLambdaStaticInvoker());
1653 // The number is omitted for the first closure type with a given
1654 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1655 // (in lexical order) with that same <lambda-sig> and context.
1657 // The AST keeps track of the number for us.
1658 unsigned Number = Lambda->getLambdaManglingNumber();
1659 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1661 mangleNumber(Number - 2);
1665 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1666 switch (qualifier->getKind()) {
1667 case NestedNameSpecifier::Global:
1671 case NestedNameSpecifier::Super:
1672 llvm_unreachable("Can't mangle __super specifier");
1674 case NestedNameSpecifier::Namespace:
1675 mangleName(qualifier->getAsNamespace());
1678 case NestedNameSpecifier::NamespaceAlias:
1679 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1682 case NestedNameSpecifier::TypeSpec:
1683 case NestedNameSpecifier::TypeSpecWithTemplate:
1684 manglePrefix(QualType(qualifier->getAsType(), 0));
1687 case NestedNameSpecifier::Identifier:
1688 // Member expressions can have these without prefixes, but that
1689 // should end up in mangleUnresolvedPrefix instead.
1690 assert(qualifier->getPrefix());
1691 manglePrefix(qualifier->getPrefix());
1693 mangleSourceName(qualifier->getAsIdentifier());
1697 llvm_unreachable("unexpected nested name specifier");
1700 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1701 // <prefix> ::= <prefix> <unqualified-name>
1702 // ::= <template-prefix> <template-args>
1703 // ::= <template-param>
1705 // ::= <substitution>
1707 DC = IgnoreLinkageSpecDecls(DC);
1709 if (DC->isTranslationUnit())
1712 if (NoFunction && isLocalContainerContext(DC))
1715 assert(!isLocalContainerContext(DC));
1717 const NamedDecl *ND = cast<NamedDecl>(DC);
1718 if (mangleSubstitution(ND))
1721 // Check if we have a template.
1722 const TemplateArgumentList *TemplateArgs = nullptr;
1723 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1724 mangleTemplatePrefix(TD);
1725 mangleTemplateArgs(*TemplateArgs);
1727 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1728 mangleUnqualifiedName(ND, nullptr);
1731 addSubstitution(ND);
1734 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1735 // <template-prefix> ::= <prefix> <template unqualified-name>
1736 // ::= <template-param>
1737 // ::= <substitution>
1738 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1739 return mangleTemplatePrefix(TD);
1741 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1742 manglePrefix(Qualified->getQualifier());
1744 if (OverloadedTemplateStorage *Overloaded
1745 = Template.getAsOverloadedTemplate()) {
1746 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1747 UnknownArity, nullptr);
1751 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1752 assert(Dependent && "Unknown template name kind?");
1753 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1754 manglePrefix(Qualifier);
1755 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1758 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1760 // <template-prefix> ::= <prefix> <template unqualified-name>
1761 // ::= <template-param>
1762 // ::= <substitution>
1763 // <template-template-param> ::= <template-param>
1766 if (mangleSubstitution(ND))
1769 // <template-template-param> ::= <template-param>
1770 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1771 mangleTemplateParameter(TTP->getIndex());
1773 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1774 if (isa<BuiltinTemplateDecl>(ND))
1775 mangleUnqualifiedName(ND, nullptr);
1777 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1780 addSubstitution(ND);
1783 /// Mangles a template name under the production <type>. Required for
1784 /// template template arguments.
1785 /// <type> ::= <class-enum-type>
1786 /// ::= <template-param>
1787 /// ::= <substitution>
1788 void CXXNameMangler::mangleType(TemplateName TN) {
1789 if (mangleSubstitution(TN))
1792 TemplateDecl *TD = nullptr;
1794 switch (TN.getKind()) {
1795 case TemplateName::QualifiedTemplate:
1796 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1799 case TemplateName::Template:
1800 TD = TN.getAsTemplateDecl();
1804 if (isa<TemplateTemplateParmDecl>(TD))
1805 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1810 case TemplateName::OverloadedTemplate:
1811 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1813 case TemplateName::DependentTemplate: {
1814 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1815 assert(Dependent->isIdentifier());
1817 // <class-enum-type> ::= <name>
1818 // <name> ::= <nested-name>
1819 mangleUnresolvedPrefix(Dependent->getQualifier());
1820 mangleSourceName(Dependent->getIdentifier());
1824 case TemplateName::SubstTemplateTemplateParm: {
1825 // Substituted template parameters are mangled as the substituted
1826 // template. This will check for the substitution twice, which is
1827 // fine, but we have to return early so that we don't try to *add*
1828 // the substitution twice.
1829 SubstTemplateTemplateParmStorage *subst
1830 = TN.getAsSubstTemplateTemplateParm();
1831 mangleType(subst->getReplacement());
1835 case TemplateName::SubstTemplateTemplateParmPack: {
1836 // FIXME: not clear how to mangle this!
1837 // template <template <class> class T...> class A {
1838 // template <template <class> class U...> void foo(B<T,U> x...);
1840 Out << "_SUBSTPACK_";
1845 addSubstitution(TN);
1848 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1850 // Only certain other types are valid as prefixes; enumerate them.
1851 switch (Ty->getTypeClass()) {
1854 case Type::Adjusted:
1857 case Type::BlockPointer:
1858 case Type::LValueReference:
1859 case Type::RValueReference:
1860 case Type::MemberPointer:
1861 case Type::ConstantArray:
1862 case Type::IncompleteArray:
1863 case Type::VariableArray:
1864 case Type::DependentSizedArray:
1865 case Type::DependentSizedExtVector:
1867 case Type::ExtVector:
1868 case Type::FunctionProto:
1869 case Type::FunctionNoProto:
1871 case Type::Attributed:
1873 case Type::PackExpansion:
1874 case Type::ObjCObject:
1875 case Type::ObjCInterface:
1876 case Type::ObjCObjectPointer:
1877 case Type::ObjCTypeParam:
1880 llvm_unreachable("type is illegal as a nested name specifier");
1882 case Type::SubstTemplateTypeParmPack:
1883 // FIXME: not clear how to mangle this!
1884 // template <class T...> class A {
1885 // template <class U...> void foo(decltype(T::foo(U())) x...);
1887 Out << "_SUBSTPACK_";
1890 // <unresolved-type> ::= <template-param>
1892 // ::= <template-template-param> <template-args>
1893 // (this last is not official yet)
1894 case Type::TypeOfExpr:
1896 case Type::Decltype:
1897 case Type::TemplateTypeParm:
1898 case Type::UnaryTransform:
1899 case Type::SubstTemplateTypeParm:
1901 // Some callers want a prefix before the mangled type.
1904 // This seems to do everything we want. It's not really
1905 // sanctioned for a substituted template parameter, though.
1908 // We never want to print 'E' directly after an unresolved-type,
1909 // so we return directly.
1913 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
1916 case Type::UnresolvedUsing:
1917 mangleSourceNameWithAbiTags(
1918 cast<UnresolvedUsingType>(Ty)->getDecl());
1923 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
1926 case Type::TemplateSpecialization: {
1927 const TemplateSpecializationType *TST =
1928 cast<TemplateSpecializationType>(Ty);
1929 TemplateName TN = TST->getTemplateName();
1930 switch (TN.getKind()) {
1931 case TemplateName::Template:
1932 case TemplateName::QualifiedTemplate: {
1933 TemplateDecl *TD = TN.getAsTemplateDecl();
1935 // If the base is a template template parameter, this is an
1937 assert(TD && "no template for template specialization type");
1938 if (isa<TemplateTemplateParmDecl>(TD))
1939 goto unresolvedType;
1941 mangleSourceNameWithAbiTags(TD);
1945 case TemplateName::OverloadedTemplate:
1946 case TemplateName::DependentTemplate:
1947 llvm_unreachable("invalid base for a template specialization type");
1949 case TemplateName::SubstTemplateTemplateParm: {
1950 SubstTemplateTemplateParmStorage *subst =
1951 TN.getAsSubstTemplateTemplateParm();
1952 mangleExistingSubstitution(subst->getReplacement());
1956 case TemplateName::SubstTemplateTemplateParmPack: {
1957 // FIXME: not clear how to mangle this!
1958 // template <template <class U> class T...> class A {
1959 // template <class U...> void foo(decltype(T<U>::foo) x...);
1961 Out << "_SUBSTPACK_";
1966 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1970 case Type::InjectedClassName:
1971 mangleSourceNameWithAbiTags(
1972 cast<InjectedClassNameType>(Ty)->getDecl());
1975 case Type::DependentName:
1976 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1979 case Type::DependentTemplateSpecialization: {
1980 const DependentTemplateSpecializationType *DTST =
1981 cast<DependentTemplateSpecializationType>(Ty);
1982 mangleSourceName(DTST->getIdentifier());
1983 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1987 case Type::Elaborated:
1988 return mangleUnresolvedTypeOrSimpleId(
1989 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1995 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1996 switch (Name.getNameKind()) {
1997 case DeclarationName::CXXConstructorName:
1998 case DeclarationName::CXXDestructorName:
1999 case DeclarationName::CXXUsingDirective:
2000 case DeclarationName::Identifier:
2001 case DeclarationName::ObjCMultiArgSelector:
2002 case DeclarationName::ObjCOneArgSelector:
2003 case DeclarationName::ObjCZeroArgSelector:
2004 llvm_unreachable("Not an operator name");
2006 case DeclarationName::CXXConversionFunctionName:
2007 // <operator-name> ::= cv <type> # (cast)
2009 mangleType(Name.getCXXNameType());
2012 case DeclarationName::CXXLiteralOperatorName:
2014 mangleSourceName(Name.getCXXLiteralIdentifier());
2017 case DeclarationName::CXXOperatorName:
2018 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2024 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2026 // <operator-name> ::= nw # new
2027 case OO_New: Out << "nw"; break;
2029 case OO_Array_New: Out << "na"; break;
2031 case OO_Delete: Out << "dl"; break;
2032 // ::= da # delete[]
2033 case OO_Array_Delete: Out << "da"; break;
2034 // ::= ps # + (unary)
2035 // ::= pl # + (binary or unknown)
2037 Out << (Arity == 1? "ps" : "pl"); break;
2038 // ::= ng # - (unary)
2039 // ::= mi # - (binary or unknown)
2041 Out << (Arity == 1? "ng" : "mi"); break;
2042 // ::= ad # & (unary)
2043 // ::= an # & (binary or unknown)
2045 Out << (Arity == 1? "ad" : "an"); break;
2046 // ::= de # * (unary)
2047 // ::= ml # * (binary or unknown)
2049 // Use binary when unknown.
2050 Out << (Arity == 1? "de" : "ml"); break;
2052 case OO_Tilde: Out << "co"; break;
2054 case OO_Slash: Out << "dv"; break;
2056 case OO_Percent: Out << "rm"; break;
2058 case OO_Pipe: Out << "or"; break;
2060 case OO_Caret: Out << "eo"; break;
2062 case OO_Equal: Out << "aS"; break;
2064 case OO_PlusEqual: Out << "pL"; break;
2066 case OO_MinusEqual: Out << "mI"; break;
2068 case OO_StarEqual: Out << "mL"; break;
2070 case OO_SlashEqual: Out << "dV"; break;
2072 case OO_PercentEqual: Out << "rM"; break;
2074 case OO_AmpEqual: Out << "aN"; break;
2076 case OO_PipeEqual: Out << "oR"; break;
2078 case OO_CaretEqual: Out << "eO"; break;
2080 case OO_LessLess: Out << "ls"; break;
2082 case OO_GreaterGreater: Out << "rs"; break;
2084 case OO_LessLessEqual: Out << "lS"; break;
2086 case OO_GreaterGreaterEqual: Out << "rS"; break;
2088 case OO_EqualEqual: Out << "eq"; break;
2090 case OO_ExclaimEqual: Out << "ne"; break;
2092 case OO_Less: Out << "lt"; break;
2094 case OO_Greater: Out << "gt"; break;
2096 case OO_LessEqual: Out << "le"; break;
2098 case OO_GreaterEqual: Out << "ge"; break;
2100 case OO_Exclaim: Out << "nt"; break;
2102 case OO_AmpAmp: Out << "aa"; break;
2104 case OO_PipePipe: Out << "oo"; break;
2106 case OO_PlusPlus: Out << "pp"; break;
2108 case OO_MinusMinus: Out << "mm"; break;
2110 case OO_Comma: Out << "cm"; break;
2112 case OO_ArrowStar: Out << "pm"; break;
2114 case OO_Arrow: Out << "pt"; break;
2116 case OO_Call: Out << "cl"; break;
2118 case OO_Subscript: Out << "ix"; break;
2121 // The conditional operator can't be overloaded, but we still handle it when
2122 // mangling expressions.
2123 case OO_Conditional: Out << "qu"; break;
2124 // Proposal on cxx-abi-dev, 2015-10-21.
2125 // ::= aw # co_await
2126 case OO_Coawait: Out << "aw"; break;
2129 case NUM_OVERLOADED_OPERATORS:
2130 llvm_unreachable("Not an overloaded operator");
2134 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
2135 // Vendor qualifiers come first.
2137 // Address space qualifiers start with an ordinary letter.
2138 if (Quals.hasAddressSpace()) {
2139 // Address space extension:
2141 // <type> ::= U <target-addrspace>
2142 // <type> ::= U <OpenCL-addrspace>
2143 // <type> ::= U <CUDA-addrspace>
2145 SmallString<64> ASString;
2146 unsigned AS = Quals.getAddressSpace();
2148 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2149 // <target-addrspace> ::= "AS" <address-space-number>
2150 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2151 ASString = "AS" + llvm::utostr(TargetAS);
2154 default: llvm_unreachable("Not a language specific address space");
2155 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
2156 case LangAS::opencl_global: ASString = "CLglobal"; break;
2157 case LangAS::opencl_local: ASString = "CLlocal"; break;
2158 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2159 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2160 case LangAS::cuda_device: ASString = "CUdevice"; break;
2161 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2162 case LangAS::cuda_shared: ASString = "CUshared"; break;
2165 mangleVendorQualifier(ASString);
2168 // The ARC ownership qualifiers start with underscores.
2169 switch (Quals.getObjCLifetime()) {
2170 // Objective-C ARC Extension:
2172 // <type> ::= U "__strong"
2173 // <type> ::= U "__weak"
2174 // <type> ::= U "__autoreleasing"
2175 case Qualifiers::OCL_None:
2178 case Qualifiers::OCL_Weak:
2179 mangleVendorQualifier("__weak");
2182 case Qualifiers::OCL_Strong:
2183 mangleVendorQualifier("__strong");
2186 case Qualifiers::OCL_Autoreleasing:
2187 mangleVendorQualifier("__autoreleasing");
2190 case Qualifiers::OCL_ExplicitNone:
2191 // The __unsafe_unretained qualifier is *not* mangled, so that
2192 // __unsafe_unretained types in ARC produce the same manglings as the
2193 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2194 // better ABI compatibility.
2196 // It's safe to do this because unqualified 'id' won't show up
2197 // in any type signatures that need to be mangled.
2201 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2202 if (Quals.hasRestrict())
2204 if (Quals.hasVolatile())
2206 if (Quals.hasConst())
2210 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2211 Out << 'U' << name.size() << name;
2214 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2215 // <ref-qualifier> ::= R # lvalue reference
2216 // ::= O # rvalue-reference
2217 switch (RefQualifier) {
2231 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2232 Context.mangleObjCMethodName(MD, Out);
2235 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2238 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2240 if (Ty->isOpenCLSpecificType())
2242 if (Ty->isBuiltinType())
2248 void CXXNameMangler::mangleType(QualType T) {
2249 // If our type is instantiation-dependent but not dependent, we mangle
2250 // it as it was written in the source, removing any top-level sugar.
2251 // Otherwise, use the canonical type.
2253 // FIXME: This is an approximation of the instantiation-dependent name
2254 // mangling rules, since we should really be using the type as written and
2255 // augmented via semantic analysis (i.e., with implicit conversions and
2256 // default template arguments) for any instantiation-dependent type.
2257 // Unfortunately, that requires several changes to our AST:
2258 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2259 // uniqued, so that we can handle substitutions properly
2260 // - Default template arguments will need to be represented in the
2261 // TemplateSpecializationType, since they need to be mangled even though
2262 // they aren't written.
2263 // - Conversions on non-type template arguments need to be expressed, since
2264 // they can affect the mangling of sizeof/alignof.
2266 // FIXME: This is wrong when mapping to the canonical type for a dependent
2267 // type discards instantiation-dependent portions of the type, such as for:
2269 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2270 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2272 // It's also wrong in the opposite direction when instantiation-dependent,
2273 // canonically-equivalent types differ in some irrelevant portion of inner
2274 // type sugar. In such cases, we fail to form correct substitutions, eg:
2276 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2278 // We should instead canonicalize the non-instantiation-dependent parts,
2279 // regardless of whether the type as a whole is dependent or instantiation
2281 if (!T->isInstantiationDependentType() || T->isDependentType())
2282 T = T.getCanonicalType();
2284 // Desugar any types that are purely sugar.
2286 // Don't desugar through template specialization types that aren't
2287 // type aliases. We need to mangle the template arguments as written.
2288 if (const TemplateSpecializationType *TST
2289 = dyn_cast<TemplateSpecializationType>(T))
2290 if (!TST->isTypeAlias())
2294 = T.getSingleStepDesugaredType(Context.getASTContext());
2301 SplitQualType split = T.split();
2302 Qualifiers quals = split.Quals;
2303 const Type *ty = split.Ty;
2305 bool isSubstitutable = isTypeSubstitutable(quals, ty);
2306 if (isSubstitutable && mangleSubstitution(T))
2309 // If we're mangling a qualified array type, push the qualifiers to
2310 // the element type.
2311 if (quals && isa<ArrayType>(T)) {
2312 ty = Context.getASTContext().getAsArrayType(T);
2313 quals = Qualifiers();
2315 // Note that we don't update T: we want to add the
2316 // substitution at the original type.
2320 mangleQualifiers(quals);
2321 // Recurse: even if the qualified type isn't yet substitutable,
2322 // the unqualified type might be.
2323 mangleType(QualType(ty, 0));
2325 switch (ty->getTypeClass()) {
2326 #define ABSTRACT_TYPE(CLASS, PARENT)
2327 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2329 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2331 #define TYPE(CLASS, PARENT) \
2333 mangleType(static_cast<const CLASS##Type*>(ty)); \
2335 #include "clang/AST/TypeNodes.def"
2339 // Add the substitution.
2340 if (isSubstitutable)
2344 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2345 if (!mangleStandardSubstitution(ND))
2349 void CXXNameMangler::mangleType(const BuiltinType *T) {
2350 // <type> ::= <builtin-type>
2351 // <builtin-type> ::= v # void
2355 // ::= a # signed char
2356 // ::= h # unsigned char
2358 // ::= t # unsigned short
2360 // ::= j # unsigned int
2362 // ::= m # unsigned long
2363 // ::= x # long long, __int64
2364 // ::= y # unsigned long long, __int64
2366 // ::= o # unsigned __int128
2369 // ::= e # long double, __float80
2370 // ::= g # __float128
2371 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2372 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2373 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2374 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2375 // ::= Di # char32_t
2376 // ::= Ds # char16_t
2377 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2378 // ::= u <source-name> # vendor extended type
2379 std::string type_name;
2380 switch (T->getKind()) {
2381 case BuiltinType::Void:
2384 case BuiltinType::Bool:
2387 case BuiltinType::Char_U:
2388 case BuiltinType::Char_S:
2391 case BuiltinType::UChar:
2394 case BuiltinType::UShort:
2397 case BuiltinType::UInt:
2400 case BuiltinType::ULong:
2403 case BuiltinType::ULongLong:
2406 case BuiltinType::UInt128:
2409 case BuiltinType::SChar:
2412 case BuiltinType::WChar_S:
2413 case BuiltinType::WChar_U:
2416 case BuiltinType::Char16:
2419 case BuiltinType::Char32:
2422 case BuiltinType::Short:
2425 case BuiltinType::Int:
2428 case BuiltinType::Long:
2431 case BuiltinType::LongLong:
2434 case BuiltinType::Int128:
2437 case BuiltinType::Half:
2440 case BuiltinType::Float:
2443 case BuiltinType::Double:
2446 case BuiltinType::LongDouble:
2447 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2451 case BuiltinType::Float128:
2452 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2453 Out << "U10__float128"; // Match the GCC mangling
2457 case BuiltinType::NullPtr:
2461 #define BUILTIN_TYPE(Id, SingletonId)
2462 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2463 case BuiltinType::Id:
2464 #include "clang/AST/BuiltinTypes.def"
2465 case BuiltinType::Dependent:
2467 llvm_unreachable("mangling a placeholder type");
2469 case BuiltinType::ObjCId:
2470 Out << "11objc_object";
2472 case BuiltinType::ObjCClass:
2473 Out << "10objc_class";
2475 case BuiltinType::ObjCSel:
2476 Out << "13objc_selector";
2478 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2479 case BuiltinType::Id: \
2480 type_name = "ocl_" #ImgType "_" #Suffix; \
2481 Out << type_name.size() << type_name; \
2483 #include "clang/Basic/OpenCLImageTypes.def"
2484 case BuiltinType::OCLSampler:
2485 Out << "11ocl_sampler";
2487 case BuiltinType::OCLEvent:
2488 Out << "9ocl_event";
2490 case BuiltinType::OCLClkEvent:
2491 Out << "12ocl_clkevent";
2493 case BuiltinType::OCLQueue:
2494 Out << "9ocl_queue";
2496 case BuiltinType::OCLNDRange:
2497 Out << "11ocl_ndrange";
2499 case BuiltinType::OCLReserveID:
2500 Out << "13ocl_reserveid";
2505 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2511 case CC_X86FastCall:
2512 case CC_X86ThisCall:
2513 case CC_X86VectorCall:
2515 case CC_X86_64Win64:
2520 case CC_IntelOclBicc:
2521 case CC_SpirFunction:
2522 case CC_OpenCLKernel:
2523 case CC_PreserveMost:
2524 case CC_PreserveAll:
2525 // FIXME: we should be mangling all of the above.
2531 llvm_unreachable("bad calling convention");
2534 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2536 if (T->getExtInfo() == FunctionType::ExtInfo())
2539 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2540 // This will get more complicated in the future if we mangle other
2541 // things here; but for now, since we mangle ns_returns_retained as
2542 // a qualifier on the result type, we can get away with this:
2543 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2544 if (!CCQualifier.empty())
2545 mangleVendorQualifier(CCQualifier);
2552 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2553 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2555 // Note that these are *not* substitution candidates. Demanglers might
2556 // have trouble with this if the parameter type is fully substituted.
2558 switch (PI.getABI()) {
2559 case ParameterABI::Ordinary:
2562 // All of these start with "swift", so they come before "ns_consumed".
2563 case ParameterABI::SwiftContext:
2564 case ParameterABI::SwiftErrorResult:
2565 case ParameterABI::SwiftIndirectResult:
2566 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2570 if (PI.isConsumed())
2571 mangleVendorQualifier("ns_consumed");
2574 // <type> ::= <function-type>
2575 // <function-type> ::= [<CV-qualifiers>] F [Y]
2576 // <bare-function-type> [<ref-qualifier>] E
2577 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2578 mangleExtFunctionInfo(T);
2580 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2581 // e.g. "const" in "int (A::*)() const".
2582 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2584 // Mangle instantiation-dependent exception-specification, if present,
2585 // per cxx-abi-dev proposal on 2016-10-11.
2586 if (T->hasInstantiationDependentExceptionSpec()) {
2587 if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
2589 mangleExpression(T->getNoexceptExpr());
2592 assert(T->getExceptionSpecType() == EST_Dynamic);
2594 for (auto ExceptTy : T->exceptions())
2595 mangleType(ExceptTy);
2598 } else if (T->isNothrow(getASTContext())) {
2604 // FIXME: We don't have enough information in the AST to produce the 'Y'
2605 // encoding for extern "C" function types.
2606 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2608 // Mangle the ref-qualifier, if present.
2609 mangleRefQualifier(T->getRefQualifier());
2614 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2615 // Function types without prototypes can arise when mangling a function type
2616 // within an overloadable function in C. We mangle these as the absence of any
2617 // parameter types (not even an empty parameter list).
2620 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2622 FunctionTypeDepth.enterResultType();
2623 mangleType(T->getReturnType());
2624 FunctionTypeDepth.leaveResultType();
2626 FunctionTypeDepth.pop(saved);
2630 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2631 bool MangleReturnType,
2632 const FunctionDecl *FD) {
2633 // Record that we're in a function type. See mangleFunctionParam
2634 // for details on what we're trying to achieve here.
2635 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2637 // <bare-function-type> ::= <signature type>+
2638 if (MangleReturnType) {
2639 FunctionTypeDepth.enterResultType();
2641 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2642 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2643 mangleVendorQualifier("ns_returns_retained");
2645 // Mangle the return type without any direct ARC ownership qualifiers.
2646 QualType ReturnTy = Proto->getReturnType();
2647 if (ReturnTy.getObjCLifetime()) {
2648 auto SplitReturnTy = ReturnTy.split();
2649 SplitReturnTy.Quals.removeObjCLifetime();
2650 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2652 mangleType(ReturnTy);
2654 FunctionTypeDepth.leaveResultType();
2657 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2658 // <builtin-type> ::= v # void
2661 FunctionTypeDepth.pop(saved);
2665 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2666 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2667 // Mangle extended parameter info as order-sensitive qualifiers here.
2668 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2669 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2673 QualType ParamTy = Proto->getParamType(I);
2674 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2677 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2678 // Attr can only take 1 character, so we can hardcode the length below.
2679 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2680 Out << "U17pass_object_size" << Attr->getType();
2685 FunctionTypeDepth.pop(saved);
2687 // <builtin-type> ::= z # ellipsis
2688 if (Proto->isVariadic())
2692 // <type> ::= <class-enum-type>
2693 // <class-enum-type> ::= <name>
2694 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2695 mangleName(T->getDecl());
2698 // <type> ::= <class-enum-type>
2699 // <class-enum-type> ::= <name>
2700 void CXXNameMangler::mangleType(const EnumType *T) {
2701 mangleType(static_cast<const TagType*>(T));
2703 void CXXNameMangler::mangleType(const RecordType *T) {
2704 mangleType(static_cast<const TagType*>(T));
2706 void CXXNameMangler::mangleType(const TagType *T) {
2707 mangleName(T->getDecl());
2710 // <type> ::= <array-type>
2711 // <array-type> ::= A <positive dimension number> _ <element type>
2712 // ::= A [<dimension expression>] _ <element type>
2713 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2714 Out << 'A' << T->getSize() << '_';
2715 mangleType(T->getElementType());
2717 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2719 // decayed vla types (size 0) will just be skipped.
2720 if (T->getSizeExpr())
2721 mangleExpression(T->getSizeExpr());
2723 mangleType(T->getElementType());
2725 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2727 mangleExpression(T->getSizeExpr());
2729 mangleType(T->getElementType());
2731 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2733 mangleType(T->getElementType());
2736 // <type> ::= <pointer-to-member-type>
2737 // <pointer-to-member-type> ::= M <class type> <member type>
2738 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2740 mangleType(QualType(T->getClass(), 0));
2741 QualType PointeeType = T->getPointeeType();
2742 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2745 // Itanium C++ ABI 5.1.8:
2747 // The type of a non-static member function is considered to be different,
2748 // for the purposes of substitution, from the type of a namespace-scope or
2749 // static member function whose type appears similar. The types of two
2750 // non-static member functions are considered to be different, for the
2751 // purposes of substitution, if the functions are members of different
2752 // classes. In other words, for the purposes of substitution, the class of
2753 // which the function is a member is considered part of the type of
2756 // Given that we already substitute member function pointers as a
2757 // whole, the net effect of this rule is just to unconditionally
2758 // suppress substitution on the function type in a member pointer.
2759 // We increment the SeqID here to emulate adding an entry to the
2760 // substitution table.
2763 mangleType(PointeeType);
2766 // <type> ::= <template-param>
2767 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2768 mangleTemplateParameter(T->getIndex());
2771 // <type> ::= <template-param>
2772 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2773 // FIXME: not clear how to mangle this!
2774 // template <class T...> class A {
2775 // template <class U...> void foo(T(*)(U) x...);
2777 Out << "_SUBSTPACK_";
2780 // <type> ::= P <type> # pointer-to
2781 void CXXNameMangler::mangleType(const PointerType *T) {
2783 mangleType(T->getPointeeType());
2785 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2787 mangleType(T->getPointeeType());
2790 // <type> ::= R <type> # reference-to
2791 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2793 mangleType(T->getPointeeType());
2796 // <type> ::= O <type> # rvalue reference-to (C++0x)
2797 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2799 mangleType(T->getPointeeType());
2802 // <type> ::= C <type> # complex pair (C 2000)
2803 void CXXNameMangler::mangleType(const ComplexType *T) {
2805 mangleType(T->getElementType());
2808 // ARM's ABI for Neon vector types specifies that they should be mangled as
2809 // if they are structs (to match ARM's initial implementation). The
2810 // vector type must be one of the special types predefined by ARM.
2811 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2812 QualType EltType = T->getElementType();
2813 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2814 const char *EltName = nullptr;
2815 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2816 switch (cast<BuiltinType>(EltType)->getKind()) {
2817 case BuiltinType::SChar:
2818 case BuiltinType::UChar:
2819 EltName = "poly8_t";
2821 case BuiltinType::Short:
2822 case BuiltinType::UShort:
2823 EltName = "poly16_t";
2825 case BuiltinType::ULongLong:
2826 EltName = "poly64_t";
2828 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2831 switch (cast<BuiltinType>(EltType)->getKind()) {
2832 case BuiltinType::SChar: EltName = "int8_t"; break;
2833 case BuiltinType::UChar: EltName = "uint8_t"; break;
2834 case BuiltinType::Short: EltName = "int16_t"; break;
2835 case BuiltinType::UShort: EltName = "uint16_t"; break;
2836 case BuiltinType::Int: EltName = "int32_t"; break;
2837 case BuiltinType::UInt: EltName = "uint32_t"; break;
2838 case BuiltinType::LongLong: EltName = "int64_t"; break;
2839 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2840 case BuiltinType::Double: EltName = "float64_t"; break;
2841 case BuiltinType::Float: EltName = "float32_t"; break;
2842 case BuiltinType::Half: EltName = "float16_t";break;
2844 llvm_unreachable("unexpected Neon vector element type");
2847 const char *BaseName = nullptr;
2848 unsigned BitSize = (T->getNumElements() *
2849 getASTContext().getTypeSize(EltType));
2851 BaseName = "__simd64_";
2853 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2854 BaseName = "__simd128_";
2856 Out << strlen(BaseName) + strlen(EltName);
2857 Out << BaseName << EltName;
2860 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2861 switch (EltType->getKind()) {
2862 case BuiltinType::SChar:
2864 case BuiltinType::Short:
2866 case BuiltinType::Int:
2868 case BuiltinType::Long:
2869 case BuiltinType::LongLong:
2871 case BuiltinType::UChar:
2873 case BuiltinType::UShort:
2875 case BuiltinType::UInt:
2877 case BuiltinType::ULong:
2878 case BuiltinType::ULongLong:
2880 case BuiltinType::Half:
2882 case BuiltinType::Float:
2884 case BuiltinType::Double:
2887 llvm_unreachable("Unexpected vector element base type");
2891 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2892 // the equivalent internal name. The vector type must be one of the special
2893 // types predefined by ARM.
2894 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2895 QualType EltType = T->getElementType();
2896 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2898 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2899 (void)BitSize; // Silence warning.
2901 assert((BitSize == 64 || BitSize == 128) &&
2902 "Neon vector type not 64 or 128 bits");
2905 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2906 switch (cast<BuiltinType>(EltType)->getKind()) {
2907 case BuiltinType::UChar:
2910 case BuiltinType::UShort:
2913 case BuiltinType::ULong:
2914 case BuiltinType::ULongLong:
2918 llvm_unreachable("unexpected Neon polynomial vector element type");
2921 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2923 std::string TypeName =
2924 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2925 Out << TypeName.length() << TypeName;
2928 // GNU extension: vector types
2929 // <type> ::= <vector-type>
2930 // <vector-type> ::= Dv <positive dimension number> _
2931 // <extended element type>
2932 // ::= Dv [<dimension expression>] _ <element type>
2933 // <extended element type> ::= <element type>
2934 // ::= p # AltiVec vector pixel
2935 // ::= b # Altivec vector bool
2936 void CXXNameMangler::mangleType(const VectorType *T) {
2937 if ((T->getVectorKind() == VectorType::NeonVector ||
2938 T->getVectorKind() == VectorType::NeonPolyVector)) {
2939 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2940 llvm::Triple::ArchType Arch =
2941 getASTContext().getTargetInfo().getTriple().getArch();
2942 if ((Arch == llvm::Triple::aarch64 ||
2943 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2944 mangleAArch64NeonVectorType(T);
2946 mangleNeonVectorType(T);
2949 Out << "Dv" << T->getNumElements() << '_';
2950 if (T->getVectorKind() == VectorType::AltiVecPixel)
2952 else if (T->getVectorKind() == VectorType::AltiVecBool)
2955 mangleType(T->getElementType());
2957 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2958 mangleType(static_cast<const VectorType*>(T));
2960 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2962 mangleExpression(T->getSizeExpr());
2964 mangleType(T->getElementType());
2967 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2968 // <type> ::= Dp <type> # pack expansion (C++0x)
2970 mangleType(T->getPattern());
2973 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2974 mangleSourceName(T->getDecl()->getIdentifier());
2977 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2978 // Treat __kindof as a vendor extended type qualifier.
2979 if (T->isKindOfType())
2980 Out << "U8__kindof";
2982 if (!T->qual_empty()) {
2983 // Mangle protocol qualifiers.
2984 SmallString<64> QualStr;
2985 llvm::raw_svector_ostream QualOS(QualStr);
2986 QualOS << "objcproto";
2987 for (const auto *I : T->quals()) {
2988 StringRef name = I->getName();
2989 QualOS << name.size() << name;
2991 Out << 'U' << QualStr.size() << QualStr;
2994 mangleType(T->getBaseType());
2996 if (T->isSpecialized()) {
2997 // Mangle type arguments as I <type>+ E
2999 for (auto typeArg : T->getTypeArgs())
3000 mangleType(typeArg);
3005 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3006 Out << "U13block_pointer";
3007 mangleType(T->getPointeeType());
3010 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3011 // Mangle injected class name types as if the user had written the
3012 // specialization out fully. It may not actually be possible to see
3013 // this mangling, though.
3014 mangleType(T->getInjectedSpecializationType());
3017 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3018 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3019 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3021 if (mangleSubstitution(QualType(T, 0)))
3024 mangleTemplatePrefix(T->getTemplateName());
3026 // FIXME: GCC does not appear to mangle the template arguments when
3027 // the template in question is a dependent template name. Should we
3028 // emulate that badness?
3029 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3030 addSubstitution(QualType(T, 0));
3034 void CXXNameMangler::mangleType(const DependentNameType *T) {
3035 // Proposal by cxx-abi-dev, 2014-03-26
3036 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3037 // # dependent elaborated type specifier using
3039 // ::= Ts <name> # dependent elaborated type specifier using
3040 // # 'struct' or 'class'
3041 // ::= Tu <name> # dependent elaborated type specifier using
3043 // ::= Te <name> # dependent elaborated type specifier using
3045 switch (T->getKeyword()) {
3060 llvm_unreachable("unexpected keyword for dependent type name");
3062 // Typename types are always nested
3064 manglePrefix(T->getQualifier());
3065 mangleSourceName(T->getIdentifier());
3069 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3070 // Dependently-scoped template types are nested if they have a prefix.
3073 // TODO: avoid making this TemplateName.
3074 TemplateName Prefix =
3075 getASTContext().getDependentTemplateName(T->getQualifier(),
3076 T->getIdentifier());
3077 mangleTemplatePrefix(Prefix);
3079 // FIXME: GCC does not appear to mangle the template arguments when
3080 // the template in question is a dependent template name. Should we
3081 // emulate that badness?
3082 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3086 void CXXNameMangler::mangleType(const TypeOfType *T) {
3087 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3088 // "extension with parameters" mangling.
3092 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3093 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3094 // "extension with parameters" mangling.
3098 void CXXNameMangler::mangleType(const DecltypeType *T) {
3099 Expr *E = T->getUnderlyingExpr();
3101 // type ::= Dt <expression> E # decltype of an id-expression
3102 // # or class member access
3103 // ::= DT <expression> E # decltype of an expression
3105 // This purports to be an exhaustive list of id-expressions and
3106 // class member accesses. Note that we do not ignore parentheses;
3107 // parentheses change the semantics of decltype for these
3108 // expressions (and cause the mangler to use the other form).
3109 if (isa<DeclRefExpr>(E) ||
3110 isa<MemberExpr>(E) ||
3111 isa<UnresolvedLookupExpr>(E) ||
3112 isa<DependentScopeDeclRefExpr>(E) ||
3113 isa<CXXDependentScopeMemberExpr>(E) ||
3114 isa<UnresolvedMemberExpr>(E))
3118 mangleExpression(E);
3122 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3123 // If this is dependent, we need to record that. If not, we simply
3124 // mangle it as the underlying type since they are equivalent.
3125 if (T->isDependentType()) {
3128 switch (T->getUTTKind()) {
3129 case UnaryTransformType::EnumUnderlyingType:
3135 mangleType(T->getBaseType());
3138 void CXXNameMangler::mangleType(const AutoType *T) {
3139 QualType D = T->getDeducedType();
3140 // <builtin-type> ::= Da # dependent auto
3142 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3143 "shouldn't need to mangle __auto_type!");
3144 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3149 void CXXNameMangler::mangleType(const AtomicType *T) {
3150 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3151 // (Until there's a standardized mangling...)
3153 mangleType(T->getValueType());
3156 void CXXNameMangler::mangleType(const PipeType *T) {
3157 // Pipe type mangling rules are described in SPIR 2.0 specification
3158 // A.1 Data types and A.3 Summary of changes
3159 // <type> ::= 8ocl_pipe
3163 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3164 const llvm::APSInt &Value) {
3165 // <expr-primary> ::= L <type> <value number> E # integer literal
3169 if (T->isBooleanType()) {
3170 // Boolean values are encoded as 0/1.
3171 Out << (Value.getBoolValue() ? '1' : '0');
3173 mangleNumber(Value);
3179 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3180 // Ignore member expressions involving anonymous unions.
3181 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3182 if (!RT->getDecl()->isAnonymousStructOrUnion())
3184 const auto *ME = dyn_cast<MemberExpr>(Base);
3187 Base = ME->getBase();
3188 IsArrow = ME->isArrow();
3191 if (Base->isImplicitCXXThis()) {
3192 // Note: GCC mangles member expressions to the implicit 'this' as
3193 // *this., whereas we represent them as this->. The Itanium C++ ABI
3194 // does not specify anything here, so we follow GCC.
3197 Out << (IsArrow ? "pt" : "dt");
3198 mangleExpression(Base);
3202 /// Mangles a member expression.
3203 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3205 NestedNameSpecifier *qualifier,
3206 NamedDecl *firstQualifierLookup,
3207 DeclarationName member,
3208 const TemplateArgumentLoc *TemplateArgs,
3209 unsigned NumTemplateArgs,
3211 // <expression> ::= dt <expression> <unresolved-name>
3212 // ::= pt <expression> <unresolved-name>
3214 mangleMemberExprBase(base, isArrow);
3215 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3218 /// Look at the callee of the given call expression and determine if
3219 /// it's a parenthesized id-expression which would have triggered ADL
3221 static bool isParenthesizedADLCallee(const CallExpr *call) {
3222 const Expr *callee = call->getCallee();
3223 const Expr *fn = callee->IgnoreParens();
3225 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3226 // too, but for those to appear in the callee, it would have to be
3228 if (callee == fn) return false;
3230 // Must be an unresolved lookup.
3231 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3232 if (!lookup) return false;
3234 assert(!lookup->requiresADL());
3236 // Must be an unqualified lookup.
3237 if (lookup->getQualifier()) return false;
3239 // Must not have found a class member. Note that if one is a class
3240 // member, they're all class members.
3241 if (lookup->getNumDecls() > 0 &&
3242 (*lookup->decls_begin())->isCXXClassMember())
3245 // Otherwise, ADL would have been triggered.
3249 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3250 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3251 Out << CastEncoding;
3252 mangleType(ECE->getType());
3253 mangleExpression(ECE->getSubExpr());
3256 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3257 if (auto *Syntactic = InitList->getSyntacticForm())
3258 InitList = Syntactic;
3259 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3260 mangleExpression(InitList->getInit(i));
3263 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3264 // <expression> ::= <unary operator-name> <expression>
3265 // ::= <binary operator-name> <expression> <expression>
3266 // ::= <trinary operator-name> <expression> <expression> <expression>
3267 // ::= cv <type> expression # conversion with one argument
3268 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3269 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3270 // ::= sc <type> <expression> # static_cast<type> (expression)
3271 // ::= cc <type> <expression> # const_cast<type> (expression)
3272 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3273 // ::= st <type> # sizeof (a type)
3274 // ::= at <type> # alignof (a type)
3275 // ::= <template-param>
3276 // ::= <function-param>
3277 // ::= sr <type> <unqualified-name> # dependent name
3278 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3279 // ::= ds <expression> <expression> # expr.*expr
3280 // ::= sZ <template-param> # size of a parameter pack
3281 // ::= sZ <function-param> # size of a function parameter pack
3282 // ::= <expr-primary>
3283 // <expr-primary> ::= L <type> <value number> E # integer literal
3284 // ::= L <type <value float> E # floating literal
3285 // ::= L <mangled-name> E # external name
3286 // ::= fpT # 'this' expression
3287 QualType ImplicitlyConvertedToType;
3290 switch (E->getStmtClass()) {
3291 case Expr::NoStmtClass:
3292 #define ABSTRACT_STMT(Type)
3293 #define EXPR(Type, Base)
3294 #define STMT(Type, Base) \
3295 case Expr::Type##Class:
3296 #include "clang/AST/StmtNodes.inc"
3299 // These all can only appear in local or variable-initialization
3300 // contexts and so should never appear in a mangling.
3301 case Expr::AddrLabelExprClass:
3302 case Expr::DesignatedInitUpdateExprClass:
3303 case Expr::ImplicitValueInitExprClass:
3304 case Expr::ArrayInitLoopExprClass:
3305 case Expr::ArrayInitIndexExprClass:
3306 case Expr::NoInitExprClass:
3307 case Expr::ParenListExprClass:
3308 case Expr::LambdaExprClass:
3309 case Expr::MSPropertyRefExprClass:
3310 case Expr::MSPropertySubscriptExprClass:
3311 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3312 case Expr::OMPArraySectionExprClass:
3313 case Expr::CXXInheritedCtorInitExprClass:
3314 llvm_unreachable("unexpected statement kind");
3316 // FIXME: invent manglings for all these.
3317 case Expr::BlockExprClass:
3318 case Expr::ChooseExprClass:
3319 case Expr::CompoundLiteralExprClass:
3320 case Expr::DesignatedInitExprClass:
3321 case Expr::ExtVectorElementExprClass:
3322 case Expr::GenericSelectionExprClass:
3323 case Expr::ObjCEncodeExprClass:
3324 case Expr::ObjCIsaExprClass:
3325 case Expr::ObjCIvarRefExprClass:
3326 case Expr::ObjCMessageExprClass:
3327 case Expr::ObjCPropertyRefExprClass:
3328 case Expr::ObjCProtocolExprClass:
3329 case Expr::ObjCSelectorExprClass:
3330 case Expr::ObjCStringLiteralClass:
3331 case Expr::ObjCBoxedExprClass:
3332 case Expr::ObjCArrayLiteralClass:
3333 case Expr::ObjCDictionaryLiteralClass:
3334 case Expr::ObjCSubscriptRefExprClass:
3335 case Expr::ObjCIndirectCopyRestoreExprClass:
3336 case Expr::ObjCAvailabilityCheckExprClass:
3337 case Expr::OffsetOfExprClass:
3338 case Expr::PredefinedExprClass:
3339 case Expr::ShuffleVectorExprClass:
3340 case Expr::ConvertVectorExprClass:
3341 case Expr::StmtExprClass:
3342 case Expr::TypeTraitExprClass:
3343 case Expr::ArrayTypeTraitExprClass:
3344 case Expr::ExpressionTraitExprClass:
3345 case Expr::VAArgExprClass:
3346 case Expr::CUDAKernelCallExprClass:
3347 case Expr::AsTypeExprClass:
3348 case Expr::PseudoObjectExprClass:
3349 case Expr::AtomicExprClass:
3352 // As bad as this diagnostic is, it's better than crashing.
3353 DiagnosticsEngine &Diags = Context.getDiags();
3354 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3355 "cannot yet mangle expression type %0");
3356 Diags.Report(E->getExprLoc(), DiagID)
3357 << E->getStmtClassName() << E->getSourceRange();
3362 case Expr::CXXUuidofExprClass: {
3363 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3364 if (UE->isTypeOperand()) {
3365 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3366 Out << "u8__uuidoft";
3369 Expr *UuidExp = UE->getExprOperand();
3370 Out << "u8__uuidofz";
3371 mangleExpression(UuidExp, Arity);
3376 // Even gcc-4.5 doesn't mangle this.
3377 case Expr::BinaryConditionalOperatorClass: {
3378 DiagnosticsEngine &Diags = Context.getDiags();
3380 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3381 "?: operator with omitted middle operand cannot be mangled");
3382 Diags.Report(E->getExprLoc(), DiagID)
3383 << E->getStmtClassName() << E->getSourceRange();
3387 // These are used for internal purposes and cannot be meaningfully mangled.
3388 case Expr::OpaqueValueExprClass:
3389 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3391 case Expr::InitListExprClass: {
3393 mangleInitListElements(cast<InitListExpr>(E));
3398 case Expr::CXXDefaultArgExprClass:
3399 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3402 case Expr::CXXDefaultInitExprClass:
3403 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3406 case Expr::CXXStdInitializerListExprClass:
3407 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3410 case Expr::SubstNonTypeTemplateParmExprClass:
3411 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3415 case Expr::UserDefinedLiteralClass:
3416 // We follow g++'s approach of mangling a UDL as a call to the literal
3418 case Expr::CXXMemberCallExprClass: // fallthrough
3419 case Expr::CallExprClass: {
3420 const CallExpr *CE = cast<CallExpr>(E);
3422 // <expression> ::= cp <simple-id> <expression>* E
3423 // We use this mangling only when the call would use ADL except
3424 // for being parenthesized. Per discussion with David
3425 // Vandervoorde, 2011.04.25.
3426 if (isParenthesizedADLCallee(CE)) {
3428 // The callee here is a parenthesized UnresolvedLookupExpr with
3429 // no qualifier and should always get mangled as a <simple-id>
3432 // <expression> ::= cl <expression>* E
3437 unsigned CallArity = CE->getNumArgs();
3438 for (const Expr *Arg : CE->arguments())
3439 if (isa<PackExpansionExpr>(Arg))
3440 CallArity = UnknownArity;
3442 mangleExpression(CE->getCallee(), CallArity);
3443 for (const Expr *Arg : CE->arguments())
3444 mangleExpression(Arg);
3449 case Expr::CXXNewExprClass: {
3450 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3451 if (New->isGlobalNew()) Out << "gs";
3452 Out << (New->isArray() ? "na" : "nw");
3453 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3454 E = New->placement_arg_end(); I != E; ++I)
3455 mangleExpression(*I);
3457 mangleType(New->getAllocatedType());
3458 if (New->hasInitializer()) {
3459 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3463 const Expr *Init = New->getInitializer();
3464 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3465 // Directly inline the initializers.
3466 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3469 mangleExpression(*I);
3470 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3471 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3472 mangleExpression(PLE->getExpr(i));
3473 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3474 isa<InitListExpr>(Init)) {
3475 // Only take InitListExprs apart for list-initialization.
3476 mangleInitListElements(cast<InitListExpr>(Init));
3478 mangleExpression(Init);
3484 case Expr::CXXPseudoDestructorExprClass: {
3485 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3486 if (const Expr *Base = PDE->getBase())
3487 mangleMemberExprBase(Base, PDE->isArrow());
3488 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3490 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3492 mangleUnresolvedPrefix(Qualifier,
3493 /*Recursive=*/true);
3494 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3498 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3501 } else if (Qualifier) {
3502 mangleUnresolvedPrefix(Qualifier);
3504 // <base-unresolved-name> ::= dn <destructor-name>
3506 QualType DestroyedType = PDE->getDestroyedType();
3507 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3511 case Expr::MemberExprClass: {
3512 const MemberExpr *ME = cast<MemberExpr>(E);
3513 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3514 ME->getQualifier(), nullptr,
3515 ME->getMemberDecl()->getDeclName(),
3516 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3521 case Expr::UnresolvedMemberExprClass: {
3522 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3523 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3524 ME->isArrow(), ME->getQualifier(), nullptr,
3525 ME->getMemberName(),
3526 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3531 case Expr::CXXDependentScopeMemberExprClass: {
3532 const CXXDependentScopeMemberExpr *ME
3533 = cast<CXXDependentScopeMemberExpr>(E);
3534 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3535 ME->isArrow(), ME->getQualifier(),
3536 ME->getFirstQualifierFoundInScope(),
3538 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3543 case Expr::UnresolvedLookupExprClass: {
3544 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3545 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3546 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3551 case Expr::CXXUnresolvedConstructExprClass: {
3552 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3553 unsigned N = CE->arg_size();
3556 mangleType(CE->getType());
3557 if (N != 1) Out << '_';
3558 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3559 if (N != 1) Out << 'E';
3563 case Expr::CXXConstructExprClass: {
3564 const auto *CE = cast<CXXConstructExpr>(E);
3565 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3567 CE->getNumArgs() >= 1 &&
3568 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3569 "implicit CXXConstructExpr must have one argument");
3570 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3573 for (auto *E : CE->arguments())
3574 mangleExpression(E);
3579 case Expr::CXXTemporaryObjectExprClass: {
3580 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3581 unsigned N = CE->getNumArgs();
3582 bool List = CE->isListInitialization();
3588 mangleType(CE->getType());
3589 if (!List && N != 1)
3591 if (CE->isStdInitListInitialization()) {
3592 // We implicitly created a std::initializer_list<T> for the first argument
3593 // of a constructor of type U in an expression of the form U{a, b, c}.
3594 // Strip all the semantic gunk off the initializer list.
3596 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3597 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3598 mangleInitListElements(ILE);
3600 for (auto *E : CE->arguments())
3601 mangleExpression(E);
3608 case Expr::CXXScalarValueInitExprClass:
3610 mangleType(E->getType());
3614 case Expr::CXXNoexceptExprClass:
3616 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3619 case Expr::UnaryExprOrTypeTraitExprClass: {
3620 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3622 if (!SAE->isInstantiationDependent()) {
3624 // If the operand of a sizeof or alignof operator is not
3625 // instantiation-dependent it is encoded as an integer literal
3626 // reflecting the result of the operator.
3628 // If the result of the operator is implicitly converted to a known
3629 // integer type, that type is used for the literal; otherwise, the type
3630 // of std::size_t or std::ptrdiff_t is used.
3631 QualType T = (ImplicitlyConvertedToType.isNull() ||
3632 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3633 : ImplicitlyConvertedToType;
3634 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3635 mangleIntegerLiteral(T, V);
3639 switch(SAE->getKind()) {
3646 case UETT_VecStep: {
3647 DiagnosticsEngine &Diags = Context.getDiags();
3648 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3649 "cannot yet mangle vec_step expression");
3650 Diags.Report(DiagID);
3653 case UETT_OpenMPRequiredSimdAlign:
3654 DiagnosticsEngine &Diags = Context.getDiags();
3655 unsigned DiagID = Diags.getCustomDiagID(
3656 DiagnosticsEngine::Error,
3657 "cannot yet mangle __builtin_omp_required_simd_align expression");
3658 Diags.Report(DiagID);
3661 if (SAE->isArgumentType()) {
3663 mangleType(SAE->getArgumentType());
3666 mangleExpression(SAE->getArgumentExpr());
3671 case Expr::CXXThrowExprClass: {
3672 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3673 // <expression> ::= tw <expression> # throw expression
3675 if (TE->getSubExpr()) {
3677 mangleExpression(TE->getSubExpr());
3684 case Expr::CXXTypeidExprClass: {
3685 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3686 // <expression> ::= ti <type> # typeid (type)
3687 // ::= te <expression> # typeid (expression)
3688 if (TIE->isTypeOperand()) {
3690 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3693 mangleExpression(TIE->getExprOperand());
3698 case Expr::CXXDeleteExprClass: {
3699 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3700 // <expression> ::= [gs] dl <expression> # [::] delete expr
3701 // ::= [gs] da <expression> # [::] delete [] expr
3702 if (DE->isGlobalDelete()) Out << "gs";
3703 Out << (DE->isArrayForm() ? "da" : "dl");
3704 mangleExpression(DE->getArgument());
3708 case Expr::UnaryOperatorClass: {
3709 const UnaryOperator *UO = cast<UnaryOperator>(E);
3710 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3712 mangleExpression(UO->getSubExpr());
3716 case Expr::ArraySubscriptExprClass: {
3717 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3719 // Array subscript is treated as a syntactically weird form of
3722 mangleExpression(AE->getLHS());
3723 mangleExpression(AE->getRHS());
3727 case Expr::CompoundAssignOperatorClass: // fallthrough
3728 case Expr::BinaryOperatorClass: {
3729 const BinaryOperator *BO = cast<BinaryOperator>(E);
3730 if (BO->getOpcode() == BO_PtrMemD)
3733 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3735 mangleExpression(BO->getLHS());
3736 mangleExpression(BO->getRHS());
3740 case Expr::ConditionalOperatorClass: {
3741 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3742 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3743 mangleExpression(CO->getCond());
3744 mangleExpression(CO->getLHS(), Arity);
3745 mangleExpression(CO->getRHS(), Arity);
3749 case Expr::ImplicitCastExprClass: {
3750 ImplicitlyConvertedToType = E->getType();
3751 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3755 case Expr::ObjCBridgedCastExprClass: {
3756 // Mangle ownership casts as a vendor extended operator __bridge,
3757 // __bridge_transfer, or __bridge_retain.
3758 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3759 Out << "v1U" << Kind.size() << Kind;
3761 // Fall through to mangle the cast itself.
3763 case Expr::CStyleCastExprClass:
3764 mangleCastExpression(E, "cv");
3767 case Expr::CXXFunctionalCastExprClass: {
3768 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3769 // FIXME: Add isImplicit to CXXConstructExpr.
3770 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3771 if (CCE->getParenOrBraceRange().isInvalid())
3772 Sub = CCE->getArg(0)->IgnoreImplicit();
3773 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3774 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3775 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3777 mangleType(E->getType());
3778 mangleInitListElements(IL);
3781 mangleCastExpression(E, "cv");
3786 case Expr::CXXStaticCastExprClass:
3787 mangleCastExpression(E, "sc");
3789 case Expr::CXXDynamicCastExprClass:
3790 mangleCastExpression(E, "dc");
3792 case Expr::CXXReinterpretCastExprClass:
3793 mangleCastExpression(E, "rc");
3795 case Expr::CXXConstCastExprClass:
3796 mangleCastExpression(E, "cc");
3799 case Expr::CXXOperatorCallExprClass: {
3800 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3801 unsigned NumArgs = CE->getNumArgs();
3802 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
3803 // (the enclosing MemberExpr covers the syntactic portion).
3804 if (CE->getOperator() != OO_Arrow)
3805 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3806 // Mangle the arguments.
3807 for (unsigned i = 0; i != NumArgs; ++i)
3808 mangleExpression(CE->getArg(i));
3812 case Expr::ParenExprClass:
3813 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3816 case Expr::DeclRefExprClass: {
3817 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3819 switch (D->getKind()) {
3821 // <expr-primary> ::= L <mangled-name> E # external name
3828 mangleFunctionParam(cast<ParmVarDecl>(D));
3831 case Decl::EnumConstant: {
3832 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3833 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3837 case Decl::NonTypeTemplateParm: {
3838 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3839 mangleTemplateParameter(PD->getIndex());
3848 case Expr::SubstNonTypeTemplateParmPackExprClass:
3849 // FIXME: not clear how to mangle this!
3850 // template <unsigned N...> class A {
3851 // template <class U...> void foo(U (&x)[N]...);
3853 Out << "_SUBSTPACK_";
3856 case Expr::FunctionParmPackExprClass: {
3857 // FIXME: not clear how to mangle this!
3858 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3859 Out << "v110_SUBSTPACK";
3860 mangleFunctionParam(FPPE->getParameterPack());
3864 case Expr::DependentScopeDeclRefExprClass: {
3865 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3866 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
3867 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
3872 case Expr::CXXBindTemporaryExprClass:
3873 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3876 case Expr::ExprWithCleanupsClass:
3877 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3880 case Expr::FloatingLiteralClass: {
3881 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3883 mangleType(FL->getType());
3884 mangleFloat(FL->getValue());
3889 case Expr::CharacterLiteralClass:
3891 mangleType(E->getType());
3892 Out << cast<CharacterLiteral>(E)->getValue();
3896 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3897 case Expr::ObjCBoolLiteralExprClass:
3899 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3903 case Expr::CXXBoolLiteralExprClass:
3905 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3909 case Expr::IntegerLiteralClass: {
3910 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3911 if (E->getType()->isSignedIntegerType())
3912 Value.setIsSigned(true);
3913 mangleIntegerLiteral(E->getType(), Value);
3917 case Expr::ImaginaryLiteralClass: {
3918 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3919 // Mangle as if a complex literal.
3920 // Proposal from David Vandevoorde, 2010.06.30.
3922 mangleType(E->getType());
3923 if (const FloatingLiteral *Imag =
3924 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3925 // Mangle a floating-point zero of the appropriate type.
3926 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3928 mangleFloat(Imag->getValue());
3931 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3932 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3933 Value.setIsSigned(true);
3934 mangleNumber(Value);
3940 case Expr::StringLiteralClass: {
3941 // Revised proposal from David Vandervoorde, 2010.07.15.
3943 assert(isa<ConstantArrayType>(E->getType()));
3944 mangleType(E->getType());
3949 case Expr::GNUNullExprClass:
3950 // FIXME: should this really be mangled the same as nullptr?
3953 case Expr::CXXNullPtrLiteralExprClass: {
3958 case Expr::PackExpansionExprClass:
3960 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3963 case Expr::SizeOfPackExprClass: {
3964 auto *SPE = cast<SizeOfPackExpr>(E);
3965 if (SPE->isPartiallySubstituted()) {
3967 for (const auto &A : SPE->getPartialArguments())
3968 mangleTemplateArg(A);
3974 const NamedDecl *Pack = SPE->getPack();
3975 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3976 mangleTemplateParameter(TTP->getIndex());
3977 else if (const NonTypeTemplateParmDecl *NTTP
3978 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3979 mangleTemplateParameter(NTTP->getIndex());
3980 else if (const TemplateTemplateParmDecl *TempTP
3981 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3982 mangleTemplateParameter(TempTP->getIndex());
3984 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3988 case Expr::MaterializeTemporaryExprClass: {
3989 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3993 case Expr::CXXFoldExprClass: {
3994 auto *FE = cast<CXXFoldExpr>(E);
3995 if (FE->isLeftFold())
3996 Out << (FE->getInit() ? "fL" : "fl");
3998 Out << (FE->getInit() ? "fR" : "fr");
4000 if (FE->getOperator() == BO_PtrMemD)
4004 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4008 mangleExpression(FE->getLHS());
4010 mangleExpression(FE->getRHS());
4014 case Expr::CXXThisExprClass:
4018 case Expr::CoawaitExprClass:
4019 // FIXME: Propose a non-vendor mangling.
4020 Out << "v18co_await";
4021 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4024 case Expr::CoyieldExprClass:
4025 // FIXME: Propose a non-vendor mangling.
4026 Out << "v18co_yield";
4027 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4032 /// Mangle an expression which refers to a parameter variable.
4034 /// <expression> ::= <function-param>
4035 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4036 /// <function-param> ::= fp <top-level CV-qualifiers>
4037 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4038 /// <function-param> ::= fL <L-1 non-negative number>
4039 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4040 /// <function-param> ::= fL <L-1 non-negative number>
4041 /// p <top-level CV-qualifiers>
4042 /// <I-1 non-negative number> _ # L > 0, I > 0
4044 /// L is the nesting depth of the parameter, defined as 1 if the
4045 /// parameter comes from the innermost function prototype scope
4046 /// enclosing the current context, 2 if from the next enclosing
4047 /// function prototype scope, and so on, with one special case: if
4048 /// we've processed the full parameter clause for the innermost
4049 /// function type, then L is one less. This definition conveniently
4050 /// makes it irrelevant whether a function's result type was written
4051 /// trailing or leading, but is otherwise overly complicated; the
4052 /// numbering was first designed without considering references to
4053 /// parameter in locations other than return types, and then the
4054 /// mangling had to be generalized without changing the existing
4057 /// I is the zero-based index of the parameter within its parameter
4058 /// declaration clause. Note that the original ABI document describes
4059 /// this using 1-based ordinals.
4060 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4061 unsigned parmDepth = parm->getFunctionScopeDepth();
4062 unsigned parmIndex = parm->getFunctionScopeIndex();
4065 // parmDepth does not include the declaring function prototype.
4066 // FunctionTypeDepth does account for that.
4067 assert(parmDepth < FunctionTypeDepth.getDepth());
4068 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4069 if (FunctionTypeDepth.isInResultType())
4072 if (nestingDepth == 0) {
4075 Out << "fL" << (nestingDepth - 1) << 'p';
4078 // Top-level qualifiers. We don't have to worry about arrays here,
4079 // because parameters declared as arrays should already have been
4080 // transformed to have pointer type. FIXME: apparently these don't
4081 // get mangled if used as an rvalue of a known non-class type?
4082 assert(!parm->getType()->isArrayType()
4083 && "parameter's type is still an array type?");
4084 mangleQualifiers(parm->getType().getQualifiers());
4087 if (parmIndex != 0) {
4088 Out << (parmIndex - 1);
4093 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4094 const CXXRecordDecl *InheritedFrom) {
4095 // <ctor-dtor-name> ::= C1 # complete object constructor
4096 // ::= C2 # base object constructor
4097 // ::= CI1 <type> # complete inheriting constructor
4098 // ::= CI2 <type> # base inheriting constructor
4100 // In addition, C5 is a comdat name with C1 and C2 in it.
4114 case Ctor_DefaultClosure:
4115 case Ctor_CopyingClosure:
4116 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4119 mangleName(InheritedFrom);
4122 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4123 // <ctor-dtor-name> ::= D0 # deleting destructor
4124 // ::= D1 # complete object destructor
4125 // ::= D2 # base object destructor
4127 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4144 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4145 unsigned NumTemplateArgs) {
4146 // <template-args> ::= I <template-arg>+ E
4148 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4149 mangleTemplateArg(TemplateArgs[i].getArgument());
4153 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4154 // <template-args> ::= I <template-arg>+ E
4156 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4157 mangleTemplateArg(AL[i]);
4161 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4162 unsigned NumTemplateArgs) {
4163 // <template-args> ::= I <template-arg>+ E
4165 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4166 mangleTemplateArg(TemplateArgs[i]);
4170 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4171 // <template-arg> ::= <type> # type or template
4172 // ::= X <expression> E # expression
4173 // ::= <expr-primary> # simple expressions
4174 // ::= J <template-arg>* E # argument pack
4175 if (!A.isInstantiationDependent() || A.isDependent())
4176 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4178 switch (A.getKind()) {
4179 case TemplateArgument::Null:
4180 llvm_unreachable("Cannot mangle NULL template argument");
4182 case TemplateArgument::Type:
4183 mangleType(A.getAsType());
4185 case TemplateArgument::Template:
4186 // This is mangled as <type>.
4187 mangleType(A.getAsTemplate());
4189 case TemplateArgument::TemplateExpansion:
4190 // <type> ::= Dp <type> # pack expansion (C++0x)
4192 mangleType(A.getAsTemplateOrTemplatePattern());
4194 case TemplateArgument::Expression: {
4195 // It's possible to end up with a DeclRefExpr here in certain
4196 // dependent cases, in which case we should mangle as a
4198 const Expr *E = A.getAsExpr()->IgnoreParens();
4199 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4200 const ValueDecl *D = DRE->getDecl();
4201 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4210 mangleExpression(E);
4214 case TemplateArgument::Integral:
4215 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4217 case TemplateArgument::Declaration: {
4218 // <expr-primary> ::= L <mangled-name> E # external name
4219 // Clang produces AST's where pointer-to-member-function expressions
4220 // and pointer-to-function expressions are represented as a declaration not
4221 // an expression. We compensate for it here to produce the correct mangling.
4222 ValueDecl *D = A.getAsDecl();
4223 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4224 if (compensateMangling) {
4226 mangleOperatorName(OO_Amp, 1);
4230 // References to external entities use the mangled name; if the name would
4231 // not normally be mangled then mangle it as unqualified.
4235 if (compensateMangling)
4240 case TemplateArgument::NullPtr: {
4241 // <expr-primary> ::= L <type> 0 E
4243 mangleType(A.getNullPtrType());
4247 case TemplateArgument::Pack: {
4248 // <template-arg> ::= J <template-arg>* E
4250 for (const auto &P : A.pack_elements())
4251 mangleTemplateArg(P);
4257 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4258 // <template-param> ::= T_ # first template parameter
4259 // ::= T <parameter-2 non-negative number> _
4263 Out << 'T' << (Index - 1) << '_';
4266 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4269 else if (SeqID > 1) {
4272 // <seq-id> is encoded in base-36, using digits and upper case letters.
4273 char Buffer[7]; // log(2**32) / log(36) ~= 7
4274 MutableArrayRef<char> BufferRef(Buffer);
4275 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4277 for (; SeqID != 0; SeqID /= 36) {
4278 unsigned C = SeqID % 36;
4279 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4282 Out.write(I.base(), I - BufferRef.rbegin());
4287 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4288 bool result = mangleSubstitution(tname);
4289 assert(result && "no existing substitution for template name");
4293 // <substitution> ::= S <seq-id> _
4295 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4296 // Try one of the standard substitutions first.
4297 if (mangleStandardSubstitution(ND))
4300 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4301 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4304 /// Determine whether the given type has any qualifiers that are relevant for
4306 static bool hasMangledSubstitutionQualifiers(QualType T) {
4307 Qualifiers Qs = T.getQualifiers();
4308 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4311 bool CXXNameMangler::mangleSubstitution(QualType T) {
4312 if (!hasMangledSubstitutionQualifiers(T)) {
4313 if (const RecordType *RT = T->getAs<RecordType>())
4314 return mangleSubstitution(RT->getDecl());
4317 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4319 return mangleSubstitution(TypePtr);
4322 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4323 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4324 return mangleSubstitution(TD);
4326 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4327 return mangleSubstitution(
4328 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4331 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4332 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4333 if (I == Substitutions.end())
4336 unsigned SeqID = I->second;
4343 static bool isCharType(QualType T) {
4347 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4348 T->isSpecificBuiltinType(BuiltinType::Char_U);
4351 /// Returns whether a given type is a template specialization of a given name
4352 /// with a single argument of type char.
4353 static bool isCharSpecialization(QualType T, const char *Name) {
4357 const RecordType *RT = T->getAs<RecordType>();
4361 const ClassTemplateSpecializationDecl *SD =
4362 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4366 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4369 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4370 if (TemplateArgs.size() != 1)
4373 if (!isCharType(TemplateArgs[0].getAsType()))
4376 return SD->getIdentifier()->getName() == Name;
4379 template <std::size_t StrLen>
4380 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4381 const char (&Str)[StrLen]) {
4382 if (!SD->getIdentifier()->isStr(Str))
4385 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4386 if (TemplateArgs.size() != 2)
4389 if (!isCharType(TemplateArgs[0].getAsType()))
4392 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4398 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4399 // <substitution> ::= St # ::std::
4400 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4407 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4408 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4411 // <substitution> ::= Sa # ::std::allocator
4412 if (TD->getIdentifier()->isStr("allocator")) {
4417 // <<substitution> ::= Sb # ::std::basic_string
4418 if (TD->getIdentifier()->isStr("basic_string")) {
4424 if (const ClassTemplateSpecializationDecl *SD =
4425 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4426 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4429 // <substitution> ::= Ss # ::std::basic_string<char,
4430 // ::std::char_traits<char>,
4431 // ::std::allocator<char> >
4432 if (SD->getIdentifier()->isStr("basic_string")) {
4433 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4435 if (TemplateArgs.size() != 3)
4438 if (!isCharType(TemplateArgs[0].getAsType()))
4441 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4444 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4451 // <substitution> ::= Si # ::std::basic_istream<char,
4452 // ::std::char_traits<char> >
4453 if (isStreamCharSpecialization(SD, "basic_istream")) {
4458 // <substitution> ::= So # ::std::basic_ostream<char,
4459 // ::std::char_traits<char> >
4460 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4465 // <substitution> ::= Sd # ::std::basic_iostream<char,
4466 // ::std::char_traits<char> >
4467 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4475 void CXXNameMangler::addSubstitution(QualType T) {
4476 if (!hasMangledSubstitutionQualifiers(T)) {
4477 if (const RecordType *RT = T->getAs<RecordType>()) {
4478 addSubstitution(RT->getDecl());
4483 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4484 addSubstitution(TypePtr);
4487 void CXXNameMangler::addSubstitution(TemplateName Template) {
4488 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4489 return addSubstitution(TD);
4491 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4492 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4495 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4496 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4497 Substitutions[Ptr] = SeqID++;
4500 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4501 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4502 if (Other->SeqID > SeqID) {
4503 Substitutions.swap(Other->Substitutions);
4504 SeqID = Other->SeqID;
4508 CXXNameMangler::AbiTagList
4509 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4510 // When derived abi tags are disabled there is no need to make any list.
4511 if (DisableDerivedAbiTags)
4512 return AbiTagList();
4514 llvm::raw_null_ostream NullOutStream;
4515 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4516 TrackReturnTypeTags.disableDerivedAbiTags();
4518 const FunctionProtoType *Proto =
4519 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4520 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4521 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4522 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4524 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4527 CXXNameMangler::AbiTagList
4528 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4529 // When derived abi tags are disabled there is no need to make any list.
4530 if (DisableDerivedAbiTags)
4531 return AbiTagList();
4533 llvm::raw_null_ostream NullOutStream;
4534 CXXNameMangler TrackVariableType(*this, NullOutStream);
4535 TrackVariableType.disableDerivedAbiTags();
4537 TrackVariableType.mangleType(VD->getType());
4539 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4542 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4543 const VarDecl *VD) {
4544 llvm::raw_null_ostream NullOutStream;
4545 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4546 TrackAbiTags.mangle(VD);
4547 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4552 /// Mangles the name of the declaration D and emits that name to the given
4555 /// If the declaration D requires a mangled name, this routine will emit that
4556 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4557 /// and this routine will return false. In this case, the caller should just
4558 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4560 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4562 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4563 "Invalid mangleName() call, argument is not a variable or function!");
4564 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4565 "Invalid mangleName() call on 'structor decl!");
4567 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4568 getASTContext().getSourceManager(),
4569 "Mangling declaration");
4571 CXXNameMangler Mangler(*this, Out, D);
4575 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4578 CXXNameMangler Mangler(*this, Out, D, Type);
4582 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4585 CXXNameMangler Mangler(*this, Out, D, Type);
4589 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4591 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4595 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4597 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4601 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4602 const ThunkInfo &Thunk,
4604 // <special-name> ::= T <call-offset> <base encoding>
4605 // # base is the nominal target function of thunk
4606 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4607 // # base is the nominal target function of thunk
4608 // # first call-offset is 'this' adjustment
4609 // # second call-offset is result adjustment
4611 assert(!isa<CXXDestructorDecl>(MD) &&
4612 "Use mangleCXXDtor for destructor decls!");
4613 CXXNameMangler Mangler(*this, Out);
4614 Mangler.getStream() << "_ZT";
4615 if (!Thunk.Return.isEmpty())
4616 Mangler.getStream() << 'c';
4618 // Mangle the 'this' pointer adjustment.
4619 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4620 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4622 // Mangle the return pointer adjustment if there is one.
4623 if (!Thunk.Return.isEmpty())
4624 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4625 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4627 Mangler.mangleFunctionEncoding(MD);
4630 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4631 const CXXDestructorDecl *DD, CXXDtorType Type,
4632 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4633 // <special-name> ::= T <call-offset> <base encoding>
4634 // # base is the nominal target function of thunk
4635 CXXNameMangler Mangler(*this, Out, DD, Type);
4636 Mangler.getStream() << "_ZT";
4638 // Mangle the 'this' pointer adjustment.
4639 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4640 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4642 Mangler.mangleFunctionEncoding(DD);
4645 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4646 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4648 // <special-name> ::= GV <object name> # Guard variable for one-time
4650 CXXNameMangler Mangler(*this, Out);
4651 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4652 // be a bug that is fixed in trunk.
4653 Mangler.getStream() << "_ZGV";
4654 Mangler.mangleName(D);
4657 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4659 // These symbols are internal in the Itanium ABI, so the names don't matter.
4660 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4661 // avoid duplicate symbols.
4662 Out << "__cxx_global_var_init";
4665 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4667 // Prefix the mangling of D with __dtor_.
4668 CXXNameMangler Mangler(*this, Out);
4669 Mangler.getStream() << "__dtor_";
4670 if (shouldMangleDeclName(D))
4673 Mangler.getStream() << D->getName();
4676 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4677 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4678 CXXNameMangler Mangler(*this, Out);
4679 Mangler.getStream() << "__filt_";
4680 if (shouldMangleDeclName(EnclosingDecl))
4681 Mangler.mangle(EnclosingDecl);
4683 Mangler.getStream() << EnclosingDecl->getName();
4686 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4687 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4688 CXXNameMangler Mangler(*this, Out);
4689 Mangler.getStream() << "__fin_";
4690 if (shouldMangleDeclName(EnclosingDecl))
4691 Mangler.mangle(EnclosingDecl);
4693 Mangler.getStream() << EnclosingDecl->getName();
4696 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4698 // <special-name> ::= TH <object name>
4699 CXXNameMangler Mangler(*this, Out);
4700 Mangler.getStream() << "_ZTH";
4701 Mangler.mangleName(D);
4705 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4707 // <special-name> ::= TW <object name>
4708 CXXNameMangler Mangler(*this, Out);
4709 Mangler.getStream() << "_ZTW";
4710 Mangler.mangleName(D);
4713 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4714 unsigned ManglingNumber,
4716 // We match the GCC mangling here.
4717 // <special-name> ::= GR <object name>
4718 CXXNameMangler Mangler(*this, Out);
4719 Mangler.getStream() << "_ZGR";
4720 Mangler.mangleName(D);
4721 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4722 Mangler.mangleSeqID(ManglingNumber - 1);
4725 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4727 // <special-name> ::= TV <type> # virtual table
4728 CXXNameMangler Mangler(*this, Out);
4729 Mangler.getStream() << "_ZTV";
4730 Mangler.mangleNameOrStandardSubstitution(RD);
4733 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4735 // <special-name> ::= TT <type> # VTT structure
4736 CXXNameMangler Mangler(*this, Out);
4737 Mangler.getStream() << "_ZTT";
4738 Mangler.mangleNameOrStandardSubstitution(RD);
4741 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4743 const CXXRecordDecl *Type,
4745 // <special-name> ::= TC <type> <offset number> _ <base type>
4746 CXXNameMangler Mangler(*this, Out);
4747 Mangler.getStream() << "_ZTC";
4748 Mangler.mangleNameOrStandardSubstitution(RD);
4749 Mangler.getStream() << Offset;
4750 Mangler.getStream() << '_';
4751 Mangler.mangleNameOrStandardSubstitution(Type);
4754 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4755 // <special-name> ::= TI <type> # typeinfo structure
4756 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4757 CXXNameMangler Mangler(*this, Out);
4758 Mangler.getStream() << "_ZTI";
4759 Mangler.mangleType(Ty);
4762 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4764 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4765 CXXNameMangler Mangler(*this, Out);
4766 Mangler.getStream() << "_ZTS";
4767 Mangler.mangleType(Ty);
4770 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4771 mangleCXXRTTIName(Ty, Out);
4774 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4775 llvm_unreachable("Can't mangle string literals");
4778 ItaniumMangleContext *
4779 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4780 return new ItaniumMangleContextImpl(Context, Diags);