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/ExprConcepts.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
36 using namespace clang;
40 /// Retrieve the declaration context that should be used when mangling the given
42 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
43 // The ABI assumes that lambda closure types that occur within
44 // default arguments live in the context of the function. However, due to
45 // the way in which Clang parses and creates function declarations, this is
46 // not the case: the lambda closure type ends up living in the context
47 // where the function itself resides, because the function declaration itself
48 // had not yet been created. Fix the context here.
49 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
51 if (ParmVarDecl *ContextParam
52 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
53 return ContextParam->getDeclContext();
56 // Perform the same check for block literals.
57 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
58 if (ParmVarDecl *ContextParam
59 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
60 return ContextParam->getDeclContext();
63 const DeclContext *DC = D->getDeclContext();
64 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
65 isa<OMPDeclareMapperDecl>(DC)) {
66 return getEffectiveDeclContext(cast<Decl>(DC));
69 if (const auto *VD = dyn_cast<VarDecl>(D))
71 return VD->getASTContext().getTranslationUnitDecl();
73 if (const auto *FD = dyn_cast<FunctionDecl>(D))
75 return FD->getASTContext().getTranslationUnitDecl();
77 return DC->getRedeclContext();
80 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
81 return getEffectiveDeclContext(cast<Decl>(DC));
84 static bool isLocalContainerContext(const DeclContext *DC) {
85 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
88 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
89 const DeclContext *DC = getEffectiveDeclContext(D);
90 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
91 if (isLocalContainerContext(DC))
92 return dyn_cast<RecordDecl>(D);
94 DC = getEffectiveDeclContext(D);
99 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
100 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
101 return ftd->getTemplatedDecl();
106 static const NamedDecl *getStructor(const NamedDecl *decl) {
107 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
108 return (fn ? getStructor(fn) : decl);
111 static bool isLambda(const NamedDecl *ND) {
112 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
116 return Record->isLambda();
119 static const unsigned UnknownArity = ~0U;
121 class ItaniumMangleContextImpl : public ItaniumMangleContext {
122 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
123 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
124 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
127 explicit ItaniumMangleContextImpl(ASTContext &Context,
128 DiagnosticsEngine &Diags)
129 : ItaniumMangleContext(Context, Diags) {}
131 /// @name Mangler Entry Points
134 bool shouldMangleCXXName(const NamedDecl *D) override;
135 bool shouldMangleStringLiteral(const StringLiteral *) override {
138 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
139 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
140 raw_ostream &) override;
141 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
142 const ThisAdjustment &ThisAdjustment,
143 raw_ostream &) override;
144 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
145 raw_ostream &) override;
146 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
147 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
148 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
149 const CXXRecordDecl *Type, raw_ostream &) override;
150 void mangleCXXRTTI(QualType T, raw_ostream &) override;
151 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
152 void mangleTypeName(QualType T, raw_ostream &) override;
153 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
154 raw_ostream &) override;
155 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
156 raw_ostream &) override;
158 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
159 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
160 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
161 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
162 void mangleDynamicAtExitDestructor(const VarDecl *D,
163 raw_ostream &Out) override;
164 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
165 raw_ostream &Out) override;
166 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
167 raw_ostream &Out) override;
168 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
169 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
170 raw_ostream &) override;
172 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
174 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
176 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
177 // Lambda closure types are already numbered.
181 // Anonymous tags are already numbered.
182 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
183 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 // Use the canonical number for externally visible decls.
188 if (ND->isExternallyVisible()) {
189 unsigned discriminator = getASTContext().getManglingNumber(ND);
190 if (discriminator == 1)
192 disc = discriminator - 2;
196 // Make up a reasonable number for internal decls.
197 unsigned &discriminator = Uniquifier[ND];
198 if (!discriminator) {
199 const DeclContext *DC = getEffectiveDeclContext(ND);
200 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
202 if (discriminator == 1)
204 disc = discriminator-2;
210 /// Manage the mangling of a single name.
211 class CXXNameMangler {
212 ItaniumMangleContextImpl &Context;
214 bool NullOut = false;
215 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
216 /// This mode is used when mangler creates another mangler recursively to
217 /// calculate ABI tags for the function return value or the variable type.
218 /// Also it is required to avoid infinite recursion in some cases.
219 bool DisableDerivedAbiTags = false;
221 /// The "structor" is the top-level declaration being mangled, if
222 /// that's not a template specialization; otherwise it's the pattern
223 /// for that specialization.
224 const NamedDecl *Structor;
225 unsigned StructorType;
227 /// The next substitution sequence number.
230 class FunctionTypeDepthState {
233 enum { InResultTypeMask = 1 };
236 FunctionTypeDepthState() : Bits(0) {}
238 /// The number of function types we're inside.
239 unsigned getDepth() const {
243 /// True if we're in the return type of the innermost function type.
244 bool isInResultType() const {
245 return Bits & InResultTypeMask;
248 FunctionTypeDepthState push() {
249 FunctionTypeDepthState tmp = *this;
250 Bits = (Bits & ~InResultTypeMask) + 2;
254 void enterResultType() {
255 Bits |= InResultTypeMask;
258 void leaveResultType() {
259 Bits &= ~InResultTypeMask;
262 void pop(FunctionTypeDepthState saved) {
263 assert(getDepth() == saved.getDepth() + 1);
269 // abi_tag is a gcc attribute, taking one or more strings called "tags".
270 // The goal is to annotate against which version of a library an object was
271 // built and to be able to provide backwards compatibility ("dual abi").
272 // For more information see docs/ItaniumMangleAbiTags.rst.
273 typedef SmallVector<StringRef, 4> AbiTagList;
275 // State to gather all implicit and explicit tags used in a mangled name.
276 // Must always have an instance of this while emitting any name to keep
278 class AbiTagState final {
280 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
286 AbiTagState(const AbiTagState &) = delete;
287 AbiTagState &operator=(const AbiTagState &) = delete;
289 ~AbiTagState() { pop(); }
291 void write(raw_ostream &Out, const NamedDecl *ND,
292 const AbiTagList *AdditionalAbiTags) {
293 ND = cast<NamedDecl>(ND->getCanonicalDecl());
294 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
296 !AdditionalAbiTags &&
297 "only function and variables need a list of additional abi tags");
298 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
299 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
300 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
301 AbiTag->tags().end());
303 // Don't emit abi tags for namespaces.
309 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
310 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
311 AbiTag->tags().end());
312 TagList.insert(TagList.end(), AbiTag->tags().begin(),
313 AbiTag->tags().end());
316 if (AdditionalAbiTags) {
317 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
318 AdditionalAbiTags->end());
319 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
320 AdditionalAbiTags->end());
324 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
326 writeSortedUniqueAbiTags(Out, TagList);
329 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
330 void setUsedAbiTags(const AbiTagList &AbiTags) {
331 UsedAbiTags = AbiTags;
334 const AbiTagList &getEmittedAbiTags() const {
335 return EmittedAbiTags;
338 const AbiTagList &getSortedUniqueUsedAbiTags() {
339 llvm::sort(UsedAbiTags);
340 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
346 //! All abi tags used implicitly or explicitly.
347 AbiTagList UsedAbiTags;
348 //! All explicit abi tags (i.e. not from namespace).
349 AbiTagList EmittedAbiTags;
351 AbiTagState *&LinkHead;
352 AbiTagState *Parent = nullptr;
355 assert(LinkHead == this &&
356 "abi tag link head must point to us on destruction");
358 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
359 UsedAbiTags.begin(), UsedAbiTags.end());
360 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
361 EmittedAbiTags.begin(),
362 EmittedAbiTags.end());
367 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
368 for (const auto &Tag : AbiTags) {
369 EmittedAbiTags.push_back(Tag);
377 AbiTagState *AbiTags = nullptr;
378 AbiTagState AbiTagsRoot;
380 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
381 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
383 ASTContext &getASTContext() const { return Context.getASTContext(); }
386 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
387 const NamedDecl *D = nullptr, bool NullOut_ = false)
388 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
389 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
390 // These can't be mangled without a ctor type or dtor type.
391 assert(!D || (!isa<CXXDestructorDecl>(D) &&
392 !isa<CXXConstructorDecl>(D)));
394 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
395 const CXXConstructorDecl *D, CXXCtorType Type)
396 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
397 SeqID(0), AbiTagsRoot(AbiTags) { }
398 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
399 const CXXDestructorDecl *D, CXXDtorType Type)
400 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
401 SeqID(0), AbiTagsRoot(AbiTags) { }
403 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
404 : Context(Outer.Context), Out(Out_), NullOut(false),
405 Structor(Outer.Structor), StructorType(Outer.StructorType),
406 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
407 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
409 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
410 : Context(Outer.Context), Out(Out_), NullOut(true),
411 Structor(Outer.Structor), StructorType(Outer.StructorType),
412 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
413 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
415 raw_ostream &getStream() { return Out; }
417 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
418 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
420 void mangle(const NamedDecl *D);
421 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
422 void mangleNumber(const llvm::APSInt &I);
423 void mangleNumber(int64_t Number);
424 void mangleFloat(const llvm::APFloat &F);
425 void mangleFunctionEncoding(const FunctionDecl *FD);
426 void mangleSeqID(unsigned SeqID);
427 void mangleName(const NamedDecl *ND);
428 void mangleType(QualType T);
429 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
430 void mangleLambdaSig(const CXXRecordDecl *Lambda);
434 bool mangleSubstitution(const NamedDecl *ND);
435 bool mangleSubstitution(QualType T);
436 bool mangleSubstitution(TemplateName Template);
437 bool mangleSubstitution(uintptr_t Ptr);
439 void mangleExistingSubstitution(TemplateName name);
441 bool mangleStandardSubstitution(const NamedDecl *ND);
443 void addSubstitution(const NamedDecl *ND) {
444 ND = cast<NamedDecl>(ND->getCanonicalDecl());
446 addSubstitution(reinterpret_cast<uintptr_t>(ND));
448 void addSubstitution(QualType T);
449 void addSubstitution(TemplateName Template);
450 void addSubstitution(uintptr_t Ptr);
451 // Destructive copy substitutions from other mangler.
452 void extendSubstitutions(CXXNameMangler* Other);
454 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
455 bool recursive = false);
456 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
457 DeclarationName name,
458 const TemplateArgumentLoc *TemplateArgs,
459 unsigned NumTemplateArgs,
460 unsigned KnownArity = UnknownArity);
462 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
464 void mangleNameWithAbiTags(const NamedDecl *ND,
465 const AbiTagList *AdditionalAbiTags);
466 void mangleModuleName(const Module *M);
467 void mangleModuleNamePrefix(StringRef Name);
468 void mangleTemplateName(const TemplateDecl *TD,
469 const TemplateArgument *TemplateArgs,
470 unsigned NumTemplateArgs);
471 void mangleUnqualifiedName(const NamedDecl *ND,
472 const AbiTagList *AdditionalAbiTags) {
473 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
476 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
478 const AbiTagList *AdditionalAbiTags);
479 void mangleUnscopedName(const NamedDecl *ND,
480 const AbiTagList *AdditionalAbiTags);
481 void mangleUnscopedTemplateName(const TemplateDecl *ND,
482 const AbiTagList *AdditionalAbiTags);
483 void mangleUnscopedTemplateName(TemplateName,
484 const AbiTagList *AdditionalAbiTags);
485 void mangleSourceName(const IdentifierInfo *II);
486 void mangleRegCallName(const IdentifierInfo *II);
487 void mangleSourceNameWithAbiTags(
488 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
489 void mangleLocalName(const Decl *D,
490 const AbiTagList *AdditionalAbiTags);
491 void mangleBlockForPrefix(const BlockDecl *Block);
492 void mangleUnqualifiedBlock(const BlockDecl *Block);
493 void mangleTemplateParamDecl(const NamedDecl *Decl);
494 void mangleLambda(const CXXRecordDecl *Lambda);
495 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
496 const AbiTagList *AdditionalAbiTags,
497 bool NoFunction=false);
498 void mangleNestedName(const TemplateDecl *TD,
499 const TemplateArgument *TemplateArgs,
500 unsigned NumTemplateArgs);
501 void manglePrefix(NestedNameSpecifier *qualifier);
502 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
503 void manglePrefix(QualType type);
504 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
505 void mangleTemplatePrefix(TemplateName Template);
506 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
507 StringRef Prefix = "");
508 void mangleOperatorName(DeclarationName Name, unsigned Arity);
509 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
510 void mangleVendorQualifier(StringRef qualifier);
511 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
512 void mangleRefQualifier(RefQualifierKind RefQualifier);
514 void mangleObjCMethodName(const ObjCMethodDecl *MD);
516 // Declare manglers for every type class.
517 #define ABSTRACT_TYPE(CLASS, PARENT)
518 #define NON_CANONICAL_TYPE(CLASS, PARENT)
519 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
520 #include "clang/AST/TypeNodes.inc"
522 void mangleType(const TagType*);
523 void mangleType(TemplateName);
524 static StringRef getCallingConvQualifierName(CallingConv CC);
525 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
526 void mangleExtFunctionInfo(const FunctionType *T);
527 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
528 const FunctionDecl *FD = nullptr);
529 void mangleNeonVectorType(const VectorType *T);
530 void mangleNeonVectorType(const DependentVectorType *T);
531 void mangleAArch64NeonVectorType(const VectorType *T);
532 void mangleAArch64NeonVectorType(const DependentVectorType *T);
534 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
535 void mangleMemberExprBase(const Expr *base, bool isArrow);
536 void mangleMemberExpr(const Expr *base, bool isArrow,
537 NestedNameSpecifier *qualifier,
538 NamedDecl *firstQualifierLookup,
539 DeclarationName name,
540 const TemplateArgumentLoc *TemplateArgs,
541 unsigned NumTemplateArgs,
542 unsigned knownArity);
543 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
544 void mangleInitListElements(const InitListExpr *InitList);
545 void mangleDeclRefExpr(const NamedDecl *D);
546 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
547 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
548 void mangleCXXDtorType(CXXDtorType T);
550 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
551 unsigned NumTemplateArgs);
552 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
553 unsigned NumTemplateArgs);
554 void mangleTemplateArgs(const TemplateArgumentList &AL);
555 void mangleTemplateArg(TemplateArgument A);
557 void mangleTemplateParameter(unsigned Depth, unsigned Index);
559 void mangleFunctionParam(const ParmVarDecl *parm);
561 void writeAbiTags(const NamedDecl *ND,
562 const AbiTagList *AdditionalAbiTags);
564 // Returns sorted unique list of ABI tags.
565 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
566 // Returns sorted unique list of ABI tags.
567 AbiTagList makeVariableTypeTags(const VarDecl *VD);
572 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
573 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
575 LanguageLinkage L = FD->getLanguageLinkage();
576 // Overloadable functions need mangling.
577 if (FD->hasAttr<OverloadableAttr>())
580 // "main" is not mangled.
584 // The Windows ABI expects that we would never mangle "typical"
585 // user-defined entry points regardless of visibility or freestanding-ness.
587 // N.B. This is distinct from asking about "main". "main" has a lot of
588 // special rules associated with it in the standard while these
589 // user-defined entry points are outside of the purview of the standard.
590 // For example, there can be only one definition for "main" in a standards
591 // compliant program; however nothing forbids the existence of wmain and
592 // WinMain in the same translation unit.
593 if (FD->isMSVCRTEntryPoint())
596 // C++ functions and those whose names are not a simple identifier need
598 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
601 // C functions are not mangled.
602 if (L == CLanguageLinkage)
606 // Otherwise, no mangling is done outside C++ mode.
607 if (!getASTContext().getLangOpts().CPlusPlus)
610 const VarDecl *VD = dyn_cast<VarDecl>(D);
611 if (VD && !isa<DecompositionDecl>(D)) {
612 // C variables are not mangled.
616 // Variables at global scope with non-internal linkage are not mangled
617 const DeclContext *DC = getEffectiveDeclContext(D);
618 // Check for extern variable declared locally.
619 if (DC->isFunctionOrMethod() && D->hasLinkage())
620 while (!DC->isNamespace() && !DC->isTranslationUnit())
621 DC = getEffectiveParentContext(DC);
622 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
623 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
624 !isa<VarTemplateSpecializationDecl>(D))
631 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
632 const AbiTagList *AdditionalAbiTags) {
633 assert(AbiTags && "require AbiTagState");
634 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
637 void CXXNameMangler::mangleSourceNameWithAbiTags(
638 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
639 mangleSourceName(ND->getIdentifier());
640 writeAbiTags(ND, AdditionalAbiTags);
643 void CXXNameMangler::mangle(const NamedDecl *D) {
644 // <mangled-name> ::= _Z <encoding>
646 // ::= <special-name>
648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
649 mangleFunctionEncoding(FD);
650 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
652 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
653 mangleName(IFD->getAnonField());
655 mangleName(cast<FieldDecl>(D));
658 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
659 // <encoding> ::= <function name> <bare-function-type>
661 // Don't mangle in the type if this isn't a decl we should typically mangle.
662 if (!Context.shouldMangleDeclName(FD)) {
667 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
668 if (ReturnTypeAbiTags.empty()) {
669 // There are no tags for return type, the simplest case.
671 mangleFunctionEncodingBareType(FD);
675 // Mangle function name and encoding to temporary buffer.
676 // We have to output name and encoding to the same mangler to get the same
677 // substitution as it will be in final mangling.
678 SmallString<256> FunctionEncodingBuf;
679 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
680 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
681 // Output name of the function.
682 FunctionEncodingMangler.disableDerivedAbiTags();
683 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
685 // Remember length of the function name in the buffer.
686 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
687 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
689 // Get tags from return type that are not present in function name or
691 const AbiTagList &UsedAbiTags =
692 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
693 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
694 AdditionalAbiTags.erase(
695 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
696 UsedAbiTags.begin(), UsedAbiTags.end(),
697 AdditionalAbiTags.begin()),
698 AdditionalAbiTags.end());
700 // Output name with implicit tags and function encoding from temporary buffer.
701 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
702 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
704 // Function encoding could create new substitutions so we have to add
705 // temp mangled substitutions to main mangler.
706 extendSubstitutions(&FunctionEncodingMangler);
709 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
710 if (FD->hasAttr<EnableIfAttr>()) {
711 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
712 Out << "Ua9enable_ifI";
713 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
714 E = FD->getAttrs().end();
716 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
720 mangleExpression(EIA->getCond());
724 FunctionTypeDepth.pop(Saved);
727 // When mangling an inheriting constructor, the bare function type used is
728 // that of the inherited constructor.
729 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
730 if (auto Inherited = CD->getInheritedConstructor())
731 FD = Inherited.getConstructor();
733 // Whether the mangling of a function type includes the return type depends on
734 // the context and the nature of the function. The rules for deciding whether
735 // the return type is included are:
737 // 1. Template functions (names or types) have return types encoded, with
738 // the exceptions listed below.
739 // 2. Function types not appearing as part of a function name mangling,
740 // e.g. parameters, pointer types, etc., have return type encoded, with the
741 // exceptions listed below.
742 // 3. Non-template function names do not have return types encoded.
744 // The exceptions mentioned in (1) and (2) above, for which the return type is
745 // never included, are
748 // 3. Conversion operator functions, e.g. operator int.
749 bool MangleReturnType = false;
750 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
751 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
752 isa<CXXConversionDecl>(FD)))
753 MangleReturnType = true;
755 // Mangle the type of the primary template.
756 FD = PrimaryTemplate->getTemplatedDecl();
759 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
760 MangleReturnType, FD);
763 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
764 while (isa<LinkageSpecDecl>(DC)) {
765 DC = getEffectiveParentContext(DC);
771 /// Return whether a given namespace is the 'std' namespace.
772 static bool isStd(const NamespaceDecl *NS) {
773 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
774 ->isTranslationUnit())
777 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
778 return II && II->isStr("std");
781 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
783 static bool isStdNamespace(const DeclContext *DC) {
784 if (!DC->isNamespace())
787 return isStd(cast<NamespaceDecl>(DC));
790 static const TemplateDecl *
791 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
792 // Check if we have a function template.
793 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
794 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
795 TemplateArgs = FD->getTemplateSpecializationArgs();
800 // Check if we have a class template.
801 if (const ClassTemplateSpecializationDecl *Spec =
802 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
803 TemplateArgs = &Spec->getTemplateArgs();
804 return Spec->getSpecializedTemplate();
807 // Check if we have a variable template.
808 if (const VarTemplateSpecializationDecl *Spec =
809 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
810 TemplateArgs = &Spec->getTemplateArgs();
811 return Spec->getSpecializedTemplate();
817 void CXXNameMangler::mangleName(const NamedDecl *ND) {
818 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
819 // Variables should have implicit tags from its type.
820 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
821 if (VariableTypeAbiTags.empty()) {
822 // Simple case no variable type tags.
823 mangleNameWithAbiTags(VD, nullptr);
827 // Mangle variable name to null stream to collect tags.
828 llvm::raw_null_ostream NullOutStream;
829 CXXNameMangler VariableNameMangler(*this, NullOutStream);
830 VariableNameMangler.disableDerivedAbiTags();
831 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
833 // Get tags from variable type that are not present in its name.
834 const AbiTagList &UsedAbiTags =
835 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
836 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
837 AdditionalAbiTags.erase(
838 std::set_difference(VariableTypeAbiTags.begin(),
839 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
840 UsedAbiTags.end(), AdditionalAbiTags.begin()),
841 AdditionalAbiTags.end());
843 // Output name with implicit tags.
844 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
846 mangleNameWithAbiTags(ND, nullptr);
850 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
851 const AbiTagList *AdditionalAbiTags) {
852 // <name> ::= [<module-name>] <nested-name>
853 // ::= [<module-name>] <unscoped-name>
854 // ::= [<module-name>] <unscoped-template-name> <template-args>
857 const DeclContext *DC = getEffectiveDeclContext(ND);
859 // If this is an extern variable declared locally, the relevant DeclContext
860 // is that of the containing namespace, or the translation unit.
861 // FIXME: This is a hack; extern variables declared locally should have
862 // a proper semantic declaration context!
863 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
864 while (!DC->isNamespace() && !DC->isTranslationUnit())
865 DC = getEffectiveParentContext(DC);
866 else if (GetLocalClassDecl(ND)) {
867 mangleLocalName(ND, AdditionalAbiTags);
871 DC = IgnoreLinkageSpecDecls(DC);
873 if (isLocalContainerContext(DC)) {
874 mangleLocalName(ND, AdditionalAbiTags);
878 // Do not mangle the owning module for an external linkage declaration.
879 // This enables backwards-compatibility with non-modular code, and is
880 // a valid choice since conflicts are not permitted by C++ Modules TS
881 // [basic.def.odr]/6.2.
882 if (!ND->hasExternalFormalLinkage())
883 if (Module *M = ND->getOwningModuleForLinkage())
886 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
887 // Check if we have a template.
888 const TemplateArgumentList *TemplateArgs = nullptr;
889 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
890 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
891 mangleTemplateArgs(*TemplateArgs);
895 mangleUnscopedName(ND, AdditionalAbiTags);
899 mangleNestedName(ND, DC, AdditionalAbiTags);
902 void CXXNameMangler::mangleModuleName(const Module *M) {
903 // Implement the C++ Modules TS name mangling proposal; see
904 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
906 // <module-name> ::= W <unscoped-name>+ E
907 // ::= W <module-subst> <unscoped-name>* E
909 mangleModuleNamePrefix(M->Name);
913 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
914 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
915 // ::= W <seq-id - 10> _ # otherwise
916 auto It = ModuleSubstitutions.find(Name);
917 if (It != ModuleSubstitutions.end()) {
919 Out << '_' << static_cast<char>('0' + It->second);
921 Out << 'W' << (It->second - 10) << '_';
925 // FIXME: Preserve hierarchy in module names rather than flattening
926 // them to strings; use Module*s as substitution keys.
927 auto Parts = Name.rsplit('.');
928 if (Parts.second.empty())
929 Parts.second = Parts.first;
931 mangleModuleNamePrefix(Parts.first);
933 Out << Parts.second.size() << Parts.second;
934 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
937 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
938 const TemplateArgument *TemplateArgs,
939 unsigned NumTemplateArgs) {
940 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
942 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
943 mangleUnscopedTemplateName(TD, nullptr);
944 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
946 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
950 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
951 const AbiTagList *AdditionalAbiTags) {
952 // <unscoped-name> ::= <unqualified-name>
953 // ::= St <unqualified-name> # ::std::
955 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
958 mangleUnqualifiedName(ND, AdditionalAbiTags);
961 void CXXNameMangler::mangleUnscopedTemplateName(
962 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
963 // <unscoped-template-name> ::= <unscoped-name>
964 // ::= <substitution>
965 if (mangleSubstitution(ND))
968 // <template-template-param> ::= <template-param>
969 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
970 assert(!AdditionalAbiTags &&
971 "template template param cannot have abi tags");
972 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
973 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
974 mangleUnscopedName(ND, AdditionalAbiTags);
976 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
982 void CXXNameMangler::mangleUnscopedTemplateName(
983 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
984 // <unscoped-template-name> ::= <unscoped-name>
985 // ::= <substitution>
986 if (TemplateDecl *TD = Template.getAsTemplateDecl())
987 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
989 if (mangleSubstitution(Template))
992 assert(!AdditionalAbiTags &&
993 "dependent template name cannot have abi tags");
995 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
996 assert(Dependent && "Not a dependent template name?");
997 if (const IdentifierInfo *Id = Dependent->getIdentifier())
998 mangleSourceName(Id);
1000 mangleOperatorName(Dependent->getOperator(), UnknownArity);
1002 addSubstitution(Template);
1005 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1007 // Floating-point literals are encoded using a fixed-length
1008 // lowercase hexadecimal string corresponding to the internal
1009 // representation (IEEE on Itanium), high-order bytes first,
1010 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1012 // The 'without leading zeroes' thing seems to be an editorial
1013 // mistake; see the discussion on cxx-abi-dev beginning on
1016 // Our requirements here are just barely weird enough to justify
1017 // using a custom algorithm instead of post-processing APInt::toString().
1019 llvm::APInt valueBits = f.bitcastToAPInt();
1020 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1021 assert(numCharacters != 0);
1023 // Allocate a buffer of the right number of characters.
1024 SmallVector<char, 20> buffer(numCharacters);
1026 // Fill the buffer left-to-right.
1027 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1028 // The bit-index of the next hex digit.
1029 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1031 // Project out 4 bits starting at 'digitIndex'.
1032 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1033 hexDigit >>= (digitBitIndex % 64);
1036 // Map that over to a lowercase hex digit.
1037 static const char charForHex[16] = {
1038 '0', '1', '2', '3', '4', '5', '6', '7',
1039 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1041 buffer[stringIndex] = charForHex[hexDigit];
1044 Out.write(buffer.data(), numCharacters);
1047 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1048 if (Value.isSigned() && Value.isNegative()) {
1050 Value.abs().print(Out, /*signed*/ false);
1052 Value.print(Out, /*signed*/ false);
1056 void CXXNameMangler::mangleNumber(int64_t Number) {
1057 // <number> ::= [n] <non-negative decimal integer>
1066 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1067 // <call-offset> ::= h <nv-offset> _
1068 // ::= v <v-offset> _
1069 // <nv-offset> ::= <offset number> # non-virtual base override
1070 // <v-offset> ::= <offset number> _ <virtual offset number>
1071 // # virtual base override, with vcall offset
1074 mangleNumber(NonVirtual);
1080 mangleNumber(NonVirtual);
1082 mangleNumber(Virtual);
1086 void CXXNameMangler::manglePrefix(QualType type) {
1087 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1088 if (!mangleSubstitution(QualType(TST, 0))) {
1089 mangleTemplatePrefix(TST->getTemplateName());
1091 // FIXME: GCC does not appear to mangle the template arguments when
1092 // the template in question is a dependent template name. Should we
1093 // emulate that badness?
1094 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1095 addSubstitution(QualType(TST, 0));
1097 } else if (const auto *DTST =
1098 type->getAs<DependentTemplateSpecializationType>()) {
1099 if (!mangleSubstitution(QualType(DTST, 0))) {
1100 TemplateName Template = getASTContext().getDependentTemplateName(
1101 DTST->getQualifier(), DTST->getIdentifier());
1102 mangleTemplatePrefix(Template);
1104 // FIXME: GCC does not appear to mangle the template arguments when
1105 // the template in question is a dependent template name. Should we
1106 // emulate that badness?
1107 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1108 addSubstitution(QualType(DTST, 0));
1111 // We use the QualType mangle type variant here because it handles
1117 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1119 /// \param recursive - true if this is being called recursively,
1120 /// i.e. if there is more prefix "to the right".
1121 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1125 // <unresolved-name> ::= [gs] <base-unresolved-name>
1127 // T::x / decltype(p)::x
1128 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1130 // T::N::x /decltype(p)::N::x
1131 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1132 // <base-unresolved-name>
1134 // A::x, N::y, A<T>::z; "gs" means leading "::"
1135 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1136 // <base-unresolved-name>
1138 switch (qualifier->getKind()) {
1139 case NestedNameSpecifier::Global:
1142 // We want an 'sr' unless this is the entire NNS.
1146 // We never want an 'E' here.
1149 case NestedNameSpecifier::Super:
1150 llvm_unreachable("Can't mangle __super specifier");
1152 case NestedNameSpecifier::Namespace:
1153 if (qualifier->getPrefix())
1154 mangleUnresolvedPrefix(qualifier->getPrefix(),
1155 /*recursive*/ true);
1158 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1160 case NestedNameSpecifier::NamespaceAlias:
1161 if (qualifier->getPrefix())
1162 mangleUnresolvedPrefix(qualifier->getPrefix(),
1163 /*recursive*/ true);
1166 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1169 case NestedNameSpecifier::TypeSpec:
1170 case NestedNameSpecifier::TypeSpecWithTemplate: {
1171 const Type *type = qualifier->getAsType();
1173 // We only want to use an unresolved-type encoding if this is one of:
1175 // - a template type parameter
1176 // - a template template parameter with arguments
1177 // In all of these cases, we should have no prefix.
1178 if (qualifier->getPrefix()) {
1179 mangleUnresolvedPrefix(qualifier->getPrefix(),
1180 /*recursive*/ true);
1182 // Otherwise, all the cases want this.
1186 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1192 case NestedNameSpecifier::Identifier:
1193 // Member expressions can have these without prefixes.
1194 if (qualifier->getPrefix())
1195 mangleUnresolvedPrefix(qualifier->getPrefix(),
1196 /*recursive*/ true);
1200 mangleSourceName(qualifier->getAsIdentifier());
1201 // An Identifier has no type information, so we can't emit abi tags for it.
1205 // If this was the innermost part of the NNS, and we fell out to
1206 // here, append an 'E'.
1211 /// Mangle an unresolved-name, which is generally used for names which
1212 /// weren't resolved to specific entities.
1213 void CXXNameMangler::mangleUnresolvedName(
1214 NestedNameSpecifier *qualifier, DeclarationName name,
1215 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1216 unsigned knownArity) {
1217 if (qualifier) mangleUnresolvedPrefix(qualifier);
1218 switch (name.getNameKind()) {
1219 // <base-unresolved-name> ::= <simple-id>
1220 case DeclarationName::Identifier:
1221 mangleSourceName(name.getAsIdentifierInfo());
1223 // <base-unresolved-name> ::= dn <destructor-name>
1224 case DeclarationName::CXXDestructorName:
1226 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1228 // <base-unresolved-name> ::= on <operator-name>
1229 case DeclarationName::CXXConversionFunctionName:
1230 case DeclarationName::CXXLiteralOperatorName:
1231 case DeclarationName::CXXOperatorName:
1233 mangleOperatorName(name, knownArity);
1235 case DeclarationName::CXXConstructorName:
1236 llvm_unreachable("Can't mangle a constructor name!");
1237 case DeclarationName::CXXUsingDirective:
1238 llvm_unreachable("Can't mangle a using directive name!");
1239 case DeclarationName::CXXDeductionGuideName:
1240 llvm_unreachable("Can't mangle a deduction guide name!");
1241 case DeclarationName::ObjCMultiArgSelector:
1242 case DeclarationName::ObjCOneArgSelector:
1243 case DeclarationName::ObjCZeroArgSelector:
1244 llvm_unreachable("Can't mangle Objective-C selector names here!");
1247 // The <simple-id> and on <operator-name> productions end in an optional
1250 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1253 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1254 DeclarationName Name,
1255 unsigned KnownArity,
1256 const AbiTagList *AdditionalAbiTags) {
1257 unsigned Arity = KnownArity;
1258 // <unqualified-name> ::= <operator-name>
1259 // ::= <ctor-dtor-name>
1260 // ::= <source-name>
1261 switch (Name.getNameKind()) {
1262 case DeclarationName::Identifier: {
1263 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1265 // We mangle decomposition declarations as the names of their bindings.
1266 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1267 // FIXME: Non-standard mangling for decomposition declarations:
1269 // <unqualified-name> ::= DC <source-name>* E
1271 // These can never be referenced across translation units, so we do
1272 // not need a cross-vendor mangling for anything other than demanglers.
1273 // Proposed on cxx-abi-dev on 2016-08-12
1275 for (auto *BD : DD->bindings())
1276 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1278 writeAbiTags(ND, AdditionalAbiTags);
1283 // Match GCC's naming convention for internal linkage symbols, for
1284 // symbols that are not actually visible outside of this TU. GCC
1285 // distinguishes between internal and external linkage symbols in
1286 // its mangling, to support cases like this that were valid C++ prior
1289 // void test() { extern void foo(); }
1290 // static void foo();
1292 // Don't bother with the L marker for names in anonymous namespaces; the
1293 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1294 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1295 // implying internal linkage.
1296 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1297 !ND->isExternallyVisible() &&
1298 getEffectiveDeclContext(ND)->isFileContext() &&
1299 !ND->isInAnonymousNamespace())
1302 auto *FD = dyn_cast<FunctionDecl>(ND);
1303 bool IsRegCall = FD &&
1304 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1305 clang::CC_X86RegCall;
1307 mangleRegCallName(II);
1309 mangleSourceName(II);
1311 writeAbiTags(ND, AdditionalAbiTags);
1315 // Otherwise, an anonymous entity. We must have a declaration.
1316 assert(ND && "mangling empty name without declaration");
1318 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1319 if (NS->isAnonymousNamespace()) {
1320 // This is how gcc mangles these names.
1321 Out << "12_GLOBAL__N_1";
1326 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1327 // We must have an anonymous union or struct declaration.
1328 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1330 // Itanium C++ ABI 5.1.2:
1332 // For the purposes of mangling, the name of an anonymous union is
1333 // considered to be the name of the first named data member found by a
1334 // pre-order, depth-first, declaration-order walk of the data members of
1335 // the anonymous union. If there is no such data member (i.e., if all of
1336 // the data members in the union are unnamed), then there is no way for
1337 // a program to refer to the anonymous union, and there is therefore no
1338 // need to mangle its name.
1339 assert(RD->isAnonymousStructOrUnion()
1340 && "Expected anonymous struct or union!");
1341 const FieldDecl *FD = RD->findFirstNamedDataMember();
1343 // It's actually possible for various reasons for us to get here
1344 // with an empty anonymous struct / union. Fortunately, it
1345 // doesn't really matter what name we generate.
1347 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1349 mangleSourceName(FD->getIdentifier());
1350 // Not emitting abi tags: internal name anyway.
1354 // Class extensions have no name as a category, and it's possible
1355 // for them to be the semantic parent of certain declarations
1356 // (primarily, tag decls defined within declarations). Such
1357 // declarations will always have internal linkage, so the name
1358 // doesn't really matter, but we shouldn't crash on them. For
1359 // safety, just handle all ObjC containers here.
1360 if (isa<ObjCContainerDecl>(ND))
1363 // We must have an anonymous struct.
1364 const TagDecl *TD = cast<TagDecl>(ND);
1365 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1366 assert(TD->getDeclContext() == D->getDeclContext() &&
1367 "Typedef should not be in another decl context!");
1368 assert(D->getDeclName().getAsIdentifierInfo() &&
1369 "Typedef was not named!");
1370 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1371 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1372 // Explicit abi tags are still possible; take from underlying type, not
1374 writeAbiTags(TD, nullptr);
1378 // <unnamed-type-name> ::= <closure-type-name>
1380 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1381 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1382 // # Parameter types or 'v' for 'void'.
1383 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1384 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1385 assert(!AdditionalAbiTags &&
1386 "Lambda type cannot have additional abi tags");
1387 mangleLambda(Record);
1392 if (TD->isExternallyVisible()) {
1393 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1395 if (UnnamedMangle > 1)
1396 Out << UnnamedMangle - 2;
1398 writeAbiTags(TD, AdditionalAbiTags);
1402 // Get a unique id for the anonymous struct. If it is not a real output
1403 // ID doesn't matter so use fake one.
1404 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1406 // Mangle it as a source name in the form
1408 // where n is the length of the string.
1411 Str += llvm::utostr(AnonStructId);
1418 case DeclarationName::ObjCZeroArgSelector:
1419 case DeclarationName::ObjCOneArgSelector:
1420 case DeclarationName::ObjCMultiArgSelector:
1421 llvm_unreachable("Can't mangle Objective-C selector names here!");
1423 case DeclarationName::CXXConstructorName: {
1424 const CXXRecordDecl *InheritedFrom = nullptr;
1425 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1426 if (auto Inherited =
1427 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1428 InheritedFrom = Inherited.getConstructor()->getParent();
1429 InheritedTemplateArgs =
1430 Inherited.getConstructor()->getTemplateSpecializationArgs();
1434 // If the named decl is the C++ constructor we're mangling, use the type
1436 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1438 // Otherwise, use the complete constructor name. This is relevant if a
1439 // class with a constructor is declared within a constructor.
1440 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1442 // FIXME: The template arguments are part of the enclosing prefix or
1443 // nested-name, but it's more convenient to mangle them here.
1444 if (InheritedTemplateArgs)
1445 mangleTemplateArgs(*InheritedTemplateArgs);
1447 writeAbiTags(ND, AdditionalAbiTags);
1451 case DeclarationName::CXXDestructorName:
1453 // If the named decl is the C++ destructor we're mangling, use the type we
1455 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1457 // Otherwise, use the complete destructor name. This is relevant if a
1458 // class with a destructor is declared within a destructor.
1459 mangleCXXDtorType(Dtor_Complete);
1460 writeAbiTags(ND, AdditionalAbiTags);
1463 case DeclarationName::CXXOperatorName:
1464 if (ND && Arity == UnknownArity) {
1465 Arity = cast<FunctionDecl>(ND)->getNumParams();
1467 // If we have a member function, we need to include the 'this' pointer.
1468 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1469 if (!MD->isStatic())
1473 case DeclarationName::CXXConversionFunctionName:
1474 case DeclarationName::CXXLiteralOperatorName:
1475 mangleOperatorName(Name, Arity);
1476 writeAbiTags(ND, AdditionalAbiTags);
1479 case DeclarationName::CXXDeductionGuideName:
1480 llvm_unreachable("Can't mangle a deduction guide name!");
1482 case DeclarationName::CXXUsingDirective:
1483 llvm_unreachable("Can't mangle a using directive name!");
1487 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1488 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1489 // <number> ::= [n] <non-negative decimal integer>
1490 // <identifier> ::= <unqualified source code identifier>
1491 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1495 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1496 // <source-name> ::= <positive length number> <identifier>
1497 // <number> ::= [n] <non-negative decimal integer>
1498 // <identifier> ::= <unqualified source code identifier>
1499 Out << II->getLength() << II->getName();
1502 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1503 const DeclContext *DC,
1504 const AbiTagList *AdditionalAbiTags,
1507 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1508 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1509 // <template-args> E
1512 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1513 Qualifiers MethodQuals = Method->getMethodQualifiers();
1514 // We do not consider restrict a distinguishing attribute for overloading
1515 // purposes so we must not mangle it.
1516 MethodQuals.removeRestrict();
1517 mangleQualifiers(MethodQuals);
1518 mangleRefQualifier(Method->getRefQualifier());
1521 // Check if we have a template.
1522 const TemplateArgumentList *TemplateArgs = nullptr;
1523 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1524 mangleTemplatePrefix(TD, NoFunction);
1525 mangleTemplateArgs(*TemplateArgs);
1528 manglePrefix(DC, NoFunction);
1529 mangleUnqualifiedName(ND, AdditionalAbiTags);
1534 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1535 const TemplateArgument *TemplateArgs,
1536 unsigned NumTemplateArgs) {
1537 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1541 mangleTemplatePrefix(TD);
1542 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1547 void CXXNameMangler::mangleLocalName(const Decl *D,
1548 const AbiTagList *AdditionalAbiTags) {
1549 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1550 // := Z <function encoding> E s [<discriminator>]
1551 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1553 // <discriminator> := _ <non-negative number>
1554 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1555 const RecordDecl *RD = GetLocalClassDecl(D);
1556 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1561 AbiTagState LocalAbiTags(AbiTags);
1563 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1564 mangleObjCMethodName(MD);
1565 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1566 mangleBlockForPrefix(BD);
1568 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1570 // Implicit ABI tags (from namespace) are not available in the following
1571 // entity; reset to actually emitted tags, which are available.
1572 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1577 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1578 // be a bug that is fixed in trunk.
1581 // The parameter number is omitted for the last parameter, 0 for the
1582 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1583 // <entity name> will of course contain a <closure-type-name>: Its
1584 // numbering will be local to the particular argument in which it appears
1585 // -- other default arguments do not affect its encoding.
1586 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1587 if (CXXRD && CXXRD->isLambda()) {
1588 if (const ParmVarDecl *Parm
1589 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1590 if (const FunctionDecl *Func
1591 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1593 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1595 mangleNumber(Num - 2);
1601 // Mangle the name relative to the closest enclosing function.
1602 // equality ok because RD derived from ND above
1604 mangleUnqualifiedName(RD, AdditionalAbiTags);
1605 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1606 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1607 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1608 mangleUnqualifiedBlock(BD);
1610 const NamedDecl *ND = cast<NamedDecl>(D);
1611 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1612 true /*NoFunction*/);
1614 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1615 // Mangle a block in a default parameter; see above explanation for
1617 if (const ParmVarDecl *Parm
1618 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1619 if (const FunctionDecl *Func
1620 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1622 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1624 mangleNumber(Num - 2);
1629 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1630 mangleUnqualifiedBlock(BD);
1632 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1635 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1637 if (Context.getNextDiscriminator(ND, disc)) {
1641 Out << "__" << disc << '_';
1646 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1647 if (GetLocalClassDecl(Block)) {
1648 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1651 const DeclContext *DC = getEffectiveDeclContext(Block);
1652 if (isLocalContainerContext(DC)) {
1653 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1656 manglePrefix(getEffectiveDeclContext(Block));
1657 mangleUnqualifiedBlock(Block);
1660 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1661 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1662 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1663 Context->getDeclContext()->isRecord()) {
1664 const auto *ND = cast<NamedDecl>(Context);
1665 if (ND->getIdentifier()) {
1666 mangleSourceNameWithAbiTags(ND);
1672 // If we have a block mangling number, use it.
1673 unsigned Number = Block->getBlockManglingNumber();
1674 // Otherwise, just make up a number. It doesn't matter what it is because
1675 // the symbol in question isn't externally visible.
1677 Number = Context.getBlockId(Block, false);
1679 // Stored mangling numbers are 1-based.
1688 // <template-param-decl>
1689 // ::= Ty # template type parameter
1690 // ::= Tn <type> # template non-type parameter
1691 // ::= Tt <template-param-decl>* E # template template parameter
1692 // ::= Tp <template-param-decl> # template parameter pack
1693 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1694 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1695 if (Ty->isParameterPack())
1698 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1699 if (Tn->isExpandedParameterPack()) {
1700 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1702 mangleType(Tn->getExpansionType(I));
1705 QualType T = Tn->getType();
1706 if (Tn->isParameterPack()) {
1708 if (auto *PackExpansion = T->getAs<PackExpansionType>())
1709 T = PackExpansion->getPattern();
1714 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1715 if (Tt->isExpandedParameterPack()) {
1716 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1719 for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1720 mangleTemplateParamDecl(Param);
1724 if (Tt->isParameterPack())
1727 for (auto *Param : *Tt->getTemplateParameters())
1728 mangleTemplateParamDecl(Param);
1734 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1735 // If the context of a closure type is an initializer for a class member
1736 // (static or nonstatic), it is encoded in a qualified name with a final
1737 // <prefix> of the form:
1739 // <data-member-prefix> := <member source-name> M
1741 // Technically, the data-member-prefix is part of the <prefix>. However,
1742 // since a closure type will always be mangled with a prefix, it's easier
1743 // to emit that last part of the prefix here.
1744 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1745 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1746 !isa<ParmVarDecl>(Context)) {
1747 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1748 // reasonable mangling here.
1749 if (const IdentifierInfo *Name
1750 = cast<NamedDecl>(Context)->getIdentifier()) {
1751 mangleSourceName(Name);
1752 const TemplateArgumentList *TemplateArgs = nullptr;
1753 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1754 mangleTemplateArgs(*TemplateArgs);
1761 mangleLambdaSig(Lambda);
1764 // The number is omitted for the first closure type with a given
1765 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1766 // (in lexical order) with that same <lambda-sig> and context.
1768 // The AST keeps track of the number for us.
1769 unsigned Number = Lambda->getLambdaManglingNumber();
1770 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1772 mangleNumber(Number - 2);
1776 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
1777 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1778 mangleTemplateParamDecl(D);
1779 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1780 getAs<FunctionProtoType>();
1781 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1782 Lambda->getLambdaStaticInvoker());
1785 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1786 switch (qualifier->getKind()) {
1787 case NestedNameSpecifier::Global:
1791 case NestedNameSpecifier::Super:
1792 llvm_unreachable("Can't mangle __super specifier");
1794 case NestedNameSpecifier::Namespace:
1795 mangleName(qualifier->getAsNamespace());
1798 case NestedNameSpecifier::NamespaceAlias:
1799 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1802 case NestedNameSpecifier::TypeSpec:
1803 case NestedNameSpecifier::TypeSpecWithTemplate:
1804 manglePrefix(QualType(qualifier->getAsType(), 0));
1807 case NestedNameSpecifier::Identifier:
1808 // Member expressions can have these without prefixes, but that
1809 // should end up in mangleUnresolvedPrefix instead.
1810 assert(qualifier->getPrefix());
1811 manglePrefix(qualifier->getPrefix());
1813 mangleSourceName(qualifier->getAsIdentifier());
1817 llvm_unreachable("unexpected nested name specifier");
1820 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1821 // <prefix> ::= <prefix> <unqualified-name>
1822 // ::= <template-prefix> <template-args>
1823 // ::= <template-param>
1825 // ::= <substitution>
1827 DC = IgnoreLinkageSpecDecls(DC);
1829 if (DC->isTranslationUnit())
1832 if (NoFunction && isLocalContainerContext(DC))
1835 assert(!isLocalContainerContext(DC));
1837 const NamedDecl *ND = cast<NamedDecl>(DC);
1838 if (mangleSubstitution(ND))
1841 // Check if we have a template.
1842 const TemplateArgumentList *TemplateArgs = nullptr;
1843 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1844 mangleTemplatePrefix(TD);
1845 mangleTemplateArgs(*TemplateArgs);
1847 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1848 mangleUnqualifiedName(ND, nullptr);
1851 addSubstitution(ND);
1854 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1855 // <template-prefix> ::= <prefix> <template unqualified-name>
1856 // ::= <template-param>
1857 // ::= <substitution>
1858 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1859 return mangleTemplatePrefix(TD);
1861 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1862 manglePrefix(Qualified->getQualifier());
1864 if (OverloadedTemplateStorage *Overloaded
1865 = Template.getAsOverloadedTemplate()) {
1866 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1867 UnknownArity, nullptr);
1871 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1872 assert(Dependent && "Unknown template name kind?");
1873 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1874 manglePrefix(Qualifier);
1875 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1878 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1880 // <template-prefix> ::= <prefix> <template unqualified-name>
1881 // ::= <template-param>
1882 // ::= <substitution>
1883 // <template-template-param> ::= <template-param>
1886 if (mangleSubstitution(ND))
1889 // <template-template-param> ::= <template-param>
1890 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1891 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1893 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1894 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
1895 mangleUnqualifiedName(ND, nullptr);
1897 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1900 addSubstitution(ND);
1903 /// Mangles a template name under the production <type>. Required for
1904 /// template template arguments.
1905 /// <type> ::= <class-enum-type>
1906 /// ::= <template-param>
1907 /// ::= <substitution>
1908 void CXXNameMangler::mangleType(TemplateName TN) {
1909 if (mangleSubstitution(TN))
1912 TemplateDecl *TD = nullptr;
1914 switch (TN.getKind()) {
1915 case TemplateName::QualifiedTemplate:
1916 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1919 case TemplateName::Template:
1920 TD = TN.getAsTemplateDecl();
1924 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
1925 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1930 case TemplateName::OverloadedTemplate:
1931 case TemplateName::AssumedTemplate:
1932 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1934 case TemplateName::DependentTemplate: {
1935 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1936 assert(Dependent->isIdentifier());
1938 // <class-enum-type> ::= <name>
1939 // <name> ::= <nested-name>
1940 mangleUnresolvedPrefix(Dependent->getQualifier());
1941 mangleSourceName(Dependent->getIdentifier());
1945 case TemplateName::SubstTemplateTemplateParm: {
1946 // Substituted template parameters are mangled as the substituted
1947 // template. This will check for the substitution twice, which is
1948 // fine, but we have to return early so that we don't try to *add*
1949 // the substitution twice.
1950 SubstTemplateTemplateParmStorage *subst
1951 = TN.getAsSubstTemplateTemplateParm();
1952 mangleType(subst->getReplacement());
1956 case TemplateName::SubstTemplateTemplateParmPack: {
1957 // FIXME: not clear how to mangle this!
1958 // template <template <class> class T...> class A {
1959 // template <template <class> class U...> void foo(B<T,U> x...);
1961 Out << "_SUBSTPACK_";
1966 addSubstitution(TN);
1969 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1971 // Only certain other types are valid as prefixes; enumerate them.
1972 switch (Ty->getTypeClass()) {
1975 case Type::Adjusted:
1978 case Type::BlockPointer:
1979 case Type::LValueReference:
1980 case Type::RValueReference:
1981 case Type::MemberPointer:
1982 case Type::ConstantArray:
1983 case Type::IncompleteArray:
1984 case Type::VariableArray:
1985 case Type::DependentSizedArray:
1986 case Type::DependentAddressSpace:
1987 case Type::DependentVector:
1988 case Type::DependentSizedExtVector:
1990 case Type::ExtVector:
1991 case Type::FunctionProto:
1992 case Type::FunctionNoProto:
1994 case Type::Attributed:
1996 case Type::DeducedTemplateSpecialization:
1997 case Type::PackExpansion:
1998 case Type::ObjCObject:
1999 case Type::ObjCInterface:
2000 case Type::ObjCObjectPointer:
2001 case Type::ObjCTypeParam:
2004 case Type::MacroQualified:
2005 llvm_unreachable("type is illegal as a nested name specifier");
2007 case Type::SubstTemplateTypeParmPack:
2008 // FIXME: not clear how to mangle this!
2009 // template <class T...> class A {
2010 // template <class U...> void foo(decltype(T::foo(U())) x...);
2012 Out << "_SUBSTPACK_";
2015 // <unresolved-type> ::= <template-param>
2017 // ::= <template-template-param> <template-args>
2018 // (this last is not official yet)
2019 case Type::TypeOfExpr:
2021 case Type::Decltype:
2022 case Type::TemplateTypeParm:
2023 case Type::UnaryTransform:
2024 case Type::SubstTemplateTypeParm:
2026 // Some callers want a prefix before the mangled type.
2029 // This seems to do everything we want. It's not really
2030 // sanctioned for a substituted template parameter, though.
2033 // We never want to print 'E' directly after an unresolved-type,
2034 // so we return directly.
2038 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2041 case Type::UnresolvedUsing:
2042 mangleSourceNameWithAbiTags(
2043 cast<UnresolvedUsingType>(Ty)->getDecl());
2048 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2051 case Type::TemplateSpecialization: {
2052 const TemplateSpecializationType *TST =
2053 cast<TemplateSpecializationType>(Ty);
2054 TemplateName TN = TST->getTemplateName();
2055 switch (TN.getKind()) {
2056 case TemplateName::Template:
2057 case TemplateName::QualifiedTemplate: {
2058 TemplateDecl *TD = TN.getAsTemplateDecl();
2060 // If the base is a template template parameter, this is an
2062 assert(TD && "no template for template specialization type");
2063 if (isa<TemplateTemplateParmDecl>(TD))
2064 goto unresolvedType;
2066 mangleSourceNameWithAbiTags(TD);
2070 case TemplateName::OverloadedTemplate:
2071 case TemplateName::AssumedTemplate:
2072 case TemplateName::DependentTemplate:
2073 llvm_unreachable("invalid base for a template specialization type");
2075 case TemplateName::SubstTemplateTemplateParm: {
2076 SubstTemplateTemplateParmStorage *subst =
2077 TN.getAsSubstTemplateTemplateParm();
2078 mangleExistingSubstitution(subst->getReplacement());
2082 case TemplateName::SubstTemplateTemplateParmPack: {
2083 // FIXME: not clear how to mangle this!
2084 // template <template <class U> class T...> class A {
2085 // template <class U...> void foo(decltype(T<U>::foo) x...);
2087 Out << "_SUBSTPACK_";
2092 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
2096 case Type::InjectedClassName:
2097 mangleSourceNameWithAbiTags(
2098 cast<InjectedClassNameType>(Ty)->getDecl());
2101 case Type::DependentName:
2102 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2105 case Type::DependentTemplateSpecialization: {
2106 const DependentTemplateSpecializationType *DTST =
2107 cast<DependentTemplateSpecializationType>(Ty);
2108 mangleSourceName(DTST->getIdentifier());
2109 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2113 case Type::Elaborated:
2114 return mangleUnresolvedTypeOrSimpleId(
2115 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2121 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2122 switch (Name.getNameKind()) {
2123 case DeclarationName::CXXConstructorName:
2124 case DeclarationName::CXXDestructorName:
2125 case DeclarationName::CXXDeductionGuideName:
2126 case DeclarationName::CXXUsingDirective:
2127 case DeclarationName::Identifier:
2128 case DeclarationName::ObjCMultiArgSelector:
2129 case DeclarationName::ObjCOneArgSelector:
2130 case DeclarationName::ObjCZeroArgSelector:
2131 llvm_unreachable("Not an operator name");
2133 case DeclarationName::CXXConversionFunctionName:
2134 // <operator-name> ::= cv <type> # (cast)
2136 mangleType(Name.getCXXNameType());
2139 case DeclarationName::CXXLiteralOperatorName:
2141 mangleSourceName(Name.getCXXLiteralIdentifier());
2144 case DeclarationName::CXXOperatorName:
2145 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2151 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2153 // <operator-name> ::= nw # new
2154 case OO_New: Out << "nw"; break;
2156 case OO_Array_New: Out << "na"; break;
2158 case OO_Delete: Out << "dl"; break;
2159 // ::= da # delete[]
2160 case OO_Array_Delete: Out << "da"; break;
2161 // ::= ps # + (unary)
2162 // ::= pl # + (binary or unknown)
2164 Out << (Arity == 1? "ps" : "pl"); break;
2165 // ::= ng # - (unary)
2166 // ::= mi # - (binary or unknown)
2168 Out << (Arity == 1? "ng" : "mi"); break;
2169 // ::= ad # & (unary)
2170 // ::= an # & (binary or unknown)
2172 Out << (Arity == 1? "ad" : "an"); break;
2173 // ::= de # * (unary)
2174 // ::= ml # * (binary or unknown)
2176 // Use binary when unknown.
2177 Out << (Arity == 1? "de" : "ml"); break;
2179 case OO_Tilde: Out << "co"; break;
2181 case OO_Slash: Out << "dv"; break;
2183 case OO_Percent: Out << "rm"; break;
2185 case OO_Pipe: Out << "or"; break;
2187 case OO_Caret: Out << "eo"; break;
2189 case OO_Equal: Out << "aS"; break;
2191 case OO_PlusEqual: Out << "pL"; break;
2193 case OO_MinusEqual: Out << "mI"; break;
2195 case OO_StarEqual: Out << "mL"; break;
2197 case OO_SlashEqual: Out << "dV"; break;
2199 case OO_PercentEqual: Out << "rM"; break;
2201 case OO_AmpEqual: Out << "aN"; break;
2203 case OO_PipeEqual: Out << "oR"; break;
2205 case OO_CaretEqual: Out << "eO"; break;
2207 case OO_LessLess: Out << "ls"; break;
2209 case OO_GreaterGreater: Out << "rs"; break;
2211 case OO_LessLessEqual: Out << "lS"; break;
2213 case OO_GreaterGreaterEqual: Out << "rS"; break;
2215 case OO_EqualEqual: Out << "eq"; break;
2217 case OO_ExclaimEqual: Out << "ne"; break;
2219 case OO_Less: Out << "lt"; break;
2221 case OO_Greater: Out << "gt"; break;
2223 case OO_LessEqual: Out << "le"; break;
2225 case OO_GreaterEqual: Out << "ge"; break;
2227 case OO_Exclaim: Out << "nt"; break;
2229 case OO_AmpAmp: Out << "aa"; break;
2231 case OO_PipePipe: Out << "oo"; break;
2233 case OO_PlusPlus: Out << "pp"; break;
2235 case OO_MinusMinus: Out << "mm"; break;
2237 case OO_Comma: Out << "cm"; break;
2239 case OO_ArrowStar: Out << "pm"; break;
2241 case OO_Arrow: Out << "pt"; break;
2243 case OO_Call: Out << "cl"; break;
2245 case OO_Subscript: Out << "ix"; break;
2248 // The conditional operator can't be overloaded, but we still handle it when
2249 // mangling expressions.
2250 case OO_Conditional: Out << "qu"; break;
2251 // Proposal on cxx-abi-dev, 2015-10-21.
2252 // ::= aw # co_await
2253 case OO_Coawait: Out << "aw"; break;
2254 // Proposed in cxx-abi github issue 43.
2256 case OO_Spaceship: Out << "ss"; break;
2259 case NUM_OVERLOADED_OPERATORS:
2260 llvm_unreachable("Not an overloaded operator");
2264 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2265 // Vendor qualifiers come first and if they are order-insensitive they must
2266 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2268 // <type> ::= U <addrspace-expr>
2271 mangleExpression(DAST->getAddrSpaceExpr());
2275 // Address space qualifiers start with an ordinary letter.
2276 if (Quals.hasAddressSpace()) {
2277 // Address space extension:
2279 // <type> ::= U <target-addrspace>
2280 // <type> ::= U <OpenCL-addrspace>
2281 // <type> ::= U <CUDA-addrspace>
2283 SmallString<64> ASString;
2284 LangAS AS = Quals.getAddressSpace();
2286 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2287 // <target-addrspace> ::= "AS" <address-space-number>
2288 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2290 ASString = "AS" + llvm::utostr(TargetAS);
2293 default: llvm_unreachable("Not a language specific address space");
2294 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2295 // "private"| "generic" ]
2296 case LangAS::opencl_global: ASString = "CLglobal"; break;
2297 case LangAS::opencl_local: ASString = "CLlocal"; break;
2298 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2299 case LangAS::opencl_private: ASString = "CLprivate"; break;
2300 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
2301 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2302 case LangAS::cuda_device: ASString = "CUdevice"; break;
2303 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2304 case LangAS::cuda_shared: ASString = "CUshared"; break;
2305 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2306 case LangAS::ptr32_sptr:
2307 ASString = "ptr32_sptr";
2309 case LangAS::ptr32_uptr:
2310 ASString = "ptr32_uptr";
2317 if (!ASString.empty())
2318 mangleVendorQualifier(ASString);
2321 // The ARC ownership qualifiers start with underscores.
2322 // Objective-C ARC Extension:
2324 // <type> ::= U "__strong"
2325 // <type> ::= U "__weak"
2326 // <type> ::= U "__autoreleasing"
2328 // Note: we emit __weak first to preserve the order as
2329 // required by the Itanium ABI.
2330 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2331 mangleVendorQualifier("__weak");
2333 // __unaligned (from -fms-extensions)
2334 if (Quals.hasUnaligned())
2335 mangleVendorQualifier("__unaligned");
2337 // Remaining ARC ownership qualifiers.
2338 switch (Quals.getObjCLifetime()) {
2339 case Qualifiers::OCL_None:
2342 case Qualifiers::OCL_Weak:
2343 // Do nothing as we already handled this case above.
2346 case Qualifiers::OCL_Strong:
2347 mangleVendorQualifier("__strong");
2350 case Qualifiers::OCL_Autoreleasing:
2351 mangleVendorQualifier("__autoreleasing");
2354 case Qualifiers::OCL_ExplicitNone:
2355 // The __unsafe_unretained qualifier is *not* mangled, so that
2356 // __unsafe_unretained types in ARC produce the same manglings as the
2357 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2358 // better ABI compatibility.
2360 // It's safe to do this because unqualified 'id' won't show up
2361 // in any type signatures that need to be mangled.
2365 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2366 if (Quals.hasRestrict())
2368 if (Quals.hasVolatile())
2370 if (Quals.hasConst())
2374 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2375 Out << 'U' << name.size() << name;
2378 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2379 // <ref-qualifier> ::= R # lvalue reference
2380 // ::= O # rvalue-reference
2381 switch (RefQualifier) {
2395 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2396 Context.mangleObjCMethodName(MD, Out);
2399 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2403 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2405 if (Ty->isOpenCLSpecificType())
2407 if (Ty->isBuiltinType())
2409 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2410 // substitution candidates.
2411 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2417 void CXXNameMangler::mangleType(QualType T) {
2418 // If our type is instantiation-dependent but not dependent, we mangle
2419 // it as it was written in the source, removing any top-level sugar.
2420 // Otherwise, use the canonical type.
2422 // FIXME: This is an approximation of the instantiation-dependent name
2423 // mangling rules, since we should really be using the type as written and
2424 // augmented via semantic analysis (i.e., with implicit conversions and
2425 // default template arguments) for any instantiation-dependent type.
2426 // Unfortunately, that requires several changes to our AST:
2427 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2428 // uniqued, so that we can handle substitutions properly
2429 // - Default template arguments will need to be represented in the
2430 // TemplateSpecializationType, since they need to be mangled even though
2431 // they aren't written.
2432 // - Conversions on non-type template arguments need to be expressed, since
2433 // they can affect the mangling of sizeof/alignof.
2435 // FIXME: This is wrong when mapping to the canonical type for a dependent
2436 // type discards instantiation-dependent portions of the type, such as for:
2438 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2439 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2441 // It's also wrong in the opposite direction when instantiation-dependent,
2442 // canonically-equivalent types differ in some irrelevant portion of inner
2443 // type sugar. In such cases, we fail to form correct substitutions, eg:
2445 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2447 // We should instead canonicalize the non-instantiation-dependent parts,
2448 // regardless of whether the type as a whole is dependent or instantiation
2450 if (!T->isInstantiationDependentType() || T->isDependentType())
2451 T = T.getCanonicalType();
2453 // Desugar any types that are purely sugar.
2455 // Don't desugar through template specialization types that aren't
2456 // type aliases. We need to mangle the template arguments as written.
2457 if (const TemplateSpecializationType *TST
2458 = dyn_cast<TemplateSpecializationType>(T))
2459 if (!TST->isTypeAlias())
2463 = T.getSingleStepDesugaredType(Context.getASTContext());
2470 SplitQualType split = T.split();
2471 Qualifiers quals = split.Quals;
2472 const Type *ty = split.Ty;
2474 bool isSubstitutable =
2475 isTypeSubstitutable(quals, ty, Context.getASTContext());
2476 if (isSubstitutable && mangleSubstitution(T))
2479 // If we're mangling a qualified array type, push the qualifiers to
2480 // the element type.
2481 if (quals && isa<ArrayType>(T)) {
2482 ty = Context.getASTContext().getAsArrayType(T);
2483 quals = Qualifiers();
2485 // Note that we don't update T: we want to add the
2486 // substitution at the original type.
2489 if (quals || ty->isDependentAddressSpaceType()) {
2490 if (const DependentAddressSpaceType *DAST =
2491 dyn_cast<DependentAddressSpaceType>(ty)) {
2492 SplitQualType splitDAST = DAST->getPointeeType().split();
2493 mangleQualifiers(splitDAST.Quals, DAST);
2494 mangleType(QualType(splitDAST.Ty, 0));
2496 mangleQualifiers(quals);
2498 // Recurse: even if the qualified type isn't yet substitutable,
2499 // the unqualified type might be.
2500 mangleType(QualType(ty, 0));
2503 switch (ty->getTypeClass()) {
2504 #define ABSTRACT_TYPE(CLASS, PARENT)
2505 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2507 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2509 #define TYPE(CLASS, PARENT) \
2511 mangleType(static_cast<const CLASS##Type*>(ty)); \
2513 #include "clang/AST/TypeNodes.inc"
2517 // Add the substitution.
2518 if (isSubstitutable)
2522 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2523 if (!mangleStandardSubstitution(ND))
2527 void CXXNameMangler::mangleType(const BuiltinType *T) {
2528 // <type> ::= <builtin-type>
2529 // <builtin-type> ::= v # void
2533 // ::= a # signed char
2534 // ::= h # unsigned char
2536 // ::= t # unsigned short
2538 // ::= j # unsigned int
2540 // ::= m # unsigned long
2541 // ::= x # long long, __int64
2542 // ::= y # unsigned long long, __int64
2544 // ::= o # unsigned __int128
2547 // ::= e # long double, __float80
2548 // ::= g # __float128
2549 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2550 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2551 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2552 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2553 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2554 // ::= Di # char32_t
2555 // ::= Ds # char16_t
2556 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2557 // ::= u <source-name> # vendor extended type
2558 std::string type_name;
2559 switch (T->getKind()) {
2560 case BuiltinType::Void:
2563 case BuiltinType::Bool:
2566 case BuiltinType::Char_U:
2567 case BuiltinType::Char_S:
2570 case BuiltinType::UChar:
2573 case BuiltinType::UShort:
2576 case BuiltinType::UInt:
2579 case BuiltinType::ULong:
2582 case BuiltinType::ULongLong:
2585 case BuiltinType::UInt128:
2588 case BuiltinType::SChar:
2591 case BuiltinType::WChar_S:
2592 case BuiltinType::WChar_U:
2595 case BuiltinType::Char8:
2598 case BuiltinType::Char16:
2601 case BuiltinType::Char32:
2604 case BuiltinType::Short:
2607 case BuiltinType::Int:
2610 case BuiltinType::Long:
2613 case BuiltinType::LongLong:
2616 case BuiltinType::Int128:
2619 case BuiltinType::Float16:
2622 case BuiltinType::ShortAccum:
2623 case BuiltinType::Accum:
2624 case BuiltinType::LongAccum:
2625 case BuiltinType::UShortAccum:
2626 case BuiltinType::UAccum:
2627 case BuiltinType::ULongAccum:
2628 case BuiltinType::ShortFract:
2629 case BuiltinType::Fract:
2630 case BuiltinType::LongFract:
2631 case BuiltinType::UShortFract:
2632 case BuiltinType::UFract:
2633 case BuiltinType::ULongFract:
2634 case BuiltinType::SatShortAccum:
2635 case BuiltinType::SatAccum:
2636 case BuiltinType::SatLongAccum:
2637 case BuiltinType::SatUShortAccum:
2638 case BuiltinType::SatUAccum:
2639 case BuiltinType::SatULongAccum:
2640 case BuiltinType::SatShortFract:
2641 case BuiltinType::SatFract:
2642 case BuiltinType::SatLongFract:
2643 case BuiltinType::SatUShortFract:
2644 case BuiltinType::SatUFract:
2645 case BuiltinType::SatULongFract:
2646 llvm_unreachable("Fixed point types are disabled for c++");
2647 case BuiltinType::Half:
2650 case BuiltinType::Float:
2653 case BuiltinType::Double:
2656 case BuiltinType::LongDouble: {
2657 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2658 getASTContext().getLangOpts().OpenMPIsDevice
2659 ? getASTContext().getAuxTargetInfo()
2660 : &getASTContext().getTargetInfo();
2661 Out << TI->getLongDoubleMangling();
2664 case BuiltinType::Float128: {
2665 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2666 getASTContext().getLangOpts().OpenMPIsDevice
2667 ? getASTContext().getAuxTargetInfo()
2668 : &getASTContext().getTargetInfo();
2669 Out << TI->getFloat128Mangling();
2672 case BuiltinType::NullPtr:
2676 #define BUILTIN_TYPE(Id, SingletonId)
2677 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2678 case BuiltinType::Id:
2679 #include "clang/AST/BuiltinTypes.def"
2680 case BuiltinType::Dependent:
2682 llvm_unreachable("mangling a placeholder type");
2684 case BuiltinType::ObjCId:
2685 Out << "11objc_object";
2687 case BuiltinType::ObjCClass:
2688 Out << "10objc_class";
2690 case BuiltinType::ObjCSel:
2691 Out << "13objc_selector";
2693 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2694 case BuiltinType::Id: \
2695 type_name = "ocl_" #ImgType "_" #Suffix; \
2696 Out << type_name.size() << type_name; \
2698 #include "clang/Basic/OpenCLImageTypes.def"
2699 case BuiltinType::OCLSampler:
2700 Out << "11ocl_sampler";
2702 case BuiltinType::OCLEvent:
2703 Out << "9ocl_event";
2705 case BuiltinType::OCLClkEvent:
2706 Out << "12ocl_clkevent";
2708 case BuiltinType::OCLQueue:
2709 Out << "9ocl_queue";
2711 case BuiltinType::OCLReserveID:
2712 Out << "13ocl_reserveid";
2714 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2715 case BuiltinType::Id: \
2716 type_name = "ocl_" #ExtType; \
2717 Out << type_name.size() << type_name; \
2719 #include "clang/Basic/OpenCLExtensionTypes.def"
2720 // The SVE types are effectively target-specific. The mangling scheme
2721 // is defined in the appendices to the Procedure Call Standard for the
2722 // Arm Architecture.
2723 #define SVE_TYPE(Name, Id, SingletonId) \
2724 case BuiltinType::Id: \
2726 Out << 'u' << type_name.size() << type_name; \
2728 #include "clang/Basic/AArch64SVEACLETypes.def"
2732 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2737 case CC_X86VectorCall:
2742 case CC_AArch64VectorCall:
2743 case CC_IntelOclBicc:
2744 case CC_SpirFunction:
2745 case CC_OpenCLKernel:
2746 case CC_PreserveMost:
2747 case CC_PreserveAll:
2748 // FIXME: we should be mangling all of the above.
2751 case CC_X86ThisCall:
2752 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2753 // used explicitly. At this point, we don't have that much information in
2754 // the AST, since clang tends to bake the convention into the canonical
2755 // function type. thiscall only rarely used explicitly, so don't mangle it
2761 case CC_X86FastCall:
2770 llvm_unreachable("bad calling convention");
2773 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2775 if (T->getExtInfo() == FunctionType::ExtInfo())
2778 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2779 // This will get more complicated in the future if we mangle other
2780 // things here; but for now, since we mangle ns_returns_retained as
2781 // a qualifier on the result type, we can get away with this:
2782 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2783 if (!CCQualifier.empty())
2784 mangleVendorQualifier(CCQualifier);
2791 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2792 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2794 // Note that these are *not* substitution candidates. Demanglers might
2795 // have trouble with this if the parameter type is fully substituted.
2797 switch (PI.getABI()) {
2798 case ParameterABI::Ordinary:
2801 // All of these start with "swift", so they come before "ns_consumed".
2802 case ParameterABI::SwiftContext:
2803 case ParameterABI::SwiftErrorResult:
2804 case ParameterABI::SwiftIndirectResult:
2805 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2809 if (PI.isConsumed())
2810 mangleVendorQualifier("ns_consumed");
2812 if (PI.isNoEscape())
2813 mangleVendorQualifier("noescape");
2816 // <type> ::= <function-type>
2817 // <function-type> ::= [<CV-qualifiers>] F [Y]
2818 // <bare-function-type> [<ref-qualifier>] E
2819 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2820 mangleExtFunctionInfo(T);
2822 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2823 // e.g. "const" in "int (A::*)() const".
2824 mangleQualifiers(T->getMethodQuals());
2826 // Mangle instantiation-dependent exception-specification, if present,
2827 // per cxx-abi-dev proposal on 2016-10-11.
2828 if (T->hasInstantiationDependentExceptionSpec()) {
2829 if (isComputedNoexcept(T->getExceptionSpecType())) {
2831 mangleExpression(T->getNoexceptExpr());
2834 assert(T->getExceptionSpecType() == EST_Dynamic);
2836 for (auto ExceptTy : T->exceptions())
2837 mangleType(ExceptTy);
2840 } else if (T->isNothrow()) {
2846 // FIXME: We don't have enough information in the AST to produce the 'Y'
2847 // encoding for extern "C" function types.
2848 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2850 // Mangle the ref-qualifier, if present.
2851 mangleRefQualifier(T->getRefQualifier());
2856 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2857 // Function types without prototypes can arise when mangling a function type
2858 // within an overloadable function in C. We mangle these as the absence of any
2859 // parameter types (not even an empty parameter list).
2862 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2864 FunctionTypeDepth.enterResultType();
2865 mangleType(T->getReturnType());
2866 FunctionTypeDepth.leaveResultType();
2868 FunctionTypeDepth.pop(saved);
2872 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2873 bool MangleReturnType,
2874 const FunctionDecl *FD) {
2875 // Record that we're in a function type. See mangleFunctionParam
2876 // for details on what we're trying to achieve here.
2877 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2879 // <bare-function-type> ::= <signature type>+
2880 if (MangleReturnType) {
2881 FunctionTypeDepth.enterResultType();
2883 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2884 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2885 mangleVendorQualifier("ns_returns_retained");
2887 // Mangle the return type without any direct ARC ownership qualifiers.
2888 QualType ReturnTy = Proto->getReturnType();
2889 if (ReturnTy.getObjCLifetime()) {
2890 auto SplitReturnTy = ReturnTy.split();
2891 SplitReturnTy.Quals.removeObjCLifetime();
2892 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2894 mangleType(ReturnTy);
2896 FunctionTypeDepth.leaveResultType();
2899 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2900 // <builtin-type> ::= v # void
2903 FunctionTypeDepth.pop(saved);
2907 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2908 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2909 // Mangle extended parameter info as order-sensitive qualifiers here.
2910 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2911 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2915 QualType ParamTy = Proto->getParamType(I);
2916 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2919 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2920 // Attr can only take 1 character, so we can hardcode the length below.
2921 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2922 if (Attr->isDynamic())
2923 Out << "U25pass_dynamic_object_size" << Attr->getType();
2925 Out << "U17pass_object_size" << Attr->getType();
2930 FunctionTypeDepth.pop(saved);
2932 // <builtin-type> ::= z # ellipsis
2933 if (Proto->isVariadic())
2937 // <type> ::= <class-enum-type>
2938 // <class-enum-type> ::= <name>
2939 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2940 mangleName(T->getDecl());
2943 // <type> ::= <class-enum-type>
2944 // <class-enum-type> ::= <name>
2945 void CXXNameMangler::mangleType(const EnumType *T) {
2946 mangleType(static_cast<const TagType*>(T));
2948 void CXXNameMangler::mangleType(const RecordType *T) {
2949 mangleType(static_cast<const TagType*>(T));
2951 void CXXNameMangler::mangleType(const TagType *T) {
2952 mangleName(T->getDecl());
2955 // <type> ::= <array-type>
2956 // <array-type> ::= A <positive dimension number> _ <element type>
2957 // ::= A [<dimension expression>] _ <element type>
2958 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2959 Out << 'A' << T->getSize() << '_';
2960 mangleType(T->getElementType());
2962 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2964 // decayed vla types (size 0) will just be skipped.
2965 if (T->getSizeExpr())
2966 mangleExpression(T->getSizeExpr());
2968 mangleType(T->getElementType());
2970 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2972 mangleExpression(T->getSizeExpr());
2974 mangleType(T->getElementType());
2976 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2978 mangleType(T->getElementType());
2981 // <type> ::= <pointer-to-member-type>
2982 // <pointer-to-member-type> ::= M <class type> <member type>
2983 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2985 mangleType(QualType(T->getClass(), 0));
2986 QualType PointeeType = T->getPointeeType();
2987 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2990 // Itanium C++ ABI 5.1.8:
2992 // The type of a non-static member function is considered to be different,
2993 // for the purposes of substitution, from the type of a namespace-scope or
2994 // static member function whose type appears similar. The types of two
2995 // non-static member functions are considered to be different, for the
2996 // purposes of substitution, if the functions are members of different
2997 // classes. In other words, for the purposes of substitution, the class of
2998 // which the function is a member is considered part of the type of
3001 // Given that we already substitute member function pointers as a
3002 // whole, the net effect of this rule is just to unconditionally
3003 // suppress substitution on the function type in a member pointer.
3004 // We increment the SeqID here to emulate adding an entry to the
3005 // substitution table.
3008 mangleType(PointeeType);
3011 // <type> ::= <template-param>
3012 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3013 mangleTemplateParameter(T->getDepth(), T->getIndex());
3016 // <type> ::= <template-param>
3017 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3018 // FIXME: not clear how to mangle this!
3019 // template <class T...> class A {
3020 // template <class U...> void foo(T(*)(U) x...);
3022 Out << "_SUBSTPACK_";
3025 // <type> ::= P <type> # pointer-to
3026 void CXXNameMangler::mangleType(const PointerType *T) {
3028 mangleType(T->getPointeeType());
3030 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3032 mangleType(T->getPointeeType());
3035 // <type> ::= R <type> # reference-to
3036 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3038 mangleType(T->getPointeeType());
3041 // <type> ::= O <type> # rvalue reference-to (C++0x)
3042 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3044 mangleType(T->getPointeeType());
3047 // <type> ::= C <type> # complex pair (C 2000)
3048 void CXXNameMangler::mangleType(const ComplexType *T) {
3050 mangleType(T->getElementType());
3053 // ARM's ABI for Neon vector types specifies that they should be mangled as
3054 // if they are structs (to match ARM's initial implementation). The
3055 // vector type must be one of the special types predefined by ARM.
3056 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3057 QualType EltType = T->getElementType();
3058 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3059 const char *EltName = nullptr;
3060 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3061 switch (cast<BuiltinType>(EltType)->getKind()) {
3062 case BuiltinType::SChar:
3063 case BuiltinType::UChar:
3064 EltName = "poly8_t";
3066 case BuiltinType::Short:
3067 case BuiltinType::UShort:
3068 EltName = "poly16_t";
3070 case BuiltinType::ULongLong:
3071 EltName = "poly64_t";
3073 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3076 switch (cast<BuiltinType>(EltType)->getKind()) {
3077 case BuiltinType::SChar: EltName = "int8_t"; break;
3078 case BuiltinType::UChar: EltName = "uint8_t"; break;
3079 case BuiltinType::Short: EltName = "int16_t"; break;
3080 case BuiltinType::UShort: EltName = "uint16_t"; break;
3081 case BuiltinType::Int: EltName = "int32_t"; break;
3082 case BuiltinType::UInt: EltName = "uint32_t"; break;
3083 case BuiltinType::LongLong: EltName = "int64_t"; break;
3084 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3085 case BuiltinType::Double: EltName = "float64_t"; break;
3086 case BuiltinType::Float: EltName = "float32_t"; break;
3087 case BuiltinType::Half: EltName = "float16_t";break;
3089 llvm_unreachable("unexpected Neon vector element type");
3092 const char *BaseName = nullptr;
3093 unsigned BitSize = (T->getNumElements() *
3094 getASTContext().getTypeSize(EltType));
3096 BaseName = "__simd64_";
3098 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3099 BaseName = "__simd128_";
3101 Out << strlen(BaseName) + strlen(EltName);
3102 Out << BaseName << EltName;
3105 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3106 DiagnosticsEngine &Diags = Context.getDiags();
3107 unsigned DiagID = Diags.getCustomDiagID(
3108 DiagnosticsEngine::Error,
3109 "cannot mangle this dependent neon vector type yet");
3110 Diags.Report(T->getAttributeLoc(), DiagID);
3113 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3114 switch (EltType->getKind()) {
3115 case BuiltinType::SChar:
3117 case BuiltinType::Short:
3119 case BuiltinType::Int:
3121 case BuiltinType::Long:
3122 case BuiltinType::LongLong:
3124 case BuiltinType::UChar:
3126 case BuiltinType::UShort:
3128 case BuiltinType::UInt:
3130 case BuiltinType::ULong:
3131 case BuiltinType::ULongLong:
3133 case BuiltinType::Half:
3135 case BuiltinType::Float:
3137 case BuiltinType::Double:
3140 llvm_unreachable("Unexpected vector element base type");
3144 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3145 // the equivalent internal name. The vector type must be one of the special
3146 // types predefined by ARM.
3147 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3148 QualType EltType = T->getElementType();
3149 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3151 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3152 (void)BitSize; // Silence warning.
3154 assert((BitSize == 64 || BitSize == 128) &&
3155 "Neon vector type not 64 or 128 bits");
3158 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3159 switch (cast<BuiltinType>(EltType)->getKind()) {
3160 case BuiltinType::UChar:
3163 case BuiltinType::UShort:
3166 case BuiltinType::ULong:
3167 case BuiltinType::ULongLong:
3171 llvm_unreachable("unexpected Neon polynomial vector element type");
3174 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3176 std::string TypeName =
3177 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3178 Out << TypeName.length() << TypeName;
3180 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3181 DiagnosticsEngine &Diags = Context.getDiags();
3182 unsigned DiagID = Diags.getCustomDiagID(
3183 DiagnosticsEngine::Error,
3184 "cannot mangle this dependent neon vector type yet");
3185 Diags.Report(T->getAttributeLoc(), DiagID);
3188 // GNU extension: vector types
3189 // <type> ::= <vector-type>
3190 // <vector-type> ::= Dv <positive dimension number> _
3191 // <extended element type>
3192 // ::= Dv [<dimension expression>] _ <element type>
3193 // <extended element type> ::= <element type>
3194 // ::= p # AltiVec vector pixel
3195 // ::= b # Altivec vector bool
3196 void CXXNameMangler::mangleType(const VectorType *T) {
3197 if ((T->getVectorKind() == VectorType::NeonVector ||
3198 T->getVectorKind() == VectorType::NeonPolyVector)) {
3199 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3200 llvm::Triple::ArchType Arch =
3201 getASTContext().getTargetInfo().getTriple().getArch();
3202 if ((Arch == llvm::Triple::aarch64 ||
3203 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3204 mangleAArch64NeonVectorType(T);
3206 mangleNeonVectorType(T);
3209 Out << "Dv" << T->getNumElements() << '_';
3210 if (T->getVectorKind() == VectorType::AltiVecPixel)
3212 else if (T->getVectorKind() == VectorType::AltiVecBool)
3215 mangleType(T->getElementType());
3218 void CXXNameMangler::mangleType(const DependentVectorType *T) {
3219 if ((T->getVectorKind() == VectorType::NeonVector ||
3220 T->getVectorKind() == VectorType::NeonPolyVector)) {
3221 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3222 llvm::Triple::ArchType Arch =
3223 getASTContext().getTargetInfo().getTriple().getArch();
3224 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3225 !Target.isOSDarwin())
3226 mangleAArch64NeonVectorType(T);
3228 mangleNeonVectorType(T);
3233 mangleExpression(T->getSizeExpr());
3235 if (T->getVectorKind() == VectorType::AltiVecPixel)
3237 else if (T->getVectorKind() == VectorType::AltiVecBool)
3240 mangleType(T->getElementType());
3243 void CXXNameMangler::mangleType(const ExtVectorType *T) {
3244 mangleType(static_cast<const VectorType*>(T));
3246 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3248 mangleExpression(T->getSizeExpr());
3250 mangleType(T->getElementType());
3253 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3254 SplitQualType split = T->getPointeeType().split();
3255 mangleQualifiers(split.Quals, T);
3256 mangleType(QualType(split.Ty, 0));
3259 void CXXNameMangler::mangleType(const PackExpansionType *T) {
3260 // <type> ::= Dp <type> # pack expansion (C++0x)
3262 mangleType(T->getPattern());
3265 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3266 mangleSourceName(T->getDecl()->getIdentifier());
3269 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3270 // Treat __kindof as a vendor extended type qualifier.
3271 if (T->isKindOfType())
3272 Out << "U8__kindof";
3274 if (!T->qual_empty()) {
3275 // Mangle protocol qualifiers.
3276 SmallString<64> QualStr;
3277 llvm::raw_svector_ostream QualOS(QualStr);
3278 QualOS << "objcproto";
3279 for (const auto *I : T->quals()) {
3280 StringRef name = I->getName();
3281 QualOS << name.size() << name;
3283 Out << 'U' << QualStr.size() << QualStr;
3286 mangleType(T->getBaseType());
3288 if (T->isSpecialized()) {
3289 // Mangle type arguments as I <type>+ E
3291 for (auto typeArg : T->getTypeArgs())
3292 mangleType(typeArg);
3297 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3298 Out << "U13block_pointer";
3299 mangleType(T->getPointeeType());
3302 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3303 // Mangle injected class name types as if the user had written the
3304 // specialization out fully. It may not actually be possible to see
3305 // this mangling, though.
3306 mangleType(T->getInjectedSpecializationType());
3309 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3310 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3311 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3313 if (mangleSubstitution(QualType(T, 0)))
3316 mangleTemplatePrefix(T->getTemplateName());
3318 // FIXME: GCC does not appear to mangle the template arguments when
3319 // the template in question is a dependent template name. Should we
3320 // emulate that badness?
3321 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3322 addSubstitution(QualType(T, 0));
3326 void CXXNameMangler::mangleType(const DependentNameType *T) {
3327 // Proposal by cxx-abi-dev, 2014-03-26
3328 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3329 // # dependent elaborated type specifier using
3331 // ::= Ts <name> # dependent elaborated type specifier using
3332 // # 'struct' or 'class'
3333 // ::= Tu <name> # dependent elaborated type specifier using
3335 // ::= Te <name> # dependent elaborated type specifier using
3337 switch (T->getKeyword()) {
3353 // Typename types are always nested
3355 manglePrefix(T->getQualifier());
3356 mangleSourceName(T->getIdentifier());
3360 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3361 // Dependently-scoped template types are nested if they have a prefix.
3364 // TODO: avoid making this TemplateName.
3365 TemplateName Prefix =
3366 getASTContext().getDependentTemplateName(T->getQualifier(),
3367 T->getIdentifier());
3368 mangleTemplatePrefix(Prefix);
3370 // FIXME: GCC does not appear to mangle the template arguments when
3371 // the template in question is a dependent template name. Should we
3372 // emulate that badness?
3373 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3377 void CXXNameMangler::mangleType(const TypeOfType *T) {
3378 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3379 // "extension with parameters" mangling.
3383 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3384 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3385 // "extension with parameters" mangling.
3389 void CXXNameMangler::mangleType(const DecltypeType *T) {
3390 Expr *E = T->getUnderlyingExpr();
3392 // type ::= Dt <expression> E # decltype of an id-expression
3393 // # or class member access
3394 // ::= DT <expression> E # decltype of an expression
3396 // This purports to be an exhaustive list of id-expressions and
3397 // class member accesses. Note that we do not ignore parentheses;
3398 // parentheses change the semantics of decltype for these
3399 // expressions (and cause the mangler to use the other form).
3400 if (isa<DeclRefExpr>(E) ||
3401 isa<MemberExpr>(E) ||
3402 isa<UnresolvedLookupExpr>(E) ||
3403 isa<DependentScopeDeclRefExpr>(E) ||
3404 isa<CXXDependentScopeMemberExpr>(E) ||
3405 isa<UnresolvedMemberExpr>(E))
3409 mangleExpression(E);
3413 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3414 // If this is dependent, we need to record that. If not, we simply
3415 // mangle it as the underlying type since they are equivalent.
3416 if (T->isDependentType()) {
3419 switch (T->getUTTKind()) {
3420 case UnaryTransformType::EnumUnderlyingType:
3426 mangleType(T->getBaseType());
3429 void CXXNameMangler::mangleType(const AutoType *T) {
3430 assert(T->getDeducedType().isNull() &&
3431 "Deduced AutoType shouldn't be handled here!");
3432 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3433 "shouldn't need to mangle __auto_type!");
3434 // <builtin-type> ::= Da # auto
3435 // ::= Dc # decltype(auto)
3436 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3439 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3440 // FIXME: This is not the right mangling. We also need to include a scope
3441 // here in some cases.
3442 QualType D = T->getDeducedType();
3444 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3449 void CXXNameMangler::mangleType(const AtomicType *T) {
3450 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3451 // (Until there's a standardized mangling...)
3453 mangleType(T->getValueType());
3456 void CXXNameMangler::mangleType(const PipeType *T) {
3457 // Pipe type mangling rules are described in SPIR 2.0 specification
3458 // A.1 Data types and A.3 Summary of changes
3459 // <type> ::= 8ocl_pipe
3463 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3464 const llvm::APSInt &Value) {
3465 // <expr-primary> ::= L <type> <value number> E # integer literal
3469 if (T->isBooleanType()) {
3470 // Boolean values are encoded as 0/1.
3471 Out << (Value.getBoolValue() ? '1' : '0');
3473 mangleNumber(Value);
3479 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3480 // Ignore member expressions involving anonymous unions.
3481 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3482 if (!RT->getDecl()->isAnonymousStructOrUnion())
3484 const auto *ME = dyn_cast<MemberExpr>(Base);
3487 Base = ME->getBase();
3488 IsArrow = ME->isArrow();
3491 if (Base->isImplicitCXXThis()) {
3492 // Note: GCC mangles member expressions to the implicit 'this' as
3493 // *this., whereas we represent them as this->. The Itanium C++ ABI
3494 // does not specify anything here, so we follow GCC.
3497 Out << (IsArrow ? "pt" : "dt");
3498 mangleExpression(Base);
3502 /// Mangles a member expression.
3503 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3505 NestedNameSpecifier *qualifier,
3506 NamedDecl *firstQualifierLookup,
3507 DeclarationName member,
3508 const TemplateArgumentLoc *TemplateArgs,
3509 unsigned NumTemplateArgs,
3511 // <expression> ::= dt <expression> <unresolved-name>
3512 // ::= pt <expression> <unresolved-name>
3514 mangleMemberExprBase(base, isArrow);
3515 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3518 /// Look at the callee of the given call expression and determine if
3519 /// it's a parenthesized id-expression which would have triggered ADL
3521 static bool isParenthesizedADLCallee(const CallExpr *call) {
3522 const Expr *callee = call->getCallee();
3523 const Expr *fn = callee->IgnoreParens();
3525 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3526 // too, but for those to appear in the callee, it would have to be
3528 if (callee == fn) return false;
3530 // Must be an unresolved lookup.
3531 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3532 if (!lookup) return false;
3534 assert(!lookup->requiresADL());
3536 // Must be an unqualified lookup.
3537 if (lookup->getQualifier()) return false;
3539 // Must not have found a class member. Note that if one is a class
3540 // member, they're all class members.
3541 if (lookup->getNumDecls() > 0 &&
3542 (*lookup->decls_begin())->isCXXClassMember())
3545 // Otherwise, ADL would have been triggered.
3549 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3550 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3551 Out << CastEncoding;
3552 mangleType(ECE->getType());
3553 mangleExpression(ECE->getSubExpr());
3556 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3557 if (auto *Syntactic = InitList->getSyntacticForm())
3558 InitList = Syntactic;
3559 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3560 mangleExpression(InitList->getInit(i));
3563 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) {
3564 switch (D->getKind()) {
3566 // <expr-primary> ::= L <mangled-name> E # external name
3573 mangleFunctionParam(cast<ParmVarDecl>(D));
3576 case Decl::EnumConstant: {
3577 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3578 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3582 case Decl::NonTypeTemplateParm:
3583 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3584 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
3589 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3590 // <expression> ::= <unary operator-name> <expression>
3591 // ::= <binary operator-name> <expression> <expression>
3592 // ::= <trinary operator-name> <expression> <expression> <expression>
3593 // ::= cv <type> expression # conversion with one argument
3594 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3595 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3596 // ::= sc <type> <expression> # static_cast<type> (expression)
3597 // ::= cc <type> <expression> # const_cast<type> (expression)
3598 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3599 // ::= st <type> # sizeof (a type)
3600 // ::= at <type> # alignof (a type)
3601 // ::= <template-param>
3602 // ::= <function-param>
3603 // ::= sr <type> <unqualified-name> # dependent name
3604 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3605 // ::= ds <expression> <expression> # expr.*expr
3606 // ::= sZ <template-param> # size of a parameter pack
3607 // ::= sZ <function-param> # size of a function parameter pack
3608 // ::= <expr-primary>
3609 // <expr-primary> ::= L <type> <value number> E # integer literal
3610 // ::= L <type <value float> E # floating literal
3611 // ::= L <mangled-name> E # external name
3612 // ::= fpT # 'this' expression
3613 QualType ImplicitlyConvertedToType;
3616 switch (E->getStmtClass()) {
3617 case Expr::NoStmtClass:
3618 #define ABSTRACT_STMT(Type)
3619 #define EXPR(Type, Base)
3620 #define STMT(Type, Base) \
3621 case Expr::Type##Class:
3622 #include "clang/AST/StmtNodes.inc"
3625 // These all can only appear in local or variable-initialization
3626 // contexts and so should never appear in a mangling.
3627 case Expr::AddrLabelExprClass:
3628 case Expr::DesignatedInitUpdateExprClass:
3629 case Expr::ImplicitValueInitExprClass:
3630 case Expr::ArrayInitLoopExprClass:
3631 case Expr::ArrayInitIndexExprClass:
3632 case Expr::NoInitExprClass:
3633 case Expr::ParenListExprClass:
3634 case Expr::LambdaExprClass:
3635 case Expr::MSPropertyRefExprClass:
3636 case Expr::MSPropertySubscriptExprClass:
3637 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3638 case Expr::OMPArraySectionExprClass:
3639 case Expr::CXXInheritedCtorInitExprClass:
3640 llvm_unreachable("unexpected statement kind");
3642 case Expr::ConstantExprClass:
3643 E = cast<ConstantExpr>(E)->getSubExpr();
3646 // FIXME: invent manglings for all these.
3647 case Expr::BlockExprClass:
3648 case Expr::ChooseExprClass:
3649 case Expr::CompoundLiteralExprClass:
3650 case Expr::ExtVectorElementExprClass:
3651 case Expr::GenericSelectionExprClass:
3652 case Expr::ObjCEncodeExprClass:
3653 case Expr::ObjCIsaExprClass:
3654 case Expr::ObjCIvarRefExprClass:
3655 case Expr::ObjCMessageExprClass:
3656 case Expr::ObjCPropertyRefExprClass:
3657 case Expr::ObjCProtocolExprClass:
3658 case Expr::ObjCSelectorExprClass:
3659 case Expr::ObjCStringLiteralClass:
3660 case Expr::ObjCBoxedExprClass:
3661 case Expr::ObjCArrayLiteralClass:
3662 case Expr::ObjCDictionaryLiteralClass:
3663 case Expr::ObjCSubscriptRefExprClass:
3664 case Expr::ObjCIndirectCopyRestoreExprClass:
3665 case Expr::ObjCAvailabilityCheckExprClass:
3666 case Expr::OffsetOfExprClass:
3667 case Expr::PredefinedExprClass:
3668 case Expr::ShuffleVectorExprClass:
3669 case Expr::ConvertVectorExprClass:
3670 case Expr::StmtExprClass:
3671 case Expr::TypeTraitExprClass:
3672 case Expr::RequiresExprClass:
3673 case Expr::ArrayTypeTraitExprClass:
3674 case Expr::ExpressionTraitExprClass:
3675 case Expr::VAArgExprClass:
3676 case Expr::CUDAKernelCallExprClass:
3677 case Expr::AsTypeExprClass:
3678 case Expr::PseudoObjectExprClass:
3679 case Expr::AtomicExprClass:
3680 case Expr::SourceLocExprClass:
3681 case Expr::FixedPointLiteralClass:
3682 case Expr::BuiltinBitCastExprClass:
3685 // As bad as this diagnostic is, it's better than crashing.
3686 DiagnosticsEngine &Diags = Context.getDiags();
3687 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3688 "cannot yet mangle expression type %0");
3689 Diags.Report(E->getExprLoc(), DiagID)
3690 << E->getStmtClassName() << E->getSourceRange();
3695 case Expr::CXXUuidofExprClass: {
3696 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3697 if (UE->isTypeOperand()) {
3698 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3699 Out << "u8__uuidoft";
3702 Expr *UuidExp = UE->getExprOperand();
3703 Out << "u8__uuidofz";
3704 mangleExpression(UuidExp, Arity);
3709 // Even gcc-4.5 doesn't mangle this.
3710 case Expr::BinaryConditionalOperatorClass: {
3711 DiagnosticsEngine &Diags = Context.getDiags();
3713 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3714 "?: operator with omitted middle operand cannot be mangled");
3715 Diags.Report(E->getExprLoc(), DiagID)
3716 << E->getStmtClassName() << E->getSourceRange();
3720 // These are used for internal purposes and cannot be meaningfully mangled.
3721 case Expr::OpaqueValueExprClass:
3722 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3724 case Expr::InitListExprClass: {
3726 mangleInitListElements(cast<InitListExpr>(E));
3731 case Expr::DesignatedInitExprClass: {
3732 auto *DIE = cast<DesignatedInitExpr>(E);
3733 for (const auto &Designator : DIE->designators()) {
3734 if (Designator.isFieldDesignator()) {
3736 mangleSourceName(Designator.getFieldName());
3737 } else if (Designator.isArrayDesignator()) {
3739 mangleExpression(DIE->getArrayIndex(Designator));
3741 assert(Designator.isArrayRangeDesignator() &&
3742 "unknown designator kind");
3744 mangleExpression(DIE->getArrayRangeStart(Designator));
3745 mangleExpression(DIE->getArrayRangeEnd(Designator));
3748 mangleExpression(DIE->getInit());
3752 case Expr::CXXDefaultArgExprClass:
3753 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3756 case Expr::CXXDefaultInitExprClass:
3757 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3760 case Expr::CXXStdInitializerListExprClass:
3761 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3764 case Expr::SubstNonTypeTemplateParmExprClass:
3765 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3769 case Expr::UserDefinedLiteralClass:
3770 // We follow g++'s approach of mangling a UDL as a call to the literal
3772 case Expr::CXXMemberCallExprClass: // fallthrough
3773 case Expr::CallExprClass: {
3774 const CallExpr *CE = cast<CallExpr>(E);
3776 // <expression> ::= cp <simple-id> <expression>* E
3777 // We use this mangling only when the call would use ADL except
3778 // for being parenthesized. Per discussion with David
3779 // Vandervoorde, 2011.04.25.
3780 if (isParenthesizedADLCallee(CE)) {
3782 // The callee here is a parenthesized UnresolvedLookupExpr with
3783 // no qualifier and should always get mangled as a <simple-id>
3786 // <expression> ::= cl <expression>* E
3791 unsigned CallArity = CE->getNumArgs();
3792 for (const Expr *Arg : CE->arguments())
3793 if (isa<PackExpansionExpr>(Arg))
3794 CallArity = UnknownArity;
3796 mangleExpression(CE->getCallee(), CallArity);
3797 for (const Expr *Arg : CE->arguments())
3798 mangleExpression(Arg);
3803 case Expr::CXXNewExprClass: {
3804 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3805 if (New->isGlobalNew()) Out << "gs";
3806 Out << (New->isArray() ? "na" : "nw");
3807 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3808 E = New->placement_arg_end(); I != E; ++I)
3809 mangleExpression(*I);
3811 mangleType(New->getAllocatedType());
3812 if (New->hasInitializer()) {
3813 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3817 const Expr *Init = New->getInitializer();
3818 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3819 // Directly inline the initializers.
3820 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3823 mangleExpression(*I);
3824 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3825 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3826 mangleExpression(PLE->getExpr(i));
3827 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3828 isa<InitListExpr>(Init)) {
3829 // Only take InitListExprs apart for list-initialization.
3830 mangleInitListElements(cast<InitListExpr>(Init));
3832 mangleExpression(Init);
3838 case Expr::CXXPseudoDestructorExprClass: {
3839 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3840 if (const Expr *Base = PDE->getBase())
3841 mangleMemberExprBase(Base, PDE->isArrow());
3842 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3843 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3845 mangleUnresolvedPrefix(Qualifier,
3846 /*recursive=*/true);
3847 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3851 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3854 } else if (Qualifier) {
3855 mangleUnresolvedPrefix(Qualifier);
3857 // <base-unresolved-name> ::= dn <destructor-name>
3859 QualType DestroyedType = PDE->getDestroyedType();
3860 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3864 case Expr::MemberExprClass: {
3865 const MemberExpr *ME = cast<MemberExpr>(E);
3866 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3867 ME->getQualifier(), nullptr,
3868 ME->getMemberDecl()->getDeclName(),
3869 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3874 case Expr::UnresolvedMemberExprClass: {
3875 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3876 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3877 ME->isArrow(), ME->getQualifier(), nullptr,
3878 ME->getMemberName(),
3879 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3884 case Expr::CXXDependentScopeMemberExprClass: {
3885 const CXXDependentScopeMemberExpr *ME
3886 = cast<CXXDependentScopeMemberExpr>(E);
3887 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3888 ME->isArrow(), ME->getQualifier(),
3889 ME->getFirstQualifierFoundInScope(),
3891 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3896 case Expr::UnresolvedLookupExprClass: {
3897 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3898 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3899 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3904 case Expr::CXXUnresolvedConstructExprClass: {
3905 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3906 unsigned N = CE->arg_size();
3908 if (CE->isListInitialization()) {
3909 assert(N == 1 && "unexpected form for list initialization");
3910 auto *IL = cast<InitListExpr>(CE->getArg(0));
3912 mangleType(CE->getType());
3913 mangleInitListElements(IL);
3919 mangleType(CE->getType());
3920 if (N != 1) Out << '_';
3921 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3922 if (N != 1) Out << 'E';
3926 case Expr::CXXConstructExprClass: {
3927 const auto *CE = cast<CXXConstructExpr>(E);
3928 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3930 CE->getNumArgs() >= 1 &&
3931 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3932 "implicit CXXConstructExpr must have one argument");
3933 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3936 for (auto *E : CE->arguments())
3937 mangleExpression(E);
3942 case Expr::CXXTemporaryObjectExprClass: {
3943 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3944 unsigned N = CE->getNumArgs();
3945 bool List = CE->isListInitialization();
3951 mangleType(CE->getType());
3952 if (!List && N != 1)
3954 if (CE->isStdInitListInitialization()) {
3955 // We implicitly created a std::initializer_list<T> for the first argument
3956 // of a constructor of type U in an expression of the form U{a, b, c}.
3957 // Strip all the semantic gunk off the initializer list.
3959 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3960 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3961 mangleInitListElements(ILE);
3963 for (auto *E : CE->arguments())
3964 mangleExpression(E);
3971 case Expr::CXXScalarValueInitExprClass:
3973 mangleType(E->getType());
3977 case Expr::CXXNoexceptExprClass:
3979 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3982 case Expr::UnaryExprOrTypeTraitExprClass: {
3983 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3985 if (!SAE->isInstantiationDependent()) {
3987 // If the operand of a sizeof or alignof operator is not
3988 // instantiation-dependent it is encoded as an integer literal
3989 // reflecting the result of the operator.
3991 // If the result of the operator is implicitly converted to a known
3992 // integer type, that type is used for the literal; otherwise, the type
3993 // of std::size_t or std::ptrdiff_t is used.
3994 QualType T = (ImplicitlyConvertedToType.isNull() ||
3995 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3996 : ImplicitlyConvertedToType;
3997 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3998 mangleIntegerLiteral(T, V);
4002 switch(SAE->getKind()) {
4006 case UETT_PreferredAlignOf:
4010 case UETT_VecStep: {
4011 DiagnosticsEngine &Diags = Context.getDiags();
4012 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4013 "cannot yet mangle vec_step expression");
4014 Diags.Report(DiagID);
4017 case UETT_OpenMPRequiredSimdAlign: {
4018 DiagnosticsEngine &Diags = Context.getDiags();
4019 unsigned DiagID = Diags.getCustomDiagID(
4020 DiagnosticsEngine::Error,
4021 "cannot yet mangle __builtin_omp_required_simd_align expression");
4022 Diags.Report(DiagID);
4026 if (SAE->isArgumentType()) {
4028 mangleType(SAE->getArgumentType());
4031 mangleExpression(SAE->getArgumentExpr());
4036 case Expr::CXXThrowExprClass: {
4037 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4038 // <expression> ::= tw <expression> # throw expression
4040 if (TE->getSubExpr()) {
4042 mangleExpression(TE->getSubExpr());
4049 case Expr::CXXTypeidExprClass: {
4050 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4051 // <expression> ::= ti <type> # typeid (type)
4052 // ::= te <expression> # typeid (expression)
4053 if (TIE->isTypeOperand()) {
4055 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4058 mangleExpression(TIE->getExprOperand());
4063 case Expr::CXXDeleteExprClass: {
4064 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4065 // <expression> ::= [gs] dl <expression> # [::] delete expr
4066 // ::= [gs] da <expression> # [::] delete [] expr
4067 if (DE->isGlobalDelete()) Out << "gs";
4068 Out << (DE->isArrayForm() ? "da" : "dl");
4069 mangleExpression(DE->getArgument());
4073 case Expr::UnaryOperatorClass: {
4074 const UnaryOperator *UO = cast<UnaryOperator>(E);
4075 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4077 mangleExpression(UO->getSubExpr());
4081 case Expr::ArraySubscriptExprClass: {
4082 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4084 // Array subscript is treated as a syntactically weird form of
4087 mangleExpression(AE->getLHS());
4088 mangleExpression(AE->getRHS());
4092 case Expr::CompoundAssignOperatorClass: // fallthrough
4093 case Expr::BinaryOperatorClass: {
4094 const BinaryOperator *BO = cast<BinaryOperator>(E);
4095 if (BO->getOpcode() == BO_PtrMemD)
4098 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4100 mangleExpression(BO->getLHS());
4101 mangleExpression(BO->getRHS());
4105 case Expr::CXXRewrittenBinaryOperatorClass: {
4106 // The mangled form represents the original syntax.
4107 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
4108 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4109 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4111 mangleExpression(Decomposed.LHS);
4112 mangleExpression(Decomposed.RHS);
4116 case Expr::ConditionalOperatorClass: {
4117 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4118 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4119 mangleExpression(CO->getCond());
4120 mangleExpression(CO->getLHS(), Arity);
4121 mangleExpression(CO->getRHS(), Arity);
4125 case Expr::ImplicitCastExprClass: {
4126 ImplicitlyConvertedToType = E->getType();
4127 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4131 case Expr::ObjCBridgedCastExprClass: {
4132 // Mangle ownership casts as a vendor extended operator __bridge,
4133 // __bridge_transfer, or __bridge_retain.
4134 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4135 Out << "v1U" << Kind.size() << Kind;
4137 // Fall through to mangle the cast itself.
4140 case Expr::CStyleCastExprClass:
4141 mangleCastExpression(E, "cv");
4144 case Expr::CXXFunctionalCastExprClass: {
4145 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4146 // FIXME: Add isImplicit to CXXConstructExpr.
4147 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4148 if (CCE->getParenOrBraceRange().isInvalid())
4149 Sub = CCE->getArg(0)->IgnoreImplicit();
4150 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4151 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4152 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4154 mangleType(E->getType());
4155 mangleInitListElements(IL);
4158 mangleCastExpression(E, "cv");
4163 case Expr::CXXStaticCastExprClass:
4164 mangleCastExpression(E, "sc");
4166 case Expr::CXXDynamicCastExprClass:
4167 mangleCastExpression(E, "dc");
4169 case Expr::CXXReinterpretCastExprClass:
4170 mangleCastExpression(E, "rc");
4172 case Expr::CXXConstCastExprClass:
4173 mangleCastExpression(E, "cc");
4176 case Expr::CXXOperatorCallExprClass: {
4177 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4178 unsigned NumArgs = CE->getNumArgs();
4179 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4180 // (the enclosing MemberExpr covers the syntactic portion).
4181 if (CE->getOperator() != OO_Arrow)
4182 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4183 // Mangle the arguments.
4184 for (unsigned i = 0; i != NumArgs; ++i)
4185 mangleExpression(CE->getArg(i));
4189 case Expr::ParenExprClass:
4190 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4194 case Expr::ConceptSpecializationExprClass: {
4195 // <expr-primary> ::= L <mangled-name> E # external name
4197 auto *CSE = cast<ConceptSpecializationExpr>(E);
4198 mangleTemplateName(CSE->getNamedConcept(),
4199 CSE->getTemplateArguments().data(),
4200 CSE->getTemplateArguments().size());
4205 case Expr::DeclRefExprClass:
4206 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4209 case Expr::SubstNonTypeTemplateParmPackExprClass:
4210 // FIXME: not clear how to mangle this!
4211 // template <unsigned N...> class A {
4212 // template <class U...> void foo(U (&x)[N]...);
4214 Out << "_SUBSTPACK_";
4217 case Expr::FunctionParmPackExprClass: {
4218 // FIXME: not clear how to mangle this!
4219 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4220 Out << "v110_SUBSTPACK";
4221 mangleDeclRefExpr(FPPE->getParameterPack());
4225 case Expr::DependentScopeDeclRefExprClass: {
4226 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4227 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4228 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4233 case Expr::CXXBindTemporaryExprClass:
4234 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4237 case Expr::ExprWithCleanupsClass:
4238 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4241 case Expr::FloatingLiteralClass: {
4242 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4244 mangleType(FL->getType());
4245 mangleFloat(FL->getValue());
4250 case Expr::CharacterLiteralClass:
4252 mangleType(E->getType());
4253 Out << cast<CharacterLiteral>(E)->getValue();
4257 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4258 case Expr::ObjCBoolLiteralExprClass:
4260 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4264 case Expr::CXXBoolLiteralExprClass:
4266 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4270 case Expr::IntegerLiteralClass: {
4271 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4272 if (E->getType()->isSignedIntegerType())
4273 Value.setIsSigned(true);
4274 mangleIntegerLiteral(E->getType(), Value);
4278 case Expr::ImaginaryLiteralClass: {
4279 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4280 // Mangle as if a complex literal.
4281 // Proposal from David Vandevoorde, 2010.06.30.
4283 mangleType(E->getType());
4284 if (const FloatingLiteral *Imag =
4285 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4286 // Mangle a floating-point zero of the appropriate type.
4287 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4289 mangleFloat(Imag->getValue());
4292 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4293 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4294 Value.setIsSigned(true);
4295 mangleNumber(Value);
4301 case Expr::StringLiteralClass: {
4302 // Revised proposal from David Vandervoorde, 2010.07.15.
4304 assert(isa<ConstantArrayType>(E->getType()));
4305 mangleType(E->getType());
4310 case Expr::GNUNullExprClass:
4311 // Mangle as if an integer literal 0.
4313 mangleType(E->getType());
4317 case Expr::CXXNullPtrLiteralExprClass: {
4322 case Expr::PackExpansionExprClass:
4324 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4327 case Expr::SizeOfPackExprClass: {
4328 auto *SPE = cast<SizeOfPackExpr>(E);
4329 if (SPE->isPartiallySubstituted()) {
4331 for (const auto &A : SPE->getPartialArguments())
4332 mangleTemplateArg(A);
4338 const NamedDecl *Pack = SPE->getPack();
4339 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4340 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
4341 else if (const NonTypeTemplateParmDecl *NTTP
4342 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4343 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
4344 else if (const TemplateTemplateParmDecl *TempTP
4345 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4346 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
4348 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4352 case Expr::MaterializeTemporaryExprClass: {
4353 mangleExpression(cast<MaterializeTemporaryExpr>(E)->getSubExpr());
4357 case Expr::CXXFoldExprClass: {
4358 auto *FE = cast<CXXFoldExpr>(E);
4359 if (FE->isLeftFold())
4360 Out << (FE->getInit() ? "fL" : "fl");
4362 Out << (FE->getInit() ? "fR" : "fr");
4364 if (FE->getOperator() == BO_PtrMemD)
4368 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4372 mangleExpression(FE->getLHS());
4374 mangleExpression(FE->getRHS());
4378 case Expr::CXXThisExprClass:
4382 case Expr::CoawaitExprClass:
4383 // FIXME: Propose a non-vendor mangling.
4384 Out << "v18co_await";
4385 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4388 case Expr::DependentCoawaitExprClass:
4389 // FIXME: Propose a non-vendor mangling.
4390 Out << "v18co_await";
4391 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4394 case Expr::CoyieldExprClass:
4395 // FIXME: Propose a non-vendor mangling.
4396 Out << "v18co_yield";
4397 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4402 /// Mangle an expression which refers to a parameter variable.
4404 /// <expression> ::= <function-param>
4405 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4406 /// <function-param> ::= fp <top-level CV-qualifiers>
4407 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4408 /// <function-param> ::= fL <L-1 non-negative number>
4409 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4410 /// <function-param> ::= fL <L-1 non-negative number>
4411 /// p <top-level CV-qualifiers>
4412 /// <I-1 non-negative number> _ # L > 0, I > 0
4414 /// L is the nesting depth of the parameter, defined as 1 if the
4415 /// parameter comes from the innermost function prototype scope
4416 /// enclosing the current context, 2 if from the next enclosing
4417 /// function prototype scope, and so on, with one special case: if
4418 /// we've processed the full parameter clause for the innermost
4419 /// function type, then L is one less. This definition conveniently
4420 /// makes it irrelevant whether a function's result type was written
4421 /// trailing or leading, but is otherwise overly complicated; the
4422 /// numbering was first designed without considering references to
4423 /// parameter in locations other than return types, and then the
4424 /// mangling had to be generalized without changing the existing
4427 /// I is the zero-based index of the parameter within its parameter
4428 /// declaration clause. Note that the original ABI document describes
4429 /// this using 1-based ordinals.
4430 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4431 unsigned parmDepth = parm->getFunctionScopeDepth();
4432 unsigned parmIndex = parm->getFunctionScopeIndex();
4435 // parmDepth does not include the declaring function prototype.
4436 // FunctionTypeDepth does account for that.
4437 assert(parmDepth < FunctionTypeDepth.getDepth());
4438 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4439 if (FunctionTypeDepth.isInResultType())
4442 if (nestingDepth == 0) {
4445 Out << "fL" << (nestingDepth - 1) << 'p';
4448 // Top-level qualifiers. We don't have to worry about arrays here,
4449 // because parameters declared as arrays should already have been
4450 // transformed to have pointer type. FIXME: apparently these don't
4451 // get mangled if used as an rvalue of a known non-class type?
4452 assert(!parm->getType()->isArrayType()
4453 && "parameter's type is still an array type?");
4455 if (const DependentAddressSpaceType *DAST =
4456 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4457 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4459 mangleQualifiers(parm->getType().getQualifiers());
4463 if (parmIndex != 0) {
4464 Out << (parmIndex - 1);
4469 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4470 const CXXRecordDecl *InheritedFrom) {
4471 // <ctor-dtor-name> ::= C1 # complete object constructor
4472 // ::= C2 # base object constructor
4473 // ::= CI1 <type> # complete inheriting constructor
4474 // ::= CI2 <type> # base inheriting constructor
4476 // In addition, C5 is a comdat name with C1 and C2 in it.
4490 case Ctor_DefaultClosure:
4491 case Ctor_CopyingClosure:
4492 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4495 mangleName(InheritedFrom);
4498 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4499 // <ctor-dtor-name> ::= D0 # deleting destructor
4500 // ::= D1 # complete object destructor
4501 // ::= D2 # base object destructor
4503 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4520 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4521 unsigned NumTemplateArgs) {
4522 // <template-args> ::= I <template-arg>+ E
4524 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4525 mangleTemplateArg(TemplateArgs[i].getArgument());
4529 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4530 // <template-args> ::= I <template-arg>+ E
4532 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4533 mangleTemplateArg(AL[i]);
4537 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4538 unsigned NumTemplateArgs) {
4539 // <template-args> ::= I <template-arg>+ E
4541 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4542 mangleTemplateArg(TemplateArgs[i]);
4546 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4547 // <template-arg> ::= <type> # type or template
4548 // ::= X <expression> E # expression
4549 // ::= <expr-primary> # simple expressions
4550 // ::= J <template-arg>* E # argument pack
4551 if (!A.isInstantiationDependent() || A.isDependent())
4552 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4554 switch (A.getKind()) {
4555 case TemplateArgument::Null:
4556 llvm_unreachable("Cannot mangle NULL template argument");
4558 case TemplateArgument::Type:
4559 mangleType(A.getAsType());
4561 case TemplateArgument::Template:
4562 // This is mangled as <type>.
4563 mangleType(A.getAsTemplate());
4565 case TemplateArgument::TemplateExpansion:
4566 // <type> ::= Dp <type> # pack expansion (C++0x)
4568 mangleType(A.getAsTemplateOrTemplatePattern());
4570 case TemplateArgument::Expression: {
4571 // It's possible to end up with a DeclRefExpr here in certain
4572 // dependent cases, in which case we should mangle as a
4574 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts();
4575 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4576 const ValueDecl *D = DRE->getDecl();
4577 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4586 mangleExpression(E);
4590 case TemplateArgument::Integral:
4591 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4593 case TemplateArgument::Declaration: {
4594 // <expr-primary> ::= L <mangled-name> E # external name
4595 // Clang produces AST's where pointer-to-member-function expressions
4596 // and pointer-to-function expressions are represented as a declaration not
4597 // an expression. We compensate for it here to produce the correct mangling.
4598 ValueDecl *D = A.getAsDecl();
4599 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4600 if (compensateMangling) {
4602 mangleOperatorName(OO_Amp, 1);
4606 // References to external entities use the mangled name; if the name would
4607 // not normally be mangled then mangle it as unqualified.
4611 if (compensateMangling)
4616 case TemplateArgument::NullPtr: {
4617 // <expr-primary> ::= L <type> 0 E
4619 mangleType(A.getNullPtrType());
4623 case TemplateArgument::Pack: {
4624 // <template-arg> ::= J <template-arg>* E
4626 for (const auto &P : A.pack_elements())
4627 mangleTemplateArg(P);
4633 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
4634 // <template-param> ::= T_ # first template parameter
4635 // ::= T <parameter-2 non-negative number> _
4636 // ::= TL <L-1 non-negative number> __
4637 // ::= TL <L-1 non-negative number> _
4638 // <parameter-2 non-negative number> _
4640 // The latter two manglings are from a proposal here:
4641 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
4644 Out << 'L' << (Depth - 1) << '_';
4650 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4653 else if (SeqID > 1) {
4656 // <seq-id> is encoded in base-36, using digits and upper case letters.
4657 char Buffer[7]; // log(2**32) / log(36) ~= 7
4658 MutableArrayRef<char> BufferRef(Buffer);
4659 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4661 for (; SeqID != 0; SeqID /= 36) {
4662 unsigned C = SeqID % 36;
4663 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4666 Out.write(I.base(), I - BufferRef.rbegin());
4671 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4672 bool result = mangleSubstitution(tname);
4673 assert(result && "no existing substitution for template name");
4677 // <substitution> ::= S <seq-id> _
4679 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4680 // Try one of the standard substitutions first.
4681 if (mangleStandardSubstitution(ND))
4684 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4685 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4688 /// Determine whether the given type has any qualifiers that are relevant for
4690 static bool hasMangledSubstitutionQualifiers(QualType T) {
4691 Qualifiers Qs = T.getQualifiers();
4692 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
4695 bool CXXNameMangler::mangleSubstitution(QualType T) {
4696 if (!hasMangledSubstitutionQualifiers(T)) {
4697 if (const RecordType *RT = T->getAs<RecordType>())
4698 return mangleSubstitution(RT->getDecl());
4701 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4703 return mangleSubstitution(TypePtr);
4706 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4707 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4708 return mangleSubstitution(TD);
4710 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4711 return mangleSubstitution(
4712 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4715 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4716 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4717 if (I == Substitutions.end())
4720 unsigned SeqID = I->second;
4727 static bool isCharType(QualType T) {
4731 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4732 T->isSpecificBuiltinType(BuiltinType::Char_U);
4735 /// Returns whether a given type is a template specialization of a given name
4736 /// with a single argument of type char.
4737 static bool isCharSpecialization(QualType T, const char *Name) {
4741 const RecordType *RT = T->getAs<RecordType>();
4745 const ClassTemplateSpecializationDecl *SD =
4746 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4750 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4753 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4754 if (TemplateArgs.size() != 1)
4757 if (!isCharType(TemplateArgs[0].getAsType()))
4760 return SD->getIdentifier()->getName() == Name;
4763 template <std::size_t StrLen>
4764 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4765 const char (&Str)[StrLen]) {
4766 if (!SD->getIdentifier()->isStr(Str))
4769 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4770 if (TemplateArgs.size() != 2)
4773 if (!isCharType(TemplateArgs[0].getAsType()))
4776 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4782 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4783 // <substitution> ::= St # ::std::
4784 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4791 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4792 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4795 // <substitution> ::= Sa # ::std::allocator
4796 if (TD->getIdentifier()->isStr("allocator")) {
4801 // <<substitution> ::= Sb # ::std::basic_string
4802 if (TD->getIdentifier()->isStr("basic_string")) {
4808 if (const ClassTemplateSpecializationDecl *SD =
4809 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4810 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4813 // <substitution> ::= Ss # ::std::basic_string<char,
4814 // ::std::char_traits<char>,
4815 // ::std::allocator<char> >
4816 if (SD->getIdentifier()->isStr("basic_string")) {
4817 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4819 if (TemplateArgs.size() != 3)
4822 if (!isCharType(TemplateArgs[0].getAsType()))
4825 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4828 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4835 // <substitution> ::= Si # ::std::basic_istream<char,
4836 // ::std::char_traits<char> >
4837 if (isStreamCharSpecialization(SD, "basic_istream")) {
4842 // <substitution> ::= So # ::std::basic_ostream<char,
4843 // ::std::char_traits<char> >
4844 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4849 // <substitution> ::= Sd # ::std::basic_iostream<char,
4850 // ::std::char_traits<char> >
4851 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4859 void CXXNameMangler::addSubstitution(QualType T) {
4860 if (!hasMangledSubstitutionQualifiers(T)) {
4861 if (const RecordType *RT = T->getAs<RecordType>()) {
4862 addSubstitution(RT->getDecl());
4867 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4868 addSubstitution(TypePtr);
4871 void CXXNameMangler::addSubstitution(TemplateName Template) {
4872 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4873 return addSubstitution(TD);
4875 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4876 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4879 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4880 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4881 Substitutions[Ptr] = SeqID++;
4884 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4885 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4886 if (Other->SeqID > SeqID) {
4887 Substitutions.swap(Other->Substitutions);
4888 SeqID = Other->SeqID;
4892 CXXNameMangler::AbiTagList
4893 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4894 // When derived abi tags are disabled there is no need to make any list.
4895 if (DisableDerivedAbiTags)
4896 return AbiTagList();
4898 llvm::raw_null_ostream NullOutStream;
4899 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4900 TrackReturnTypeTags.disableDerivedAbiTags();
4902 const FunctionProtoType *Proto =
4903 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4904 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
4905 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4906 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4907 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4908 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
4910 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4913 CXXNameMangler::AbiTagList
4914 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4915 // When derived abi tags are disabled there is no need to make any list.
4916 if (DisableDerivedAbiTags)
4917 return AbiTagList();
4919 llvm::raw_null_ostream NullOutStream;
4920 CXXNameMangler TrackVariableType(*this, NullOutStream);
4921 TrackVariableType.disableDerivedAbiTags();
4923 TrackVariableType.mangleType(VD->getType());
4925 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4928 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4929 const VarDecl *VD) {
4930 llvm::raw_null_ostream NullOutStream;
4931 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4932 TrackAbiTags.mangle(VD);
4933 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4938 /// Mangles the name of the declaration D and emits that name to the given
4941 /// If the declaration D requires a mangled name, this routine will emit that
4942 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4943 /// and this routine will return false. In this case, the caller should just
4944 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4946 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4948 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4949 "Invalid mangleName() call, argument is not a variable or function!");
4950 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4951 "Invalid mangleName() call on 'structor decl!");
4953 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4954 getASTContext().getSourceManager(),
4955 "Mangling declaration");
4957 CXXNameMangler Mangler(*this, Out, D);
4961 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4964 CXXNameMangler Mangler(*this, Out, D, Type);
4968 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4971 CXXNameMangler Mangler(*this, Out, D, Type);
4975 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4977 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4981 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4983 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4987 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4988 const ThunkInfo &Thunk,
4990 // <special-name> ::= T <call-offset> <base encoding>
4991 // # base is the nominal target function of thunk
4992 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4993 // # base is the nominal target function of thunk
4994 // # first call-offset is 'this' adjustment
4995 // # second call-offset is result adjustment
4997 assert(!isa<CXXDestructorDecl>(MD) &&
4998 "Use mangleCXXDtor for destructor decls!");
4999 CXXNameMangler Mangler(*this, Out);
5000 Mangler.getStream() << "_ZT";
5001 if (!Thunk.Return.isEmpty())
5002 Mangler.getStream() << 'c';
5004 // Mangle the 'this' pointer adjustment.
5005 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
5006 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
5008 // Mangle the return pointer adjustment if there is one.
5009 if (!Thunk.Return.isEmpty())
5010 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
5011 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
5013 Mangler.mangleFunctionEncoding(MD);
5016 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
5017 const CXXDestructorDecl *DD, CXXDtorType Type,
5018 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
5019 // <special-name> ::= T <call-offset> <base encoding>
5020 // # base is the nominal target function of thunk
5021 CXXNameMangler Mangler(*this, Out, DD, Type);
5022 Mangler.getStream() << "_ZT";
5024 // Mangle the 'this' pointer adjustment.
5025 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
5026 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
5028 Mangler.mangleFunctionEncoding(DD);
5031 /// Returns the mangled name for a guard variable for the passed in VarDecl.
5032 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
5034 // <special-name> ::= GV <object name> # Guard variable for one-time
5036 CXXNameMangler Mangler(*this, Out);
5037 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
5038 // be a bug that is fixed in trunk.
5039 Mangler.getStream() << "_ZGV";
5040 Mangler.mangleName(D);
5043 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
5045 // These symbols are internal in the Itanium ABI, so the names don't matter.
5046 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
5047 // avoid duplicate symbols.
5048 Out << "__cxx_global_var_init";
5051 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
5053 // Prefix the mangling of D with __dtor_.
5054 CXXNameMangler Mangler(*this, Out);
5055 Mangler.getStream() << "__dtor_";
5056 if (shouldMangleDeclName(D))
5059 Mangler.getStream() << D->getName();
5062 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
5063 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5064 CXXNameMangler Mangler(*this, Out);
5065 Mangler.getStream() << "__filt_";
5066 if (shouldMangleDeclName(EnclosingDecl))
5067 Mangler.mangle(EnclosingDecl);
5069 Mangler.getStream() << EnclosingDecl->getName();
5072 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
5073 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5074 CXXNameMangler Mangler(*this, Out);
5075 Mangler.getStream() << "__fin_";
5076 if (shouldMangleDeclName(EnclosingDecl))
5077 Mangler.mangle(EnclosingDecl);
5079 Mangler.getStream() << EnclosingDecl->getName();
5082 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
5084 // <special-name> ::= TH <object name>
5085 CXXNameMangler Mangler(*this, Out);
5086 Mangler.getStream() << "_ZTH";
5087 Mangler.mangleName(D);
5091 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
5093 // <special-name> ::= TW <object name>
5094 CXXNameMangler Mangler(*this, Out);
5095 Mangler.getStream() << "_ZTW";
5096 Mangler.mangleName(D);
5099 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
5100 unsigned ManglingNumber,
5102 // We match the GCC mangling here.
5103 // <special-name> ::= GR <object name>
5104 CXXNameMangler Mangler(*this, Out);
5105 Mangler.getStream() << "_ZGR";
5106 Mangler.mangleName(D);
5107 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
5108 Mangler.mangleSeqID(ManglingNumber - 1);
5111 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5113 // <special-name> ::= TV <type> # virtual table
5114 CXXNameMangler Mangler(*this, Out);
5115 Mangler.getStream() << "_ZTV";
5116 Mangler.mangleNameOrStandardSubstitution(RD);
5119 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5121 // <special-name> ::= TT <type> # VTT structure
5122 CXXNameMangler Mangler(*this, Out);
5123 Mangler.getStream() << "_ZTT";
5124 Mangler.mangleNameOrStandardSubstitution(RD);
5127 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5129 const CXXRecordDecl *Type,
5131 // <special-name> ::= TC <type> <offset number> _ <base type>
5132 CXXNameMangler Mangler(*this, Out);
5133 Mangler.getStream() << "_ZTC";
5134 Mangler.mangleNameOrStandardSubstitution(RD);
5135 Mangler.getStream() << Offset;
5136 Mangler.getStream() << '_';
5137 Mangler.mangleNameOrStandardSubstitution(Type);
5140 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
5141 // <special-name> ::= TI <type> # typeinfo structure
5142 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5143 CXXNameMangler Mangler(*this, Out);
5144 Mangler.getStream() << "_ZTI";
5145 Mangler.mangleType(Ty);
5148 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5150 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5151 CXXNameMangler Mangler(*this, Out);
5152 Mangler.getStream() << "_ZTS";
5153 Mangler.mangleType(Ty);
5156 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5157 mangleCXXRTTIName(Ty, Out);
5160 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5161 llvm_unreachable("Can't mangle string literals");
5164 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
5166 CXXNameMangler Mangler(*this, Out);
5167 Mangler.mangleLambdaSig(Lambda);
5170 ItaniumMangleContext *
5171 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5172 return new ItaniumMangleContextImpl(Context, Diags);