1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
14 // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
35 #define MANGLE_CHECKER 0
41 using namespace clang;
45 /// Retrieve the declaration context that should be used when mangling the given
47 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
68 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
72 if (const auto *VD = dyn_cast<VarDecl>(D))
74 return VD->getASTContext().getTranslationUnitDecl();
76 if (const auto *FD = dyn_cast<FunctionDecl>(D))
78 return FD->getASTContext().getTranslationUnitDecl();
83 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
84 return getEffectiveDeclContext(cast<Decl>(DC));
87 static bool isLocalContainerContext(const DeclContext *DC) {
88 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
92 const DeclContext *DC = getEffectiveDeclContext(D);
93 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
94 if (isLocalContainerContext(DC))
95 return dyn_cast<RecordDecl>(D);
97 DC = getEffectiveDeclContext(D);
102 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
103 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
104 return ftd->getTemplatedDecl();
109 static const NamedDecl *getStructor(const NamedDecl *decl) {
110 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
111 return (fn ? getStructor(fn) : decl);
114 static bool isLambda(const NamedDecl *ND) {
115 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
119 return Record->isLambda();
122 static const unsigned UnknownArity = ~0U;
124 class ItaniumMangleContextImpl : public ItaniumMangleContext {
125 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
130 explicit ItaniumMangleContextImpl(ASTContext &Context,
131 DiagnosticsEngine &Diags)
132 : ItaniumMangleContext(Context, Diags) {}
134 /// @name Mangler Entry Points
137 bool shouldMangleCXXName(const NamedDecl *D) override;
138 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
142 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
143 raw_ostream &) override;
144 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145 const ThisAdjustment &ThisAdjustment,
146 raw_ostream &) override;
147 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
148 raw_ostream &) override;
149 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
150 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
151 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
152 const CXXRecordDecl *Type, raw_ostream &) override;
153 void mangleCXXRTTI(QualType T, raw_ostream &) override;
154 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
155 void mangleTypeName(QualType T, raw_ostream &) override;
156 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
157 raw_ostream &) override;
158 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
159 raw_ostream &) override;
161 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
162 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
163 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
164 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
165 void mangleDynamicAtExitDestructor(const VarDecl *D,
166 raw_ostream &Out) override;
167 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
168 raw_ostream &Out) override;
169 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
171 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
172 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
173 raw_ostream &) override;
175 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
177 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
178 // Lambda closure types are already numbered.
182 // Anonymous tags are already numbered.
183 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
184 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
188 // Use the canonical number for externally visible decls.
189 if (ND->isExternallyVisible()) {
190 unsigned discriminator = getASTContext().getManglingNumber(ND);
191 if (discriminator == 1)
193 disc = discriminator - 2;
197 // Make up a reasonable number for internal decls.
198 unsigned &discriminator = Uniquifier[ND];
199 if (!discriminator) {
200 const DeclContext *DC = getEffectiveDeclContext(ND);
201 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
203 if (discriminator == 1)
205 disc = discriminator-2;
211 /// Manage the mangling of a single name.
212 class CXXNameMangler {
213 ItaniumMangleContextImpl &Context;
216 /// The "structor" is the top-level declaration being mangled, if
217 /// that's not a template specialization; otherwise it's the pattern
218 /// for that specialization.
219 const NamedDecl *Structor;
220 unsigned StructorType;
222 /// The next substitution sequence number.
225 class FunctionTypeDepthState {
228 enum { InResultTypeMask = 1 };
231 FunctionTypeDepthState() : Bits(0) {}
233 /// The number of function types we're inside.
234 unsigned getDepth() const {
238 /// True if we're in the return type of the innermost function type.
239 bool isInResultType() const {
240 return Bits & InResultTypeMask;
243 FunctionTypeDepthState push() {
244 FunctionTypeDepthState tmp = *this;
245 Bits = (Bits & ~InResultTypeMask) + 2;
249 void enterResultType() {
250 Bits |= InResultTypeMask;
253 void leaveResultType() {
254 Bits &= ~InResultTypeMask;
257 void pop(FunctionTypeDepthState saved) {
258 assert(getDepth() == saved.getDepth() + 1);
264 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
266 ASTContext &getASTContext() const { return Context.getASTContext(); }
269 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
270 const NamedDecl *D = nullptr)
271 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
273 // These can't be mangled without a ctor type or dtor type.
274 assert(!D || (!isa<CXXDestructorDecl>(D) &&
275 !isa<CXXConstructorDecl>(D)));
277 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
278 const CXXConstructorDecl *D, CXXCtorType Type)
279 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
281 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
282 const CXXDestructorDecl *D, CXXDtorType Type)
283 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
288 if (Out.str()[0] == '\01')
292 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
293 assert(status == 0 && "Could not demangle mangled name!");
297 raw_ostream &getStream() { return Out; }
299 void mangle(const NamedDecl *D);
300 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
301 void mangleNumber(const llvm::APSInt &I);
302 void mangleNumber(int64_t Number);
303 void mangleFloat(const llvm::APFloat &F);
304 void mangleFunctionEncoding(const FunctionDecl *FD);
305 void mangleSeqID(unsigned SeqID);
306 void mangleName(const NamedDecl *ND);
307 void mangleType(QualType T);
308 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
312 bool mangleSubstitution(const NamedDecl *ND);
313 bool mangleSubstitution(QualType T);
314 bool mangleSubstitution(TemplateName Template);
315 bool mangleSubstitution(uintptr_t Ptr);
317 void mangleExistingSubstitution(QualType type);
318 void mangleExistingSubstitution(TemplateName name);
320 bool mangleStandardSubstitution(const NamedDecl *ND);
322 void addSubstitution(const NamedDecl *ND) {
323 ND = cast<NamedDecl>(ND->getCanonicalDecl());
325 addSubstitution(reinterpret_cast<uintptr_t>(ND));
327 void addSubstitution(QualType T);
328 void addSubstitution(TemplateName Template);
329 void addSubstitution(uintptr_t Ptr);
331 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
332 bool recursive = false);
333 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
334 DeclarationName name,
335 unsigned KnownArity = UnknownArity);
337 void mangleName(const TemplateDecl *TD,
338 const TemplateArgument *TemplateArgs,
339 unsigned NumTemplateArgs);
340 void mangleUnqualifiedName(const NamedDecl *ND) {
341 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
343 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
344 unsigned KnownArity);
345 void mangleUnscopedName(const NamedDecl *ND);
346 void mangleUnscopedTemplateName(const TemplateDecl *ND);
347 void mangleUnscopedTemplateName(TemplateName);
348 void mangleSourceName(const IdentifierInfo *II);
349 void mangleLocalName(const Decl *D);
350 void mangleBlockForPrefix(const BlockDecl *Block);
351 void mangleUnqualifiedBlock(const BlockDecl *Block);
352 void mangleLambda(const CXXRecordDecl *Lambda);
353 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
354 bool NoFunction=false);
355 void mangleNestedName(const TemplateDecl *TD,
356 const TemplateArgument *TemplateArgs,
357 unsigned NumTemplateArgs);
358 void manglePrefix(NestedNameSpecifier *qualifier);
359 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
360 void manglePrefix(QualType type);
361 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
362 void mangleTemplatePrefix(TemplateName Template);
363 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
364 StringRef Prefix = "");
365 void mangleOperatorName(DeclarationName Name, unsigned Arity);
366 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
367 void mangleQualifiers(Qualifiers Quals);
368 void mangleRefQualifier(RefQualifierKind RefQualifier);
370 void mangleObjCMethodName(const ObjCMethodDecl *MD);
372 // Declare manglers for every type class.
373 #define ABSTRACT_TYPE(CLASS, PARENT)
374 #define NON_CANONICAL_TYPE(CLASS, PARENT)
375 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
376 #include "clang/AST/TypeNodes.def"
378 void mangleType(const TagType*);
379 void mangleType(TemplateName);
380 void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType,
381 const FunctionDecl *FD = nullptr);
382 void mangleNeonVectorType(const VectorType *T);
383 void mangleAArch64NeonVectorType(const VectorType *T);
385 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
386 void mangleMemberExprBase(const Expr *base, bool isArrow);
387 void mangleMemberExpr(const Expr *base, bool isArrow,
388 NestedNameSpecifier *qualifier,
389 NamedDecl *firstQualifierLookup,
390 DeclarationName name,
391 unsigned knownArity);
392 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
393 void mangleInitListElements(const InitListExpr *InitList);
394 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
395 void mangleCXXCtorType(CXXCtorType T);
396 void mangleCXXDtorType(CXXDtorType T);
398 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
399 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
400 unsigned NumTemplateArgs);
401 void mangleTemplateArgs(const TemplateArgumentList &AL);
402 void mangleTemplateArg(TemplateArgument A);
404 void mangleTemplateParameter(unsigned Index);
406 void mangleFunctionParam(const ParmVarDecl *parm);
411 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
412 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
414 LanguageLinkage L = FD->getLanguageLinkage();
415 // Overloadable functions need mangling.
416 if (FD->hasAttr<OverloadableAttr>())
419 // "main" is not mangled.
423 // C++ functions and those whose names are not a simple identifier need
425 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
428 // C functions are not mangled.
429 if (L == CLanguageLinkage)
433 // Otherwise, no mangling is done outside C++ mode.
434 if (!getASTContext().getLangOpts().CPlusPlus)
437 const VarDecl *VD = dyn_cast<VarDecl>(D);
439 // C variables are not mangled.
443 // Variables at global scope with non-internal linkage are not mangled
444 const DeclContext *DC = getEffectiveDeclContext(D);
445 // Check for extern variable declared locally.
446 if (DC->isFunctionOrMethod() && D->hasLinkage())
447 while (!DC->isNamespace() && !DC->isTranslationUnit())
448 DC = getEffectiveParentContext(DC);
449 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
450 !isa<VarTemplateSpecializationDecl>(D))
457 void CXXNameMangler::mangle(const NamedDecl *D) {
458 // <mangled-name> ::= _Z <encoding>
460 // ::= <special-name>
462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
463 mangleFunctionEncoding(FD);
464 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
466 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
467 mangleName(IFD->getAnonField());
469 mangleName(cast<FieldDecl>(D));
472 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
473 // <encoding> ::= <function name> <bare-function-type>
476 // Don't mangle in the type if this isn't a decl we should typically mangle.
477 if (!Context.shouldMangleDeclName(FD))
480 if (FD->hasAttr<EnableIfAttr>()) {
481 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
482 Out << "Ua9enable_ifI";
483 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
485 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
486 E = FD->getAttrs().rend();
488 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
492 mangleExpression(EIA->getCond());
496 FunctionTypeDepth.pop(Saved);
499 // Whether the mangling of a function type includes the return type depends on
500 // the context and the nature of the function. The rules for deciding whether
501 // the return type is included are:
503 // 1. Template functions (names or types) have return types encoded, with
504 // the exceptions listed below.
505 // 2. Function types not appearing as part of a function name mangling,
506 // e.g. parameters, pointer types, etc., have return type encoded, with the
507 // exceptions listed below.
508 // 3. Non-template function names do not have return types encoded.
510 // The exceptions mentioned in (1) and (2) above, for which the return type is
511 // never included, are
514 // 3. Conversion operator functions, e.g. operator int.
515 bool MangleReturnType = false;
516 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
517 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
518 isa<CXXConversionDecl>(FD)))
519 MangleReturnType = true;
521 // Mangle the type of the primary template.
522 FD = PrimaryTemplate->getTemplatedDecl();
525 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
526 MangleReturnType, FD);
529 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
530 while (isa<LinkageSpecDecl>(DC)) {
531 DC = getEffectiveParentContext(DC);
537 /// Return whether a given namespace is the 'std' namespace.
538 static bool isStd(const NamespaceDecl *NS) {
539 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
540 ->isTranslationUnit())
543 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
544 return II && II->isStr("std");
547 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
549 static bool isStdNamespace(const DeclContext *DC) {
550 if (!DC->isNamespace())
553 return isStd(cast<NamespaceDecl>(DC));
556 static const TemplateDecl *
557 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
558 // Check if we have a function template.
559 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
560 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
561 TemplateArgs = FD->getTemplateSpecializationArgs();
566 // Check if we have a class template.
567 if (const ClassTemplateSpecializationDecl *Spec =
568 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
569 TemplateArgs = &Spec->getTemplateArgs();
570 return Spec->getSpecializedTemplate();
573 // Check if we have a variable template.
574 if (const VarTemplateSpecializationDecl *Spec =
575 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
576 TemplateArgs = &Spec->getTemplateArgs();
577 return Spec->getSpecializedTemplate();
583 void CXXNameMangler::mangleName(const NamedDecl *ND) {
584 // <name> ::= <nested-name>
585 // ::= <unscoped-name>
586 // ::= <unscoped-template-name> <template-args>
589 const DeclContext *DC = getEffectiveDeclContext(ND);
591 // If this is an extern variable declared locally, the relevant DeclContext
592 // is that of the containing namespace, or the translation unit.
593 // FIXME: This is a hack; extern variables declared locally should have
594 // a proper semantic declaration context!
595 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
596 while (!DC->isNamespace() && !DC->isTranslationUnit())
597 DC = getEffectiveParentContext(DC);
598 else if (GetLocalClassDecl(ND)) {
603 DC = IgnoreLinkageSpecDecls(DC);
605 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
606 // Check if we have a template.
607 const TemplateArgumentList *TemplateArgs = nullptr;
608 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
609 mangleUnscopedTemplateName(TD);
610 mangleTemplateArgs(*TemplateArgs);
614 mangleUnscopedName(ND);
618 if (isLocalContainerContext(DC)) {
623 mangleNestedName(ND, DC);
625 void CXXNameMangler::mangleName(const TemplateDecl *TD,
626 const TemplateArgument *TemplateArgs,
627 unsigned NumTemplateArgs) {
628 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
630 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
631 mangleUnscopedTemplateName(TD);
632 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
634 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
638 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
639 // <unscoped-name> ::= <unqualified-name>
640 // ::= St <unqualified-name> # ::std::
642 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
645 mangleUnqualifiedName(ND);
648 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
649 // <unscoped-template-name> ::= <unscoped-name>
650 // ::= <substitution>
651 if (mangleSubstitution(ND))
654 // <template-template-param> ::= <template-param>
655 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
656 mangleTemplateParameter(TTP->getIndex());
658 mangleUnscopedName(ND->getTemplatedDecl());
663 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
664 // <unscoped-template-name> ::= <unscoped-name>
665 // ::= <substitution>
666 if (TemplateDecl *TD = Template.getAsTemplateDecl())
667 return mangleUnscopedTemplateName(TD);
669 if (mangleSubstitution(Template))
672 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
673 assert(Dependent && "Not a dependent template name?");
674 if (const IdentifierInfo *Id = Dependent->getIdentifier())
675 mangleSourceName(Id);
677 mangleOperatorName(Dependent->getOperator(), UnknownArity);
679 addSubstitution(Template);
682 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
684 // Floating-point literals are encoded using a fixed-length
685 // lowercase hexadecimal string corresponding to the internal
686 // representation (IEEE on Itanium), high-order bytes first,
687 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
689 // The 'without leading zeroes' thing seems to be an editorial
690 // mistake; see the discussion on cxx-abi-dev beginning on
693 // Our requirements here are just barely weird enough to justify
694 // using a custom algorithm instead of post-processing APInt::toString().
696 llvm::APInt valueBits = f.bitcastToAPInt();
697 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
698 assert(numCharacters != 0);
700 // Allocate a buffer of the right number of characters.
701 SmallVector<char, 20> buffer(numCharacters);
703 // Fill the buffer left-to-right.
704 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
705 // The bit-index of the next hex digit.
706 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
708 // Project out 4 bits starting at 'digitIndex'.
709 llvm::integerPart hexDigit
710 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
711 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
714 // Map that over to a lowercase hex digit.
715 static const char charForHex[16] = {
716 '0', '1', '2', '3', '4', '5', '6', '7',
717 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
719 buffer[stringIndex] = charForHex[hexDigit];
722 Out.write(buffer.data(), numCharacters);
725 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
726 if (Value.isSigned() && Value.isNegative()) {
728 Value.abs().print(Out, /*signed*/ false);
730 Value.print(Out, /*signed*/ false);
734 void CXXNameMangler::mangleNumber(int64_t Number) {
735 // <number> ::= [n] <non-negative decimal integer>
744 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
745 // <call-offset> ::= h <nv-offset> _
746 // ::= v <v-offset> _
747 // <nv-offset> ::= <offset number> # non-virtual base override
748 // <v-offset> ::= <offset number> _ <virtual offset number>
749 // # virtual base override, with vcall offset
752 mangleNumber(NonVirtual);
758 mangleNumber(NonVirtual);
760 mangleNumber(Virtual);
764 void CXXNameMangler::manglePrefix(QualType type) {
765 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
766 if (!mangleSubstitution(QualType(TST, 0))) {
767 mangleTemplatePrefix(TST->getTemplateName());
769 // FIXME: GCC does not appear to mangle the template arguments when
770 // the template in question is a dependent template name. Should we
771 // emulate that badness?
772 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
773 addSubstitution(QualType(TST, 0));
775 } else if (const auto *DTST =
776 type->getAs<DependentTemplateSpecializationType>()) {
777 if (!mangleSubstitution(QualType(DTST, 0))) {
778 TemplateName Template = getASTContext().getDependentTemplateName(
779 DTST->getQualifier(), DTST->getIdentifier());
780 mangleTemplatePrefix(Template);
782 // FIXME: GCC does not appear to mangle the template arguments when
783 // the template in question is a dependent template name. Should we
784 // emulate that badness?
785 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
786 addSubstitution(QualType(DTST, 0));
789 // We use the QualType mangle type variant here because it handles
795 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
797 /// \param recursive - true if this is being called recursively,
798 /// i.e. if there is more prefix "to the right".
799 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
803 // <unresolved-name> ::= [gs] <base-unresolved-name>
805 // T::x / decltype(p)::x
806 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
808 // T::N::x /decltype(p)::N::x
809 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
810 // <base-unresolved-name>
812 // A::x, N::y, A<T>::z; "gs" means leading "::"
813 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
814 // <base-unresolved-name>
816 switch (qualifier->getKind()) {
817 case NestedNameSpecifier::Global:
820 // We want an 'sr' unless this is the entire NNS.
824 // We never want an 'E' here.
827 case NestedNameSpecifier::Super:
828 llvm_unreachable("Can't mangle __super specifier");
830 case NestedNameSpecifier::Namespace:
831 if (qualifier->getPrefix())
832 mangleUnresolvedPrefix(qualifier->getPrefix(),
836 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
838 case NestedNameSpecifier::NamespaceAlias:
839 if (qualifier->getPrefix())
840 mangleUnresolvedPrefix(qualifier->getPrefix(),
844 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
847 case NestedNameSpecifier::TypeSpec:
848 case NestedNameSpecifier::TypeSpecWithTemplate: {
849 const Type *type = qualifier->getAsType();
851 // We only want to use an unresolved-type encoding if this is one of:
853 // - a template type parameter
854 // - a template template parameter with arguments
855 // In all of these cases, we should have no prefix.
856 if (qualifier->getPrefix()) {
857 mangleUnresolvedPrefix(qualifier->getPrefix(),
860 // Otherwise, all the cases want this.
864 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
870 case NestedNameSpecifier::Identifier:
871 // Member expressions can have these without prefixes.
872 if (qualifier->getPrefix())
873 mangleUnresolvedPrefix(qualifier->getPrefix(),
878 mangleSourceName(qualifier->getAsIdentifier());
882 // If this was the innermost part of the NNS, and we fell out to
883 // here, append an 'E'.
888 /// Mangle an unresolved-name, which is generally used for names which
889 /// weren't resolved to specific entities.
890 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
891 DeclarationName name,
892 unsigned knownArity) {
893 if (qualifier) mangleUnresolvedPrefix(qualifier);
894 switch (name.getNameKind()) {
895 // <base-unresolved-name> ::= <simple-id>
896 case DeclarationName::Identifier:
897 mangleSourceName(name.getAsIdentifierInfo());
899 // <base-unresolved-name> ::= dn <destructor-name>
900 case DeclarationName::CXXDestructorName:
902 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
904 // <base-unresolved-name> ::= on <operator-name>
905 case DeclarationName::CXXConversionFunctionName:
906 case DeclarationName::CXXLiteralOperatorName:
907 case DeclarationName::CXXOperatorName:
909 mangleOperatorName(name, knownArity);
911 case DeclarationName::CXXConstructorName:
912 llvm_unreachable("Can't mangle a constructor name!");
913 case DeclarationName::CXXUsingDirective:
914 llvm_unreachable("Can't mangle a using directive name!");
915 case DeclarationName::ObjCMultiArgSelector:
916 case DeclarationName::ObjCOneArgSelector:
917 case DeclarationName::ObjCZeroArgSelector:
918 llvm_unreachable("Can't mangle Objective-C selector names here!");
922 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
923 DeclarationName Name,
924 unsigned KnownArity) {
925 unsigned Arity = KnownArity;
926 // <unqualified-name> ::= <operator-name>
927 // ::= <ctor-dtor-name>
929 switch (Name.getNameKind()) {
930 case DeclarationName::Identifier: {
931 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
932 // We must avoid conflicts between internally- and externally-
933 // linked variable and function declaration names in the same TU:
934 // void test() { extern void foo(); }
935 // static void foo();
936 // This naming convention is the same as that followed by GCC,
937 // though it shouldn't actually matter.
938 if (ND && ND->getFormalLinkage() == InternalLinkage &&
939 getEffectiveDeclContext(ND)->isFileContext())
942 mangleSourceName(II);
946 // Otherwise, an anonymous entity. We must have a declaration.
947 assert(ND && "mangling empty name without declaration");
949 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
950 if (NS->isAnonymousNamespace()) {
951 // This is how gcc mangles these names.
952 Out << "12_GLOBAL__N_1";
957 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
958 // We must have an anonymous union or struct declaration.
959 const RecordDecl *RD =
960 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
962 // Itanium C++ ABI 5.1.2:
964 // For the purposes of mangling, the name of an anonymous union is
965 // considered to be the name of the first named data member found by a
966 // pre-order, depth-first, declaration-order walk of the data members of
967 // the anonymous union. If there is no such data member (i.e., if all of
968 // the data members in the union are unnamed), then there is no way for
969 // a program to refer to the anonymous union, and there is therefore no
970 // need to mangle its name.
971 assert(RD->isAnonymousStructOrUnion()
972 && "Expected anonymous struct or union!");
973 const FieldDecl *FD = RD->findFirstNamedDataMember();
975 // It's actually possible for various reasons for us to get here
976 // with an empty anonymous struct / union. Fortunately, it
977 // doesn't really matter what name we generate.
979 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
981 mangleSourceName(FD->getIdentifier());
985 // Class extensions have no name as a category, and it's possible
986 // for them to be the semantic parent of certain declarations
987 // (primarily, tag decls defined within declarations). Such
988 // declarations will always have internal linkage, so the name
989 // doesn't really matter, but we shouldn't crash on them. For
990 // safety, just handle all ObjC containers here.
991 if (isa<ObjCContainerDecl>(ND))
994 // We must have an anonymous struct.
995 const TagDecl *TD = cast<TagDecl>(ND);
996 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
997 assert(TD->getDeclContext() == D->getDeclContext() &&
998 "Typedef should not be in another decl context!");
999 assert(D->getDeclName().getAsIdentifierInfo() &&
1000 "Typedef was not named!");
1001 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1005 // <unnamed-type-name> ::= <closure-type-name>
1007 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1008 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1009 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1010 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1011 mangleLambda(Record);
1016 if (TD->isExternallyVisible()) {
1017 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1019 if (UnnamedMangle > 1)
1020 Out << llvm::utostr(UnnamedMangle - 2);
1025 // Get a unique id for the anonymous struct.
1026 unsigned AnonStructId = Context.getAnonymousStructId(TD);
1028 // Mangle it as a source name in the form
1030 // where n is the length of the string.
1033 Str += llvm::utostr(AnonStructId);
1040 case DeclarationName::ObjCZeroArgSelector:
1041 case DeclarationName::ObjCOneArgSelector:
1042 case DeclarationName::ObjCMultiArgSelector:
1043 llvm_unreachable("Can't mangle Objective-C selector names here!");
1045 case DeclarationName::CXXConstructorName:
1047 // If the named decl is the C++ constructor we're mangling, use the type
1049 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1051 // Otherwise, use the complete constructor name. This is relevant if a
1052 // class with a constructor is declared within a constructor.
1053 mangleCXXCtorType(Ctor_Complete);
1056 case DeclarationName::CXXDestructorName:
1058 // If the named decl is the C++ destructor we're mangling, use the type we
1060 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1062 // Otherwise, use the complete destructor name. This is relevant if a
1063 // class with a destructor is declared within a destructor.
1064 mangleCXXDtorType(Dtor_Complete);
1067 case DeclarationName::CXXOperatorName:
1068 if (ND && Arity == UnknownArity) {
1069 Arity = cast<FunctionDecl>(ND)->getNumParams();
1071 // If we have a member function, we need to include the 'this' pointer.
1072 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1073 if (!MD->isStatic())
1077 case DeclarationName::CXXConversionFunctionName:
1078 case DeclarationName::CXXLiteralOperatorName:
1079 mangleOperatorName(Name, Arity);
1082 case DeclarationName::CXXUsingDirective:
1083 llvm_unreachable("Can't mangle a using directive name!");
1087 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1088 // <source-name> ::= <positive length number> <identifier>
1089 // <number> ::= [n] <non-negative decimal integer>
1090 // <identifier> ::= <unqualified source code identifier>
1091 Out << II->getLength() << II->getName();
1094 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1095 const DeclContext *DC,
1098 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1099 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1100 // <template-args> E
1103 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1104 Qualifiers MethodQuals =
1105 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1106 // We do not consider restrict a distinguishing attribute for overloading
1107 // purposes so we must not mangle it.
1108 MethodQuals.removeRestrict();
1109 mangleQualifiers(MethodQuals);
1110 mangleRefQualifier(Method->getRefQualifier());
1113 // Check if we have a template.
1114 const TemplateArgumentList *TemplateArgs = nullptr;
1115 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1116 mangleTemplatePrefix(TD, NoFunction);
1117 mangleTemplateArgs(*TemplateArgs);
1120 manglePrefix(DC, NoFunction);
1121 mangleUnqualifiedName(ND);
1126 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1127 const TemplateArgument *TemplateArgs,
1128 unsigned NumTemplateArgs) {
1129 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1133 mangleTemplatePrefix(TD);
1134 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1139 void CXXNameMangler::mangleLocalName(const Decl *D) {
1140 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1141 // := Z <function encoding> E s [<discriminator>]
1142 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1144 // <discriminator> := _ <non-negative number>
1145 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1146 const RecordDecl *RD = GetLocalClassDecl(D);
1147 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1151 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1152 mangleObjCMethodName(MD);
1153 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1154 mangleBlockForPrefix(BD);
1156 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1161 // The parameter number is omitted for the last parameter, 0 for the
1162 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1163 // <entity name> will of course contain a <closure-type-name>: Its
1164 // numbering will be local to the particular argument in which it appears
1165 // -- other default arguments do not affect its encoding.
1166 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1167 if (CXXRD->isLambda()) {
1168 if (const ParmVarDecl *Parm
1169 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1170 if (const FunctionDecl *Func
1171 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1173 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1175 mangleNumber(Num - 2);
1181 // Mangle the name relative to the closest enclosing function.
1182 // equality ok because RD derived from ND above
1184 mangleUnqualifiedName(RD);
1185 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1186 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1187 mangleUnqualifiedBlock(BD);
1189 const NamedDecl *ND = cast<NamedDecl>(D);
1190 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1192 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1193 // Mangle a block in a default parameter; see above explanation for
1195 if (const ParmVarDecl *Parm
1196 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1197 if (const FunctionDecl *Func
1198 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1200 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1202 mangleNumber(Num - 2);
1207 mangleUnqualifiedBlock(BD);
1209 mangleUnqualifiedName(cast<NamedDecl>(D));
1212 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1214 if (Context.getNextDiscriminator(ND, disc)) {
1218 Out << "__" << disc << '_';
1223 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1224 if (GetLocalClassDecl(Block)) {
1225 mangleLocalName(Block);
1228 const DeclContext *DC = getEffectiveDeclContext(Block);
1229 if (isLocalContainerContext(DC)) {
1230 mangleLocalName(Block);
1233 manglePrefix(getEffectiveDeclContext(Block));
1234 mangleUnqualifiedBlock(Block);
1237 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1238 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1239 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1240 Context->getDeclContext()->isRecord()) {
1241 if (const IdentifierInfo *Name
1242 = cast<NamedDecl>(Context)->getIdentifier()) {
1243 mangleSourceName(Name);
1249 // If we have a block mangling number, use it.
1250 unsigned Number = Block->getBlockManglingNumber();
1251 // Otherwise, just make up a number. It doesn't matter what it is because
1252 // the symbol in question isn't externally visible.
1254 Number = Context.getBlockId(Block, false);
1261 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1262 // If the context of a closure type is an initializer for a class member
1263 // (static or nonstatic), it is encoded in a qualified name with a final
1264 // <prefix> of the form:
1266 // <data-member-prefix> := <member source-name> M
1268 // Technically, the data-member-prefix is part of the <prefix>. However,
1269 // since a closure type will always be mangled with a prefix, it's easier
1270 // to emit that last part of the prefix here.
1271 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1272 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1273 Context->getDeclContext()->isRecord()) {
1274 if (const IdentifierInfo *Name
1275 = cast<NamedDecl>(Context)->getIdentifier()) {
1276 mangleSourceName(Name);
1283 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1284 getAs<FunctionProtoType>();
1285 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1286 Lambda->getLambdaStaticInvoker());
1289 // The number is omitted for the first closure type with a given
1290 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1291 // (in lexical order) with that same <lambda-sig> and context.
1293 // The AST keeps track of the number for us.
1294 unsigned Number = Lambda->getLambdaManglingNumber();
1295 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1297 mangleNumber(Number - 2);
1301 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1302 switch (qualifier->getKind()) {
1303 case NestedNameSpecifier::Global:
1307 case NestedNameSpecifier::Super:
1308 llvm_unreachable("Can't mangle __super specifier");
1310 case NestedNameSpecifier::Namespace:
1311 mangleName(qualifier->getAsNamespace());
1314 case NestedNameSpecifier::NamespaceAlias:
1315 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1318 case NestedNameSpecifier::TypeSpec:
1319 case NestedNameSpecifier::TypeSpecWithTemplate:
1320 manglePrefix(QualType(qualifier->getAsType(), 0));
1323 case NestedNameSpecifier::Identifier:
1324 // Member expressions can have these without prefixes, but that
1325 // should end up in mangleUnresolvedPrefix instead.
1326 assert(qualifier->getPrefix());
1327 manglePrefix(qualifier->getPrefix());
1329 mangleSourceName(qualifier->getAsIdentifier());
1333 llvm_unreachable("unexpected nested name specifier");
1336 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1337 // <prefix> ::= <prefix> <unqualified-name>
1338 // ::= <template-prefix> <template-args>
1339 // ::= <template-param>
1341 // ::= <substitution>
1343 DC = IgnoreLinkageSpecDecls(DC);
1345 if (DC->isTranslationUnit())
1348 if (NoFunction && isLocalContainerContext(DC))
1351 assert(!isLocalContainerContext(DC));
1353 const NamedDecl *ND = cast<NamedDecl>(DC);
1354 if (mangleSubstitution(ND))
1357 // Check if we have a template.
1358 const TemplateArgumentList *TemplateArgs = nullptr;
1359 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1360 mangleTemplatePrefix(TD);
1361 mangleTemplateArgs(*TemplateArgs);
1363 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1364 mangleUnqualifiedName(ND);
1367 addSubstitution(ND);
1370 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1371 // <template-prefix> ::= <prefix> <template unqualified-name>
1372 // ::= <template-param>
1373 // ::= <substitution>
1374 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1375 return mangleTemplatePrefix(TD);
1377 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1378 manglePrefix(Qualified->getQualifier());
1380 if (OverloadedTemplateStorage *Overloaded
1381 = Template.getAsOverloadedTemplate()) {
1382 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1387 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1388 assert(Dependent && "Unknown template name kind?");
1389 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1390 manglePrefix(Qualifier);
1391 mangleUnscopedTemplateName(Template);
1394 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1396 // <template-prefix> ::= <prefix> <template unqualified-name>
1397 // ::= <template-param>
1398 // ::= <substitution>
1399 // <template-template-param> ::= <template-param>
1402 if (mangleSubstitution(ND))
1405 // <template-template-param> ::= <template-param>
1406 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1407 mangleTemplateParameter(TTP->getIndex());
1409 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1410 mangleUnqualifiedName(ND->getTemplatedDecl());
1413 addSubstitution(ND);
1416 /// Mangles a template name under the production <type>. Required for
1417 /// template template arguments.
1418 /// <type> ::= <class-enum-type>
1419 /// ::= <template-param>
1420 /// ::= <substitution>
1421 void CXXNameMangler::mangleType(TemplateName TN) {
1422 if (mangleSubstitution(TN))
1425 TemplateDecl *TD = nullptr;
1427 switch (TN.getKind()) {
1428 case TemplateName::QualifiedTemplate:
1429 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1432 case TemplateName::Template:
1433 TD = TN.getAsTemplateDecl();
1437 if (isa<TemplateTemplateParmDecl>(TD))
1438 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1443 case TemplateName::OverloadedTemplate:
1444 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1446 case TemplateName::DependentTemplate: {
1447 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1448 assert(Dependent->isIdentifier());
1450 // <class-enum-type> ::= <name>
1451 // <name> ::= <nested-name>
1452 mangleUnresolvedPrefix(Dependent->getQualifier());
1453 mangleSourceName(Dependent->getIdentifier());
1457 case TemplateName::SubstTemplateTemplateParm: {
1458 // Substituted template parameters are mangled as the substituted
1459 // template. This will check for the substitution twice, which is
1460 // fine, but we have to return early so that we don't try to *add*
1461 // the substitution twice.
1462 SubstTemplateTemplateParmStorage *subst
1463 = TN.getAsSubstTemplateTemplateParm();
1464 mangleType(subst->getReplacement());
1468 case TemplateName::SubstTemplateTemplateParmPack: {
1469 // FIXME: not clear how to mangle this!
1470 // template <template <class> class T...> class A {
1471 // template <template <class> class U...> void foo(B<T,U> x...);
1473 Out << "_SUBSTPACK_";
1478 addSubstitution(TN);
1481 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1483 // Only certain other types are valid as prefixes; enumerate them.
1484 switch (Ty->getTypeClass()) {
1487 case Type::Adjusted:
1490 case Type::BlockPointer:
1491 case Type::LValueReference:
1492 case Type::RValueReference:
1493 case Type::MemberPointer:
1494 case Type::ConstantArray:
1495 case Type::IncompleteArray:
1496 case Type::VariableArray:
1497 case Type::DependentSizedArray:
1498 case Type::DependentSizedExtVector:
1500 case Type::ExtVector:
1501 case Type::FunctionProto:
1502 case Type::FunctionNoProto:
1504 case Type::Attributed:
1506 case Type::PackExpansion:
1507 case Type::ObjCObject:
1508 case Type::ObjCInterface:
1509 case Type::ObjCObjectPointer:
1511 llvm_unreachable("type is illegal as a nested name specifier");
1513 case Type::SubstTemplateTypeParmPack:
1514 // FIXME: not clear how to mangle this!
1515 // template <class T...> class A {
1516 // template <class U...> void foo(decltype(T::foo(U())) x...);
1518 Out << "_SUBSTPACK_";
1521 // <unresolved-type> ::= <template-param>
1523 // ::= <template-template-param> <template-args>
1524 // (this last is not official yet)
1525 case Type::TypeOfExpr:
1527 case Type::Decltype:
1528 case Type::TemplateTypeParm:
1529 case Type::UnaryTransform:
1530 case Type::SubstTemplateTypeParm:
1532 // Some callers want a prefix before the mangled type.
1535 // This seems to do everything we want. It's not really
1536 // sanctioned for a substituted template parameter, though.
1539 // We never want to print 'E' directly after an unresolved-type,
1540 // so we return directly.
1544 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1547 case Type::UnresolvedUsing:
1549 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1554 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1557 case Type::TemplateSpecialization: {
1558 const TemplateSpecializationType *TST =
1559 cast<TemplateSpecializationType>(Ty);
1560 TemplateName TN = TST->getTemplateName();
1561 switch (TN.getKind()) {
1562 case TemplateName::Template:
1563 case TemplateName::QualifiedTemplate: {
1564 TemplateDecl *TD = TN.getAsTemplateDecl();
1566 // If the base is a template template parameter, this is an
1568 assert(TD && "no template for template specialization type");
1569 if (isa<TemplateTemplateParmDecl>(TD))
1570 goto unresolvedType;
1572 mangleSourceName(TD->getIdentifier());
1576 case TemplateName::OverloadedTemplate:
1577 case TemplateName::DependentTemplate:
1578 llvm_unreachable("invalid base for a template specialization type");
1580 case TemplateName::SubstTemplateTemplateParm: {
1581 SubstTemplateTemplateParmStorage *subst =
1582 TN.getAsSubstTemplateTemplateParm();
1583 mangleExistingSubstitution(subst->getReplacement());
1587 case TemplateName::SubstTemplateTemplateParmPack: {
1588 // FIXME: not clear how to mangle this!
1589 // template <template <class U> class T...> class A {
1590 // template <class U...> void foo(decltype(T<U>::foo) x...);
1592 Out << "_SUBSTPACK_";
1597 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1601 case Type::InjectedClassName:
1603 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1606 case Type::DependentName:
1607 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1610 case Type::DependentTemplateSpecialization: {
1611 const DependentTemplateSpecializationType *DTST =
1612 cast<DependentTemplateSpecializationType>(Ty);
1613 mangleSourceName(DTST->getIdentifier());
1614 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1618 case Type::Elaborated:
1619 return mangleUnresolvedTypeOrSimpleId(
1620 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1626 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1627 switch (Name.getNameKind()) {
1628 case DeclarationName::CXXConstructorName:
1629 case DeclarationName::CXXDestructorName:
1630 case DeclarationName::CXXUsingDirective:
1631 case DeclarationName::Identifier:
1632 case DeclarationName::ObjCMultiArgSelector:
1633 case DeclarationName::ObjCOneArgSelector:
1634 case DeclarationName::ObjCZeroArgSelector:
1635 llvm_unreachable("Not an operator name");
1637 case DeclarationName::CXXConversionFunctionName:
1638 // <operator-name> ::= cv <type> # (cast)
1640 mangleType(Name.getCXXNameType());
1643 case DeclarationName::CXXLiteralOperatorName:
1645 mangleSourceName(Name.getCXXLiteralIdentifier());
1648 case DeclarationName::CXXOperatorName:
1649 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1657 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1659 // <operator-name> ::= nw # new
1660 case OO_New: Out << "nw"; break;
1662 case OO_Array_New: Out << "na"; break;
1664 case OO_Delete: Out << "dl"; break;
1665 // ::= da # delete[]
1666 case OO_Array_Delete: Out << "da"; break;
1667 // ::= ps # + (unary)
1668 // ::= pl # + (binary or unknown)
1670 Out << (Arity == 1? "ps" : "pl"); break;
1671 // ::= ng # - (unary)
1672 // ::= mi # - (binary or unknown)
1674 Out << (Arity == 1? "ng" : "mi"); break;
1675 // ::= ad # & (unary)
1676 // ::= an # & (binary or unknown)
1678 Out << (Arity == 1? "ad" : "an"); break;
1679 // ::= de # * (unary)
1680 // ::= ml # * (binary or unknown)
1682 // Use binary when unknown.
1683 Out << (Arity == 1? "de" : "ml"); break;
1685 case OO_Tilde: Out << "co"; break;
1687 case OO_Slash: Out << "dv"; break;
1689 case OO_Percent: Out << "rm"; break;
1691 case OO_Pipe: Out << "or"; break;
1693 case OO_Caret: Out << "eo"; break;
1695 case OO_Equal: Out << "aS"; break;
1697 case OO_PlusEqual: Out << "pL"; break;
1699 case OO_MinusEqual: Out << "mI"; break;
1701 case OO_StarEqual: Out << "mL"; break;
1703 case OO_SlashEqual: Out << "dV"; break;
1705 case OO_PercentEqual: Out << "rM"; break;
1707 case OO_AmpEqual: Out << "aN"; break;
1709 case OO_PipeEqual: Out << "oR"; break;
1711 case OO_CaretEqual: Out << "eO"; break;
1713 case OO_LessLess: Out << "ls"; break;
1715 case OO_GreaterGreater: Out << "rs"; break;
1717 case OO_LessLessEqual: Out << "lS"; break;
1719 case OO_GreaterGreaterEqual: Out << "rS"; break;
1721 case OO_EqualEqual: Out << "eq"; break;
1723 case OO_ExclaimEqual: Out << "ne"; break;
1725 case OO_Less: Out << "lt"; break;
1727 case OO_Greater: Out << "gt"; break;
1729 case OO_LessEqual: Out << "le"; break;
1731 case OO_GreaterEqual: Out << "ge"; break;
1733 case OO_Exclaim: Out << "nt"; break;
1735 case OO_AmpAmp: Out << "aa"; break;
1737 case OO_PipePipe: Out << "oo"; break;
1739 case OO_PlusPlus: Out << "pp"; break;
1741 case OO_MinusMinus: Out << "mm"; break;
1743 case OO_Comma: Out << "cm"; break;
1745 case OO_ArrowStar: Out << "pm"; break;
1747 case OO_Arrow: Out << "pt"; break;
1749 case OO_Call: Out << "cl"; break;
1751 case OO_Subscript: Out << "ix"; break;
1754 // The conditional operator can't be overloaded, but we still handle it when
1755 // mangling expressions.
1756 case OO_Conditional: Out << "qu"; break;
1757 // Proposal on cxx-abi-dev, 2015-10-21.
1758 // ::= aw # co_await
1759 case OO_Coawait: Out << "aw"; break;
1762 case NUM_OVERLOADED_OPERATORS:
1763 llvm_unreachable("Not an overloaded operator");
1767 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1768 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1769 if (Quals.hasRestrict())
1771 if (Quals.hasVolatile())
1773 if (Quals.hasConst())
1776 if (Quals.hasAddressSpace()) {
1777 // Address space extension:
1779 // <type> ::= U <target-addrspace>
1780 // <type> ::= U <OpenCL-addrspace>
1781 // <type> ::= U <CUDA-addrspace>
1783 SmallString<64> ASString;
1784 unsigned AS = Quals.getAddressSpace();
1786 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1787 // <target-addrspace> ::= "AS" <address-space-number>
1788 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1789 ASString = "AS" + llvm::utostr_32(TargetAS);
1792 default: llvm_unreachable("Not a language specific address space");
1793 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1794 case LangAS::opencl_global: ASString = "CLglobal"; break;
1795 case LangAS::opencl_local: ASString = "CLlocal"; break;
1796 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1797 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1798 case LangAS::cuda_device: ASString = "CUdevice"; break;
1799 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1800 case LangAS::cuda_shared: ASString = "CUshared"; break;
1803 Out << 'U' << ASString.size() << ASString;
1806 StringRef LifetimeName;
1807 switch (Quals.getObjCLifetime()) {
1808 // Objective-C ARC Extension:
1810 // <type> ::= U "__strong"
1811 // <type> ::= U "__weak"
1812 // <type> ::= U "__autoreleasing"
1813 case Qualifiers::OCL_None:
1816 case Qualifiers::OCL_Weak:
1817 LifetimeName = "__weak";
1820 case Qualifiers::OCL_Strong:
1821 LifetimeName = "__strong";
1824 case Qualifiers::OCL_Autoreleasing:
1825 LifetimeName = "__autoreleasing";
1828 case Qualifiers::OCL_ExplicitNone:
1829 // The __unsafe_unretained qualifier is *not* mangled, so that
1830 // __unsafe_unretained types in ARC produce the same manglings as the
1831 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1832 // better ABI compatibility.
1834 // It's safe to do this because unqualified 'id' won't show up
1835 // in any type signatures that need to be mangled.
1838 if (!LifetimeName.empty())
1839 Out << 'U' << LifetimeName.size() << LifetimeName;
1842 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1843 // <ref-qualifier> ::= R # lvalue reference
1844 // ::= O # rvalue-reference
1845 switch (RefQualifier) {
1859 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1860 Context.mangleObjCMethodName(MD, Out);
1863 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1866 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1868 if (Ty->isOpenCLSpecificType())
1870 if (Ty->isBuiltinType())
1876 void CXXNameMangler::mangleType(QualType T) {
1877 // If our type is instantiation-dependent but not dependent, we mangle
1878 // it as it was written in the source, removing any top-level sugar.
1879 // Otherwise, use the canonical type.
1881 // FIXME: This is an approximation of the instantiation-dependent name
1882 // mangling rules, since we should really be using the type as written and
1883 // augmented via semantic analysis (i.e., with implicit conversions and
1884 // default template arguments) for any instantiation-dependent type.
1885 // Unfortunately, that requires several changes to our AST:
1886 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1887 // uniqued, so that we can handle substitutions properly
1888 // - Default template arguments will need to be represented in the
1889 // TemplateSpecializationType, since they need to be mangled even though
1890 // they aren't written.
1891 // - Conversions on non-type template arguments need to be expressed, since
1892 // they can affect the mangling of sizeof/alignof.
1893 if (!T->isInstantiationDependentType() || T->isDependentType())
1894 T = T.getCanonicalType();
1896 // Desugar any types that are purely sugar.
1898 // Don't desugar through template specialization types that aren't
1899 // type aliases. We need to mangle the template arguments as written.
1900 if (const TemplateSpecializationType *TST
1901 = dyn_cast<TemplateSpecializationType>(T))
1902 if (!TST->isTypeAlias())
1906 = T.getSingleStepDesugaredType(Context.getASTContext());
1913 SplitQualType split = T.split();
1914 Qualifiers quals = split.Quals;
1915 const Type *ty = split.Ty;
1917 bool isSubstitutable = isTypeSubstitutable(quals, ty);
1918 if (isSubstitutable && mangleSubstitution(T))
1921 // If we're mangling a qualified array type, push the qualifiers to
1922 // the element type.
1923 if (quals && isa<ArrayType>(T)) {
1924 ty = Context.getASTContext().getAsArrayType(T);
1925 quals = Qualifiers();
1927 // Note that we don't update T: we want to add the
1928 // substitution at the original type.
1932 mangleQualifiers(quals);
1933 // Recurse: even if the qualified type isn't yet substitutable,
1934 // the unqualified type might be.
1935 mangleType(QualType(ty, 0));
1937 switch (ty->getTypeClass()) {
1938 #define ABSTRACT_TYPE(CLASS, PARENT)
1939 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1941 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1943 #define TYPE(CLASS, PARENT) \
1945 mangleType(static_cast<const CLASS##Type*>(ty)); \
1947 #include "clang/AST/TypeNodes.def"
1951 // Add the substitution.
1952 if (isSubstitutable)
1956 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1957 if (!mangleStandardSubstitution(ND))
1961 void CXXNameMangler::mangleType(const BuiltinType *T) {
1962 // <type> ::= <builtin-type>
1963 // <builtin-type> ::= v # void
1967 // ::= a # signed char
1968 // ::= h # unsigned char
1970 // ::= t # unsigned short
1972 // ::= j # unsigned int
1974 // ::= m # unsigned long
1975 // ::= x # long long, __int64
1976 // ::= y # unsigned long long, __int64
1978 // ::= o # unsigned __int128
1981 // ::= e # long double, __float80
1982 // UNSUPPORTED: ::= g # __float128
1983 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1984 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1985 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1986 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1987 // ::= Di # char32_t
1988 // ::= Ds # char16_t
1989 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1990 // ::= u <source-name> # vendor extended type
1991 switch (T->getKind()) {
1992 case BuiltinType::Void:
1995 case BuiltinType::Bool:
1998 case BuiltinType::Char_U:
1999 case BuiltinType::Char_S:
2002 case BuiltinType::UChar:
2005 case BuiltinType::UShort:
2008 case BuiltinType::UInt:
2011 case BuiltinType::ULong:
2014 case BuiltinType::ULongLong:
2017 case BuiltinType::UInt128:
2020 case BuiltinType::SChar:
2023 case BuiltinType::WChar_S:
2024 case BuiltinType::WChar_U:
2027 case BuiltinType::Char16:
2030 case BuiltinType::Char32:
2033 case BuiltinType::Short:
2036 case BuiltinType::Int:
2039 case BuiltinType::Long:
2042 case BuiltinType::LongLong:
2045 case BuiltinType::Int128:
2048 case BuiltinType::Half:
2051 case BuiltinType::Float:
2054 case BuiltinType::Double:
2057 case BuiltinType::LongDouble:
2058 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2062 case BuiltinType::NullPtr:
2066 #define BUILTIN_TYPE(Id, SingletonId)
2067 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2068 case BuiltinType::Id:
2069 #include "clang/AST/BuiltinTypes.def"
2070 case BuiltinType::Dependent:
2071 llvm_unreachable("mangling a placeholder type");
2072 case BuiltinType::ObjCId:
2073 Out << "11objc_object";
2075 case BuiltinType::ObjCClass:
2076 Out << "10objc_class";
2078 case BuiltinType::ObjCSel:
2079 Out << "13objc_selector";
2081 case BuiltinType::OCLImage1d:
2082 Out << "11ocl_image1d";
2084 case BuiltinType::OCLImage1dArray:
2085 Out << "16ocl_image1darray";
2087 case BuiltinType::OCLImage1dBuffer:
2088 Out << "17ocl_image1dbuffer";
2090 case BuiltinType::OCLImage2d:
2091 Out << "11ocl_image2d";
2093 case BuiltinType::OCLImage2dArray:
2094 Out << "16ocl_image2darray";
2096 case BuiltinType::OCLImage2dDepth:
2097 Out << "16ocl_image2ddepth";
2099 case BuiltinType::OCLImage2dArrayDepth:
2100 Out << "21ocl_image2darraydepth";
2102 case BuiltinType::OCLImage2dMSAA:
2103 Out << "15ocl_image2dmsaa";
2105 case BuiltinType::OCLImage2dArrayMSAA:
2106 Out << "20ocl_image2darraymsaa";
2108 case BuiltinType::OCLImage2dMSAADepth:
2109 Out << "20ocl_image2dmsaadepth";
2111 case BuiltinType::OCLImage2dArrayMSAADepth:
2112 Out << "35ocl_image2darraymsaadepth";
2114 case BuiltinType::OCLImage3d:
2115 Out << "11ocl_image3d";
2117 case BuiltinType::OCLSampler:
2118 Out << "11ocl_sampler";
2120 case BuiltinType::OCLEvent:
2121 Out << "9ocl_event";
2123 case BuiltinType::OCLClkEvent:
2124 Out << "12ocl_clkevent";
2126 case BuiltinType::OCLQueue:
2127 Out << "9ocl_queue";
2129 case BuiltinType::OCLNDRange:
2130 Out << "11ocl_ndrange";
2132 case BuiltinType::OCLReserveID:
2133 Out << "13ocl_reserveid";
2138 // <type> ::= <function-type>
2139 // <function-type> ::= [<CV-qualifiers>] F [Y]
2140 // <bare-function-type> [<ref-qualifier>] E
2141 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2142 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2143 // e.g. "const" in "int (A::*)() const".
2144 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2148 // FIXME: We don't have enough information in the AST to produce the 'Y'
2149 // encoding for extern "C" function types.
2150 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2152 // Mangle the ref-qualifier, if present.
2153 mangleRefQualifier(T->getRefQualifier());
2158 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2159 // Function types without prototypes can arise when mangling a function type
2160 // within an overloadable function in C. We mangle these as the absence of any
2161 // parameter types (not even an empty parameter list).
2164 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2166 FunctionTypeDepth.enterResultType();
2167 mangleType(T->getReturnType());
2168 FunctionTypeDepth.leaveResultType();
2170 FunctionTypeDepth.pop(saved);
2174 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2175 bool MangleReturnType,
2176 const FunctionDecl *FD) {
2177 // We should never be mangling something without a prototype.
2178 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2180 // Record that we're in a function type. See mangleFunctionParam
2181 // for details on what we're trying to achieve here.
2182 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2184 // <bare-function-type> ::= <signature type>+
2185 if (MangleReturnType) {
2186 FunctionTypeDepth.enterResultType();
2187 mangleType(Proto->getReturnType());
2188 FunctionTypeDepth.leaveResultType();
2191 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2192 // <builtin-type> ::= v # void
2195 FunctionTypeDepth.pop(saved);
2199 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2200 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2201 const auto &ParamTy = Proto->getParamType(I);
2202 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2205 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2206 // Attr can only take 1 character, so we can hardcode the length below.
2207 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2208 Out << "U17pass_object_size" << Attr->getType();
2213 FunctionTypeDepth.pop(saved);
2215 // <builtin-type> ::= z # ellipsis
2216 if (Proto->isVariadic())
2220 // <type> ::= <class-enum-type>
2221 // <class-enum-type> ::= <name>
2222 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2223 mangleName(T->getDecl());
2226 // <type> ::= <class-enum-type>
2227 // <class-enum-type> ::= <name>
2228 void CXXNameMangler::mangleType(const EnumType *T) {
2229 mangleType(static_cast<const TagType*>(T));
2231 void CXXNameMangler::mangleType(const RecordType *T) {
2232 mangleType(static_cast<const TagType*>(T));
2234 void CXXNameMangler::mangleType(const TagType *T) {
2235 mangleName(T->getDecl());
2238 // <type> ::= <array-type>
2239 // <array-type> ::= A <positive dimension number> _ <element type>
2240 // ::= A [<dimension expression>] _ <element type>
2241 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2242 Out << 'A' << T->getSize() << '_';
2243 mangleType(T->getElementType());
2245 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2247 // decayed vla types (size 0) will just be skipped.
2248 if (T->getSizeExpr())
2249 mangleExpression(T->getSizeExpr());
2251 mangleType(T->getElementType());
2253 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2255 mangleExpression(T->getSizeExpr());
2257 mangleType(T->getElementType());
2259 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2261 mangleType(T->getElementType());
2264 // <type> ::= <pointer-to-member-type>
2265 // <pointer-to-member-type> ::= M <class type> <member type>
2266 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2268 mangleType(QualType(T->getClass(), 0));
2269 QualType PointeeType = T->getPointeeType();
2270 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2273 // Itanium C++ ABI 5.1.8:
2275 // The type of a non-static member function is considered to be different,
2276 // for the purposes of substitution, from the type of a namespace-scope or
2277 // static member function whose type appears similar. The types of two
2278 // non-static member functions are considered to be different, for the
2279 // purposes of substitution, if the functions are members of different
2280 // classes. In other words, for the purposes of substitution, the class of
2281 // which the function is a member is considered part of the type of
2284 // Given that we already substitute member function pointers as a
2285 // whole, the net effect of this rule is just to unconditionally
2286 // suppress substitution on the function type in a member pointer.
2287 // We increment the SeqID here to emulate adding an entry to the
2288 // substitution table.
2291 mangleType(PointeeType);
2294 // <type> ::= <template-param>
2295 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2296 mangleTemplateParameter(T->getIndex());
2299 // <type> ::= <template-param>
2300 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2301 // FIXME: not clear how to mangle this!
2302 // template <class T...> class A {
2303 // template <class U...> void foo(T(*)(U) x...);
2305 Out << "_SUBSTPACK_";
2308 // <type> ::= P <type> # pointer-to
2309 void CXXNameMangler::mangleType(const PointerType *T) {
2311 mangleType(T->getPointeeType());
2313 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2315 mangleType(T->getPointeeType());
2318 // <type> ::= R <type> # reference-to
2319 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2321 mangleType(T->getPointeeType());
2324 // <type> ::= O <type> # rvalue reference-to (C++0x)
2325 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2327 mangleType(T->getPointeeType());
2330 // <type> ::= C <type> # complex pair (C 2000)
2331 void CXXNameMangler::mangleType(const ComplexType *T) {
2333 mangleType(T->getElementType());
2336 // ARM's ABI for Neon vector types specifies that they should be mangled as
2337 // if they are structs (to match ARM's initial implementation). The
2338 // vector type must be one of the special types predefined by ARM.
2339 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2340 QualType EltType = T->getElementType();
2341 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2342 const char *EltName = nullptr;
2343 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2344 switch (cast<BuiltinType>(EltType)->getKind()) {
2345 case BuiltinType::SChar:
2346 case BuiltinType::UChar:
2347 EltName = "poly8_t";
2349 case BuiltinType::Short:
2350 case BuiltinType::UShort:
2351 EltName = "poly16_t";
2353 case BuiltinType::ULongLong:
2354 EltName = "poly64_t";
2356 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2359 switch (cast<BuiltinType>(EltType)->getKind()) {
2360 case BuiltinType::SChar: EltName = "int8_t"; break;
2361 case BuiltinType::UChar: EltName = "uint8_t"; break;
2362 case BuiltinType::Short: EltName = "int16_t"; break;
2363 case BuiltinType::UShort: EltName = "uint16_t"; break;
2364 case BuiltinType::Int: EltName = "int32_t"; break;
2365 case BuiltinType::UInt: EltName = "uint32_t"; break;
2366 case BuiltinType::LongLong: EltName = "int64_t"; break;
2367 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2368 case BuiltinType::Double: EltName = "float64_t"; break;
2369 case BuiltinType::Float: EltName = "float32_t"; break;
2370 case BuiltinType::Half: EltName = "float16_t";break;
2372 llvm_unreachable("unexpected Neon vector element type");
2375 const char *BaseName = nullptr;
2376 unsigned BitSize = (T->getNumElements() *
2377 getASTContext().getTypeSize(EltType));
2379 BaseName = "__simd64_";
2381 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2382 BaseName = "__simd128_";
2384 Out << strlen(BaseName) + strlen(EltName);
2385 Out << BaseName << EltName;
2388 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2389 switch (EltType->getKind()) {
2390 case BuiltinType::SChar:
2392 case BuiltinType::Short:
2394 case BuiltinType::Int:
2396 case BuiltinType::Long:
2397 case BuiltinType::LongLong:
2399 case BuiltinType::UChar:
2401 case BuiltinType::UShort:
2403 case BuiltinType::UInt:
2405 case BuiltinType::ULong:
2406 case BuiltinType::ULongLong:
2408 case BuiltinType::Half:
2410 case BuiltinType::Float:
2412 case BuiltinType::Double:
2415 llvm_unreachable("Unexpected vector element base type");
2419 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2420 // the equivalent internal name. The vector type must be one of the special
2421 // types predefined by ARM.
2422 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2423 QualType EltType = T->getElementType();
2424 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2426 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2427 (void)BitSize; // Silence warning.
2429 assert((BitSize == 64 || BitSize == 128) &&
2430 "Neon vector type not 64 or 128 bits");
2433 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2434 switch (cast<BuiltinType>(EltType)->getKind()) {
2435 case BuiltinType::UChar:
2438 case BuiltinType::UShort:
2441 case BuiltinType::ULong:
2442 case BuiltinType::ULongLong:
2446 llvm_unreachable("unexpected Neon polynomial vector element type");
2449 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2451 std::string TypeName =
2452 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2453 Out << TypeName.length() << TypeName;
2456 // GNU extension: vector types
2457 // <type> ::= <vector-type>
2458 // <vector-type> ::= Dv <positive dimension number> _
2459 // <extended element type>
2460 // ::= Dv [<dimension expression>] _ <element type>
2461 // <extended element type> ::= <element type>
2462 // ::= p # AltiVec vector pixel
2463 // ::= b # Altivec vector bool
2464 void CXXNameMangler::mangleType(const VectorType *T) {
2465 if ((T->getVectorKind() == VectorType::NeonVector ||
2466 T->getVectorKind() == VectorType::NeonPolyVector)) {
2467 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2468 llvm::Triple::ArchType Arch =
2469 getASTContext().getTargetInfo().getTriple().getArch();
2470 if ((Arch == llvm::Triple::aarch64 ||
2471 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2472 mangleAArch64NeonVectorType(T);
2474 mangleNeonVectorType(T);
2477 Out << "Dv" << T->getNumElements() << '_';
2478 if (T->getVectorKind() == VectorType::AltiVecPixel)
2480 else if (T->getVectorKind() == VectorType::AltiVecBool)
2483 mangleType(T->getElementType());
2485 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2486 mangleType(static_cast<const VectorType*>(T));
2488 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2490 mangleExpression(T->getSizeExpr());
2492 mangleType(T->getElementType());
2495 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2496 // <type> ::= Dp <type> # pack expansion (C++0x)
2498 mangleType(T->getPattern());
2501 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2502 mangleSourceName(T->getDecl()->getIdentifier());
2505 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2506 // Treat __kindof as a vendor extended type qualifier.
2507 if (T->isKindOfType())
2508 Out << "U8__kindof";
2510 if (!T->qual_empty()) {
2511 // Mangle protocol qualifiers.
2512 SmallString<64> QualStr;
2513 llvm::raw_svector_ostream QualOS(QualStr);
2514 QualOS << "objcproto";
2515 for (const auto *I : T->quals()) {
2516 StringRef name = I->getName();
2517 QualOS << name.size() << name;
2519 Out << 'U' << QualStr.size() << QualStr;
2522 mangleType(T->getBaseType());
2524 if (T->isSpecialized()) {
2525 // Mangle type arguments as I <type>+ E
2527 for (auto typeArg : T->getTypeArgs())
2528 mangleType(typeArg);
2533 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2534 Out << "U13block_pointer";
2535 mangleType(T->getPointeeType());
2538 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2539 // Mangle injected class name types as if the user had written the
2540 // specialization out fully. It may not actually be possible to see
2541 // this mangling, though.
2542 mangleType(T->getInjectedSpecializationType());
2545 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2546 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2547 mangleName(TD, T->getArgs(), T->getNumArgs());
2549 if (mangleSubstitution(QualType(T, 0)))
2552 mangleTemplatePrefix(T->getTemplateName());
2554 // FIXME: GCC does not appear to mangle the template arguments when
2555 // the template in question is a dependent template name. Should we
2556 // emulate that badness?
2557 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2558 addSubstitution(QualType(T, 0));
2562 void CXXNameMangler::mangleType(const DependentNameType *T) {
2563 // Proposal by cxx-abi-dev, 2014-03-26
2564 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2565 // # dependent elaborated type specifier using
2567 // ::= Ts <name> # dependent elaborated type specifier using
2568 // # 'struct' or 'class'
2569 // ::= Tu <name> # dependent elaborated type specifier using
2571 // ::= Te <name> # dependent elaborated type specifier using
2573 switch (T->getKeyword()) {
2588 llvm_unreachable("unexpected keyword for dependent type name");
2590 // Typename types are always nested
2592 manglePrefix(T->getQualifier());
2593 mangleSourceName(T->getIdentifier());
2597 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2598 // Dependently-scoped template types are nested if they have a prefix.
2601 // TODO: avoid making this TemplateName.
2602 TemplateName Prefix =
2603 getASTContext().getDependentTemplateName(T->getQualifier(),
2604 T->getIdentifier());
2605 mangleTemplatePrefix(Prefix);
2607 // FIXME: GCC does not appear to mangle the template arguments when
2608 // the template in question is a dependent template name. Should we
2609 // emulate that badness?
2610 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2614 void CXXNameMangler::mangleType(const TypeOfType *T) {
2615 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2616 // "extension with parameters" mangling.
2620 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2621 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2622 // "extension with parameters" mangling.
2626 void CXXNameMangler::mangleType(const DecltypeType *T) {
2627 Expr *E = T->getUnderlyingExpr();
2629 // type ::= Dt <expression> E # decltype of an id-expression
2630 // # or class member access
2631 // ::= DT <expression> E # decltype of an expression
2633 // This purports to be an exhaustive list of id-expressions and
2634 // class member accesses. Note that we do not ignore parentheses;
2635 // parentheses change the semantics of decltype for these
2636 // expressions (and cause the mangler to use the other form).
2637 if (isa<DeclRefExpr>(E) ||
2638 isa<MemberExpr>(E) ||
2639 isa<UnresolvedLookupExpr>(E) ||
2640 isa<DependentScopeDeclRefExpr>(E) ||
2641 isa<CXXDependentScopeMemberExpr>(E) ||
2642 isa<UnresolvedMemberExpr>(E))
2646 mangleExpression(E);
2650 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2651 // If this is dependent, we need to record that. If not, we simply
2652 // mangle it as the underlying type since they are equivalent.
2653 if (T->isDependentType()) {
2656 switch (T->getUTTKind()) {
2657 case UnaryTransformType::EnumUnderlyingType:
2663 mangleType(T->getUnderlyingType());
2666 void CXXNameMangler::mangleType(const AutoType *T) {
2667 QualType D = T->getDeducedType();
2668 // <builtin-type> ::= Da # dependent auto
2670 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2671 "shouldn't need to mangle __auto_type!");
2672 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2677 void CXXNameMangler::mangleType(const AtomicType *T) {
2678 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2679 // (Until there's a standardized mangling...)
2681 mangleType(T->getValueType());
2684 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2685 const llvm::APSInt &Value) {
2686 // <expr-primary> ::= L <type> <value number> E # integer literal
2690 if (T->isBooleanType()) {
2691 // Boolean values are encoded as 0/1.
2692 Out << (Value.getBoolValue() ? '1' : '0');
2694 mangleNumber(Value);
2700 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2701 // Ignore member expressions involving anonymous unions.
2702 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2703 if (!RT->getDecl()->isAnonymousStructOrUnion())
2705 const auto *ME = dyn_cast<MemberExpr>(Base);
2708 Base = ME->getBase();
2709 IsArrow = ME->isArrow();
2712 if (Base->isImplicitCXXThis()) {
2713 // Note: GCC mangles member expressions to the implicit 'this' as
2714 // *this., whereas we represent them as this->. The Itanium C++ ABI
2715 // does not specify anything here, so we follow GCC.
2718 Out << (IsArrow ? "pt" : "dt");
2719 mangleExpression(Base);
2723 /// Mangles a member expression.
2724 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2726 NestedNameSpecifier *qualifier,
2727 NamedDecl *firstQualifierLookup,
2728 DeclarationName member,
2730 // <expression> ::= dt <expression> <unresolved-name>
2731 // ::= pt <expression> <unresolved-name>
2733 mangleMemberExprBase(base, isArrow);
2734 mangleUnresolvedName(qualifier, member, arity);
2737 /// Look at the callee of the given call expression and determine if
2738 /// it's a parenthesized id-expression which would have triggered ADL
2740 static bool isParenthesizedADLCallee(const CallExpr *call) {
2741 const Expr *callee = call->getCallee();
2742 const Expr *fn = callee->IgnoreParens();
2744 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2745 // too, but for those to appear in the callee, it would have to be
2747 if (callee == fn) return false;
2749 // Must be an unresolved lookup.
2750 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2751 if (!lookup) return false;
2753 assert(!lookup->requiresADL());
2755 // Must be an unqualified lookup.
2756 if (lookup->getQualifier()) return false;
2758 // Must not have found a class member. Note that if one is a class
2759 // member, they're all class members.
2760 if (lookup->getNumDecls() > 0 &&
2761 (*lookup->decls_begin())->isCXXClassMember())
2764 // Otherwise, ADL would have been triggered.
2768 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2769 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2770 Out << CastEncoding;
2771 mangleType(ECE->getType());
2772 mangleExpression(ECE->getSubExpr());
2775 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2776 if (auto *Syntactic = InitList->getSyntacticForm())
2777 InitList = Syntactic;
2778 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2779 mangleExpression(InitList->getInit(i));
2782 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2783 // <expression> ::= <unary operator-name> <expression>
2784 // ::= <binary operator-name> <expression> <expression>
2785 // ::= <trinary operator-name> <expression> <expression> <expression>
2786 // ::= cv <type> expression # conversion with one argument
2787 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2788 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2789 // ::= sc <type> <expression> # static_cast<type> (expression)
2790 // ::= cc <type> <expression> # const_cast<type> (expression)
2791 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
2792 // ::= st <type> # sizeof (a type)
2793 // ::= at <type> # alignof (a type)
2794 // ::= <template-param>
2795 // ::= <function-param>
2796 // ::= sr <type> <unqualified-name> # dependent name
2797 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2798 // ::= ds <expression> <expression> # expr.*expr
2799 // ::= sZ <template-param> # size of a parameter pack
2800 // ::= sZ <function-param> # size of a function parameter pack
2801 // ::= <expr-primary>
2802 // <expr-primary> ::= L <type> <value number> E # integer literal
2803 // ::= L <type <value float> E # floating literal
2804 // ::= L <mangled-name> E # external name
2805 // ::= fpT # 'this' expression
2806 QualType ImplicitlyConvertedToType;
2809 switch (E->getStmtClass()) {
2810 case Expr::NoStmtClass:
2811 #define ABSTRACT_STMT(Type)
2812 #define EXPR(Type, Base)
2813 #define STMT(Type, Base) \
2814 case Expr::Type##Class:
2815 #include "clang/AST/StmtNodes.inc"
2818 // These all can only appear in local or variable-initialization
2819 // contexts and so should never appear in a mangling.
2820 case Expr::AddrLabelExprClass:
2821 case Expr::DesignatedInitUpdateExprClass:
2822 case Expr::ImplicitValueInitExprClass:
2823 case Expr::NoInitExprClass:
2824 case Expr::ParenListExprClass:
2825 case Expr::LambdaExprClass:
2826 case Expr::MSPropertyRefExprClass:
2827 case Expr::MSPropertySubscriptExprClass:
2828 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
2829 case Expr::OMPArraySectionExprClass:
2830 llvm_unreachable("unexpected statement kind");
2832 // FIXME: invent manglings for all these.
2833 case Expr::BlockExprClass:
2834 case Expr::ChooseExprClass:
2835 case Expr::CompoundLiteralExprClass:
2836 case Expr::DesignatedInitExprClass:
2837 case Expr::ExtVectorElementExprClass:
2838 case Expr::GenericSelectionExprClass:
2839 case Expr::ObjCEncodeExprClass:
2840 case Expr::ObjCIsaExprClass:
2841 case Expr::ObjCIvarRefExprClass:
2842 case Expr::ObjCMessageExprClass:
2843 case Expr::ObjCPropertyRefExprClass:
2844 case Expr::ObjCProtocolExprClass:
2845 case Expr::ObjCSelectorExprClass:
2846 case Expr::ObjCStringLiteralClass:
2847 case Expr::ObjCBoxedExprClass:
2848 case Expr::ObjCArrayLiteralClass:
2849 case Expr::ObjCDictionaryLiteralClass:
2850 case Expr::ObjCSubscriptRefExprClass:
2851 case Expr::ObjCIndirectCopyRestoreExprClass:
2852 case Expr::OffsetOfExprClass:
2853 case Expr::PredefinedExprClass:
2854 case Expr::ShuffleVectorExprClass:
2855 case Expr::ConvertVectorExprClass:
2856 case Expr::StmtExprClass:
2857 case Expr::TypeTraitExprClass:
2858 case Expr::ArrayTypeTraitExprClass:
2859 case Expr::ExpressionTraitExprClass:
2860 case Expr::VAArgExprClass:
2861 case Expr::CUDAKernelCallExprClass:
2862 case Expr::AsTypeExprClass:
2863 case Expr::PseudoObjectExprClass:
2864 case Expr::AtomicExprClass:
2866 // As bad as this diagnostic is, it's better than crashing.
2867 DiagnosticsEngine &Diags = Context.getDiags();
2868 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2869 "cannot yet mangle expression type %0");
2870 Diags.Report(E->getExprLoc(), DiagID)
2871 << E->getStmtClassName() << E->getSourceRange();
2875 case Expr::CXXUuidofExprClass: {
2876 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2877 if (UE->isTypeOperand()) {
2878 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2879 Out << "u8__uuidoft";
2882 Expr *UuidExp = UE->getExprOperand();
2883 Out << "u8__uuidofz";
2884 mangleExpression(UuidExp, Arity);
2889 // Even gcc-4.5 doesn't mangle this.
2890 case Expr::BinaryConditionalOperatorClass: {
2891 DiagnosticsEngine &Diags = Context.getDiags();
2893 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2894 "?: operator with omitted middle operand cannot be mangled");
2895 Diags.Report(E->getExprLoc(), DiagID)
2896 << E->getStmtClassName() << E->getSourceRange();
2900 // These are used for internal purposes and cannot be meaningfully mangled.
2901 case Expr::OpaqueValueExprClass:
2902 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2904 case Expr::InitListExprClass: {
2906 mangleInitListElements(cast<InitListExpr>(E));
2911 case Expr::CXXDefaultArgExprClass:
2912 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2915 case Expr::CXXDefaultInitExprClass:
2916 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2919 case Expr::CXXStdInitializerListExprClass:
2920 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2923 case Expr::SubstNonTypeTemplateParmExprClass:
2924 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2928 case Expr::UserDefinedLiteralClass:
2929 // We follow g++'s approach of mangling a UDL as a call to the literal
2931 case Expr::CXXMemberCallExprClass: // fallthrough
2932 case Expr::CallExprClass: {
2933 const CallExpr *CE = cast<CallExpr>(E);
2935 // <expression> ::= cp <simple-id> <expression>* E
2936 // We use this mangling only when the call would use ADL except
2937 // for being parenthesized. Per discussion with David
2938 // Vandervoorde, 2011.04.25.
2939 if (isParenthesizedADLCallee(CE)) {
2941 // The callee here is a parenthesized UnresolvedLookupExpr with
2942 // no qualifier and should always get mangled as a <simple-id>
2945 // <expression> ::= cl <expression>* E
2950 unsigned CallArity = CE->getNumArgs();
2951 for (const Expr *Arg : CE->arguments())
2952 if (isa<PackExpansionExpr>(Arg))
2953 CallArity = UnknownArity;
2955 mangleExpression(CE->getCallee(), CallArity);
2956 for (const Expr *Arg : CE->arguments())
2957 mangleExpression(Arg);
2962 case Expr::CXXNewExprClass: {
2963 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2964 if (New->isGlobalNew()) Out << "gs";
2965 Out << (New->isArray() ? "na" : "nw");
2966 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2967 E = New->placement_arg_end(); I != E; ++I)
2968 mangleExpression(*I);
2970 mangleType(New->getAllocatedType());
2971 if (New->hasInitializer()) {
2972 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2976 const Expr *Init = New->getInitializer();
2977 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2978 // Directly inline the initializers.
2979 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2982 mangleExpression(*I);
2983 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2984 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2985 mangleExpression(PLE->getExpr(i));
2986 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2987 isa<InitListExpr>(Init)) {
2988 // Only take InitListExprs apart for list-initialization.
2989 mangleInitListElements(cast<InitListExpr>(Init));
2991 mangleExpression(Init);
2997 case Expr::CXXPseudoDestructorExprClass: {
2998 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2999 if (const Expr *Base = PDE->getBase())
3000 mangleMemberExprBase(Base, PDE->isArrow());
3001 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3003 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3005 mangleUnresolvedPrefix(Qualifier,
3006 /*Recursive=*/true);
3007 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3011 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3014 } else if (Qualifier) {
3015 mangleUnresolvedPrefix(Qualifier);
3017 // <base-unresolved-name> ::= dn <destructor-name>
3019 QualType DestroyedType = PDE->getDestroyedType();
3020 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3024 case Expr::MemberExprClass: {
3025 const MemberExpr *ME = cast<MemberExpr>(E);
3026 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3027 ME->getQualifier(), nullptr,
3028 ME->getMemberDecl()->getDeclName(), Arity);
3032 case Expr::UnresolvedMemberExprClass: {
3033 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3034 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3035 ME->isArrow(), ME->getQualifier(), nullptr,
3036 ME->getMemberName(), Arity);
3037 if (ME->hasExplicitTemplateArgs())
3038 mangleTemplateArgs(ME->getExplicitTemplateArgs());
3042 case Expr::CXXDependentScopeMemberExprClass: {
3043 const CXXDependentScopeMemberExpr *ME
3044 = cast<CXXDependentScopeMemberExpr>(E);
3045 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3046 ME->isArrow(), ME->getQualifier(),
3047 ME->getFirstQualifierFoundInScope(),
3048 ME->getMember(), Arity);
3049 if (ME->hasExplicitTemplateArgs())
3050 mangleTemplateArgs(ME->getExplicitTemplateArgs());
3054 case Expr::UnresolvedLookupExprClass: {
3055 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3056 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3058 // All the <unresolved-name> productions end in a
3059 // base-unresolved-name, where <template-args> are just tacked
3061 if (ULE->hasExplicitTemplateArgs())
3062 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
3066 case Expr::CXXUnresolvedConstructExprClass: {
3067 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3068 unsigned N = CE->arg_size();
3071 mangleType(CE->getType());
3072 if (N != 1) Out << '_';
3073 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3074 if (N != 1) Out << 'E';
3078 case Expr::CXXConstructExprClass: {
3079 const auto *CE = cast<CXXConstructExpr>(E);
3080 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3082 CE->getNumArgs() >= 1 &&
3083 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3084 "implicit CXXConstructExpr must have one argument");
3085 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3088 for (auto *E : CE->arguments())
3089 mangleExpression(E);
3094 case Expr::CXXTemporaryObjectExprClass: {
3095 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3096 unsigned N = CE->getNumArgs();
3097 bool List = CE->isListInitialization();
3103 mangleType(CE->getType());
3104 if (!List && N != 1)
3106 if (CE->isStdInitListInitialization()) {
3107 // We implicitly created a std::initializer_list<T> for the first argument
3108 // of a constructor of type U in an expression of the form U{a, b, c}.
3109 // Strip all the semantic gunk off the initializer list.
3111 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3112 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3113 mangleInitListElements(ILE);
3115 for (auto *E : CE->arguments())
3116 mangleExpression(E);
3123 case Expr::CXXScalarValueInitExprClass:
3125 mangleType(E->getType());
3129 case Expr::CXXNoexceptExprClass:
3131 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3134 case Expr::UnaryExprOrTypeTraitExprClass: {
3135 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3137 if (!SAE->isInstantiationDependent()) {
3139 // If the operand of a sizeof or alignof operator is not
3140 // instantiation-dependent it is encoded as an integer literal
3141 // reflecting the result of the operator.
3143 // If the result of the operator is implicitly converted to a known
3144 // integer type, that type is used for the literal; otherwise, the type
3145 // of std::size_t or std::ptrdiff_t is used.
3146 QualType T = (ImplicitlyConvertedToType.isNull() ||
3147 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3148 : ImplicitlyConvertedToType;
3149 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3150 mangleIntegerLiteral(T, V);
3154 switch(SAE->getKind()) {
3161 case UETT_VecStep: {
3162 DiagnosticsEngine &Diags = Context.getDiags();
3163 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3164 "cannot yet mangle vec_step expression");
3165 Diags.Report(DiagID);
3168 case UETT_OpenMPRequiredSimdAlign:
3169 DiagnosticsEngine &Diags = Context.getDiags();
3170 unsigned DiagID = Diags.getCustomDiagID(
3171 DiagnosticsEngine::Error,
3172 "cannot yet mangle __builtin_omp_required_simd_align expression");
3173 Diags.Report(DiagID);
3176 if (SAE->isArgumentType()) {
3178 mangleType(SAE->getArgumentType());
3181 mangleExpression(SAE->getArgumentExpr());
3186 case Expr::CXXThrowExprClass: {
3187 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3188 // <expression> ::= tw <expression> # throw expression
3190 if (TE->getSubExpr()) {
3192 mangleExpression(TE->getSubExpr());
3199 case Expr::CXXTypeidExprClass: {
3200 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3201 // <expression> ::= ti <type> # typeid (type)
3202 // ::= te <expression> # typeid (expression)
3203 if (TIE->isTypeOperand()) {
3205 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3208 mangleExpression(TIE->getExprOperand());
3213 case Expr::CXXDeleteExprClass: {
3214 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3215 // <expression> ::= [gs] dl <expression> # [::] delete expr
3216 // ::= [gs] da <expression> # [::] delete [] expr
3217 if (DE->isGlobalDelete()) Out << "gs";
3218 Out << (DE->isArrayForm() ? "da" : "dl");
3219 mangleExpression(DE->getArgument());
3223 case Expr::UnaryOperatorClass: {
3224 const UnaryOperator *UO = cast<UnaryOperator>(E);
3225 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3227 mangleExpression(UO->getSubExpr());
3231 case Expr::ArraySubscriptExprClass: {
3232 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3234 // Array subscript is treated as a syntactically weird form of
3237 mangleExpression(AE->getLHS());
3238 mangleExpression(AE->getRHS());
3242 case Expr::CompoundAssignOperatorClass: // fallthrough
3243 case Expr::BinaryOperatorClass: {
3244 const BinaryOperator *BO = cast<BinaryOperator>(E);
3245 if (BO->getOpcode() == BO_PtrMemD)
3248 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3250 mangleExpression(BO->getLHS());
3251 mangleExpression(BO->getRHS());
3255 case Expr::ConditionalOperatorClass: {
3256 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3257 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3258 mangleExpression(CO->getCond());
3259 mangleExpression(CO->getLHS(), Arity);
3260 mangleExpression(CO->getRHS(), Arity);
3264 case Expr::ImplicitCastExprClass: {
3265 ImplicitlyConvertedToType = E->getType();
3266 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3270 case Expr::ObjCBridgedCastExprClass: {
3271 // Mangle ownership casts as a vendor extended operator __bridge,
3272 // __bridge_transfer, or __bridge_retain.
3273 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3274 Out << "v1U" << Kind.size() << Kind;
3276 // Fall through to mangle the cast itself.
3278 case Expr::CStyleCastExprClass:
3279 mangleCastExpression(E, "cv");
3282 case Expr::CXXFunctionalCastExprClass: {
3283 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3284 // FIXME: Add isImplicit to CXXConstructExpr.
3285 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3286 if (CCE->getParenOrBraceRange().isInvalid())
3287 Sub = CCE->getArg(0)->IgnoreImplicit();
3288 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3289 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3290 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3292 mangleType(E->getType());
3293 mangleInitListElements(IL);
3296 mangleCastExpression(E, "cv");
3301 case Expr::CXXStaticCastExprClass:
3302 mangleCastExpression(E, "sc");
3304 case Expr::CXXDynamicCastExprClass:
3305 mangleCastExpression(E, "dc");
3307 case Expr::CXXReinterpretCastExprClass:
3308 mangleCastExpression(E, "rc");
3310 case Expr::CXXConstCastExprClass:
3311 mangleCastExpression(E, "cc");
3314 case Expr::CXXOperatorCallExprClass: {
3315 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3316 unsigned NumArgs = CE->getNumArgs();
3317 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3318 // Mangle the arguments.
3319 for (unsigned i = 0; i != NumArgs; ++i)
3320 mangleExpression(CE->getArg(i));
3324 case Expr::ParenExprClass:
3325 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3328 case Expr::DeclRefExprClass: {
3329 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3331 switch (D->getKind()) {
3333 // <expr-primary> ::= L <mangled-name> E # external name
3340 mangleFunctionParam(cast<ParmVarDecl>(D));
3343 case Decl::EnumConstant: {
3344 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3345 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3349 case Decl::NonTypeTemplateParm: {
3350 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3351 mangleTemplateParameter(PD->getIndex());
3360 case Expr::SubstNonTypeTemplateParmPackExprClass:
3361 // FIXME: not clear how to mangle this!
3362 // template <unsigned N...> class A {
3363 // template <class U...> void foo(U (&x)[N]...);
3365 Out << "_SUBSTPACK_";
3368 case Expr::FunctionParmPackExprClass: {
3369 // FIXME: not clear how to mangle this!
3370 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3371 Out << "v110_SUBSTPACK";
3372 mangleFunctionParam(FPPE->getParameterPack());
3376 case Expr::DependentScopeDeclRefExprClass: {
3377 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3378 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3380 // All the <unresolved-name> productions end in a
3381 // base-unresolved-name, where <template-args> are just tacked
3383 if (DRE->hasExplicitTemplateArgs())
3384 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3388 case Expr::CXXBindTemporaryExprClass:
3389 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3392 case Expr::ExprWithCleanupsClass:
3393 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3396 case Expr::FloatingLiteralClass: {
3397 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3399 mangleType(FL->getType());
3400 mangleFloat(FL->getValue());
3405 case Expr::CharacterLiteralClass:
3407 mangleType(E->getType());
3408 Out << cast<CharacterLiteral>(E)->getValue();
3412 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3413 case Expr::ObjCBoolLiteralExprClass:
3415 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3419 case Expr::CXXBoolLiteralExprClass:
3421 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3425 case Expr::IntegerLiteralClass: {
3426 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3427 if (E->getType()->isSignedIntegerType())
3428 Value.setIsSigned(true);
3429 mangleIntegerLiteral(E->getType(), Value);
3433 case Expr::ImaginaryLiteralClass: {
3434 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3435 // Mangle as if a complex literal.
3436 // Proposal from David Vandevoorde, 2010.06.30.
3438 mangleType(E->getType());
3439 if (const FloatingLiteral *Imag =
3440 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3441 // Mangle a floating-point zero of the appropriate type.
3442 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3444 mangleFloat(Imag->getValue());
3447 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3448 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3449 Value.setIsSigned(true);
3450 mangleNumber(Value);
3456 case Expr::StringLiteralClass: {
3457 // Revised proposal from David Vandervoorde, 2010.07.15.
3459 assert(isa<ConstantArrayType>(E->getType()));
3460 mangleType(E->getType());
3465 case Expr::GNUNullExprClass:
3466 // FIXME: should this really be mangled the same as nullptr?
3469 case Expr::CXXNullPtrLiteralExprClass: {
3474 case Expr::PackExpansionExprClass:
3476 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3479 case Expr::SizeOfPackExprClass: {
3480 auto *SPE = cast<SizeOfPackExpr>(E);
3481 if (SPE->isPartiallySubstituted()) {
3483 for (const auto &A : SPE->getPartialArguments())
3484 mangleTemplateArg(A);
3490 const NamedDecl *Pack = SPE->getPack();
3491 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3492 mangleTemplateParameter(TTP->getIndex());
3493 else if (const NonTypeTemplateParmDecl *NTTP
3494 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3495 mangleTemplateParameter(NTTP->getIndex());
3496 else if (const TemplateTemplateParmDecl *TempTP
3497 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3498 mangleTemplateParameter(TempTP->getIndex());
3500 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3504 case Expr::MaterializeTemporaryExprClass: {
3505 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3509 case Expr::CXXFoldExprClass: {
3510 auto *FE = cast<CXXFoldExpr>(E);
3511 if (FE->isLeftFold())
3512 Out << (FE->getInit() ? "fL" : "fl");
3514 Out << (FE->getInit() ? "fR" : "fr");
3516 if (FE->getOperator() == BO_PtrMemD)
3520 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3524 mangleExpression(FE->getLHS());
3526 mangleExpression(FE->getRHS());
3530 case Expr::CXXThisExprClass:
3534 case Expr::CoawaitExprClass:
3535 // FIXME: Propose a non-vendor mangling.
3536 Out << "v18co_await";
3537 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3540 case Expr::CoyieldExprClass:
3541 // FIXME: Propose a non-vendor mangling.
3542 Out << "v18co_yield";
3543 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3548 /// Mangle an expression which refers to a parameter variable.
3550 /// <expression> ::= <function-param>
3551 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3552 /// <function-param> ::= fp <top-level CV-qualifiers>
3553 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3554 /// <function-param> ::= fL <L-1 non-negative number>
3555 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3556 /// <function-param> ::= fL <L-1 non-negative number>
3557 /// p <top-level CV-qualifiers>
3558 /// <I-1 non-negative number> _ # L > 0, I > 0
3560 /// L is the nesting depth of the parameter, defined as 1 if the
3561 /// parameter comes from the innermost function prototype scope
3562 /// enclosing the current context, 2 if from the next enclosing
3563 /// function prototype scope, and so on, with one special case: if
3564 /// we've processed the full parameter clause for the innermost
3565 /// function type, then L is one less. This definition conveniently
3566 /// makes it irrelevant whether a function's result type was written
3567 /// trailing or leading, but is otherwise overly complicated; the
3568 /// numbering was first designed without considering references to
3569 /// parameter in locations other than return types, and then the
3570 /// mangling had to be generalized without changing the existing
3573 /// I is the zero-based index of the parameter within its parameter
3574 /// declaration clause. Note that the original ABI document describes
3575 /// this using 1-based ordinals.
3576 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3577 unsigned parmDepth = parm->getFunctionScopeDepth();
3578 unsigned parmIndex = parm->getFunctionScopeIndex();
3581 // parmDepth does not include the declaring function prototype.
3582 // FunctionTypeDepth does account for that.
3583 assert(parmDepth < FunctionTypeDepth.getDepth());
3584 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3585 if (FunctionTypeDepth.isInResultType())
3588 if (nestingDepth == 0) {
3591 Out << "fL" << (nestingDepth - 1) << 'p';
3594 // Top-level qualifiers. We don't have to worry about arrays here,
3595 // because parameters declared as arrays should already have been
3596 // transformed to have pointer type. FIXME: apparently these don't
3597 // get mangled if used as an rvalue of a known non-class type?
3598 assert(!parm->getType()->isArrayType()
3599 && "parameter's type is still an array type?");
3600 mangleQualifiers(parm->getType().getQualifiers());
3603 if (parmIndex != 0) {
3604 Out << (parmIndex - 1);
3609 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3610 // <ctor-dtor-name> ::= C1 # complete object constructor
3611 // ::= C2 # base object constructor
3613 // In addition, C5 is a comdat name with C1 and C2 in it.
3624 case Ctor_DefaultClosure:
3625 case Ctor_CopyingClosure:
3626 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
3630 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3631 // <ctor-dtor-name> ::= D0 # deleting destructor
3632 // ::= D1 # complete object destructor
3633 // ::= D2 # base object destructor
3635 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
3652 void CXXNameMangler::mangleTemplateArgs(
3653 const ASTTemplateArgumentListInfo &TemplateArgs) {
3654 // <template-args> ::= I <template-arg>+ E
3656 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3657 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3661 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3662 // <template-args> ::= I <template-arg>+ E
3664 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3665 mangleTemplateArg(AL[i]);
3669 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3670 unsigned NumTemplateArgs) {
3671 // <template-args> ::= I <template-arg>+ E
3673 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3674 mangleTemplateArg(TemplateArgs[i]);
3678 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3679 // <template-arg> ::= <type> # type or template
3680 // ::= X <expression> E # expression
3681 // ::= <expr-primary> # simple expressions
3682 // ::= J <template-arg>* E # argument pack
3683 if (!A.isInstantiationDependent() || A.isDependent())
3684 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3686 switch (A.getKind()) {
3687 case TemplateArgument::Null:
3688 llvm_unreachable("Cannot mangle NULL template argument");
3690 case TemplateArgument::Type:
3691 mangleType(A.getAsType());
3693 case TemplateArgument::Template:
3694 // This is mangled as <type>.
3695 mangleType(A.getAsTemplate());
3697 case TemplateArgument::TemplateExpansion:
3698 // <type> ::= Dp <type> # pack expansion (C++0x)
3700 mangleType(A.getAsTemplateOrTemplatePattern());
3702 case TemplateArgument::Expression: {
3703 // It's possible to end up with a DeclRefExpr here in certain
3704 // dependent cases, in which case we should mangle as a
3706 const Expr *E = A.getAsExpr()->IgnoreParens();
3707 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3708 const ValueDecl *D = DRE->getDecl();
3709 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3718 mangleExpression(E);
3722 case TemplateArgument::Integral:
3723 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3725 case TemplateArgument::Declaration: {
3726 // <expr-primary> ::= L <mangled-name> E # external name
3727 // Clang produces AST's where pointer-to-member-function expressions
3728 // and pointer-to-function expressions are represented as a declaration not
3729 // an expression. We compensate for it here to produce the correct mangling.
3730 ValueDecl *D = A.getAsDecl();
3731 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
3732 if (compensateMangling) {
3734 mangleOperatorName(OO_Amp, 1);
3738 // References to external entities use the mangled name; if the name would
3739 // not normally be manged then mangle it as unqualified.
3743 if (compensateMangling)
3748 case TemplateArgument::NullPtr: {
3749 // <expr-primary> ::= L <type> 0 E
3751 mangleType(A.getNullPtrType());
3755 case TemplateArgument::Pack: {
3756 // <template-arg> ::= J <template-arg>* E
3758 for (const auto &P : A.pack_elements())
3759 mangleTemplateArg(P);
3765 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3766 // <template-param> ::= T_ # first template parameter
3767 // ::= T <parameter-2 non-negative number> _
3771 Out << 'T' << (Index - 1) << '_';
3774 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3777 else if (SeqID > 1) {
3780 // <seq-id> is encoded in base-36, using digits and upper case letters.
3781 char Buffer[7]; // log(2**32) / log(36) ~= 7
3782 MutableArrayRef<char> BufferRef(Buffer);
3783 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
3785 for (; SeqID != 0; SeqID /= 36) {
3786 unsigned C = SeqID % 36;
3787 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3790 Out.write(I.base(), I - BufferRef.rbegin());
3795 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3796 bool result = mangleSubstitution(type);
3797 assert(result && "no existing substitution for type");
3801 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3802 bool result = mangleSubstitution(tname);
3803 assert(result && "no existing substitution for template name");
3807 // <substitution> ::= S <seq-id> _
3809 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3810 // Try one of the standard substitutions first.
3811 if (mangleStandardSubstitution(ND))
3814 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3815 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3818 /// Determine whether the given type has any qualifiers that are relevant for
3820 static bool hasMangledSubstitutionQualifiers(QualType T) {
3821 Qualifiers Qs = T.getQualifiers();
3822 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3825 bool CXXNameMangler::mangleSubstitution(QualType T) {
3826 if (!hasMangledSubstitutionQualifiers(T)) {
3827 if (const RecordType *RT = T->getAs<RecordType>())
3828 return mangleSubstitution(RT->getDecl());
3831 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3833 return mangleSubstitution(TypePtr);
3836 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3837 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3838 return mangleSubstitution(TD);
3840 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3841 return mangleSubstitution(
3842 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3845 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3846 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3847 if (I == Substitutions.end())
3850 unsigned SeqID = I->second;
3857 static bool isCharType(QualType T) {
3861 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3862 T->isSpecificBuiltinType(BuiltinType::Char_U);
3865 /// Returns whether a given type is a template specialization of a given name
3866 /// with a single argument of type char.
3867 static bool isCharSpecialization(QualType T, const char *Name) {
3871 const RecordType *RT = T->getAs<RecordType>();
3875 const ClassTemplateSpecializationDecl *SD =
3876 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3880 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3883 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3884 if (TemplateArgs.size() != 1)
3887 if (!isCharType(TemplateArgs[0].getAsType()))
3890 return SD->getIdentifier()->getName() == Name;
3893 template <std::size_t StrLen>
3894 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3895 const char (&Str)[StrLen]) {
3896 if (!SD->getIdentifier()->isStr(Str))
3899 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3900 if (TemplateArgs.size() != 2)
3903 if (!isCharType(TemplateArgs[0].getAsType()))
3906 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3912 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3913 // <substitution> ::= St # ::std::
3914 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3921 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3922 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3925 // <substitution> ::= Sa # ::std::allocator
3926 if (TD->getIdentifier()->isStr("allocator")) {
3931 // <<substitution> ::= Sb # ::std::basic_string
3932 if (TD->getIdentifier()->isStr("basic_string")) {
3938 if (const ClassTemplateSpecializationDecl *SD =
3939 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3940 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3943 // <substitution> ::= Ss # ::std::basic_string<char,
3944 // ::std::char_traits<char>,
3945 // ::std::allocator<char> >
3946 if (SD->getIdentifier()->isStr("basic_string")) {
3947 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3949 if (TemplateArgs.size() != 3)
3952 if (!isCharType(TemplateArgs[0].getAsType()))
3955 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3958 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3965 // <substitution> ::= Si # ::std::basic_istream<char,
3966 // ::std::char_traits<char> >
3967 if (isStreamCharSpecialization(SD, "basic_istream")) {
3972 // <substitution> ::= So # ::std::basic_ostream<char,
3973 // ::std::char_traits<char> >
3974 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3979 // <substitution> ::= Sd # ::std::basic_iostream<char,
3980 // ::std::char_traits<char> >
3981 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3989 void CXXNameMangler::addSubstitution(QualType T) {
3990 if (!hasMangledSubstitutionQualifiers(T)) {
3991 if (const RecordType *RT = T->getAs<RecordType>()) {
3992 addSubstitution(RT->getDecl());
3997 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3998 addSubstitution(TypePtr);
4001 void CXXNameMangler::addSubstitution(TemplateName Template) {
4002 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4003 return addSubstitution(TD);
4005 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4006 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4009 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4010 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4011 Substitutions[Ptr] = SeqID++;
4016 /// Mangles the name of the declaration D and emits that name to the given
4019 /// If the declaration D requires a mangled name, this routine will emit that
4020 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4021 /// and this routine will return false. In this case, the caller should just
4022 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4024 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4026 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4027 "Invalid mangleName() call, argument is not a variable or function!");
4028 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4029 "Invalid mangleName() call on 'structor decl!");
4031 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4032 getASTContext().getSourceManager(),
4033 "Mangling declaration");
4035 CXXNameMangler Mangler(*this, Out, D);
4039 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4042 CXXNameMangler Mangler(*this, Out, D, Type);
4046 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4049 CXXNameMangler Mangler(*this, Out, D, Type);
4053 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4055 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4059 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4061 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4065 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4066 const ThunkInfo &Thunk,
4068 // <special-name> ::= T <call-offset> <base encoding>
4069 // # base is the nominal target function of thunk
4070 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4071 // # base is the nominal target function of thunk
4072 // # first call-offset is 'this' adjustment
4073 // # second call-offset is result adjustment
4075 assert(!isa<CXXDestructorDecl>(MD) &&
4076 "Use mangleCXXDtor for destructor decls!");
4077 CXXNameMangler Mangler(*this, Out);
4078 Mangler.getStream() << "_ZT";
4079 if (!Thunk.Return.isEmpty())
4080 Mangler.getStream() << 'c';
4082 // Mangle the 'this' pointer adjustment.
4083 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4084 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4086 // Mangle the return pointer adjustment if there is one.
4087 if (!Thunk.Return.isEmpty())
4088 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4089 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4091 Mangler.mangleFunctionEncoding(MD);
4094 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4095 const CXXDestructorDecl *DD, CXXDtorType Type,
4096 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4097 // <special-name> ::= T <call-offset> <base encoding>
4098 // # base is the nominal target function of thunk
4099 CXXNameMangler Mangler(*this, Out, DD, Type);
4100 Mangler.getStream() << "_ZT";
4102 // Mangle the 'this' pointer adjustment.
4103 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4104 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4106 Mangler.mangleFunctionEncoding(DD);
4109 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4110 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4112 // <special-name> ::= GV <object name> # Guard variable for one-time
4114 CXXNameMangler Mangler(*this, Out);
4115 Mangler.getStream() << "_ZGV";
4116 Mangler.mangleName(D);
4119 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4121 // These symbols are internal in the Itanium ABI, so the names don't matter.
4122 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4123 // avoid duplicate symbols.
4124 Out << "__cxx_global_var_init";
4127 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4129 // Prefix the mangling of D with __dtor_.
4130 CXXNameMangler Mangler(*this, Out);
4131 Mangler.getStream() << "__dtor_";
4132 if (shouldMangleDeclName(D))
4135 Mangler.getStream() << D->getName();
4138 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4139 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4140 CXXNameMangler Mangler(*this, Out);
4141 Mangler.getStream() << "__filt_";
4142 if (shouldMangleDeclName(EnclosingDecl))
4143 Mangler.mangle(EnclosingDecl);
4145 Mangler.getStream() << EnclosingDecl->getName();
4148 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4149 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4150 CXXNameMangler Mangler(*this, Out);
4151 Mangler.getStream() << "__fin_";
4152 if (shouldMangleDeclName(EnclosingDecl))
4153 Mangler.mangle(EnclosingDecl);
4155 Mangler.getStream() << EnclosingDecl->getName();
4158 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4160 // <special-name> ::= TH <object name>
4161 CXXNameMangler Mangler(*this, Out);
4162 Mangler.getStream() << "_ZTH";
4163 Mangler.mangleName(D);
4167 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4169 // <special-name> ::= TW <object name>
4170 CXXNameMangler Mangler(*this, Out);
4171 Mangler.getStream() << "_ZTW";
4172 Mangler.mangleName(D);
4175 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4176 unsigned ManglingNumber,
4178 // We match the GCC mangling here.
4179 // <special-name> ::= GR <object name>
4180 CXXNameMangler Mangler(*this, Out);
4181 Mangler.getStream() << "_ZGR";
4182 Mangler.mangleName(D);
4183 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4184 Mangler.mangleSeqID(ManglingNumber - 1);
4187 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4189 // <special-name> ::= TV <type> # virtual table
4190 CXXNameMangler Mangler(*this, Out);
4191 Mangler.getStream() << "_ZTV";
4192 Mangler.mangleNameOrStandardSubstitution(RD);
4195 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4197 // <special-name> ::= TT <type> # VTT structure
4198 CXXNameMangler Mangler(*this, Out);
4199 Mangler.getStream() << "_ZTT";
4200 Mangler.mangleNameOrStandardSubstitution(RD);
4203 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4205 const CXXRecordDecl *Type,
4207 // <special-name> ::= TC <type> <offset number> _ <base type>
4208 CXXNameMangler Mangler(*this, Out);
4209 Mangler.getStream() << "_ZTC";
4210 Mangler.mangleNameOrStandardSubstitution(RD);
4211 Mangler.getStream() << Offset;
4212 Mangler.getStream() << '_';
4213 Mangler.mangleNameOrStandardSubstitution(Type);
4216 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4217 // <special-name> ::= TI <type> # typeinfo structure
4218 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4219 CXXNameMangler Mangler(*this, Out);
4220 Mangler.getStream() << "_ZTI";
4221 Mangler.mangleType(Ty);
4224 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4226 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4227 CXXNameMangler Mangler(*this, Out);
4228 Mangler.getStream() << "_ZTS";
4229 Mangler.mangleType(Ty);
4232 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4233 mangleCXXRTTIName(Ty, Out);
4236 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4237 llvm_unreachable("Can't mangle string literals");
4240 ItaniumMangleContext *
4241 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4242 return new ItaniumMangleContextImpl(Context, Diags);