1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implements C++ name mangling according to the Itanium C++ ABI,
10 // which is used in GCC 3.2 and newer (and many compilers that are
11 // ABI-compatible with GCC):
13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
15 //===----------------------------------------------------------------------===//
16 #include "clang/AST/Mangle.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
35 using namespace clang;
39 /// Retrieve the declaration context that should be used when mangling the given
41 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
42 // The ABI assumes that lambda closure types that occur within
43 // default arguments live in the context of the function. However, due to
44 // the way in which Clang parses and creates function declarations, this is
45 // not the case: the lambda closure type ends up living in the context
46 // where the function itself resides, because the function declaration itself
47 // had not yet been created. Fix the context here.
48 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
50 if (ParmVarDecl *ContextParam
51 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
52 return ContextParam->getDeclContext();
55 // Perform the same check for block literals.
56 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
59 return ContextParam->getDeclContext();
62 const DeclContext *DC = D->getDeclContext();
63 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
64 isa<OMPDeclareMapperDecl>(DC)) {
65 return getEffectiveDeclContext(cast<Decl>(DC));
68 if (const auto *VD = dyn_cast<VarDecl>(D))
70 return VD->getASTContext().getTranslationUnitDecl();
72 if (const auto *FD = dyn_cast<FunctionDecl>(D))
74 return FD->getASTContext().getTranslationUnitDecl();
76 return DC->getRedeclContext();
79 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
80 return getEffectiveDeclContext(cast<Decl>(DC));
83 static bool isLocalContainerContext(const DeclContext *DC) {
84 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
87 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
88 const DeclContext *DC = getEffectiveDeclContext(D);
89 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
90 if (isLocalContainerContext(DC))
91 return dyn_cast<RecordDecl>(D);
93 DC = getEffectiveDeclContext(D);
98 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
99 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
100 return ftd->getTemplatedDecl();
105 static const NamedDecl *getStructor(const NamedDecl *decl) {
106 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
107 return (fn ? getStructor(fn) : decl);
110 static bool isLambda(const NamedDecl *ND) {
111 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
115 return Record->isLambda();
118 static const unsigned UnknownArity = ~0U;
120 class ItaniumMangleContextImpl : public ItaniumMangleContext {
121 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
122 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
123 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
126 explicit ItaniumMangleContextImpl(ASTContext &Context,
127 DiagnosticsEngine &Diags)
128 : ItaniumMangleContext(Context, Diags) {}
130 /// @name Mangler Entry Points
133 bool shouldMangleCXXName(const NamedDecl *D) override;
134 bool shouldMangleStringLiteral(const StringLiteral *) override {
137 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
138 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
139 raw_ostream &) override;
140 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
141 const ThisAdjustment &ThisAdjustment,
142 raw_ostream &) override;
143 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
144 raw_ostream &) override;
145 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
146 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
147 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
148 const CXXRecordDecl *Type, raw_ostream &) override;
149 void mangleCXXRTTI(QualType T, raw_ostream &) override;
150 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
151 void mangleTypeName(QualType T, raw_ostream &) override;
152 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
153 raw_ostream &) override;
154 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
155 raw_ostream &) override;
157 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
158 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
159 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
160 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
161 void mangleDynamicAtExitDestructor(const VarDecl *D,
162 raw_ostream &Out) override;
163 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164 raw_ostream &Out) override;
165 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166 raw_ostream &Out) override;
167 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169 raw_ostream &) override;
171 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
173 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
174 // Lambda closure types are already numbered.
178 // Anonymous tags are already numbered.
179 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
180 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
184 // Use the canonical number for externally visible decls.
185 if (ND->isExternallyVisible()) {
186 unsigned discriminator = getASTContext().getManglingNumber(ND);
187 if (discriminator == 1)
189 disc = discriminator - 2;
193 // Make up a reasonable number for internal decls.
194 unsigned &discriminator = Uniquifier[ND];
195 if (!discriminator) {
196 const DeclContext *DC = getEffectiveDeclContext(ND);
197 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
199 if (discriminator == 1)
201 disc = discriminator-2;
207 /// Manage the mangling of a single name.
208 class CXXNameMangler {
209 ItaniumMangleContextImpl &Context;
211 bool NullOut = false;
212 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
213 /// This mode is used when mangler creates another mangler recursively to
214 /// calculate ABI tags for the function return value or the variable type.
215 /// Also it is required to avoid infinite recursion in some cases.
216 bool DisableDerivedAbiTags = false;
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
224 /// The next substitution sequence number.
227 class FunctionTypeDepthState {
230 enum { InResultTypeMask = 1 };
233 FunctionTypeDepthState() : Bits(0) {}
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
251 void enterResultType() {
252 Bits |= InResultTypeMask;
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
266 // abi_tag is a gcc attribute, taking one or more strings called "tags".
267 // The goal is to annotate against which version of a library an object was
268 // built and to be able to provide backwards compatibility ("dual abi").
269 // For more information see docs/ItaniumMangleAbiTags.rst.
270 typedef SmallVector<StringRef, 4> AbiTagList;
272 // State to gather all implicit and explicit tags used in a mangled name.
273 // Must always have an instance of this while emitting any name to keep
275 class AbiTagState final {
277 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
283 AbiTagState(const AbiTagState &) = delete;
284 AbiTagState &operator=(const AbiTagState &) = delete;
286 ~AbiTagState() { pop(); }
288 void write(raw_ostream &Out, const NamedDecl *ND,
289 const AbiTagList *AdditionalAbiTags) {
290 ND = cast<NamedDecl>(ND->getCanonicalDecl());
291 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
293 !AdditionalAbiTags &&
294 "only function and variables need a list of additional abi tags");
295 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
296 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
297 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
298 AbiTag->tags().end());
300 // Don't emit abi tags for namespaces.
306 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
307 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
308 AbiTag->tags().end());
309 TagList.insert(TagList.end(), AbiTag->tags().begin(),
310 AbiTag->tags().end());
313 if (AdditionalAbiTags) {
314 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
315 AdditionalAbiTags->end());
316 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
317 AdditionalAbiTags->end());
321 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
323 writeSortedUniqueAbiTags(Out, TagList);
326 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
327 void setUsedAbiTags(const AbiTagList &AbiTags) {
328 UsedAbiTags = AbiTags;
331 const AbiTagList &getEmittedAbiTags() const {
332 return EmittedAbiTags;
335 const AbiTagList &getSortedUniqueUsedAbiTags() {
336 llvm::sort(UsedAbiTags);
337 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
343 //! All abi tags used implicitly or explicitly.
344 AbiTagList UsedAbiTags;
345 //! All explicit abi tags (i.e. not from namespace).
346 AbiTagList EmittedAbiTags;
348 AbiTagState *&LinkHead;
349 AbiTagState *Parent = nullptr;
352 assert(LinkHead == this &&
353 "abi tag link head must point to us on destruction");
355 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
356 UsedAbiTags.begin(), UsedAbiTags.end());
357 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
358 EmittedAbiTags.begin(),
359 EmittedAbiTags.end());
364 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
365 for (const auto &Tag : AbiTags) {
366 EmittedAbiTags.push_back(Tag);
374 AbiTagState *AbiTags = nullptr;
375 AbiTagState AbiTagsRoot;
377 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
378 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
380 ASTContext &getASTContext() const { return Context.getASTContext(); }
383 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
384 const NamedDecl *D = nullptr, bool NullOut_ = false)
385 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
386 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
387 // These can't be mangled without a ctor type or dtor type.
388 assert(!D || (!isa<CXXDestructorDecl>(D) &&
389 !isa<CXXConstructorDecl>(D)));
391 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
392 const CXXConstructorDecl *D, CXXCtorType Type)
393 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
394 SeqID(0), AbiTagsRoot(AbiTags) { }
395 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
396 const CXXDestructorDecl *D, CXXDtorType Type)
397 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
398 SeqID(0), AbiTagsRoot(AbiTags) { }
400 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
401 : Context(Outer.Context), Out(Out_), NullOut(false),
402 Structor(Outer.Structor), StructorType(Outer.StructorType),
403 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
404 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
406 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(true),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
412 raw_ostream &getStream() { return Out; }
414 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
415 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
417 void mangle(const NamedDecl *D);
418 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
419 void mangleNumber(const llvm::APSInt &I);
420 void mangleNumber(int64_t Number);
421 void mangleFloat(const llvm::APFloat &F);
422 void mangleFunctionEncoding(const FunctionDecl *FD);
423 void mangleSeqID(unsigned SeqID);
424 void mangleName(const NamedDecl *ND);
425 void mangleType(QualType T);
426 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
430 bool mangleSubstitution(const NamedDecl *ND);
431 bool mangleSubstitution(QualType T);
432 bool mangleSubstitution(TemplateName Template);
433 bool mangleSubstitution(uintptr_t Ptr);
435 void mangleExistingSubstitution(TemplateName name);
437 bool mangleStandardSubstitution(const NamedDecl *ND);
439 void addSubstitution(const NamedDecl *ND) {
440 ND = cast<NamedDecl>(ND->getCanonicalDecl());
442 addSubstitution(reinterpret_cast<uintptr_t>(ND));
444 void addSubstitution(QualType T);
445 void addSubstitution(TemplateName Template);
446 void addSubstitution(uintptr_t Ptr);
447 // Destructive copy substitutions from other mangler.
448 void extendSubstitutions(CXXNameMangler* Other);
450 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
451 bool recursive = false);
452 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
453 DeclarationName name,
454 const TemplateArgumentLoc *TemplateArgs,
455 unsigned NumTemplateArgs,
456 unsigned KnownArity = UnknownArity);
458 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
460 void mangleNameWithAbiTags(const NamedDecl *ND,
461 const AbiTagList *AdditionalAbiTags);
462 void mangleModuleName(const Module *M);
463 void mangleModuleNamePrefix(StringRef Name);
464 void mangleTemplateName(const TemplateDecl *TD,
465 const TemplateArgument *TemplateArgs,
466 unsigned NumTemplateArgs);
467 void mangleUnqualifiedName(const NamedDecl *ND,
468 const AbiTagList *AdditionalAbiTags) {
469 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
472 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
474 const AbiTagList *AdditionalAbiTags);
475 void mangleUnscopedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags);
477 void mangleUnscopedTemplateName(const TemplateDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
479 void mangleUnscopedTemplateName(TemplateName,
480 const AbiTagList *AdditionalAbiTags);
481 void mangleSourceName(const IdentifierInfo *II);
482 void mangleRegCallName(const IdentifierInfo *II);
483 void mangleSourceNameWithAbiTags(
484 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
485 void mangleLocalName(const Decl *D,
486 const AbiTagList *AdditionalAbiTags);
487 void mangleBlockForPrefix(const BlockDecl *Block);
488 void mangleUnqualifiedBlock(const BlockDecl *Block);
489 void mangleTemplateParamDecl(const NamedDecl *Decl);
490 void mangleLambda(const CXXRecordDecl *Lambda);
491 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
492 const AbiTagList *AdditionalAbiTags,
493 bool NoFunction=false);
494 void mangleNestedName(const TemplateDecl *TD,
495 const TemplateArgument *TemplateArgs,
496 unsigned NumTemplateArgs);
497 void manglePrefix(NestedNameSpecifier *qualifier);
498 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
499 void manglePrefix(QualType type);
500 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
501 void mangleTemplatePrefix(TemplateName Template);
502 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
503 StringRef Prefix = "");
504 void mangleOperatorName(DeclarationName Name, unsigned Arity);
505 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
506 void mangleVendorQualifier(StringRef qualifier);
507 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
508 void mangleRefQualifier(RefQualifierKind RefQualifier);
510 void mangleObjCMethodName(const ObjCMethodDecl *MD);
512 // Declare manglers for every type class.
513 #define ABSTRACT_TYPE(CLASS, PARENT)
514 #define NON_CANONICAL_TYPE(CLASS, PARENT)
515 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
516 #include "clang/AST/TypeNodes.def"
518 void mangleType(const TagType*);
519 void mangleType(TemplateName);
520 static StringRef getCallingConvQualifierName(CallingConv CC);
521 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
522 void mangleExtFunctionInfo(const FunctionType *T);
523 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
524 const FunctionDecl *FD = nullptr);
525 void mangleNeonVectorType(const VectorType *T);
526 void mangleNeonVectorType(const DependentVectorType *T);
527 void mangleAArch64NeonVectorType(const VectorType *T);
528 void mangleAArch64NeonVectorType(const DependentVectorType *T);
530 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
531 void mangleMemberExprBase(const Expr *base, bool isArrow);
532 void mangleMemberExpr(const Expr *base, bool isArrow,
533 NestedNameSpecifier *qualifier,
534 NamedDecl *firstQualifierLookup,
535 DeclarationName name,
536 const TemplateArgumentLoc *TemplateArgs,
537 unsigned NumTemplateArgs,
538 unsigned knownArity);
539 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
540 void mangleInitListElements(const InitListExpr *InitList);
541 void mangleDeclRefExpr(const NamedDecl *D);
542 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
543 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
544 void mangleCXXDtorType(CXXDtorType T);
546 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
547 unsigned NumTemplateArgs);
548 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
549 unsigned NumTemplateArgs);
550 void mangleTemplateArgs(const TemplateArgumentList &AL);
551 void mangleTemplateArg(TemplateArgument A);
553 void mangleTemplateParameter(unsigned Index);
555 void mangleFunctionParam(const ParmVarDecl *parm);
557 void writeAbiTags(const NamedDecl *ND,
558 const AbiTagList *AdditionalAbiTags);
560 // Returns sorted unique list of ABI tags.
561 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
562 // Returns sorted unique list of ABI tags.
563 AbiTagList makeVariableTypeTags(const VarDecl *VD);
568 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
569 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
571 LanguageLinkage L = FD->getLanguageLinkage();
572 // Overloadable functions need mangling.
573 if (FD->hasAttr<OverloadableAttr>())
576 // "main" is not mangled.
580 // The Windows ABI expects that we would never mangle "typical"
581 // user-defined entry points regardless of visibility or freestanding-ness.
583 // N.B. This is distinct from asking about "main". "main" has a lot of
584 // special rules associated with it in the standard while these
585 // user-defined entry points are outside of the purview of the standard.
586 // For example, there can be only one definition for "main" in a standards
587 // compliant program; however nothing forbids the existence of wmain and
588 // WinMain in the same translation unit.
589 if (FD->isMSVCRTEntryPoint())
592 // C++ functions and those whose names are not a simple identifier need
594 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
597 // C functions are not mangled.
598 if (L == CLanguageLinkage)
602 // Otherwise, no mangling is done outside C++ mode.
603 if (!getASTContext().getLangOpts().CPlusPlus)
606 const VarDecl *VD = dyn_cast<VarDecl>(D);
607 if (VD && !isa<DecompositionDecl>(D)) {
608 // C variables are not mangled.
612 // Variables at global scope with non-internal linkage are not mangled
613 const DeclContext *DC = getEffectiveDeclContext(D);
614 // Check for extern variable declared locally.
615 if (DC->isFunctionOrMethod() && D->hasLinkage())
616 while (!DC->isNamespace() && !DC->isTranslationUnit())
617 DC = getEffectiveParentContext(DC);
618 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
619 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
620 !isa<VarTemplateSpecializationDecl>(D))
627 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
628 const AbiTagList *AdditionalAbiTags) {
629 assert(AbiTags && "require AbiTagState");
630 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
633 void CXXNameMangler::mangleSourceNameWithAbiTags(
634 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
635 mangleSourceName(ND->getIdentifier());
636 writeAbiTags(ND, AdditionalAbiTags);
639 void CXXNameMangler::mangle(const NamedDecl *D) {
640 // <mangled-name> ::= _Z <encoding>
642 // ::= <special-name>
644 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
645 mangleFunctionEncoding(FD);
646 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
648 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
649 mangleName(IFD->getAnonField());
651 mangleName(cast<FieldDecl>(D));
654 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
655 // <encoding> ::= <function name> <bare-function-type>
657 // Don't mangle in the type if this isn't a decl we should typically mangle.
658 if (!Context.shouldMangleDeclName(FD)) {
663 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
664 if (ReturnTypeAbiTags.empty()) {
665 // There are no tags for return type, the simplest case.
667 mangleFunctionEncodingBareType(FD);
671 // Mangle function name and encoding to temporary buffer.
672 // We have to output name and encoding to the same mangler to get the same
673 // substitution as it will be in final mangling.
674 SmallString<256> FunctionEncodingBuf;
675 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
676 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
677 // Output name of the function.
678 FunctionEncodingMangler.disableDerivedAbiTags();
679 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
681 // Remember length of the function name in the buffer.
682 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
683 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
685 // Get tags from return type that are not present in function name or
687 const AbiTagList &UsedAbiTags =
688 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
689 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
690 AdditionalAbiTags.erase(
691 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
692 UsedAbiTags.begin(), UsedAbiTags.end(),
693 AdditionalAbiTags.begin()),
694 AdditionalAbiTags.end());
696 // Output name with implicit tags and function encoding from temporary buffer.
697 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
698 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
700 // Function encoding could create new substitutions so we have to add
701 // temp mangled substitutions to main mangler.
702 extendSubstitutions(&FunctionEncodingMangler);
705 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
706 if (FD->hasAttr<EnableIfAttr>()) {
707 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
708 Out << "Ua9enable_ifI";
709 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
710 E = FD->getAttrs().end();
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> ::= [<module-name>] <nested-name>
849 // ::= [<module-name>] <unscoped-name>
850 // ::= [<module-name>] <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 (isLocalContainerContext(DC)) {
870 mangleLocalName(ND, AdditionalAbiTags);
874 // Do not mangle the owning module for an external linkage declaration.
875 // This enables backwards-compatibility with non-modular code, and is
876 // a valid choice since conflicts are not permitted by C++ Modules TS
877 // [basic.def.odr]/6.2.
878 if (!ND->hasExternalFormalLinkage())
879 if (Module *M = ND->getOwningModuleForLinkage())
882 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
883 // Check if we have a template.
884 const TemplateArgumentList *TemplateArgs = nullptr;
885 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
886 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
887 mangleTemplateArgs(*TemplateArgs);
891 mangleUnscopedName(ND, AdditionalAbiTags);
895 mangleNestedName(ND, DC, AdditionalAbiTags);
898 void CXXNameMangler::mangleModuleName(const Module *M) {
899 // Implement the C++ Modules TS name mangling proposal; see
900 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
902 // <module-name> ::= W <unscoped-name>+ E
903 // ::= W <module-subst> <unscoped-name>* E
905 mangleModuleNamePrefix(M->Name);
909 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
910 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
911 // ::= W <seq-id - 10> _ # otherwise
912 auto It = ModuleSubstitutions.find(Name);
913 if (It != ModuleSubstitutions.end()) {
915 Out << '_' << static_cast<char>('0' + It->second);
917 Out << 'W' << (It->second - 10) << '_';
921 // FIXME: Preserve hierarchy in module names rather than flattening
922 // them to strings; use Module*s as substitution keys.
923 auto Parts = Name.rsplit('.');
924 if (Parts.second.empty())
925 Parts.second = Parts.first;
927 mangleModuleNamePrefix(Parts.first);
929 Out << Parts.second.size() << Parts.second;
930 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
933 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
934 const TemplateArgument *TemplateArgs,
935 unsigned NumTemplateArgs) {
936 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
938 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
939 mangleUnscopedTemplateName(TD, nullptr);
940 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
942 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
946 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
947 const AbiTagList *AdditionalAbiTags) {
948 // <unscoped-name> ::= <unqualified-name>
949 // ::= St <unqualified-name> # ::std::
951 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
954 mangleUnqualifiedName(ND, AdditionalAbiTags);
957 void CXXNameMangler::mangleUnscopedTemplateName(
958 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
959 // <unscoped-template-name> ::= <unscoped-name>
960 // ::= <substitution>
961 if (mangleSubstitution(ND))
964 // <template-template-param> ::= <template-param>
965 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
966 assert(!AdditionalAbiTags &&
967 "template template param cannot have abi tags");
968 mangleTemplateParameter(TTP->getIndex());
969 } else if (isa<BuiltinTemplateDecl>(ND)) {
970 mangleUnscopedName(ND, AdditionalAbiTags);
972 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
978 void CXXNameMangler::mangleUnscopedTemplateName(
979 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
980 // <unscoped-template-name> ::= <unscoped-name>
981 // ::= <substitution>
982 if (TemplateDecl *TD = Template.getAsTemplateDecl())
983 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
985 if (mangleSubstitution(Template))
988 assert(!AdditionalAbiTags &&
989 "dependent template name cannot have abi tags");
991 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
992 assert(Dependent && "Not a dependent template name?");
993 if (const IdentifierInfo *Id = Dependent->getIdentifier())
994 mangleSourceName(Id);
996 mangleOperatorName(Dependent->getOperator(), UnknownArity);
998 addSubstitution(Template);
1001 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1003 // Floating-point literals are encoded using a fixed-length
1004 // lowercase hexadecimal string corresponding to the internal
1005 // representation (IEEE on Itanium), high-order bytes first,
1006 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1008 // The 'without leading zeroes' thing seems to be an editorial
1009 // mistake; see the discussion on cxx-abi-dev beginning on
1012 // Our requirements here are just barely weird enough to justify
1013 // using a custom algorithm instead of post-processing APInt::toString().
1015 llvm::APInt valueBits = f.bitcastToAPInt();
1016 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1017 assert(numCharacters != 0);
1019 // Allocate a buffer of the right number of characters.
1020 SmallVector<char, 20> buffer(numCharacters);
1022 // Fill the buffer left-to-right.
1023 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1024 // The bit-index of the next hex digit.
1025 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1027 // Project out 4 bits starting at 'digitIndex'.
1028 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1029 hexDigit >>= (digitBitIndex % 64);
1032 // Map that over to a lowercase hex digit.
1033 static const char charForHex[16] = {
1034 '0', '1', '2', '3', '4', '5', '6', '7',
1035 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1037 buffer[stringIndex] = charForHex[hexDigit];
1040 Out.write(buffer.data(), numCharacters);
1043 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1044 if (Value.isSigned() && Value.isNegative()) {
1046 Value.abs().print(Out, /*signed*/ false);
1048 Value.print(Out, /*signed*/ false);
1052 void CXXNameMangler::mangleNumber(int64_t Number) {
1053 // <number> ::= [n] <non-negative decimal integer>
1062 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1063 // <call-offset> ::= h <nv-offset> _
1064 // ::= v <v-offset> _
1065 // <nv-offset> ::= <offset number> # non-virtual base override
1066 // <v-offset> ::= <offset number> _ <virtual offset number>
1067 // # virtual base override, with vcall offset
1070 mangleNumber(NonVirtual);
1076 mangleNumber(NonVirtual);
1078 mangleNumber(Virtual);
1082 void CXXNameMangler::manglePrefix(QualType type) {
1083 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1084 if (!mangleSubstitution(QualType(TST, 0))) {
1085 mangleTemplatePrefix(TST->getTemplateName());
1087 // FIXME: GCC does not appear to mangle the template arguments when
1088 // the template in question is a dependent template name. Should we
1089 // emulate that badness?
1090 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1091 addSubstitution(QualType(TST, 0));
1093 } else if (const auto *DTST =
1094 type->getAs<DependentTemplateSpecializationType>()) {
1095 if (!mangleSubstitution(QualType(DTST, 0))) {
1096 TemplateName Template = getASTContext().getDependentTemplateName(
1097 DTST->getQualifier(), DTST->getIdentifier());
1098 mangleTemplatePrefix(Template);
1100 // FIXME: GCC does not appear to mangle the template arguments when
1101 // the template in question is a dependent template name. Should we
1102 // emulate that badness?
1103 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1104 addSubstitution(QualType(DTST, 0));
1107 // We use the QualType mangle type variant here because it handles
1113 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1115 /// \param recursive - true if this is being called recursively,
1116 /// i.e. if there is more prefix "to the right".
1117 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1121 // <unresolved-name> ::= [gs] <base-unresolved-name>
1123 // T::x / decltype(p)::x
1124 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1126 // T::N::x /decltype(p)::N::x
1127 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1128 // <base-unresolved-name>
1130 // A::x, N::y, A<T>::z; "gs" means leading "::"
1131 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1132 // <base-unresolved-name>
1134 switch (qualifier->getKind()) {
1135 case NestedNameSpecifier::Global:
1138 // We want an 'sr' unless this is the entire NNS.
1142 // We never want an 'E' here.
1145 case NestedNameSpecifier::Super:
1146 llvm_unreachable("Can't mangle __super specifier");
1148 case NestedNameSpecifier::Namespace:
1149 if (qualifier->getPrefix())
1150 mangleUnresolvedPrefix(qualifier->getPrefix(),
1151 /*recursive*/ true);
1154 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1156 case NestedNameSpecifier::NamespaceAlias:
1157 if (qualifier->getPrefix())
1158 mangleUnresolvedPrefix(qualifier->getPrefix(),
1159 /*recursive*/ true);
1162 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1165 case NestedNameSpecifier::TypeSpec:
1166 case NestedNameSpecifier::TypeSpecWithTemplate: {
1167 const Type *type = qualifier->getAsType();
1169 // We only want to use an unresolved-type encoding if this is one of:
1171 // - a template type parameter
1172 // - a template template parameter with arguments
1173 // In all of these cases, we should have no prefix.
1174 if (qualifier->getPrefix()) {
1175 mangleUnresolvedPrefix(qualifier->getPrefix(),
1176 /*recursive*/ true);
1178 // Otherwise, all the cases want this.
1182 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1188 case NestedNameSpecifier::Identifier:
1189 // Member expressions can have these without prefixes.
1190 if (qualifier->getPrefix())
1191 mangleUnresolvedPrefix(qualifier->getPrefix(),
1192 /*recursive*/ true);
1196 mangleSourceName(qualifier->getAsIdentifier());
1197 // An Identifier has no type information, so we can't emit abi tags for it.
1201 // If this was the innermost part of the NNS, and we fell out to
1202 // here, append an 'E'.
1207 /// Mangle an unresolved-name, which is generally used for names which
1208 /// weren't resolved to specific entities.
1209 void CXXNameMangler::mangleUnresolvedName(
1210 NestedNameSpecifier *qualifier, DeclarationName name,
1211 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1212 unsigned knownArity) {
1213 if (qualifier) mangleUnresolvedPrefix(qualifier);
1214 switch (name.getNameKind()) {
1215 // <base-unresolved-name> ::= <simple-id>
1216 case DeclarationName::Identifier:
1217 mangleSourceName(name.getAsIdentifierInfo());
1219 // <base-unresolved-name> ::= dn <destructor-name>
1220 case DeclarationName::CXXDestructorName:
1222 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1224 // <base-unresolved-name> ::= on <operator-name>
1225 case DeclarationName::CXXConversionFunctionName:
1226 case DeclarationName::CXXLiteralOperatorName:
1227 case DeclarationName::CXXOperatorName:
1229 mangleOperatorName(name, knownArity);
1231 case DeclarationName::CXXConstructorName:
1232 llvm_unreachable("Can't mangle a constructor name!");
1233 case DeclarationName::CXXUsingDirective:
1234 llvm_unreachable("Can't mangle a using directive name!");
1235 case DeclarationName::CXXDeductionGuideName:
1236 llvm_unreachable("Can't mangle a deduction guide name!");
1237 case DeclarationName::ObjCMultiArgSelector:
1238 case DeclarationName::ObjCOneArgSelector:
1239 case DeclarationName::ObjCZeroArgSelector:
1240 llvm_unreachable("Can't mangle Objective-C selector names here!");
1243 // The <simple-id> and on <operator-name> productions end in an optional
1246 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1249 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1250 DeclarationName Name,
1251 unsigned KnownArity,
1252 const AbiTagList *AdditionalAbiTags) {
1253 unsigned Arity = KnownArity;
1254 // <unqualified-name> ::= <operator-name>
1255 // ::= <ctor-dtor-name>
1256 // ::= <source-name>
1257 switch (Name.getNameKind()) {
1258 case DeclarationName::Identifier: {
1259 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1261 // We mangle decomposition declarations as the names of their bindings.
1262 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1263 // FIXME: Non-standard mangling for decomposition declarations:
1265 // <unqualified-name> ::= DC <source-name>* E
1267 // These can never be referenced across translation units, so we do
1268 // not need a cross-vendor mangling for anything other than demanglers.
1269 // Proposed on cxx-abi-dev on 2016-08-12
1271 for (auto *BD : DD->bindings())
1272 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1274 writeAbiTags(ND, AdditionalAbiTags);
1279 // Match GCC's naming convention for internal linkage symbols, for
1280 // symbols that are not actually visible outside of this TU. GCC
1281 // distinguishes between internal and external linkage symbols in
1282 // its mangling, to support cases like this that were valid C++ prior
1285 // void test() { extern void foo(); }
1286 // static void foo();
1288 // Don't bother with the L marker for names in anonymous namespaces; the
1289 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1290 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1291 // implying internal linkage.
1292 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1293 !ND->isExternallyVisible() &&
1294 getEffectiveDeclContext(ND)->isFileContext() &&
1295 !ND->isInAnonymousNamespace())
1298 auto *FD = dyn_cast<FunctionDecl>(ND);
1299 bool IsRegCall = FD &&
1300 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1301 clang::CC_X86RegCall;
1303 mangleRegCallName(II);
1305 mangleSourceName(II);
1307 writeAbiTags(ND, AdditionalAbiTags);
1311 // Otherwise, an anonymous entity. We must have a declaration.
1312 assert(ND && "mangling empty name without declaration");
1314 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1315 if (NS->isAnonymousNamespace()) {
1316 // This is how gcc mangles these names.
1317 Out << "12_GLOBAL__N_1";
1322 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1323 // We must have an anonymous union or struct declaration.
1324 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
1326 // Itanium C++ ABI 5.1.2:
1328 // For the purposes of mangling, the name of an anonymous union is
1329 // considered to be the name of the first named data member found by a
1330 // pre-order, depth-first, declaration-order walk of the data members of
1331 // the anonymous union. If there is no such data member (i.e., if all of
1332 // the data members in the union are unnamed), then there is no way for
1333 // a program to refer to the anonymous union, and there is therefore no
1334 // need to mangle its name.
1335 assert(RD->isAnonymousStructOrUnion()
1336 && "Expected anonymous struct or union!");
1337 const FieldDecl *FD = RD->findFirstNamedDataMember();
1339 // It's actually possible for various reasons for us to get here
1340 // with an empty anonymous struct / union. Fortunately, it
1341 // doesn't really matter what name we generate.
1343 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1345 mangleSourceName(FD->getIdentifier());
1346 // Not emitting abi tags: internal name anyway.
1350 // Class extensions have no name as a category, and it's possible
1351 // for them to be the semantic parent of certain declarations
1352 // (primarily, tag decls defined within declarations). Such
1353 // declarations will always have internal linkage, so the name
1354 // doesn't really matter, but we shouldn't crash on them. For
1355 // safety, just handle all ObjC containers here.
1356 if (isa<ObjCContainerDecl>(ND))
1359 // We must have an anonymous struct.
1360 const TagDecl *TD = cast<TagDecl>(ND);
1361 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1362 assert(TD->getDeclContext() == D->getDeclContext() &&
1363 "Typedef should not be in another decl context!");
1364 assert(D->getDeclName().getAsIdentifierInfo() &&
1365 "Typedef was not named!");
1366 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1367 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1368 // Explicit abi tags are still possible; take from underlying type, not
1370 writeAbiTags(TD, nullptr);
1374 // <unnamed-type-name> ::= <closure-type-name>
1376 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1377 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1378 // # Parameter types or 'v' for 'void'.
1379 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1380 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1381 assert(!AdditionalAbiTags &&
1382 "Lambda type cannot have additional abi tags");
1383 mangleLambda(Record);
1388 if (TD->isExternallyVisible()) {
1389 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1391 if (UnnamedMangle > 1)
1392 Out << UnnamedMangle - 2;
1394 writeAbiTags(TD, AdditionalAbiTags);
1398 // Get a unique id for the anonymous struct. If it is not a real output
1399 // ID doesn't matter so use fake one.
1400 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1402 // Mangle it as a source name in the form
1404 // where n is the length of the string.
1407 Str += llvm::utostr(AnonStructId);
1414 case DeclarationName::ObjCZeroArgSelector:
1415 case DeclarationName::ObjCOneArgSelector:
1416 case DeclarationName::ObjCMultiArgSelector:
1417 llvm_unreachable("Can't mangle Objective-C selector names here!");
1419 case DeclarationName::CXXConstructorName: {
1420 const CXXRecordDecl *InheritedFrom = nullptr;
1421 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1422 if (auto Inherited =
1423 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1424 InheritedFrom = Inherited.getConstructor()->getParent();
1425 InheritedTemplateArgs =
1426 Inherited.getConstructor()->getTemplateSpecializationArgs();
1430 // If the named decl is the C++ constructor we're mangling, use the type
1432 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1434 // Otherwise, use the complete constructor name. This is relevant if a
1435 // class with a constructor is declared within a constructor.
1436 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1438 // FIXME: The template arguments are part of the enclosing prefix or
1439 // nested-name, but it's more convenient to mangle them here.
1440 if (InheritedTemplateArgs)
1441 mangleTemplateArgs(*InheritedTemplateArgs);
1443 writeAbiTags(ND, AdditionalAbiTags);
1447 case DeclarationName::CXXDestructorName:
1449 // If the named decl is the C++ destructor we're mangling, use the type we
1451 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1453 // Otherwise, use the complete destructor name. This is relevant if a
1454 // class with a destructor is declared within a destructor.
1455 mangleCXXDtorType(Dtor_Complete);
1456 writeAbiTags(ND, AdditionalAbiTags);
1459 case DeclarationName::CXXOperatorName:
1460 if (ND && Arity == UnknownArity) {
1461 Arity = cast<FunctionDecl>(ND)->getNumParams();
1463 // If we have a member function, we need to include the 'this' pointer.
1464 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1465 if (!MD->isStatic())
1469 case DeclarationName::CXXConversionFunctionName:
1470 case DeclarationName::CXXLiteralOperatorName:
1471 mangleOperatorName(Name, Arity);
1472 writeAbiTags(ND, AdditionalAbiTags);
1475 case DeclarationName::CXXDeductionGuideName:
1476 llvm_unreachable("Can't mangle a deduction guide name!");
1478 case DeclarationName::CXXUsingDirective:
1479 llvm_unreachable("Can't mangle a using directive name!");
1483 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1484 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1485 // <number> ::= [n] <non-negative decimal integer>
1486 // <identifier> ::= <unqualified source code identifier>
1487 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1491 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1492 // <source-name> ::= <positive length number> <identifier>
1493 // <number> ::= [n] <non-negative decimal integer>
1494 // <identifier> ::= <unqualified source code identifier>
1495 Out << II->getLength() << II->getName();
1498 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1499 const DeclContext *DC,
1500 const AbiTagList *AdditionalAbiTags,
1503 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1504 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1505 // <template-args> E
1508 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1509 Qualifiers MethodQuals = Method->getMethodQualifiers();
1510 // We do not consider restrict a distinguishing attribute for overloading
1511 // purposes so we must not mangle it.
1512 MethodQuals.removeRestrict();
1513 mangleQualifiers(MethodQuals);
1514 mangleRefQualifier(Method->getRefQualifier());
1517 // Check if we have a template.
1518 const TemplateArgumentList *TemplateArgs = nullptr;
1519 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1520 mangleTemplatePrefix(TD, NoFunction);
1521 mangleTemplateArgs(*TemplateArgs);
1524 manglePrefix(DC, NoFunction);
1525 mangleUnqualifiedName(ND, AdditionalAbiTags);
1530 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1531 const TemplateArgument *TemplateArgs,
1532 unsigned NumTemplateArgs) {
1533 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1537 mangleTemplatePrefix(TD);
1538 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1543 void CXXNameMangler::mangleLocalName(const Decl *D,
1544 const AbiTagList *AdditionalAbiTags) {
1545 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1546 // := Z <function encoding> E s [<discriminator>]
1547 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1549 // <discriminator> := _ <non-negative number>
1550 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1551 const RecordDecl *RD = GetLocalClassDecl(D);
1552 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1557 AbiTagState LocalAbiTags(AbiTags);
1559 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1560 mangleObjCMethodName(MD);
1561 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1562 mangleBlockForPrefix(BD);
1564 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1566 // Implicit ABI tags (from namespace) are not available in the following
1567 // entity; reset to actually emitted tags, which are available.
1568 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1573 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1574 // be a bug that is fixed in trunk.
1577 // The parameter number is omitted for the last parameter, 0 for the
1578 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1579 // <entity name> will of course contain a <closure-type-name>: Its
1580 // numbering will be local to the particular argument in which it appears
1581 // -- other default arguments do not affect its encoding.
1582 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1583 if (CXXRD && CXXRD->isLambda()) {
1584 if (const ParmVarDecl *Parm
1585 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1586 if (const FunctionDecl *Func
1587 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1589 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1591 mangleNumber(Num - 2);
1597 // Mangle the name relative to the closest enclosing function.
1598 // equality ok because RD derived from ND above
1600 mangleUnqualifiedName(RD, AdditionalAbiTags);
1601 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1602 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1603 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1604 mangleUnqualifiedBlock(BD);
1606 const NamedDecl *ND = cast<NamedDecl>(D);
1607 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1608 true /*NoFunction*/);
1610 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1611 // Mangle a block in a default parameter; see above explanation for
1613 if (const ParmVarDecl *Parm
1614 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1615 if (const FunctionDecl *Func
1616 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1618 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1620 mangleNumber(Num - 2);
1625 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1626 mangleUnqualifiedBlock(BD);
1628 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1631 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1633 if (Context.getNextDiscriminator(ND, disc)) {
1637 Out << "__" << disc << '_';
1642 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1643 if (GetLocalClassDecl(Block)) {
1644 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1647 const DeclContext *DC = getEffectiveDeclContext(Block);
1648 if (isLocalContainerContext(DC)) {
1649 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1652 manglePrefix(getEffectiveDeclContext(Block));
1653 mangleUnqualifiedBlock(Block);
1656 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1657 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1658 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1659 Context->getDeclContext()->isRecord()) {
1660 const auto *ND = cast<NamedDecl>(Context);
1661 if (ND->getIdentifier()) {
1662 mangleSourceNameWithAbiTags(ND);
1668 // If we have a block mangling number, use it.
1669 unsigned Number = Block->getBlockManglingNumber();
1670 // Otherwise, just make up a number. It doesn't matter what it is because
1671 // the symbol in question isn't externally visible.
1673 Number = Context.getBlockId(Block, false);
1675 // Stored mangling numbers are 1-based.
1684 // <template-param-decl>
1685 // ::= Ty # template type parameter
1686 // ::= Tn <type> # template non-type parameter
1687 // ::= Tt <template-param-decl>* E # template template parameter
1688 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1689 if (isa<TemplateTypeParmDecl>(Decl)) {
1691 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1693 mangleType(Tn->getType());
1694 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1696 for (auto *Param : *Tt->getTemplateParameters())
1697 mangleTemplateParamDecl(Param);
1702 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1703 // If the context of a closure type is an initializer for a class member
1704 // (static or nonstatic), it is encoded in a qualified name with a final
1705 // <prefix> of the form:
1707 // <data-member-prefix> := <member source-name> M
1709 // Technically, the data-member-prefix is part of the <prefix>. However,
1710 // since a closure type will always be mangled with a prefix, it's easier
1711 // to emit that last part of the prefix here.
1712 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1713 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1714 !isa<ParmVarDecl>(Context)) {
1715 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1716 // reasonable mangling here.
1717 if (const IdentifierInfo *Name
1718 = cast<NamedDecl>(Context)->getIdentifier()) {
1719 mangleSourceName(Name);
1720 const TemplateArgumentList *TemplateArgs = nullptr;
1721 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1722 mangleTemplateArgs(*TemplateArgs);
1729 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1730 mangleTemplateParamDecl(D);
1731 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1732 getAs<FunctionProtoType>();
1733 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1734 Lambda->getLambdaStaticInvoker());
1737 // The number is omitted for the first closure type with a given
1738 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1739 // (in lexical order) with that same <lambda-sig> and context.
1741 // The AST keeps track of the number for us.
1742 unsigned Number = Lambda->getLambdaManglingNumber();
1743 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1745 mangleNumber(Number - 2);
1749 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1750 switch (qualifier->getKind()) {
1751 case NestedNameSpecifier::Global:
1755 case NestedNameSpecifier::Super:
1756 llvm_unreachable("Can't mangle __super specifier");
1758 case NestedNameSpecifier::Namespace:
1759 mangleName(qualifier->getAsNamespace());
1762 case NestedNameSpecifier::NamespaceAlias:
1763 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1766 case NestedNameSpecifier::TypeSpec:
1767 case NestedNameSpecifier::TypeSpecWithTemplate:
1768 manglePrefix(QualType(qualifier->getAsType(), 0));
1771 case NestedNameSpecifier::Identifier:
1772 // Member expressions can have these without prefixes, but that
1773 // should end up in mangleUnresolvedPrefix instead.
1774 assert(qualifier->getPrefix());
1775 manglePrefix(qualifier->getPrefix());
1777 mangleSourceName(qualifier->getAsIdentifier());
1781 llvm_unreachable("unexpected nested name specifier");
1784 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1785 // <prefix> ::= <prefix> <unqualified-name>
1786 // ::= <template-prefix> <template-args>
1787 // ::= <template-param>
1789 // ::= <substitution>
1791 DC = IgnoreLinkageSpecDecls(DC);
1793 if (DC->isTranslationUnit())
1796 if (NoFunction && isLocalContainerContext(DC))
1799 assert(!isLocalContainerContext(DC));
1801 const NamedDecl *ND = cast<NamedDecl>(DC);
1802 if (mangleSubstitution(ND))
1805 // Check if we have a template.
1806 const TemplateArgumentList *TemplateArgs = nullptr;
1807 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1808 mangleTemplatePrefix(TD);
1809 mangleTemplateArgs(*TemplateArgs);
1811 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1812 mangleUnqualifiedName(ND, nullptr);
1815 addSubstitution(ND);
1818 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1819 // <template-prefix> ::= <prefix> <template unqualified-name>
1820 // ::= <template-param>
1821 // ::= <substitution>
1822 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1823 return mangleTemplatePrefix(TD);
1825 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1826 manglePrefix(Qualified->getQualifier());
1828 if (OverloadedTemplateStorage *Overloaded
1829 = Template.getAsOverloadedTemplate()) {
1830 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1831 UnknownArity, nullptr);
1835 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1836 assert(Dependent && "Unknown template name kind?");
1837 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1838 manglePrefix(Qualifier);
1839 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1842 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1844 // <template-prefix> ::= <prefix> <template unqualified-name>
1845 // ::= <template-param>
1846 // ::= <substitution>
1847 // <template-template-param> ::= <template-param>
1850 if (mangleSubstitution(ND))
1853 // <template-template-param> ::= <template-param>
1854 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1855 mangleTemplateParameter(TTP->getIndex());
1857 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1858 if (isa<BuiltinTemplateDecl>(ND))
1859 mangleUnqualifiedName(ND, nullptr);
1861 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1864 addSubstitution(ND);
1867 /// Mangles a template name under the production <type>. Required for
1868 /// template template arguments.
1869 /// <type> ::= <class-enum-type>
1870 /// ::= <template-param>
1871 /// ::= <substitution>
1872 void CXXNameMangler::mangleType(TemplateName TN) {
1873 if (mangleSubstitution(TN))
1876 TemplateDecl *TD = nullptr;
1878 switch (TN.getKind()) {
1879 case TemplateName::QualifiedTemplate:
1880 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1883 case TemplateName::Template:
1884 TD = TN.getAsTemplateDecl();
1888 if (isa<TemplateTemplateParmDecl>(TD))
1889 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1894 case TemplateName::OverloadedTemplate:
1895 case TemplateName::AssumedTemplate:
1896 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1898 case TemplateName::DependentTemplate: {
1899 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1900 assert(Dependent->isIdentifier());
1902 // <class-enum-type> ::= <name>
1903 // <name> ::= <nested-name>
1904 mangleUnresolvedPrefix(Dependent->getQualifier());
1905 mangleSourceName(Dependent->getIdentifier());
1909 case TemplateName::SubstTemplateTemplateParm: {
1910 // Substituted template parameters are mangled as the substituted
1911 // template. This will check for the substitution twice, which is
1912 // fine, but we have to return early so that we don't try to *add*
1913 // the substitution twice.
1914 SubstTemplateTemplateParmStorage *subst
1915 = TN.getAsSubstTemplateTemplateParm();
1916 mangleType(subst->getReplacement());
1920 case TemplateName::SubstTemplateTemplateParmPack: {
1921 // FIXME: not clear how to mangle this!
1922 // template <template <class> class T...> class A {
1923 // template <template <class> class U...> void foo(B<T,U> x...);
1925 Out << "_SUBSTPACK_";
1930 addSubstitution(TN);
1933 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1935 // Only certain other types are valid as prefixes; enumerate them.
1936 switch (Ty->getTypeClass()) {
1939 case Type::Adjusted:
1942 case Type::BlockPointer:
1943 case Type::LValueReference:
1944 case Type::RValueReference:
1945 case Type::MemberPointer:
1946 case Type::ConstantArray:
1947 case Type::IncompleteArray:
1948 case Type::VariableArray:
1949 case Type::DependentSizedArray:
1950 case Type::DependentAddressSpace:
1951 case Type::DependentVector:
1952 case Type::DependentSizedExtVector:
1954 case Type::ExtVector:
1955 case Type::FunctionProto:
1956 case Type::FunctionNoProto:
1958 case Type::Attributed:
1960 case Type::DeducedTemplateSpecialization:
1961 case Type::PackExpansion:
1962 case Type::ObjCObject:
1963 case Type::ObjCInterface:
1964 case Type::ObjCObjectPointer:
1965 case Type::ObjCTypeParam:
1968 case Type::MacroQualified:
1969 llvm_unreachable("type is illegal as a nested name specifier");
1971 case Type::SubstTemplateTypeParmPack:
1972 // FIXME: not clear how to mangle this!
1973 // template <class T...> class A {
1974 // template <class U...> void foo(decltype(T::foo(U())) x...);
1976 Out << "_SUBSTPACK_";
1979 // <unresolved-type> ::= <template-param>
1981 // ::= <template-template-param> <template-args>
1982 // (this last is not official yet)
1983 case Type::TypeOfExpr:
1985 case Type::Decltype:
1986 case Type::TemplateTypeParm:
1987 case Type::UnaryTransform:
1988 case Type::SubstTemplateTypeParm:
1990 // Some callers want a prefix before the mangled type.
1993 // This seems to do everything we want. It's not really
1994 // sanctioned for a substituted template parameter, though.
1997 // We never want to print 'E' directly after an unresolved-type,
1998 // so we return directly.
2002 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2005 case Type::UnresolvedUsing:
2006 mangleSourceNameWithAbiTags(
2007 cast<UnresolvedUsingType>(Ty)->getDecl());
2012 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2015 case Type::TemplateSpecialization: {
2016 const TemplateSpecializationType *TST =
2017 cast<TemplateSpecializationType>(Ty);
2018 TemplateName TN = TST->getTemplateName();
2019 switch (TN.getKind()) {
2020 case TemplateName::Template:
2021 case TemplateName::QualifiedTemplate: {
2022 TemplateDecl *TD = TN.getAsTemplateDecl();
2024 // If the base is a template template parameter, this is an
2026 assert(TD && "no template for template specialization type");
2027 if (isa<TemplateTemplateParmDecl>(TD))
2028 goto unresolvedType;
2030 mangleSourceNameWithAbiTags(TD);
2034 case TemplateName::OverloadedTemplate:
2035 case TemplateName::AssumedTemplate:
2036 case TemplateName::DependentTemplate:
2037 llvm_unreachable("invalid base for a template specialization type");
2039 case TemplateName::SubstTemplateTemplateParm: {
2040 SubstTemplateTemplateParmStorage *subst =
2041 TN.getAsSubstTemplateTemplateParm();
2042 mangleExistingSubstitution(subst->getReplacement());
2046 case TemplateName::SubstTemplateTemplateParmPack: {
2047 // FIXME: not clear how to mangle this!
2048 // template <template <class U> class T...> class A {
2049 // template <class U...> void foo(decltype(T<U>::foo) x...);
2051 Out << "_SUBSTPACK_";
2056 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
2060 case Type::InjectedClassName:
2061 mangleSourceNameWithAbiTags(
2062 cast<InjectedClassNameType>(Ty)->getDecl());
2065 case Type::DependentName:
2066 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2069 case Type::DependentTemplateSpecialization: {
2070 const DependentTemplateSpecializationType *DTST =
2071 cast<DependentTemplateSpecializationType>(Ty);
2072 mangleSourceName(DTST->getIdentifier());
2073 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2077 case Type::Elaborated:
2078 return mangleUnresolvedTypeOrSimpleId(
2079 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2085 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2086 switch (Name.getNameKind()) {
2087 case DeclarationName::CXXConstructorName:
2088 case DeclarationName::CXXDestructorName:
2089 case DeclarationName::CXXDeductionGuideName:
2090 case DeclarationName::CXXUsingDirective:
2091 case DeclarationName::Identifier:
2092 case DeclarationName::ObjCMultiArgSelector:
2093 case DeclarationName::ObjCOneArgSelector:
2094 case DeclarationName::ObjCZeroArgSelector:
2095 llvm_unreachable("Not an operator name");
2097 case DeclarationName::CXXConversionFunctionName:
2098 // <operator-name> ::= cv <type> # (cast)
2100 mangleType(Name.getCXXNameType());
2103 case DeclarationName::CXXLiteralOperatorName:
2105 mangleSourceName(Name.getCXXLiteralIdentifier());
2108 case DeclarationName::CXXOperatorName:
2109 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2115 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2117 // <operator-name> ::= nw # new
2118 case OO_New: Out << "nw"; break;
2120 case OO_Array_New: Out << "na"; break;
2122 case OO_Delete: Out << "dl"; break;
2123 // ::= da # delete[]
2124 case OO_Array_Delete: Out << "da"; break;
2125 // ::= ps # + (unary)
2126 // ::= pl # + (binary or unknown)
2128 Out << (Arity == 1? "ps" : "pl"); break;
2129 // ::= ng # - (unary)
2130 // ::= mi # - (binary or unknown)
2132 Out << (Arity == 1? "ng" : "mi"); break;
2133 // ::= ad # & (unary)
2134 // ::= an # & (binary or unknown)
2136 Out << (Arity == 1? "ad" : "an"); break;
2137 // ::= de # * (unary)
2138 // ::= ml # * (binary or unknown)
2140 // Use binary when unknown.
2141 Out << (Arity == 1? "de" : "ml"); break;
2143 case OO_Tilde: Out << "co"; break;
2145 case OO_Slash: Out << "dv"; break;
2147 case OO_Percent: Out << "rm"; break;
2149 case OO_Pipe: Out << "or"; break;
2151 case OO_Caret: Out << "eo"; break;
2153 case OO_Equal: Out << "aS"; break;
2155 case OO_PlusEqual: Out << "pL"; break;
2157 case OO_MinusEqual: Out << "mI"; break;
2159 case OO_StarEqual: Out << "mL"; break;
2161 case OO_SlashEqual: Out << "dV"; break;
2163 case OO_PercentEqual: Out << "rM"; break;
2165 case OO_AmpEqual: Out << "aN"; break;
2167 case OO_PipeEqual: Out << "oR"; break;
2169 case OO_CaretEqual: Out << "eO"; break;
2171 case OO_LessLess: Out << "ls"; break;
2173 case OO_GreaterGreater: Out << "rs"; break;
2175 case OO_LessLessEqual: Out << "lS"; break;
2177 case OO_GreaterGreaterEqual: Out << "rS"; break;
2179 case OO_EqualEqual: Out << "eq"; break;
2181 case OO_ExclaimEqual: Out << "ne"; break;
2183 case OO_Less: Out << "lt"; break;
2185 case OO_Greater: Out << "gt"; break;
2187 case OO_LessEqual: Out << "le"; break;
2189 case OO_GreaterEqual: Out << "ge"; break;
2191 case OO_Exclaim: Out << "nt"; break;
2193 case OO_AmpAmp: Out << "aa"; break;
2195 case OO_PipePipe: Out << "oo"; break;
2197 case OO_PlusPlus: Out << "pp"; break;
2199 case OO_MinusMinus: Out << "mm"; break;
2201 case OO_Comma: Out << "cm"; break;
2203 case OO_ArrowStar: Out << "pm"; break;
2205 case OO_Arrow: Out << "pt"; break;
2207 case OO_Call: Out << "cl"; break;
2209 case OO_Subscript: Out << "ix"; break;
2212 // The conditional operator can't be overloaded, but we still handle it when
2213 // mangling expressions.
2214 case OO_Conditional: Out << "qu"; break;
2215 // Proposal on cxx-abi-dev, 2015-10-21.
2216 // ::= aw # co_await
2217 case OO_Coawait: Out << "aw"; break;
2218 // Proposed in cxx-abi github issue 43.
2220 case OO_Spaceship: Out << "ss"; break;
2223 case NUM_OVERLOADED_OPERATORS:
2224 llvm_unreachable("Not an overloaded operator");
2228 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2229 // Vendor qualifiers come first and if they are order-insensitive they must
2230 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2232 // <type> ::= U <addrspace-expr>
2235 mangleExpression(DAST->getAddrSpaceExpr());
2239 // Address space qualifiers start with an ordinary letter.
2240 if (Quals.hasAddressSpace()) {
2241 // Address space extension:
2243 // <type> ::= U <target-addrspace>
2244 // <type> ::= U <OpenCL-addrspace>
2245 // <type> ::= U <CUDA-addrspace>
2247 SmallString<64> ASString;
2248 LangAS AS = Quals.getAddressSpace();
2250 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2251 // <target-addrspace> ::= "AS" <address-space-number>
2252 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2254 ASString = "AS" + llvm::utostr(TargetAS);
2257 default: llvm_unreachable("Not a language specific address space");
2258 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2259 // "private"| "generic" ]
2260 case LangAS::opencl_global: ASString = "CLglobal"; break;
2261 case LangAS::opencl_local: ASString = "CLlocal"; break;
2262 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2263 case LangAS::opencl_private: ASString = "CLprivate"; break;
2264 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
2265 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2266 case LangAS::cuda_device: ASString = "CUdevice"; break;
2267 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2268 case LangAS::cuda_shared: ASString = "CUshared"; break;
2271 if (!ASString.empty())
2272 mangleVendorQualifier(ASString);
2275 // The ARC ownership qualifiers start with underscores.
2276 // Objective-C ARC Extension:
2278 // <type> ::= U "__strong"
2279 // <type> ::= U "__weak"
2280 // <type> ::= U "__autoreleasing"
2282 // Note: we emit __weak first to preserve the order as
2283 // required by the Itanium ABI.
2284 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2285 mangleVendorQualifier("__weak");
2287 // __unaligned (from -fms-extensions)
2288 if (Quals.hasUnaligned())
2289 mangleVendorQualifier("__unaligned");
2291 // Remaining ARC ownership qualifiers.
2292 switch (Quals.getObjCLifetime()) {
2293 case Qualifiers::OCL_None:
2296 case Qualifiers::OCL_Weak:
2297 // Do nothing as we already handled this case above.
2300 case Qualifiers::OCL_Strong:
2301 mangleVendorQualifier("__strong");
2304 case Qualifiers::OCL_Autoreleasing:
2305 mangleVendorQualifier("__autoreleasing");
2308 case Qualifiers::OCL_ExplicitNone:
2309 // The __unsafe_unretained qualifier is *not* mangled, so that
2310 // __unsafe_unretained types in ARC produce the same manglings as the
2311 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2312 // better ABI compatibility.
2314 // It's safe to do this because unqualified 'id' won't show up
2315 // in any type signatures that need to be mangled.
2319 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2320 if (Quals.hasRestrict())
2322 if (Quals.hasVolatile())
2324 if (Quals.hasConst())
2328 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2329 Out << 'U' << name.size() << name;
2332 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2333 // <ref-qualifier> ::= R # lvalue reference
2334 // ::= O # rvalue-reference
2335 switch (RefQualifier) {
2349 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2350 Context.mangleObjCMethodName(MD, Out);
2353 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2357 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2359 if (Ty->isOpenCLSpecificType())
2361 if (Ty->isBuiltinType())
2363 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2364 // substitution candidates.
2365 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2371 void CXXNameMangler::mangleType(QualType T) {
2372 // If our type is instantiation-dependent but not dependent, we mangle
2373 // it as it was written in the source, removing any top-level sugar.
2374 // Otherwise, use the canonical type.
2376 // FIXME: This is an approximation of the instantiation-dependent name
2377 // mangling rules, since we should really be using the type as written and
2378 // augmented via semantic analysis (i.e., with implicit conversions and
2379 // default template arguments) for any instantiation-dependent type.
2380 // Unfortunately, that requires several changes to our AST:
2381 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2382 // uniqued, so that we can handle substitutions properly
2383 // - Default template arguments will need to be represented in the
2384 // TemplateSpecializationType, since they need to be mangled even though
2385 // they aren't written.
2386 // - Conversions on non-type template arguments need to be expressed, since
2387 // they can affect the mangling of sizeof/alignof.
2389 // FIXME: This is wrong when mapping to the canonical type for a dependent
2390 // type discards instantiation-dependent portions of the type, such as for:
2392 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2393 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2395 // It's also wrong in the opposite direction when instantiation-dependent,
2396 // canonically-equivalent types differ in some irrelevant portion of inner
2397 // type sugar. In such cases, we fail to form correct substitutions, eg:
2399 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2401 // We should instead canonicalize the non-instantiation-dependent parts,
2402 // regardless of whether the type as a whole is dependent or instantiation
2404 if (!T->isInstantiationDependentType() || T->isDependentType())
2405 T = T.getCanonicalType();
2407 // Desugar any types that are purely sugar.
2409 // Don't desugar through template specialization types that aren't
2410 // type aliases. We need to mangle the template arguments as written.
2411 if (const TemplateSpecializationType *TST
2412 = dyn_cast<TemplateSpecializationType>(T))
2413 if (!TST->isTypeAlias())
2417 = T.getSingleStepDesugaredType(Context.getASTContext());
2424 SplitQualType split = T.split();
2425 Qualifiers quals = split.Quals;
2426 const Type *ty = split.Ty;
2428 bool isSubstitutable =
2429 isTypeSubstitutable(quals, ty, Context.getASTContext());
2430 if (isSubstitutable && mangleSubstitution(T))
2433 // If we're mangling a qualified array type, push the qualifiers to
2434 // the element type.
2435 if (quals && isa<ArrayType>(T)) {
2436 ty = Context.getASTContext().getAsArrayType(T);
2437 quals = Qualifiers();
2439 // Note that we don't update T: we want to add the
2440 // substitution at the original type.
2443 if (quals || ty->isDependentAddressSpaceType()) {
2444 if (const DependentAddressSpaceType *DAST =
2445 dyn_cast<DependentAddressSpaceType>(ty)) {
2446 SplitQualType splitDAST = DAST->getPointeeType().split();
2447 mangleQualifiers(splitDAST.Quals, DAST);
2448 mangleType(QualType(splitDAST.Ty, 0));
2450 mangleQualifiers(quals);
2452 // Recurse: even if the qualified type isn't yet substitutable,
2453 // the unqualified type might be.
2454 mangleType(QualType(ty, 0));
2457 switch (ty->getTypeClass()) {
2458 #define ABSTRACT_TYPE(CLASS, PARENT)
2459 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2461 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2463 #define TYPE(CLASS, PARENT) \
2465 mangleType(static_cast<const CLASS##Type*>(ty)); \
2467 #include "clang/AST/TypeNodes.def"
2471 // Add the substitution.
2472 if (isSubstitutable)
2476 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2477 if (!mangleStandardSubstitution(ND))
2481 void CXXNameMangler::mangleType(const BuiltinType *T) {
2482 // <type> ::= <builtin-type>
2483 // <builtin-type> ::= v # void
2487 // ::= a # signed char
2488 // ::= h # unsigned char
2490 // ::= t # unsigned short
2492 // ::= j # unsigned int
2494 // ::= m # unsigned long
2495 // ::= x # long long, __int64
2496 // ::= y # unsigned long long, __int64
2498 // ::= o # unsigned __int128
2501 // ::= e # long double, __float80
2502 // ::= g # __float128
2503 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2504 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2505 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2506 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2507 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2508 // ::= Di # char32_t
2509 // ::= Ds # char16_t
2510 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2511 // ::= u <source-name> # vendor extended type
2512 std::string type_name;
2513 switch (T->getKind()) {
2514 case BuiltinType::Void:
2517 case BuiltinType::Bool:
2520 case BuiltinType::Char_U:
2521 case BuiltinType::Char_S:
2524 case BuiltinType::UChar:
2527 case BuiltinType::UShort:
2530 case BuiltinType::UInt:
2533 case BuiltinType::ULong:
2536 case BuiltinType::ULongLong:
2539 case BuiltinType::UInt128:
2542 case BuiltinType::SChar:
2545 case BuiltinType::WChar_S:
2546 case BuiltinType::WChar_U:
2549 case BuiltinType::Char8:
2552 case BuiltinType::Char16:
2555 case BuiltinType::Char32:
2558 case BuiltinType::Short:
2561 case BuiltinType::Int:
2564 case BuiltinType::Long:
2567 case BuiltinType::LongLong:
2570 case BuiltinType::Int128:
2573 case BuiltinType::Float16:
2576 case BuiltinType::ShortAccum:
2577 case BuiltinType::Accum:
2578 case BuiltinType::LongAccum:
2579 case BuiltinType::UShortAccum:
2580 case BuiltinType::UAccum:
2581 case BuiltinType::ULongAccum:
2582 case BuiltinType::ShortFract:
2583 case BuiltinType::Fract:
2584 case BuiltinType::LongFract:
2585 case BuiltinType::UShortFract:
2586 case BuiltinType::UFract:
2587 case BuiltinType::ULongFract:
2588 case BuiltinType::SatShortAccum:
2589 case BuiltinType::SatAccum:
2590 case BuiltinType::SatLongAccum:
2591 case BuiltinType::SatUShortAccum:
2592 case BuiltinType::SatUAccum:
2593 case BuiltinType::SatULongAccum:
2594 case BuiltinType::SatShortFract:
2595 case BuiltinType::SatFract:
2596 case BuiltinType::SatLongFract:
2597 case BuiltinType::SatUShortFract:
2598 case BuiltinType::SatUFract:
2599 case BuiltinType::SatULongFract:
2600 llvm_unreachable("Fixed point types are disabled for c++");
2601 case BuiltinType::Half:
2604 case BuiltinType::Float:
2607 case BuiltinType::Double:
2610 case BuiltinType::LongDouble: {
2611 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2612 getASTContext().getLangOpts().OpenMPIsDevice
2613 ? getASTContext().getAuxTargetInfo()
2614 : &getASTContext().getTargetInfo();
2615 Out << TI->getLongDoubleMangling();
2618 case BuiltinType::Float128: {
2619 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2620 getASTContext().getLangOpts().OpenMPIsDevice
2621 ? getASTContext().getAuxTargetInfo()
2622 : &getASTContext().getTargetInfo();
2623 Out << TI->getFloat128Mangling();
2626 case BuiltinType::NullPtr:
2630 #define BUILTIN_TYPE(Id, SingletonId)
2631 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2632 case BuiltinType::Id:
2633 #include "clang/AST/BuiltinTypes.def"
2634 case BuiltinType::Dependent:
2636 llvm_unreachable("mangling a placeholder type");
2638 case BuiltinType::ObjCId:
2639 Out << "11objc_object";
2641 case BuiltinType::ObjCClass:
2642 Out << "10objc_class";
2644 case BuiltinType::ObjCSel:
2645 Out << "13objc_selector";
2647 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2648 case BuiltinType::Id: \
2649 type_name = "ocl_" #ImgType "_" #Suffix; \
2650 Out << type_name.size() << type_name; \
2652 #include "clang/Basic/OpenCLImageTypes.def"
2653 case BuiltinType::OCLSampler:
2654 Out << "11ocl_sampler";
2656 case BuiltinType::OCLEvent:
2657 Out << "9ocl_event";
2659 case BuiltinType::OCLClkEvent:
2660 Out << "12ocl_clkevent";
2662 case BuiltinType::OCLQueue:
2663 Out << "9ocl_queue";
2665 case BuiltinType::OCLReserveID:
2666 Out << "13ocl_reserveid";
2668 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2669 case BuiltinType::Id: \
2670 type_name = "ocl_" #ExtType; \
2671 Out << type_name.size() << type_name; \
2673 #include "clang/Basic/OpenCLExtensionTypes.def"
2677 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2682 case CC_X86VectorCall:
2687 case CC_AArch64VectorCall:
2688 case CC_IntelOclBicc:
2689 case CC_SpirFunction:
2690 case CC_OpenCLKernel:
2691 case CC_PreserveMost:
2692 case CC_PreserveAll:
2693 // FIXME: we should be mangling all of the above.
2696 case CC_X86ThisCall:
2697 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2698 // used explicitly. At this point, we don't have that much information in
2699 // the AST, since clang tends to bake the convention into the canonical
2700 // function type. thiscall only rarely used explicitly, so don't mangle it
2706 case CC_X86FastCall:
2715 llvm_unreachable("bad calling convention");
2718 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2720 if (T->getExtInfo() == FunctionType::ExtInfo())
2723 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2724 // This will get more complicated in the future if we mangle other
2725 // things here; but for now, since we mangle ns_returns_retained as
2726 // a qualifier on the result type, we can get away with this:
2727 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2728 if (!CCQualifier.empty())
2729 mangleVendorQualifier(CCQualifier);
2736 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2737 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2739 // Note that these are *not* substitution candidates. Demanglers might
2740 // have trouble with this if the parameter type is fully substituted.
2742 switch (PI.getABI()) {
2743 case ParameterABI::Ordinary:
2746 // All of these start with "swift", so they come before "ns_consumed".
2747 case ParameterABI::SwiftContext:
2748 case ParameterABI::SwiftErrorResult:
2749 case ParameterABI::SwiftIndirectResult:
2750 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2754 if (PI.isConsumed())
2755 mangleVendorQualifier("ns_consumed");
2757 if (PI.isNoEscape())
2758 mangleVendorQualifier("noescape");
2761 // <type> ::= <function-type>
2762 // <function-type> ::= [<CV-qualifiers>] F [Y]
2763 // <bare-function-type> [<ref-qualifier>] E
2764 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2765 mangleExtFunctionInfo(T);
2767 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2768 // e.g. "const" in "int (A::*)() const".
2769 mangleQualifiers(T->getMethodQuals());
2771 // Mangle instantiation-dependent exception-specification, if present,
2772 // per cxx-abi-dev proposal on 2016-10-11.
2773 if (T->hasInstantiationDependentExceptionSpec()) {
2774 if (isComputedNoexcept(T->getExceptionSpecType())) {
2776 mangleExpression(T->getNoexceptExpr());
2779 assert(T->getExceptionSpecType() == EST_Dynamic);
2781 for (auto ExceptTy : T->exceptions())
2782 mangleType(ExceptTy);
2785 } else if (T->isNothrow()) {
2791 // FIXME: We don't have enough information in the AST to produce the 'Y'
2792 // encoding for extern "C" function types.
2793 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2795 // Mangle the ref-qualifier, if present.
2796 mangleRefQualifier(T->getRefQualifier());
2801 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2802 // Function types without prototypes can arise when mangling a function type
2803 // within an overloadable function in C. We mangle these as the absence of any
2804 // parameter types (not even an empty parameter list).
2807 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2809 FunctionTypeDepth.enterResultType();
2810 mangleType(T->getReturnType());
2811 FunctionTypeDepth.leaveResultType();
2813 FunctionTypeDepth.pop(saved);
2817 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2818 bool MangleReturnType,
2819 const FunctionDecl *FD) {
2820 // Record that we're in a function type. See mangleFunctionParam
2821 // for details on what we're trying to achieve here.
2822 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2824 // <bare-function-type> ::= <signature type>+
2825 if (MangleReturnType) {
2826 FunctionTypeDepth.enterResultType();
2828 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2829 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2830 mangleVendorQualifier("ns_returns_retained");
2832 // Mangle the return type without any direct ARC ownership qualifiers.
2833 QualType ReturnTy = Proto->getReturnType();
2834 if (ReturnTy.getObjCLifetime()) {
2835 auto SplitReturnTy = ReturnTy.split();
2836 SplitReturnTy.Quals.removeObjCLifetime();
2837 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2839 mangleType(ReturnTy);
2841 FunctionTypeDepth.leaveResultType();
2844 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2845 // <builtin-type> ::= v # void
2848 FunctionTypeDepth.pop(saved);
2852 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2853 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2854 // Mangle extended parameter info as order-sensitive qualifiers here.
2855 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2856 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2860 QualType ParamTy = Proto->getParamType(I);
2861 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2864 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2865 // Attr can only take 1 character, so we can hardcode the length below.
2866 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2867 if (Attr->isDynamic())
2868 Out << "U25pass_dynamic_object_size" << Attr->getType();
2870 Out << "U17pass_object_size" << Attr->getType();
2875 FunctionTypeDepth.pop(saved);
2877 // <builtin-type> ::= z # ellipsis
2878 if (Proto->isVariadic())
2882 // <type> ::= <class-enum-type>
2883 // <class-enum-type> ::= <name>
2884 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2885 mangleName(T->getDecl());
2888 // <type> ::= <class-enum-type>
2889 // <class-enum-type> ::= <name>
2890 void CXXNameMangler::mangleType(const EnumType *T) {
2891 mangleType(static_cast<const TagType*>(T));
2893 void CXXNameMangler::mangleType(const RecordType *T) {
2894 mangleType(static_cast<const TagType*>(T));
2896 void CXXNameMangler::mangleType(const TagType *T) {
2897 mangleName(T->getDecl());
2900 // <type> ::= <array-type>
2901 // <array-type> ::= A <positive dimension number> _ <element type>
2902 // ::= A [<dimension expression>] _ <element type>
2903 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2904 Out << 'A' << T->getSize() << '_';
2905 mangleType(T->getElementType());
2907 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2909 // decayed vla types (size 0) will just be skipped.
2910 if (T->getSizeExpr())
2911 mangleExpression(T->getSizeExpr());
2913 mangleType(T->getElementType());
2915 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2917 mangleExpression(T->getSizeExpr());
2919 mangleType(T->getElementType());
2921 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2923 mangleType(T->getElementType());
2926 // <type> ::= <pointer-to-member-type>
2927 // <pointer-to-member-type> ::= M <class type> <member type>
2928 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2930 mangleType(QualType(T->getClass(), 0));
2931 QualType PointeeType = T->getPointeeType();
2932 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2935 // Itanium C++ ABI 5.1.8:
2937 // The type of a non-static member function is considered to be different,
2938 // for the purposes of substitution, from the type of a namespace-scope or
2939 // static member function whose type appears similar. The types of two
2940 // non-static member functions are considered to be different, for the
2941 // purposes of substitution, if the functions are members of different
2942 // classes. In other words, for the purposes of substitution, the class of
2943 // which the function is a member is considered part of the type of
2946 // Given that we already substitute member function pointers as a
2947 // whole, the net effect of this rule is just to unconditionally
2948 // suppress substitution on the function type in a member pointer.
2949 // We increment the SeqID here to emulate adding an entry to the
2950 // substitution table.
2953 mangleType(PointeeType);
2956 // <type> ::= <template-param>
2957 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2958 mangleTemplateParameter(T->getIndex());
2961 // <type> ::= <template-param>
2962 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2963 // FIXME: not clear how to mangle this!
2964 // template <class T...> class A {
2965 // template <class U...> void foo(T(*)(U) x...);
2967 Out << "_SUBSTPACK_";
2970 // <type> ::= P <type> # pointer-to
2971 void CXXNameMangler::mangleType(const PointerType *T) {
2973 mangleType(T->getPointeeType());
2975 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2977 mangleType(T->getPointeeType());
2980 // <type> ::= R <type> # reference-to
2981 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2983 mangleType(T->getPointeeType());
2986 // <type> ::= O <type> # rvalue reference-to (C++0x)
2987 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2989 mangleType(T->getPointeeType());
2992 // <type> ::= C <type> # complex pair (C 2000)
2993 void CXXNameMangler::mangleType(const ComplexType *T) {
2995 mangleType(T->getElementType());
2998 // ARM's ABI for Neon vector types specifies that they should be mangled as
2999 // if they are structs (to match ARM's initial implementation). The
3000 // vector type must be one of the special types predefined by ARM.
3001 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3002 QualType EltType = T->getElementType();
3003 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3004 const char *EltName = nullptr;
3005 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3006 switch (cast<BuiltinType>(EltType)->getKind()) {
3007 case BuiltinType::SChar:
3008 case BuiltinType::UChar:
3009 EltName = "poly8_t";
3011 case BuiltinType::Short:
3012 case BuiltinType::UShort:
3013 EltName = "poly16_t";
3015 case BuiltinType::ULongLong:
3016 EltName = "poly64_t";
3018 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3021 switch (cast<BuiltinType>(EltType)->getKind()) {
3022 case BuiltinType::SChar: EltName = "int8_t"; break;
3023 case BuiltinType::UChar: EltName = "uint8_t"; break;
3024 case BuiltinType::Short: EltName = "int16_t"; break;
3025 case BuiltinType::UShort: EltName = "uint16_t"; break;
3026 case BuiltinType::Int: EltName = "int32_t"; break;
3027 case BuiltinType::UInt: EltName = "uint32_t"; break;
3028 case BuiltinType::LongLong: EltName = "int64_t"; break;
3029 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3030 case BuiltinType::Double: EltName = "float64_t"; break;
3031 case BuiltinType::Float: EltName = "float32_t"; break;
3032 case BuiltinType::Half: EltName = "float16_t";break;
3034 llvm_unreachable("unexpected Neon vector element type");
3037 const char *BaseName = nullptr;
3038 unsigned BitSize = (T->getNumElements() *
3039 getASTContext().getTypeSize(EltType));
3041 BaseName = "__simd64_";
3043 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3044 BaseName = "__simd128_";
3046 Out << strlen(BaseName) + strlen(EltName);
3047 Out << BaseName << EltName;
3050 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3051 DiagnosticsEngine &Diags = Context.getDiags();
3052 unsigned DiagID = Diags.getCustomDiagID(
3053 DiagnosticsEngine::Error,
3054 "cannot mangle this dependent neon vector type yet");
3055 Diags.Report(T->getAttributeLoc(), DiagID);
3058 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3059 switch (EltType->getKind()) {
3060 case BuiltinType::SChar:
3062 case BuiltinType::Short:
3064 case BuiltinType::Int:
3066 case BuiltinType::Long:
3067 case BuiltinType::LongLong:
3069 case BuiltinType::UChar:
3071 case BuiltinType::UShort:
3073 case BuiltinType::UInt:
3075 case BuiltinType::ULong:
3076 case BuiltinType::ULongLong:
3078 case BuiltinType::Half:
3080 case BuiltinType::Float:
3082 case BuiltinType::Double:
3085 llvm_unreachable("Unexpected vector element base type");
3089 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3090 // the equivalent internal name. The vector type must be one of the special
3091 // types predefined by ARM.
3092 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3093 QualType EltType = T->getElementType();
3094 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3096 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3097 (void)BitSize; // Silence warning.
3099 assert((BitSize == 64 || BitSize == 128) &&
3100 "Neon vector type not 64 or 128 bits");
3103 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3104 switch (cast<BuiltinType>(EltType)->getKind()) {
3105 case BuiltinType::UChar:
3108 case BuiltinType::UShort:
3111 case BuiltinType::ULong:
3112 case BuiltinType::ULongLong:
3116 llvm_unreachable("unexpected Neon polynomial vector element type");
3119 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3121 std::string TypeName =
3122 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3123 Out << TypeName.length() << TypeName;
3125 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3126 DiagnosticsEngine &Diags = Context.getDiags();
3127 unsigned DiagID = Diags.getCustomDiagID(
3128 DiagnosticsEngine::Error,
3129 "cannot mangle this dependent neon vector type yet");
3130 Diags.Report(T->getAttributeLoc(), DiagID);
3133 // GNU extension: vector types
3134 // <type> ::= <vector-type>
3135 // <vector-type> ::= Dv <positive dimension number> _
3136 // <extended element type>
3137 // ::= Dv [<dimension expression>] _ <element type>
3138 // <extended element type> ::= <element type>
3139 // ::= p # AltiVec vector pixel
3140 // ::= b # Altivec vector bool
3141 void CXXNameMangler::mangleType(const VectorType *T) {
3142 if ((T->getVectorKind() == VectorType::NeonVector ||
3143 T->getVectorKind() == VectorType::NeonPolyVector)) {
3144 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3145 llvm::Triple::ArchType Arch =
3146 getASTContext().getTargetInfo().getTriple().getArch();
3147 if ((Arch == llvm::Triple::aarch64 ||
3148 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3149 mangleAArch64NeonVectorType(T);
3151 mangleNeonVectorType(T);
3154 Out << "Dv" << T->getNumElements() << '_';
3155 if (T->getVectorKind() == VectorType::AltiVecPixel)
3157 else if (T->getVectorKind() == VectorType::AltiVecBool)
3160 mangleType(T->getElementType());
3163 void CXXNameMangler::mangleType(const DependentVectorType *T) {
3164 if ((T->getVectorKind() == VectorType::NeonVector ||
3165 T->getVectorKind() == VectorType::NeonPolyVector)) {
3166 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3167 llvm::Triple::ArchType Arch =
3168 getASTContext().getTargetInfo().getTriple().getArch();
3169 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3170 !Target.isOSDarwin())
3171 mangleAArch64NeonVectorType(T);
3173 mangleNeonVectorType(T);
3178 mangleExpression(T->getSizeExpr());
3180 if (T->getVectorKind() == VectorType::AltiVecPixel)
3182 else if (T->getVectorKind() == VectorType::AltiVecBool)
3185 mangleType(T->getElementType());
3188 void CXXNameMangler::mangleType(const ExtVectorType *T) {
3189 mangleType(static_cast<const VectorType*>(T));
3191 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3193 mangleExpression(T->getSizeExpr());
3195 mangleType(T->getElementType());
3198 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3199 SplitQualType split = T->getPointeeType().split();
3200 mangleQualifiers(split.Quals, T);
3201 mangleType(QualType(split.Ty, 0));
3204 void CXXNameMangler::mangleType(const PackExpansionType *T) {
3205 // <type> ::= Dp <type> # pack expansion (C++0x)
3207 mangleType(T->getPattern());
3210 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3211 mangleSourceName(T->getDecl()->getIdentifier());
3214 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3215 // Treat __kindof as a vendor extended type qualifier.
3216 if (T->isKindOfType())
3217 Out << "U8__kindof";
3219 if (!T->qual_empty()) {
3220 // Mangle protocol qualifiers.
3221 SmallString<64> QualStr;
3222 llvm::raw_svector_ostream QualOS(QualStr);
3223 QualOS << "objcproto";
3224 for (const auto *I : T->quals()) {
3225 StringRef name = I->getName();
3226 QualOS << name.size() << name;
3228 Out << 'U' << QualStr.size() << QualStr;
3231 mangleType(T->getBaseType());
3233 if (T->isSpecialized()) {
3234 // Mangle type arguments as I <type>+ E
3236 for (auto typeArg : T->getTypeArgs())
3237 mangleType(typeArg);
3242 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3243 Out << "U13block_pointer";
3244 mangleType(T->getPointeeType());
3247 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3248 // Mangle injected class name types as if the user had written the
3249 // specialization out fully. It may not actually be possible to see
3250 // this mangling, though.
3251 mangleType(T->getInjectedSpecializationType());
3254 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3255 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3256 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3258 if (mangleSubstitution(QualType(T, 0)))
3261 mangleTemplatePrefix(T->getTemplateName());
3263 // FIXME: GCC does not appear to mangle the template arguments when
3264 // the template in question is a dependent template name. Should we
3265 // emulate that badness?
3266 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3267 addSubstitution(QualType(T, 0));
3271 void CXXNameMangler::mangleType(const DependentNameType *T) {
3272 // Proposal by cxx-abi-dev, 2014-03-26
3273 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3274 // # dependent elaborated type specifier using
3276 // ::= Ts <name> # dependent elaborated type specifier using
3277 // # 'struct' or 'class'
3278 // ::= Tu <name> # dependent elaborated type specifier using
3280 // ::= Te <name> # dependent elaborated type specifier using
3282 switch (T->getKeyword()) {
3298 // Typename types are always nested
3300 manglePrefix(T->getQualifier());
3301 mangleSourceName(T->getIdentifier());
3305 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3306 // Dependently-scoped template types are nested if they have a prefix.
3309 // TODO: avoid making this TemplateName.
3310 TemplateName Prefix =
3311 getASTContext().getDependentTemplateName(T->getQualifier(),
3312 T->getIdentifier());
3313 mangleTemplatePrefix(Prefix);
3315 // FIXME: GCC does not appear to mangle the template arguments when
3316 // the template in question is a dependent template name. Should we
3317 // emulate that badness?
3318 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3322 void CXXNameMangler::mangleType(const TypeOfType *T) {
3323 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3324 // "extension with parameters" mangling.
3328 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3329 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3330 // "extension with parameters" mangling.
3334 void CXXNameMangler::mangleType(const DecltypeType *T) {
3335 Expr *E = T->getUnderlyingExpr();
3337 // type ::= Dt <expression> E # decltype of an id-expression
3338 // # or class member access
3339 // ::= DT <expression> E # decltype of an expression
3341 // This purports to be an exhaustive list of id-expressions and
3342 // class member accesses. Note that we do not ignore parentheses;
3343 // parentheses change the semantics of decltype for these
3344 // expressions (and cause the mangler to use the other form).
3345 if (isa<DeclRefExpr>(E) ||
3346 isa<MemberExpr>(E) ||
3347 isa<UnresolvedLookupExpr>(E) ||
3348 isa<DependentScopeDeclRefExpr>(E) ||
3349 isa<CXXDependentScopeMemberExpr>(E) ||
3350 isa<UnresolvedMemberExpr>(E))
3354 mangleExpression(E);
3358 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3359 // If this is dependent, we need to record that. If not, we simply
3360 // mangle it as the underlying type since they are equivalent.
3361 if (T->isDependentType()) {
3364 switch (T->getUTTKind()) {
3365 case UnaryTransformType::EnumUnderlyingType:
3371 mangleType(T->getBaseType());
3374 void CXXNameMangler::mangleType(const AutoType *T) {
3375 assert(T->getDeducedType().isNull() &&
3376 "Deduced AutoType shouldn't be handled here!");
3377 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3378 "shouldn't need to mangle __auto_type!");
3379 // <builtin-type> ::= Da # auto
3380 // ::= Dc # decltype(auto)
3381 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3384 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3385 // FIXME: This is not the right mangling. We also need to include a scope
3386 // here in some cases.
3387 QualType D = T->getDeducedType();
3389 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3394 void CXXNameMangler::mangleType(const AtomicType *T) {
3395 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3396 // (Until there's a standardized mangling...)
3398 mangleType(T->getValueType());
3401 void CXXNameMangler::mangleType(const PipeType *T) {
3402 // Pipe type mangling rules are described in SPIR 2.0 specification
3403 // A.1 Data types and A.3 Summary of changes
3404 // <type> ::= 8ocl_pipe
3408 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3409 const llvm::APSInt &Value) {
3410 // <expr-primary> ::= L <type> <value number> E # integer literal
3414 if (T->isBooleanType()) {
3415 // Boolean values are encoded as 0/1.
3416 Out << (Value.getBoolValue() ? '1' : '0');
3418 mangleNumber(Value);
3424 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3425 // Ignore member expressions involving anonymous unions.
3426 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3427 if (!RT->getDecl()->isAnonymousStructOrUnion())
3429 const auto *ME = dyn_cast<MemberExpr>(Base);
3432 Base = ME->getBase();
3433 IsArrow = ME->isArrow();
3436 if (Base->isImplicitCXXThis()) {
3437 // Note: GCC mangles member expressions to the implicit 'this' as
3438 // *this., whereas we represent them as this->. The Itanium C++ ABI
3439 // does not specify anything here, so we follow GCC.
3442 Out << (IsArrow ? "pt" : "dt");
3443 mangleExpression(Base);
3447 /// Mangles a member expression.
3448 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3450 NestedNameSpecifier *qualifier,
3451 NamedDecl *firstQualifierLookup,
3452 DeclarationName member,
3453 const TemplateArgumentLoc *TemplateArgs,
3454 unsigned NumTemplateArgs,
3456 // <expression> ::= dt <expression> <unresolved-name>
3457 // ::= pt <expression> <unresolved-name>
3459 mangleMemberExprBase(base, isArrow);
3460 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3463 /// Look at the callee of the given call expression and determine if
3464 /// it's a parenthesized id-expression which would have triggered ADL
3466 static bool isParenthesizedADLCallee(const CallExpr *call) {
3467 const Expr *callee = call->getCallee();
3468 const Expr *fn = callee->IgnoreParens();
3470 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3471 // too, but for those to appear in the callee, it would have to be
3473 if (callee == fn) return false;
3475 // Must be an unresolved lookup.
3476 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3477 if (!lookup) return false;
3479 assert(!lookup->requiresADL());
3481 // Must be an unqualified lookup.
3482 if (lookup->getQualifier()) return false;
3484 // Must not have found a class member. Note that if one is a class
3485 // member, they're all class members.
3486 if (lookup->getNumDecls() > 0 &&
3487 (*lookup->decls_begin())->isCXXClassMember())
3490 // Otherwise, ADL would have been triggered.
3494 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3495 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3496 Out << CastEncoding;
3497 mangleType(ECE->getType());
3498 mangleExpression(ECE->getSubExpr());
3501 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3502 if (auto *Syntactic = InitList->getSyntacticForm())
3503 InitList = Syntactic;
3504 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3505 mangleExpression(InitList->getInit(i));
3508 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) {
3509 switch (D->getKind()) {
3511 // <expr-primary> ::= L <mangled-name> E # external name
3518 mangleFunctionParam(cast<ParmVarDecl>(D));
3521 case Decl::EnumConstant: {
3522 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3523 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3527 case Decl::NonTypeTemplateParm:
3528 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3529 mangleTemplateParameter(PD->getIndex());
3534 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3535 // <expression> ::= <unary operator-name> <expression>
3536 // ::= <binary operator-name> <expression> <expression>
3537 // ::= <trinary operator-name> <expression> <expression> <expression>
3538 // ::= cv <type> expression # conversion with one argument
3539 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3540 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3541 // ::= sc <type> <expression> # static_cast<type> (expression)
3542 // ::= cc <type> <expression> # const_cast<type> (expression)
3543 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3544 // ::= st <type> # sizeof (a type)
3545 // ::= at <type> # alignof (a type)
3546 // ::= <template-param>
3547 // ::= <function-param>
3548 // ::= sr <type> <unqualified-name> # dependent name
3549 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3550 // ::= ds <expression> <expression> # expr.*expr
3551 // ::= sZ <template-param> # size of a parameter pack
3552 // ::= sZ <function-param> # size of a function parameter pack
3553 // ::= <expr-primary>
3554 // <expr-primary> ::= L <type> <value number> E # integer literal
3555 // ::= L <type <value float> E # floating literal
3556 // ::= L <mangled-name> E # external name
3557 // ::= fpT # 'this' expression
3558 QualType ImplicitlyConvertedToType;
3561 switch (E->getStmtClass()) {
3562 case Expr::NoStmtClass:
3563 #define ABSTRACT_STMT(Type)
3564 #define EXPR(Type, Base)
3565 #define STMT(Type, Base) \
3566 case Expr::Type##Class:
3567 #include "clang/AST/StmtNodes.inc"
3570 // These all can only appear in local or variable-initialization
3571 // contexts and so should never appear in a mangling.
3572 case Expr::AddrLabelExprClass:
3573 case Expr::DesignatedInitUpdateExprClass:
3574 case Expr::ImplicitValueInitExprClass:
3575 case Expr::ArrayInitLoopExprClass:
3576 case Expr::ArrayInitIndexExprClass:
3577 case Expr::NoInitExprClass:
3578 case Expr::ParenListExprClass:
3579 case Expr::LambdaExprClass:
3580 case Expr::MSPropertyRefExprClass:
3581 case Expr::MSPropertySubscriptExprClass:
3582 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3583 case Expr::OMPArraySectionExprClass:
3584 case Expr::CXXInheritedCtorInitExprClass:
3585 llvm_unreachable("unexpected statement kind");
3587 case Expr::ConstantExprClass:
3588 E = cast<ConstantExpr>(E)->getSubExpr();
3591 // FIXME: invent manglings for all these.
3592 case Expr::BlockExprClass:
3593 case Expr::ChooseExprClass:
3594 case Expr::CompoundLiteralExprClass:
3595 case Expr::ExtVectorElementExprClass:
3596 case Expr::GenericSelectionExprClass:
3597 case Expr::ObjCEncodeExprClass:
3598 case Expr::ObjCIsaExprClass:
3599 case Expr::ObjCIvarRefExprClass:
3600 case Expr::ObjCMessageExprClass:
3601 case Expr::ObjCPropertyRefExprClass:
3602 case Expr::ObjCProtocolExprClass:
3603 case Expr::ObjCSelectorExprClass:
3604 case Expr::ObjCStringLiteralClass:
3605 case Expr::ObjCBoxedExprClass:
3606 case Expr::ObjCArrayLiteralClass:
3607 case Expr::ObjCDictionaryLiteralClass:
3608 case Expr::ObjCSubscriptRefExprClass:
3609 case Expr::ObjCIndirectCopyRestoreExprClass:
3610 case Expr::ObjCAvailabilityCheckExprClass:
3611 case Expr::OffsetOfExprClass:
3612 case Expr::PredefinedExprClass:
3613 case Expr::ShuffleVectorExprClass:
3614 case Expr::ConvertVectorExprClass:
3615 case Expr::StmtExprClass:
3616 case Expr::TypeTraitExprClass:
3617 case Expr::ArrayTypeTraitExprClass:
3618 case Expr::ExpressionTraitExprClass:
3619 case Expr::VAArgExprClass:
3620 case Expr::CUDAKernelCallExprClass:
3621 case Expr::AsTypeExprClass:
3622 case Expr::PseudoObjectExprClass:
3623 case Expr::AtomicExprClass:
3624 case Expr::SourceLocExprClass:
3625 case Expr::FixedPointLiteralClass:
3626 case Expr::BuiltinBitCastExprClass:
3629 // As bad as this diagnostic is, it's better than crashing.
3630 DiagnosticsEngine &Diags = Context.getDiags();
3631 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3632 "cannot yet mangle expression type %0");
3633 Diags.Report(E->getExprLoc(), DiagID)
3634 << E->getStmtClassName() << E->getSourceRange();
3639 case Expr::CXXUuidofExprClass: {
3640 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3641 if (UE->isTypeOperand()) {
3642 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3643 Out << "u8__uuidoft";
3646 Expr *UuidExp = UE->getExprOperand();
3647 Out << "u8__uuidofz";
3648 mangleExpression(UuidExp, Arity);
3653 // Even gcc-4.5 doesn't mangle this.
3654 case Expr::BinaryConditionalOperatorClass: {
3655 DiagnosticsEngine &Diags = Context.getDiags();
3657 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3658 "?: operator with omitted middle operand cannot be mangled");
3659 Diags.Report(E->getExprLoc(), DiagID)
3660 << E->getStmtClassName() << E->getSourceRange();
3664 // These are used for internal purposes and cannot be meaningfully mangled.
3665 case Expr::OpaqueValueExprClass:
3666 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3668 case Expr::InitListExprClass: {
3670 mangleInitListElements(cast<InitListExpr>(E));
3675 case Expr::DesignatedInitExprClass: {
3676 auto *DIE = cast<DesignatedInitExpr>(E);
3677 for (const auto &Designator : DIE->designators()) {
3678 if (Designator.isFieldDesignator()) {
3680 mangleSourceName(Designator.getFieldName());
3681 } else if (Designator.isArrayDesignator()) {
3683 mangleExpression(DIE->getArrayIndex(Designator));
3685 assert(Designator.isArrayRangeDesignator() &&
3686 "unknown designator kind");
3688 mangleExpression(DIE->getArrayRangeStart(Designator));
3689 mangleExpression(DIE->getArrayRangeEnd(Designator));
3692 mangleExpression(DIE->getInit());
3696 case Expr::CXXDefaultArgExprClass:
3697 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3700 case Expr::CXXDefaultInitExprClass:
3701 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3704 case Expr::CXXStdInitializerListExprClass:
3705 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3708 case Expr::SubstNonTypeTemplateParmExprClass:
3709 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3713 case Expr::UserDefinedLiteralClass:
3714 // We follow g++'s approach of mangling a UDL as a call to the literal
3716 case Expr::CXXMemberCallExprClass: // fallthrough
3717 case Expr::CallExprClass: {
3718 const CallExpr *CE = cast<CallExpr>(E);
3720 // <expression> ::= cp <simple-id> <expression>* E
3721 // We use this mangling only when the call would use ADL except
3722 // for being parenthesized. Per discussion with David
3723 // Vandervoorde, 2011.04.25.
3724 if (isParenthesizedADLCallee(CE)) {
3726 // The callee here is a parenthesized UnresolvedLookupExpr with
3727 // no qualifier and should always get mangled as a <simple-id>
3730 // <expression> ::= cl <expression>* E
3735 unsigned CallArity = CE->getNumArgs();
3736 for (const Expr *Arg : CE->arguments())
3737 if (isa<PackExpansionExpr>(Arg))
3738 CallArity = UnknownArity;
3740 mangleExpression(CE->getCallee(), CallArity);
3741 for (const Expr *Arg : CE->arguments())
3742 mangleExpression(Arg);
3747 case Expr::CXXNewExprClass: {
3748 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3749 if (New->isGlobalNew()) Out << "gs";
3750 Out << (New->isArray() ? "na" : "nw");
3751 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3752 E = New->placement_arg_end(); I != E; ++I)
3753 mangleExpression(*I);
3755 mangleType(New->getAllocatedType());
3756 if (New->hasInitializer()) {
3757 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3761 const Expr *Init = New->getInitializer();
3762 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3763 // Directly inline the initializers.
3764 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3767 mangleExpression(*I);
3768 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3769 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3770 mangleExpression(PLE->getExpr(i));
3771 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3772 isa<InitListExpr>(Init)) {
3773 // Only take InitListExprs apart for list-initialization.
3774 mangleInitListElements(cast<InitListExpr>(Init));
3776 mangleExpression(Init);
3782 case Expr::CXXPseudoDestructorExprClass: {
3783 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3784 if (const Expr *Base = PDE->getBase())
3785 mangleMemberExprBase(Base, PDE->isArrow());
3786 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3787 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3789 mangleUnresolvedPrefix(Qualifier,
3790 /*recursive=*/true);
3791 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3795 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3798 } else if (Qualifier) {
3799 mangleUnresolvedPrefix(Qualifier);
3801 // <base-unresolved-name> ::= dn <destructor-name>
3803 QualType DestroyedType = PDE->getDestroyedType();
3804 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3808 case Expr::MemberExprClass: {
3809 const MemberExpr *ME = cast<MemberExpr>(E);
3810 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3811 ME->getQualifier(), nullptr,
3812 ME->getMemberDecl()->getDeclName(),
3813 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3818 case Expr::UnresolvedMemberExprClass: {
3819 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3820 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3821 ME->isArrow(), ME->getQualifier(), nullptr,
3822 ME->getMemberName(),
3823 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3828 case Expr::CXXDependentScopeMemberExprClass: {
3829 const CXXDependentScopeMemberExpr *ME
3830 = cast<CXXDependentScopeMemberExpr>(E);
3831 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3832 ME->isArrow(), ME->getQualifier(),
3833 ME->getFirstQualifierFoundInScope(),
3835 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3840 case Expr::UnresolvedLookupExprClass: {
3841 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3842 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3843 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3848 case Expr::CXXUnresolvedConstructExprClass: {
3849 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3850 unsigned N = CE->arg_size();
3852 if (CE->isListInitialization()) {
3853 assert(N == 1 && "unexpected form for list initialization");
3854 auto *IL = cast<InitListExpr>(CE->getArg(0));
3856 mangleType(CE->getType());
3857 mangleInitListElements(IL);
3863 mangleType(CE->getType());
3864 if (N != 1) Out << '_';
3865 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3866 if (N != 1) Out << 'E';
3870 case Expr::CXXConstructExprClass: {
3871 const auto *CE = cast<CXXConstructExpr>(E);
3872 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3874 CE->getNumArgs() >= 1 &&
3875 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3876 "implicit CXXConstructExpr must have one argument");
3877 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3880 for (auto *E : CE->arguments())
3881 mangleExpression(E);
3886 case Expr::CXXTemporaryObjectExprClass: {
3887 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3888 unsigned N = CE->getNumArgs();
3889 bool List = CE->isListInitialization();
3895 mangleType(CE->getType());
3896 if (!List && N != 1)
3898 if (CE->isStdInitListInitialization()) {
3899 // We implicitly created a std::initializer_list<T> for the first argument
3900 // of a constructor of type U in an expression of the form U{a, b, c}.
3901 // Strip all the semantic gunk off the initializer list.
3903 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3904 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3905 mangleInitListElements(ILE);
3907 for (auto *E : CE->arguments())
3908 mangleExpression(E);
3915 case Expr::CXXScalarValueInitExprClass:
3917 mangleType(E->getType());
3921 case Expr::CXXNoexceptExprClass:
3923 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3926 case Expr::UnaryExprOrTypeTraitExprClass: {
3927 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3929 if (!SAE->isInstantiationDependent()) {
3931 // If the operand of a sizeof or alignof operator is not
3932 // instantiation-dependent it is encoded as an integer literal
3933 // reflecting the result of the operator.
3935 // If the result of the operator is implicitly converted to a known
3936 // integer type, that type is used for the literal; otherwise, the type
3937 // of std::size_t or std::ptrdiff_t is used.
3938 QualType T = (ImplicitlyConvertedToType.isNull() ||
3939 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3940 : ImplicitlyConvertedToType;
3941 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3942 mangleIntegerLiteral(T, V);
3946 switch(SAE->getKind()) {
3950 case UETT_PreferredAlignOf:
3954 case UETT_VecStep: {
3955 DiagnosticsEngine &Diags = Context.getDiags();
3956 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3957 "cannot yet mangle vec_step expression");
3958 Diags.Report(DiagID);
3961 case UETT_OpenMPRequiredSimdAlign: {
3962 DiagnosticsEngine &Diags = Context.getDiags();
3963 unsigned DiagID = Diags.getCustomDiagID(
3964 DiagnosticsEngine::Error,
3965 "cannot yet mangle __builtin_omp_required_simd_align expression");
3966 Diags.Report(DiagID);
3970 if (SAE->isArgumentType()) {
3972 mangleType(SAE->getArgumentType());
3975 mangleExpression(SAE->getArgumentExpr());
3980 case Expr::CXXThrowExprClass: {
3981 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3982 // <expression> ::= tw <expression> # throw expression
3984 if (TE->getSubExpr()) {
3986 mangleExpression(TE->getSubExpr());
3993 case Expr::CXXTypeidExprClass: {
3994 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3995 // <expression> ::= ti <type> # typeid (type)
3996 // ::= te <expression> # typeid (expression)
3997 if (TIE->isTypeOperand()) {
3999 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4002 mangleExpression(TIE->getExprOperand());
4007 case Expr::CXXDeleteExprClass: {
4008 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4009 // <expression> ::= [gs] dl <expression> # [::] delete expr
4010 // ::= [gs] da <expression> # [::] delete [] expr
4011 if (DE->isGlobalDelete()) Out << "gs";
4012 Out << (DE->isArrayForm() ? "da" : "dl");
4013 mangleExpression(DE->getArgument());
4017 case Expr::UnaryOperatorClass: {
4018 const UnaryOperator *UO = cast<UnaryOperator>(E);
4019 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4021 mangleExpression(UO->getSubExpr());
4025 case Expr::ArraySubscriptExprClass: {
4026 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4028 // Array subscript is treated as a syntactically weird form of
4031 mangleExpression(AE->getLHS());
4032 mangleExpression(AE->getRHS());
4036 case Expr::CompoundAssignOperatorClass: // fallthrough
4037 case Expr::BinaryOperatorClass: {
4038 const BinaryOperator *BO = cast<BinaryOperator>(E);
4039 if (BO->getOpcode() == BO_PtrMemD)
4042 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4044 mangleExpression(BO->getLHS());
4045 mangleExpression(BO->getRHS());
4049 case Expr::ConditionalOperatorClass: {
4050 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4051 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4052 mangleExpression(CO->getCond());
4053 mangleExpression(CO->getLHS(), Arity);
4054 mangleExpression(CO->getRHS(), Arity);
4058 case Expr::ImplicitCastExprClass: {
4059 ImplicitlyConvertedToType = E->getType();
4060 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4064 case Expr::ObjCBridgedCastExprClass: {
4065 // Mangle ownership casts as a vendor extended operator __bridge,
4066 // __bridge_transfer, or __bridge_retain.
4067 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4068 Out << "v1U" << Kind.size() << Kind;
4070 // Fall through to mangle the cast itself.
4073 case Expr::CStyleCastExprClass:
4074 mangleCastExpression(E, "cv");
4077 case Expr::CXXFunctionalCastExprClass: {
4078 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4079 // FIXME: Add isImplicit to CXXConstructExpr.
4080 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4081 if (CCE->getParenOrBraceRange().isInvalid())
4082 Sub = CCE->getArg(0)->IgnoreImplicit();
4083 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4084 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4085 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4087 mangleType(E->getType());
4088 mangleInitListElements(IL);
4091 mangleCastExpression(E, "cv");
4096 case Expr::CXXStaticCastExprClass:
4097 mangleCastExpression(E, "sc");
4099 case Expr::CXXDynamicCastExprClass:
4100 mangleCastExpression(E, "dc");
4102 case Expr::CXXReinterpretCastExprClass:
4103 mangleCastExpression(E, "rc");
4105 case Expr::CXXConstCastExprClass:
4106 mangleCastExpression(E, "cc");
4109 case Expr::CXXOperatorCallExprClass: {
4110 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4111 unsigned NumArgs = CE->getNumArgs();
4112 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4113 // (the enclosing MemberExpr covers the syntactic portion).
4114 if (CE->getOperator() != OO_Arrow)
4115 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4116 // Mangle the arguments.
4117 for (unsigned i = 0; i != NumArgs; ++i)
4118 mangleExpression(CE->getArg(i));
4122 case Expr::ParenExprClass:
4123 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4126 case Expr::DeclRefExprClass:
4127 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4130 case Expr::SubstNonTypeTemplateParmPackExprClass:
4131 // FIXME: not clear how to mangle this!
4132 // template <unsigned N...> class A {
4133 // template <class U...> void foo(U (&x)[N]...);
4135 Out << "_SUBSTPACK_";
4138 case Expr::FunctionParmPackExprClass: {
4139 // FIXME: not clear how to mangle this!
4140 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4141 Out << "v110_SUBSTPACK";
4142 mangleDeclRefExpr(FPPE->getParameterPack());
4146 case Expr::DependentScopeDeclRefExprClass: {
4147 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4148 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4149 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4154 case Expr::CXXBindTemporaryExprClass:
4155 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4158 case Expr::ExprWithCleanupsClass:
4159 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4162 case Expr::FloatingLiteralClass: {
4163 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4165 mangleType(FL->getType());
4166 mangleFloat(FL->getValue());
4171 case Expr::CharacterLiteralClass:
4173 mangleType(E->getType());
4174 Out << cast<CharacterLiteral>(E)->getValue();
4178 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4179 case Expr::ObjCBoolLiteralExprClass:
4181 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4185 case Expr::CXXBoolLiteralExprClass:
4187 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4191 case Expr::IntegerLiteralClass: {
4192 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4193 if (E->getType()->isSignedIntegerType())
4194 Value.setIsSigned(true);
4195 mangleIntegerLiteral(E->getType(), Value);
4199 case Expr::ImaginaryLiteralClass: {
4200 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4201 // Mangle as if a complex literal.
4202 // Proposal from David Vandevoorde, 2010.06.30.
4204 mangleType(E->getType());
4205 if (const FloatingLiteral *Imag =
4206 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4207 // Mangle a floating-point zero of the appropriate type.
4208 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4210 mangleFloat(Imag->getValue());
4213 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4214 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4215 Value.setIsSigned(true);
4216 mangleNumber(Value);
4222 case Expr::StringLiteralClass: {
4223 // Revised proposal from David Vandervoorde, 2010.07.15.
4225 assert(isa<ConstantArrayType>(E->getType()));
4226 mangleType(E->getType());
4231 case Expr::GNUNullExprClass:
4232 // FIXME: should this really be mangled the same as nullptr?
4235 case Expr::CXXNullPtrLiteralExprClass: {
4240 case Expr::PackExpansionExprClass:
4242 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4245 case Expr::SizeOfPackExprClass: {
4246 auto *SPE = cast<SizeOfPackExpr>(E);
4247 if (SPE->isPartiallySubstituted()) {
4249 for (const auto &A : SPE->getPartialArguments())
4250 mangleTemplateArg(A);
4256 const NamedDecl *Pack = SPE->getPack();
4257 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4258 mangleTemplateParameter(TTP->getIndex());
4259 else if (const NonTypeTemplateParmDecl *NTTP
4260 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4261 mangleTemplateParameter(NTTP->getIndex());
4262 else if (const TemplateTemplateParmDecl *TempTP
4263 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4264 mangleTemplateParameter(TempTP->getIndex());
4266 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4270 case Expr::MaterializeTemporaryExprClass: {
4271 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4275 case Expr::CXXFoldExprClass: {
4276 auto *FE = cast<CXXFoldExpr>(E);
4277 if (FE->isLeftFold())
4278 Out << (FE->getInit() ? "fL" : "fl");
4280 Out << (FE->getInit() ? "fR" : "fr");
4282 if (FE->getOperator() == BO_PtrMemD)
4286 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4290 mangleExpression(FE->getLHS());
4292 mangleExpression(FE->getRHS());
4296 case Expr::CXXThisExprClass:
4300 case Expr::CoawaitExprClass:
4301 // FIXME: Propose a non-vendor mangling.
4302 Out << "v18co_await";
4303 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4306 case Expr::DependentCoawaitExprClass:
4307 // FIXME: Propose a non-vendor mangling.
4308 Out << "v18co_await";
4309 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4312 case Expr::CoyieldExprClass:
4313 // FIXME: Propose a non-vendor mangling.
4314 Out << "v18co_yield";
4315 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4320 /// Mangle an expression which refers to a parameter variable.
4322 /// <expression> ::= <function-param>
4323 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4324 /// <function-param> ::= fp <top-level CV-qualifiers>
4325 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4326 /// <function-param> ::= fL <L-1 non-negative number>
4327 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4328 /// <function-param> ::= fL <L-1 non-negative number>
4329 /// p <top-level CV-qualifiers>
4330 /// <I-1 non-negative number> _ # L > 0, I > 0
4332 /// L is the nesting depth of the parameter, defined as 1 if the
4333 /// parameter comes from the innermost function prototype scope
4334 /// enclosing the current context, 2 if from the next enclosing
4335 /// function prototype scope, and so on, with one special case: if
4336 /// we've processed the full parameter clause for the innermost
4337 /// function type, then L is one less. This definition conveniently
4338 /// makes it irrelevant whether a function's result type was written
4339 /// trailing or leading, but is otherwise overly complicated; the
4340 /// numbering was first designed without considering references to
4341 /// parameter in locations other than return types, and then the
4342 /// mangling had to be generalized without changing the existing
4345 /// I is the zero-based index of the parameter within its parameter
4346 /// declaration clause. Note that the original ABI document describes
4347 /// this using 1-based ordinals.
4348 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4349 unsigned parmDepth = parm->getFunctionScopeDepth();
4350 unsigned parmIndex = parm->getFunctionScopeIndex();
4353 // parmDepth does not include the declaring function prototype.
4354 // FunctionTypeDepth does account for that.
4355 assert(parmDepth < FunctionTypeDepth.getDepth());
4356 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4357 if (FunctionTypeDepth.isInResultType())
4360 if (nestingDepth == 0) {
4363 Out << "fL" << (nestingDepth - 1) << 'p';
4366 // Top-level qualifiers. We don't have to worry about arrays here,
4367 // because parameters declared as arrays should already have been
4368 // transformed to have pointer type. FIXME: apparently these don't
4369 // get mangled if used as an rvalue of a known non-class type?
4370 assert(!parm->getType()->isArrayType()
4371 && "parameter's type is still an array type?");
4373 if (const DependentAddressSpaceType *DAST =
4374 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4375 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4377 mangleQualifiers(parm->getType().getQualifiers());
4381 if (parmIndex != 0) {
4382 Out << (parmIndex - 1);
4387 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4388 const CXXRecordDecl *InheritedFrom) {
4389 // <ctor-dtor-name> ::= C1 # complete object constructor
4390 // ::= C2 # base object constructor
4391 // ::= CI1 <type> # complete inheriting constructor
4392 // ::= CI2 <type> # base inheriting constructor
4394 // In addition, C5 is a comdat name with C1 and C2 in it.
4408 case Ctor_DefaultClosure:
4409 case Ctor_CopyingClosure:
4410 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4413 mangleName(InheritedFrom);
4416 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4417 // <ctor-dtor-name> ::= D0 # deleting destructor
4418 // ::= D1 # complete object destructor
4419 // ::= D2 # base object destructor
4421 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4438 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4439 unsigned NumTemplateArgs) {
4440 // <template-args> ::= I <template-arg>+ E
4442 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4443 mangleTemplateArg(TemplateArgs[i].getArgument());
4447 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4448 // <template-args> ::= I <template-arg>+ E
4450 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4451 mangleTemplateArg(AL[i]);
4455 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4456 unsigned NumTemplateArgs) {
4457 // <template-args> ::= I <template-arg>+ E
4459 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4460 mangleTemplateArg(TemplateArgs[i]);
4464 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4465 // <template-arg> ::= <type> # type or template
4466 // ::= X <expression> E # expression
4467 // ::= <expr-primary> # simple expressions
4468 // ::= J <template-arg>* E # argument pack
4469 if (!A.isInstantiationDependent() || A.isDependent())
4470 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4472 switch (A.getKind()) {
4473 case TemplateArgument::Null:
4474 llvm_unreachable("Cannot mangle NULL template argument");
4476 case TemplateArgument::Type:
4477 mangleType(A.getAsType());
4479 case TemplateArgument::Template:
4480 // This is mangled as <type>.
4481 mangleType(A.getAsTemplate());
4483 case TemplateArgument::TemplateExpansion:
4484 // <type> ::= Dp <type> # pack expansion (C++0x)
4486 mangleType(A.getAsTemplateOrTemplatePattern());
4488 case TemplateArgument::Expression: {
4489 // It's possible to end up with a DeclRefExpr here in certain
4490 // dependent cases, in which case we should mangle as a
4492 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts();
4493 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4494 const ValueDecl *D = DRE->getDecl();
4495 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4504 mangleExpression(E);
4508 case TemplateArgument::Integral:
4509 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4511 case TemplateArgument::Declaration: {
4512 // <expr-primary> ::= L <mangled-name> E # external name
4513 // Clang produces AST's where pointer-to-member-function expressions
4514 // and pointer-to-function expressions are represented as a declaration not
4515 // an expression. We compensate for it here to produce the correct mangling.
4516 ValueDecl *D = A.getAsDecl();
4517 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4518 if (compensateMangling) {
4520 mangleOperatorName(OO_Amp, 1);
4524 // References to external entities use the mangled name; if the name would
4525 // not normally be mangled then mangle it as unqualified.
4529 if (compensateMangling)
4534 case TemplateArgument::NullPtr: {
4535 // <expr-primary> ::= L <type> 0 E
4537 mangleType(A.getNullPtrType());
4541 case TemplateArgument::Pack: {
4542 // <template-arg> ::= J <template-arg>* E
4544 for (const auto &P : A.pack_elements())
4545 mangleTemplateArg(P);
4551 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4552 // <template-param> ::= T_ # first template parameter
4553 // ::= T <parameter-2 non-negative number> _
4557 Out << 'T' << (Index - 1) << '_';
4560 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4563 else if (SeqID > 1) {
4566 // <seq-id> is encoded in base-36, using digits and upper case letters.
4567 char Buffer[7]; // log(2**32) / log(36) ~= 7
4568 MutableArrayRef<char> BufferRef(Buffer);
4569 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4571 for (; SeqID != 0; SeqID /= 36) {
4572 unsigned C = SeqID % 36;
4573 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4576 Out.write(I.base(), I - BufferRef.rbegin());
4581 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4582 bool result = mangleSubstitution(tname);
4583 assert(result && "no existing substitution for template name");
4587 // <substitution> ::= S <seq-id> _
4589 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4590 // Try one of the standard substitutions first.
4591 if (mangleStandardSubstitution(ND))
4594 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4595 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4598 /// Determine whether the given type has any qualifiers that are relevant for
4600 static bool hasMangledSubstitutionQualifiers(QualType T) {
4601 Qualifiers Qs = T.getQualifiers();
4602 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
4605 bool CXXNameMangler::mangleSubstitution(QualType T) {
4606 if (!hasMangledSubstitutionQualifiers(T)) {
4607 if (const RecordType *RT = T->getAs<RecordType>())
4608 return mangleSubstitution(RT->getDecl());
4611 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4613 return mangleSubstitution(TypePtr);
4616 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4617 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4618 return mangleSubstitution(TD);
4620 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4621 return mangleSubstitution(
4622 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4625 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4626 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4627 if (I == Substitutions.end())
4630 unsigned SeqID = I->second;
4637 static bool isCharType(QualType T) {
4641 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4642 T->isSpecificBuiltinType(BuiltinType::Char_U);
4645 /// Returns whether a given type is a template specialization of a given name
4646 /// with a single argument of type char.
4647 static bool isCharSpecialization(QualType T, const char *Name) {
4651 const RecordType *RT = T->getAs<RecordType>();
4655 const ClassTemplateSpecializationDecl *SD =
4656 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4660 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4663 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4664 if (TemplateArgs.size() != 1)
4667 if (!isCharType(TemplateArgs[0].getAsType()))
4670 return SD->getIdentifier()->getName() == Name;
4673 template <std::size_t StrLen>
4674 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4675 const char (&Str)[StrLen]) {
4676 if (!SD->getIdentifier()->isStr(Str))
4679 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4680 if (TemplateArgs.size() != 2)
4683 if (!isCharType(TemplateArgs[0].getAsType()))
4686 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4692 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4693 // <substitution> ::= St # ::std::
4694 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4701 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4702 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4705 // <substitution> ::= Sa # ::std::allocator
4706 if (TD->getIdentifier()->isStr("allocator")) {
4711 // <<substitution> ::= Sb # ::std::basic_string
4712 if (TD->getIdentifier()->isStr("basic_string")) {
4718 if (const ClassTemplateSpecializationDecl *SD =
4719 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4720 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4723 // <substitution> ::= Ss # ::std::basic_string<char,
4724 // ::std::char_traits<char>,
4725 // ::std::allocator<char> >
4726 if (SD->getIdentifier()->isStr("basic_string")) {
4727 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4729 if (TemplateArgs.size() != 3)
4732 if (!isCharType(TemplateArgs[0].getAsType()))
4735 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4738 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4745 // <substitution> ::= Si # ::std::basic_istream<char,
4746 // ::std::char_traits<char> >
4747 if (isStreamCharSpecialization(SD, "basic_istream")) {
4752 // <substitution> ::= So # ::std::basic_ostream<char,
4753 // ::std::char_traits<char> >
4754 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4759 // <substitution> ::= Sd # ::std::basic_iostream<char,
4760 // ::std::char_traits<char> >
4761 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4769 void CXXNameMangler::addSubstitution(QualType T) {
4770 if (!hasMangledSubstitutionQualifiers(T)) {
4771 if (const RecordType *RT = T->getAs<RecordType>()) {
4772 addSubstitution(RT->getDecl());
4777 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4778 addSubstitution(TypePtr);
4781 void CXXNameMangler::addSubstitution(TemplateName Template) {
4782 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4783 return addSubstitution(TD);
4785 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4786 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4789 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4790 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4791 Substitutions[Ptr] = SeqID++;
4794 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4795 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4796 if (Other->SeqID > SeqID) {
4797 Substitutions.swap(Other->Substitutions);
4798 SeqID = Other->SeqID;
4802 CXXNameMangler::AbiTagList
4803 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4804 // When derived abi tags are disabled there is no need to make any list.
4805 if (DisableDerivedAbiTags)
4806 return AbiTagList();
4808 llvm::raw_null_ostream NullOutStream;
4809 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4810 TrackReturnTypeTags.disableDerivedAbiTags();
4812 const FunctionProtoType *Proto =
4813 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4814 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
4815 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4816 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4817 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4818 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
4820 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4823 CXXNameMangler::AbiTagList
4824 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4825 // When derived abi tags are disabled there is no need to make any list.
4826 if (DisableDerivedAbiTags)
4827 return AbiTagList();
4829 llvm::raw_null_ostream NullOutStream;
4830 CXXNameMangler TrackVariableType(*this, NullOutStream);
4831 TrackVariableType.disableDerivedAbiTags();
4833 TrackVariableType.mangleType(VD->getType());
4835 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4838 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4839 const VarDecl *VD) {
4840 llvm::raw_null_ostream NullOutStream;
4841 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4842 TrackAbiTags.mangle(VD);
4843 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4848 /// Mangles the name of the declaration D and emits that name to the given
4851 /// If the declaration D requires a mangled name, this routine will emit that
4852 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4853 /// and this routine will return false. In this case, the caller should just
4854 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4856 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4858 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4859 "Invalid mangleName() call, argument is not a variable or function!");
4860 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4861 "Invalid mangleName() call on 'structor decl!");
4863 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4864 getASTContext().getSourceManager(),
4865 "Mangling declaration");
4867 CXXNameMangler Mangler(*this, Out, D);
4871 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4874 CXXNameMangler Mangler(*this, Out, D, Type);
4878 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4881 CXXNameMangler Mangler(*this, Out, D, Type);
4885 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4887 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4891 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4893 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4897 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4898 const ThunkInfo &Thunk,
4900 // <special-name> ::= T <call-offset> <base encoding>
4901 // # base is the nominal target function of thunk
4902 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4903 // # base is the nominal target function of thunk
4904 // # first call-offset is 'this' adjustment
4905 // # second call-offset is result adjustment
4907 assert(!isa<CXXDestructorDecl>(MD) &&
4908 "Use mangleCXXDtor for destructor decls!");
4909 CXXNameMangler Mangler(*this, Out);
4910 Mangler.getStream() << "_ZT";
4911 if (!Thunk.Return.isEmpty())
4912 Mangler.getStream() << 'c';
4914 // Mangle the 'this' pointer adjustment.
4915 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4916 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4918 // Mangle the return pointer adjustment if there is one.
4919 if (!Thunk.Return.isEmpty())
4920 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4921 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4923 Mangler.mangleFunctionEncoding(MD);
4926 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4927 const CXXDestructorDecl *DD, CXXDtorType Type,
4928 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4929 // <special-name> ::= T <call-offset> <base encoding>
4930 // # base is the nominal target function of thunk
4931 CXXNameMangler Mangler(*this, Out, DD, Type);
4932 Mangler.getStream() << "_ZT";
4934 // Mangle the 'this' pointer adjustment.
4935 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4936 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4938 Mangler.mangleFunctionEncoding(DD);
4941 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4942 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4944 // <special-name> ::= GV <object name> # Guard variable for one-time
4946 CXXNameMangler Mangler(*this, Out);
4947 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4948 // be a bug that is fixed in trunk.
4949 Mangler.getStream() << "_ZGV";
4950 Mangler.mangleName(D);
4953 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4955 // These symbols are internal in the Itanium ABI, so the names don't matter.
4956 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4957 // avoid duplicate symbols.
4958 Out << "__cxx_global_var_init";
4961 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4963 // Prefix the mangling of D with __dtor_.
4964 CXXNameMangler Mangler(*this, Out);
4965 Mangler.getStream() << "__dtor_";
4966 if (shouldMangleDeclName(D))
4969 Mangler.getStream() << D->getName();
4972 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4973 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4974 CXXNameMangler Mangler(*this, Out);
4975 Mangler.getStream() << "__filt_";
4976 if (shouldMangleDeclName(EnclosingDecl))
4977 Mangler.mangle(EnclosingDecl);
4979 Mangler.getStream() << EnclosingDecl->getName();
4982 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4983 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4984 CXXNameMangler Mangler(*this, Out);
4985 Mangler.getStream() << "__fin_";
4986 if (shouldMangleDeclName(EnclosingDecl))
4987 Mangler.mangle(EnclosingDecl);
4989 Mangler.getStream() << EnclosingDecl->getName();
4992 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4994 // <special-name> ::= TH <object name>
4995 CXXNameMangler Mangler(*this, Out);
4996 Mangler.getStream() << "_ZTH";
4997 Mangler.mangleName(D);
5001 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
5003 // <special-name> ::= TW <object name>
5004 CXXNameMangler Mangler(*this, Out);
5005 Mangler.getStream() << "_ZTW";
5006 Mangler.mangleName(D);
5009 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
5010 unsigned ManglingNumber,
5012 // We match the GCC mangling here.
5013 // <special-name> ::= GR <object name>
5014 CXXNameMangler Mangler(*this, Out);
5015 Mangler.getStream() << "_ZGR";
5016 Mangler.mangleName(D);
5017 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
5018 Mangler.mangleSeqID(ManglingNumber - 1);
5021 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5023 // <special-name> ::= TV <type> # virtual table
5024 CXXNameMangler Mangler(*this, Out);
5025 Mangler.getStream() << "_ZTV";
5026 Mangler.mangleNameOrStandardSubstitution(RD);
5029 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5031 // <special-name> ::= TT <type> # VTT structure
5032 CXXNameMangler Mangler(*this, Out);
5033 Mangler.getStream() << "_ZTT";
5034 Mangler.mangleNameOrStandardSubstitution(RD);
5037 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5039 const CXXRecordDecl *Type,
5041 // <special-name> ::= TC <type> <offset number> _ <base type>
5042 CXXNameMangler Mangler(*this, Out);
5043 Mangler.getStream() << "_ZTC";
5044 Mangler.mangleNameOrStandardSubstitution(RD);
5045 Mangler.getStream() << Offset;
5046 Mangler.getStream() << '_';
5047 Mangler.mangleNameOrStandardSubstitution(Type);
5050 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
5051 // <special-name> ::= TI <type> # typeinfo structure
5052 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5053 CXXNameMangler Mangler(*this, Out);
5054 Mangler.getStream() << "_ZTI";
5055 Mangler.mangleType(Ty);
5058 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5060 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5061 CXXNameMangler Mangler(*this, Out);
5062 Mangler.getStream() << "_ZTS";
5063 Mangler.mangleType(Ty);
5066 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5067 mangleCXXRTTIName(Ty, Out);
5070 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5071 llvm_unreachable("Can't mangle string literals");
5074 ItaniumMangleContext *
5075 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5076 return new ItaniumMangleContextImpl(Context, Diags);