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 /// \brief Retrieve the declaration context that should be used when mangling
46 /// the given declaration.
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
);
75 static const DeclContext
*getEffectiveParentContext(const DeclContext
*DC
) {
76 return getEffectiveDeclContext(cast
<Decl
>(DC
));
79 static bool isLocalContainerContext(const DeclContext
*DC
) {
80 return isa
<FunctionDecl
>(DC
) || isa
<ObjCMethodDecl
>(DC
) || isa
<BlockDecl
>(DC
);
83 static const RecordDecl
*GetLocalClassDecl(const Decl
*D
) {
84 const DeclContext
*DC
= getEffectiveDeclContext(D
);
85 while (!DC
->isNamespace() && !DC
->isTranslationUnit()) {
86 if (isLocalContainerContext(DC
))
87 return dyn_cast
<RecordDecl
>(D
);
89 DC
= getEffectiveDeclContext(D
);
94 static const FunctionDecl
*getStructor(const FunctionDecl
*fn
) {
95 if (const FunctionTemplateDecl
*ftd
= fn
->getPrimaryTemplate())
96 return ftd
->getTemplatedDecl();
101 static const NamedDecl
*getStructor(const NamedDecl
*decl
) {
102 const FunctionDecl
*fn
= dyn_cast_or_null
<FunctionDecl
>(decl
);
103 return (fn
? getStructor(fn
) : decl
);
106 static bool isLambda(const NamedDecl
*ND
) {
107 const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(ND
);
111 return Record
->isLambda();
114 static const unsigned UnknownArity
= ~0U;
116 class ItaniumMangleContextImpl
: public ItaniumMangleContext
{
117 typedef std::pair
<const DeclContext
*, IdentifierInfo
*> DiscriminatorKeyTy
;
118 llvm::DenseMap
<DiscriminatorKeyTy
, unsigned> Discriminator
;
119 llvm::DenseMap
<const NamedDecl
*, unsigned> Uniquifier
;
122 explicit ItaniumMangleContextImpl(ASTContext
&Context
,
123 DiagnosticsEngine
&Diags
)
124 : ItaniumMangleContext(Context
, Diags
) {}
126 /// @name Mangler Entry Points
129 bool shouldMangleCXXName(const NamedDecl
*D
) override
;
130 bool shouldMangleStringLiteral(const StringLiteral
*) override
{
133 void mangleCXXName(const NamedDecl
*D
, raw_ostream
&) override
;
134 void mangleThunk(const CXXMethodDecl
*MD
, const ThunkInfo
&Thunk
,
135 raw_ostream
&) override
;
136 void mangleCXXDtorThunk(const CXXDestructorDecl
*DD
, CXXDtorType Type
,
137 const ThisAdjustment
&ThisAdjustment
,
138 raw_ostream
&) override
;
139 void mangleReferenceTemporary(const VarDecl
*D
, unsigned ManglingNumber
,
140 raw_ostream
&) override
;
141 void mangleCXXVTable(const CXXRecordDecl
*RD
, raw_ostream
&) override
;
142 void mangleCXXVTT(const CXXRecordDecl
*RD
, raw_ostream
&) override
;
143 void mangleCXXCtorVTable(const CXXRecordDecl
*RD
, int64_t Offset
,
144 const CXXRecordDecl
*Type
, raw_ostream
&) override
;
145 void mangleCXXRTTI(QualType T
, raw_ostream
&) override
;
146 void mangleCXXRTTIName(QualType T
, raw_ostream
&) override
;
147 void mangleTypeName(QualType T
, raw_ostream
&) override
;
148 void mangleCXXCtor(const CXXConstructorDecl
*D
, CXXCtorType Type
,
149 raw_ostream
&) override
;
150 void mangleCXXDtor(const CXXDestructorDecl
*D
, CXXDtorType Type
,
151 raw_ostream
&) override
;
153 void mangleCXXCtorComdat(const CXXConstructorDecl
*D
, raw_ostream
&) override
;
154 void mangleCXXDtorComdat(const CXXDestructorDecl
*D
, raw_ostream
&) override
;
155 void mangleStaticGuardVariable(const VarDecl
*D
, raw_ostream
&) override
;
156 void mangleDynamicInitializer(const VarDecl
*D
, raw_ostream
&Out
) override
;
157 void mangleDynamicAtExitDestructor(const VarDecl
*D
,
158 raw_ostream
&Out
) override
;
159 void mangleItaniumThreadLocalInit(const VarDecl
*D
, raw_ostream
&) override
;
160 void mangleItaniumThreadLocalWrapper(const VarDecl
*D
,
161 raw_ostream
&) override
;
163 void mangleStringLiteral(const StringLiteral
*, raw_ostream
&) override
;
165 bool getNextDiscriminator(const NamedDecl
*ND
, unsigned &disc
) {
166 // Lambda closure types are already numbered.
170 // Anonymous tags are already numbered.
171 if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(ND
)) {
172 if (Tag
->getName().empty() && !Tag
->getTypedefNameForAnonDecl())
176 // Use the canonical number for externally visible decls.
177 if (ND
->isExternallyVisible()) {
178 unsigned discriminator
= getASTContext().getManglingNumber(ND
);
179 if (discriminator
== 1)
181 disc
= discriminator
- 2;
185 // Make up a reasonable number for internal decls.
186 unsigned &discriminator
= Uniquifier
[ND
];
187 if (!discriminator
) {
188 const DeclContext
*DC
= getEffectiveDeclContext(ND
);
189 discriminator
= ++Discriminator
[std::make_pair(DC
, ND
->getIdentifier())];
191 if (discriminator
== 1)
193 disc
= discriminator
-2;
199 /// CXXNameMangler - Manage the mangling of a single name.
200 class CXXNameMangler
{
201 ItaniumMangleContextImpl
&Context
;
204 /// The "structor" is the top-level declaration being mangled, if
205 /// that's not a template specialization; otherwise it's the pattern
206 /// for that specialization.
207 const NamedDecl
*Structor
;
208 unsigned StructorType
;
210 /// SeqID - The next subsitution sequence number.
213 class FunctionTypeDepthState
{
216 enum { InResultTypeMask
= 1 };
219 FunctionTypeDepthState() : Bits(0) {}
221 /// The number of function types we're inside.
222 unsigned getDepth() const {
226 /// True if we're in the return type of the innermost function type.
227 bool isInResultType() const {
228 return Bits
& InResultTypeMask
;
231 FunctionTypeDepthState
push() {
232 FunctionTypeDepthState tmp
= *this;
233 Bits
= (Bits
& ~InResultTypeMask
) + 2;
237 void enterResultType() {
238 Bits
|= InResultTypeMask
;
241 void leaveResultType() {
242 Bits
&= ~InResultTypeMask
;
245 void pop(FunctionTypeDepthState saved
) {
246 assert(getDepth() == saved
.getDepth() + 1);
252 llvm::DenseMap
<uintptr_t, unsigned> Substitutions
;
254 ASTContext
&getASTContext() const { return Context
.getASTContext(); }
257 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
258 const NamedDecl
*D
= nullptr)
259 : Context(C
), Out(Out_
), Structor(getStructor(D
)), StructorType(0),
261 // These can't be mangled without a ctor type or dtor type.
262 assert(!D
|| (!isa
<CXXDestructorDecl
>(D
) &&
263 !isa
<CXXConstructorDecl
>(D
)));
265 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
266 const CXXConstructorDecl
*D
, CXXCtorType Type
)
267 : Context(C
), Out(Out_
), Structor(getStructor(D
)), StructorType(Type
),
269 CXXNameMangler(ItaniumMangleContextImpl
&C
, raw_ostream
&Out_
,
270 const CXXDestructorDecl
*D
, CXXDtorType Type
)
271 : Context(C
), Out(Out_
), Structor(getStructor(D
)), StructorType(Type
),
276 if (Out
.str()[0] == '\01')
280 char *result
= abi::__cxa_demangle(Out
.str().str().c_str(), 0, 0, &status
);
281 assert(status
== 0 && "Could not demangle mangled name!");
285 raw_ostream
&getStream() { return Out
; }
287 void mangle(const NamedDecl
*D
, StringRef Prefix
= "_Z");
288 void mangleCallOffset(int64_t NonVirtual
, int64_t Virtual
);
289 void mangleNumber(const llvm::APSInt
&I
);
290 void mangleNumber(int64_t Number
);
291 void mangleFloat(const llvm::APFloat
&F
);
292 void mangleFunctionEncoding(const FunctionDecl
*FD
);
293 void mangleSeqID(unsigned SeqID
);
294 void mangleName(const NamedDecl
*ND
);
295 void mangleType(QualType T
);
296 void mangleNameOrStandardSubstitution(const NamedDecl
*ND
);
300 bool mangleSubstitution(const NamedDecl
*ND
);
301 bool mangleSubstitution(QualType T
);
302 bool mangleSubstitution(TemplateName Template
);
303 bool mangleSubstitution(uintptr_t Ptr
);
305 void mangleExistingSubstitution(QualType type
);
306 void mangleExistingSubstitution(TemplateName name
);
308 bool mangleStandardSubstitution(const NamedDecl
*ND
);
310 void addSubstitution(const NamedDecl
*ND
) {
311 ND
= cast
<NamedDecl
>(ND
->getCanonicalDecl());
313 addSubstitution(reinterpret_cast<uintptr_t>(ND
));
315 void addSubstitution(QualType T
);
316 void addSubstitution(TemplateName Template
);
317 void addSubstitution(uintptr_t Ptr
);
319 void mangleUnresolvedPrefix(NestedNameSpecifier
*qualifier
,
320 NamedDecl
*firstQualifierLookup
,
321 bool recursive
= false);
322 void mangleUnresolvedName(NestedNameSpecifier
*qualifier
,
323 NamedDecl
*firstQualifierLookup
,
324 DeclarationName name
,
325 unsigned KnownArity
= UnknownArity
);
327 void mangleName(const TemplateDecl
*TD
,
328 const TemplateArgument
*TemplateArgs
,
329 unsigned NumTemplateArgs
);
330 void mangleUnqualifiedName(const NamedDecl
*ND
) {
331 mangleUnqualifiedName(ND
, ND
->getDeclName(), UnknownArity
);
333 void mangleUnqualifiedName(const NamedDecl
*ND
, DeclarationName Name
,
334 unsigned KnownArity
);
335 void mangleUnscopedName(const NamedDecl
*ND
);
336 void mangleUnscopedTemplateName(const TemplateDecl
*ND
);
337 void mangleUnscopedTemplateName(TemplateName
);
338 void mangleSourceName(const IdentifierInfo
*II
);
339 void mangleLocalName(const Decl
*D
);
340 void mangleBlockForPrefix(const BlockDecl
*Block
);
341 void mangleUnqualifiedBlock(const BlockDecl
*Block
);
342 void mangleLambda(const CXXRecordDecl
*Lambda
);
343 void mangleNestedName(const NamedDecl
*ND
, const DeclContext
*DC
,
344 bool NoFunction
=false);
345 void mangleNestedName(const TemplateDecl
*TD
,
346 const TemplateArgument
*TemplateArgs
,
347 unsigned NumTemplateArgs
);
348 void manglePrefix(NestedNameSpecifier
*qualifier
);
349 void manglePrefix(const DeclContext
*DC
, bool NoFunction
=false);
350 void manglePrefix(QualType type
);
351 void mangleTemplatePrefix(const TemplateDecl
*ND
, bool NoFunction
=false);
352 void mangleTemplatePrefix(TemplateName Template
);
353 void mangleOperatorName(OverloadedOperatorKind OO
, unsigned Arity
);
354 void mangleQualifiers(Qualifiers Quals
);
355 void mangleRefQualifier(RefQualifierKind RefQualifier
);
357 void mangleObjCMethodName(const ObjCMethodDecl
*MD
);
359 // Declare manglers for every type class.
360 #define ABSTRACT_TYPE(CLASS, PARENT)
361 #define NON_CANONICAL_TYPE(CLASS, PARENT)
362 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
363 #include "clang/AST/TypeNodes.def"
365 void mangleType(const TagType
*);
366 void mangleType(TemplateName
);
367 void mangleBareFunctionType(const FunctionType
*T
,
368 bool MangleReturnType
);
369 void mangleNeonVectorType(const VectorType
*T
);
370 void mangleAArch64NeonVectorType(const VectorType
*T
);
372 void mangleIntegerLiteral(QualType T
, const llvm::APSInt
&Value
);
373 void mangleMemberExpr(const Expr
*base
, bool isArrow
,
374 NestedNameSpecifier
*qualifier
,
375 NamedDecl
*firstQualifierLookup
,
376 DeclarationName name
,
377 unsigned knownArity
);
378 void mangleCastExpression(const Expr
*E
, StringRef CastEncoding
);
379 void mangleExpression(const Expr
*E
, unsigned Arity
= UnknownArity
);
380 void mangleCXXCtorType(CXXCtorType T
);
381 void mangleCXXDtorType(CXXDtorType T
);
383 void mangleTemplateArgs(const ASTTemplateArgumentListInfo
&TemplateArgs
);
384 void mangleTemplateArgs(const TemplateArgument
*TemplateArgs
,
385 unsigned NumTemplateArgs
);
386 void mangleTemplateArgs(const TemplateArgumentList
&AL
);
387 void mangleTemplateArg(TemplateArgument A
);
389 void mangleTemplateParameter(unsigned Index
);
391 void mangleFunctionParam(const ParmVarDecl
*parm
);
396 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl
*D
) {
397 const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
);
399 LanguageLinkage L
= FD
->getLanguageLinkage();
400 // Overloadable functions need mangling.
401 if (FD
->hasAttr
<OverloadableAttr
>())
404 // "main" is not mangled.
408 // C++ functions and those whose names are not a simple identifier need
410 if (!FD
->getDeclName().isIdentifier() || L
== CXXLanguageLinkage
)
413 // C functions are not mangled.
414 if (L
== CLanguageLinkage
)
418 // Otherwise, no mangling is done outside C++ mode.
419 if (!getASTContext().getLangOpts().CPlusPlus
)
422 const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
424 // C variables are not mangled.
428 // Variables at global scope with non-internal linkage are not mangled
429 const DeclContext
*DC
= getEffectiveDeclContext(D
);
430 // Check for extern variable declared locally.
431 if (DC
->isFunctionOrMethod() && D
->hasLinkage())
432 while (!DC
->isNamespace() && !DC
->isTranslationUnit())
433 DC
= getEffectiveParentContext(DC
);
434 if (DC
->isTranslationUnit() && D
->getFormalLinkage() != InternalLinkage
&&
435 !isa
<VarTemplateSpecializationDecl
>(D
))
442 void CXXNameMangler::mangle(const NamedDecl
*D
, StringRef Prefix
) {
443 // <mangled-name> ::= _Z <encoding>
445 // ::= <special-name>
447 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
))
448 mangleFunctionEncoding(FD
);
449 else if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
451 else if (const IndirectFieldDecl
*IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
452 mangleName(IFD
->getAnonField());
454 mangleName(cast
<FieldDecl
>(D
));
457 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl
*FD
) {
458 // <encoding> ::= <function name> <bare-function-type>
461 // Don't mangle in the type if this isn't a decl we should typically mangle.
462 if (!Context
.shouldMangleDeclName(FD
))
465 if (FD
->hasAttr
<EnableIfAttr
>()) {
466 FunctionTypeDepthState Saved
= FunctionTypeDepth
.push();
467 Out
<< "Ua9enable_ifI";
468 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
470 for (AttrVec::const_reverse_iterator I
= FD
->getAttrs().rbegin(),
471 E
= FD
->getAttrs().rend();
473 EnableIfAttr
*EIA
= dyn_cast
<EnableIfAttr
>(*I
);
477 mangleExpression(EIA
->getCond());
481 FunctionTypeDepth
.pop(Saved
);
484 // Whether the mangling of a function type includes the return type depends on
485 // the context and the nature of the function. The rules for deciding whether
486 // the return type is included are:
488 // 1. Template functions (names or types) have return types encoded, with
489 // the exceptions listed below.
490 // 2. Function types not appearing as part of a function name mangling,
491 // e.g. parameters, pointer types, etc., have return type encoded, with the
492 // exceptions listed below.
493 // 3. Non-template function names do not have return types encoded.
495 // The exceptions mentioned in (1) and (2) above, for which the return type is
496 // never included, are
499 // 3. Conversion operator functions, e.g. operator int.
500 bool MangleReturnType
= false;
501 if (FunctionTemplateDecl
*PrimaryTemplate
= FD
->getPrimaryTemplate()) {
502 if (!(isa
<CXXConstructorDecl
>(FD
) || isa
<CXXDestructorDecl
>(FD
) ||
503 isa
<CXXConversionDecl
>(FD
)))
504 MangleReturnType
= true;
506 // Mangle the type of the primary template.
507 FD
= PrimaryTemplate
->getTemplatedDecl();
510 mangleBareFunctionType(FD
->getType()->getAs
<FunctionType
>(),
514 static const DeclContext
*IgnoreLinkageSpecDecls(const DeclContext
*DC
) {
515 while (isa
<LinkageSpecDecl
>(DC
)) {
516 DC
= getEffectiveParentContext(DC
);
522 /// isStd - Return whether a given namespace is the 'std' namespace.
523 static bool isStd(const NamespaceDecl
*NS
) {
524 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS
))
525 ->isTranslationUnit())
528 const IdentifierInfo
*II
= NS
->getOriginalNamespace()->getIdentifier();
529 return II
&& II
->isStr("std");
532 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
534 static bool isStdNamespace(const DeclContext
*DC
) {
535 if (!DC
->isNamespace())
538 return isStd(cast
<NamespaceDecl
>(DC
));
541 static const TemplateDecl
*
542 isTemplate(const NamedDecl
*ND
, const TemplateArgumentList
*&TemplateArgs
) {
543 // Check if we have a function template.
544 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(ND
)){
545 if (const TemplateDecl
*TD
= FD
->getPrimaryTemplate()) {
546 TemplateArgs
= FD
->getTemplateSpecializationArgs();
551 // Check if we have a class template.
552 if (const ClassTemplateSpecializationDecl
*Spec
=
553 dyn_cast
<ClassTemplateSpecializationDecl
>(ND
)) {
554 TemplateArgs
= &Spec
->getTemplateArgs();
555 return Spec
->getSpecializedTemplate();
558 // Check if we have a variable template.
559 if (const VarTemplateSpecializationDecl
*Spec
=
560 dyn_cast
<VarTemplateSpecializationDecl
>(ND
)) {
561 TemplateArgs
= &Spec
->getTemplateArgs();
562 return Spec
->getSpecializedTemplate();
568 void CXXNameMangler::mangleName(const NamedDecl
*ND
) {
569 // <name> ::= <nested-name>
570 // ::= <unscoped-name>
571 // ::= <unscoped-template-name> <template-args>
574 const DeclContext
*DC
= getEffectiveDeclContext(ND
);
576 // If this is an extern variable declared locally, the relevant DeclContext
577 // is that of the containing namespace, or the translation unit.
578 // FIXME: This is a hack; extern variables declared locally should have
579 // a proper semantic declaration context!
580 if (isLocalContainerContext(DC
) && ND
->hasLinkage() && !isLambda(ND
))
581 while (!DC
->isNamespace() && !DC
->isTranslationUnit())
582 DC
= getEffectiveParentContext(DC
);
583 else if (GetLocalClassDecl(ND
)) {
588 DC
= IgnoreLinkageSpecDecls(DC
);
590 if (DC
->isTranslationUnit() || isStdNamespace(DC
)) {
591 // Check if we have a template.
592 const TemplateArgumentList
*TemplateArgs
= nullptr;
593 if (const TemplateDecl
*TD
= isTemplate(ND
, TemplateArgs
)) {
594 mangleUnscopedTemplateName(TD
);
595 mangleTemplateArgs(*TemplateArgs
);
599 mangleUnscopedName(ND
);
603 if (isLocalContainerContext(DC
)) {
608 mangleNestedName(ND
, DC
);
610 void CXXNameMangler::mangleName(const TemplateDecl
*TD
,
611 const TemplateArgument
*TemplateArgs
,
612 unsigned NumTemplateArgs
) {
613 const DeclContext
*DC
= IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD
));
615 if (DC
->isTranslationUnit() || isStdNamespace(DC
)) {
616 mangleUnscopedTemplateName(TD
);
617 mangleTemplateArgs(TemplateArgs
, NumTemplateArgs
);
619 mangleNestedName(TD
, TemplateArgs
, NumTemplateArgs
);
623 void CXXNameMangler::mangleUnscopedName(const NamedDecl
*ND
) {
624 // <unscoped-name> ::= <unqualified-name>
625 // ::= St <unqualified-name> # ::std::
627 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND
))))
630 mangleUnqualifiedName(ND
);
633 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl
*ND
) {
634 // <unscoped-template-name> ::= <unscoped-name>
635 // ::= <substitution>
636 if (mangleSubstitution(ND
))
639 // <template-template-param> ::= <template-param>
640 if (const auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(ND
))
641 mangleTemplateParameter(TTP
->getIndex());
643 mangleUnscopedName(ND
->getTemplatedDecl());
648 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template
) {
649 // <unscoped-template-name> ::= <unscoped-name>
650 // ::= <substitution>
651 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
652 return mangleUnscopedTemplateName(TD
);
654 if (mangleSubstitution(Template
))
657 DependentTemplateName
*Dependent
= Template
.getAsDependentTemplateName();
658 assert(Dependent
&& "Not a dependent template name?");
659 if (const IdentifierInfo
*Id
= Dependent
->getIdentifier())
660 mangleSourceName(Id
);
662 mangleOperatorName(Dependent
->getOperator(), UnknownArity
);
664 addSubstitution(Template
);
667 void CXXNameMangler::mangleFloat(const llvm::APFloat
&f
) {
669 // Floating-point literals are encoded using a fixed-length
670 // lowercase hexadecimal string corresponding to the internal
671 // representation (IEEE on Itanium), high-order bytes first,
672 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
674 // The 'without leading zeroes' thing seems to be an editorial
675 // mistake; see the discussion on cxx-abi-dev beginning on
678 // Our requirements here are just barely weird enough to justify
679 // using a custom algorithm instead of post-processing APInt::toString().
681 llvm::APInt valueBits
= f
.bitcastToAPInt();
682 unsigned numCharacters
= (valueBits
.getBitWidth() + 3) / 4;
683 assert(numCharacters
!= 0);
685 // Allocate a buffer of the right number of characters.
686 SmallVector
<char, 20> buffer
;
687 buffer
.set_size(numCharacters
);
689 // Fill the buffer left-to-right.
690 for (unsigned stringIndex
= 0; stringIndex
!= numCharacters
; ++stringIndex
) {
691 // The bit-index of the next hex digit.
692 unsigned digitBitIndex
= 4 * (numCharacters
- stringIndex
- 1);
694 // Project out 4 bits starting at 'digitIndex'.
695 llvm::integerPart hexDigit
696 = valueBits
.getRawData()[digitBitIndex
/ llvm::integerPartWidth
];
697 hexDigit
>>= (digitBitIndex
% llvm::integerPartWidth
);
700 // Map that over to a lowercase hex digit.
701 static const char charForHex
[16] = {
702 '0', '1', '2', '3', '4', '5', '6', '7',
703 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
705 buffer
[stringIndex
] = charForHex
[hexDigit
];
708 Out
.write(buffer
.data(), numCharacters
);
711 void CXXNameMangler::mangleNumber(const llvm::APSInt
&Value
) {
712 if (Value
.isSigned() && Value
.isNegative()) {
714 Value
.abs().print(Out
, /*signed*/ false);
716 Value
.print(Out
, /*signed*/ false);
720 void CXXNameMangler::mangleNumber(int64_t Number
) {
721 // <number> ::= [n] <non-negative decimal integer>
730 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual
, int64_t Virtual
) {
731 // <call-offset> ::= h <nv-offset> _
732 // ::= v <v-offset> _
733 // <nv-offset> ::= <offset number> # non-virtual base override
734 // <v-offset> ::= <offset number> _ <virtual offset number>
735 // # virtual base override, with vcall offset
738 mangleNumber(NonVirtual
);
744 mangleNumber(NonVirtual
);
746 mangleNumber(Virtual
);
750 void CXXNameMangler::manglePrefix(QualType type
) {
751 if (const TemplateSpecializationType
*TST
=
752 type
->getAs
<TemplateSpecializationType
>()) {
753 if (!mangleSubstitution(QualType(TST
, 0))) {
754 mangleTemplatePrefix(TST
->getTemplateName());
756 // FIXME: GCC does not appear to mangle the template arguments when
757 // the template in question is a dependent template name. Should we
758 // emulate that badness?
759 mangleTemplateArgs(TST
->getArgs(), TST
->getNumArgs());
760 addSubstitution(QualType(TST
, 0));
762 } else if (const DependentTemplateSpecializationType
*DTST
763 = type
->getAs
<DependentTemplateSpecializationType
>()) {
764 TemplateName Template
765 = getASTContext().getDependentTemplateName(DTST
->getQualifier(),
766 DTST
->getIdentifier());
767 mangleTemplatePrefix(Template
);
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(DTST
->getArgs(), DTST
->getNumArgs());
774 // We use the QualType mangle type variant here because it handles
780 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
782 /// \param firstQualifierLookup - the entity found by unqualified lookup
783 /// for the first name in the qualifier, if this is for a member expression
784 /// \param recursive - true if this is being called recursively,
785 /// i.e. if there is more prefix "to the right".
786 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier
*qualifier
,
787 NamedDecl
*firstQualifierLookup
,
791 // <unresolved-name> ::= [gs] <base-unresolved-name>
793 // T::x / decltype(p)::x
794 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
796 // T::N::x /decltype(p)::N::x
797 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
798 // <base-unresolved-name>
800 // A::x, N::y, A<T>::z; "gs" means leading "::"
801 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
802 // <base-unresolved-name>
804 switch (qualifier
->getKind()) {
805 case NestedNameSpecifier::Global
:
808 // We want an 'sr' unless this is the entire NNS.
812 // We never want an 'E' here.
815 case NestedNameSpecifier::Super
:
816 llvm_unreachable("Can't mangle __super specifier");
818 case NestedNameSpecifier::Namespace
:
819 if (qualifier
->getPrefix())
820 mangleUnresolvedPrefix(qualifier
->getPrefix(), firstQualifierLookup
,
824 mangleSourceName(qualifier
->getAsNamespace()->getIdentifier());
826 case NestedNameSpecifier::NamespaceAlias
:
827 if (qualifier
->getPrefix())
828 mangleUnresolvedPrefix(qualifier
->getPrefix(), firstQualifierLookup
,
832 mangleSourceName(qualifier
->getAsNamespaceAlias()->getIdentifier());
835 case NestedNameSpecifier::TypeSpec
:
836 case NestedNameSpecifier::TypeSpecWithTemplate
: {
837 const Type
*type
= qualifier
->getAsType();
839 // We only want to use an unresolved-type encoding if this is one of:
841 // - a template type parameter
842 // - a template template parameter with arguments
843 // In all of these cases, we should have no prefix.
844 if (qualifier
->getPrefix()) {
845 mangleUnresolvedPrefix(qualifier
->getPrefix(), firstQualifierLookup
,
848 // Otherwise, all the cases want this.
852 // Only certain other types are valid as prefixes; enumerate them.
853 switch (type
->getTypeClass()) {
859 case Type::BlockPointer
:
860 case Type::LValueReference
:
861 case Type::RValueReference
:
862 case Type::MemberPointer
:
863 case Type::ConstantArray
:
864 case Type::IncompleteArray
:
865 case Type::VariableArray
:
866 case Type::DependentSizedArray
:
867 case Type::DependentSizedExtVector
:
869 case Type::ExtVector
:
870 case Type::FunctionProto
:
871 case Type::FunctionNoProto
:
874 case Type::Elaborated
:
875 case Type::Attributed
:
877 case Type::PackExpansion
:
878 case Type::ObjCObject
:
879 case Type::ObjCInterface
:
880 case Type::ObjCObjectPointer
:
882 llvm_unreachable("type is illegal as a nested name specifier");
884 case Type::SubstTemplateTypeParmPack
:
885 // FIXME: not clear how to mangle this!
886 // template <class T...> class A {
887 // template <class U...> void foo(decltype(T::foo(U())) x...);
889 Out
<< "_SUBSTPACK_";
892 // <unresolved-type> ::= <template-param>
894 // ::= <template-template-param> <template-args>
895 // (this last is not official yet)
896 case Type::TypeOfExpr
:
899 case Type::TemplateTypeParm
:
900 case Type::UnaryTransform
:
901 case Type::SubstTemplateTypeParm
:
903 assert(!qualifier
->getPrefix());
905 // We only get here recursively if we're followed by identifiers.
906 if (recursive
) Out
<< 'N';
908 // This seems to do everything we want. It's not really
909 // sanctioned for a substituted template parameter, though.
910 mangleType(QualType(type
, 0));
912 // We never want to print 'E' directly after an unresolved-type,
913 // so we return directly.
917 mangleSourceName(cast
<TypedefType
>(type
)->getDecl()->getIdentifier());
920 case Type::UnresolvedUsing
:
921 mangleSourceName(cast
<UnresolvedUsingType
>(type
)->getDecl()
926 mangleSourceName(cast
<RecordType
>(type
)->getDecl()->getIdentifier());
929 case Type::TemplateSpecialization
: {
930 const TemplateSpecializationType
*tst
931 = cast
<TemplateSpecializationType
>(type
);
932 TemplateName name
= tst
->getTemplateName();
933 switch (name
.getKind()) {
934 case TemplateName::Template
:
935 case TemplateName::QualifiedTemplate
: {
936 TemplateDecl
*temp
= name
.getAsTemplateDecl();
938 // If the base is a template template parameter, this is an
940 assert(temp
&& "no template for template specialization type");
941 if (isa
<TemplateTemplateParmDecl
>(temp
)) goto unresolvedType
;
943 mangleSourceName(temp
->getIdentifier());
947 case TemplateName::OverloadedTemplate
:
948 case TemplateName::DependentTemplate
:
949 llvm_unreachable("invalid base for a template specialization type");
951 case TemplateName::SubstTemplateTemplateParm
: {
952 SubstTemplateTemplateParmStorage
*subst
953 = name
.getAsSubstTemplateTemplateParm();
954 mangleExistingSubstitution(subst
->getReplacement());
958 case TemplateName::SubstTemplateTemplateParmPack
: {
959 // FIXME: not clear how to mangle this!
960 // template <template <class U> class T...> class A {
961 // template <class U...> void foo(decltype(T<U>::foo) x...);
963 Out
<< "_SUBSTPACK_";
968 mangleTemplateArgs(tst
->getArgs(), tst
->getNumArgs());
972 case Type::InjectedClassName
:
973 mangleSourceName(cast
<InjectedClassNameType
>(type
)->getDecl()
977 case Type::DependentName
:
978 mangleSourceName(cast
<DependentNameType
>(type
)->getIdentifier());
981 case Type::DependentTemplateSpecialization
: {
982 const DependentTemplateSpecializationType
*tst
983 = cast
<DependentTemplateSpecializationType
>(type
);
984 mangleSourceName(tst
->getIdentifier());
985 mangleTemplateArgs(tst
->getArgs(), tst
->getNumArgs());
992 case NestedNameSpecifier::Identifier
:
993 // Member expressions can have these without prefixes.
994 if (qualifier
->getPrefix()) {
995 mangleUnresolvedPrefix(qualifier
->getPrefix(), firstQualifierLookup
,
997 } else if (firstQualifierLookup
) {
999 // Try to make a proper qualifier out of the lookup result, and
1000 // then just recurse on that.
1001 NestedNameSpecifier
*newQualifier
;
1002 if (TypeDecl
*typeDecl
= dyn_cast
<TypeDecl
>(firstQualifierLookup
)) {
1003 QualType type
= getASTContext().getTypeDeclType(typeDecl
);
1005 // Pretend we had a different nested name specifier.
1006 newQualifier
= NestedNameSpecifier::Create(getASTContext(),
1010 } else if (NamespaceDecl
*nspace
=
1011 dyn_cast
<NamespaceDecl
>(firstQualifierLookup
)) {
1012 newQualifier
= NestedNameSpecifier::Create(getASTContext(),
1015 } else if (NamespaceAliasDecl
*alias
=
1016 dyn_cast
<NamespaceAliasDecl
>(firstQualifierLookup
)) {
1017 newQualifier
= NestedNameSpecifier::Create(getASTContext(),
1021 // No sensible mangling to do here.
1022 newQualifier
= nullptr;
1026 return mangleUnresolvedPrefix(newQualifier
, /*lookup*/ nullptr,
1033 mangleSourceName(qualifier
->getAsIdentifier());
1037 // If this was the innermost part of the NNS, and we fell out to
1038 // here, append an 'E'.
1043 /// Mangle an unresolved-name, which is generally used for names which
1044 /// weren't resolved to specific entities.
1045 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier
*qualifier
,
1046 NamedDecl
*firstQualifierLookup
,
1047 DeclarationName name
,
1048 unsigned knownArity
) {
1049 if (qualifier
) mangleUnresolvedPrefix(qualifier
, firstQualifierLookup
);
1050 mangleUnqualifiedName(nullptr, name
, knownArity
);
1053 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl
*ND
,
1054 DeclarationName Name
,
1055 unsigned KnownArity
) {
1056 // <unqualified-name> ::= <operator-name>
1057 // ::= <ctor-dtor-name>
1058 // ::= <source-name>
1059 switch (Name
.getNameKind()) {
1060 case DeclarationName::Identifier
: {
1061 if (const IdentifierInfo
*II
= Name
.getAsIdentifierInfo()) {
1062 // We must avoid conflicts between internally- and externally-
1063 // linked variable and function declaration names in the same TU:
1064 // void test() { extern void foo(); }
1065 // static void foo();
1066 // This naming convention is the same as that followed by GCC,
1067 // though it shouldn't actually matter.
1068 if (ND
&& ND
->getFormalLinkage() == InternalLinkage
&&
1069 getEffectiveDeclContext(ND
)->isFileContext())
1072 mangleSourceName(II
);
1076 // Otherwise, an anonymous entity. We must have a declaration.
1077 assert(ND
&& "mangling empty name without declaration");
1079 if (const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(ND
)) {
1080 if (NS
->isAnonymousNamespace()) {
1081 // This is how gcc mangles these names.
1082 Out
<< "12_GLOBAL__N_1";
1087 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(ND
)) {
1088 // We must have an anonymous union or struct declaration.
1089 const RecordDecl
*RD
=
1090 cast
<RecordDecl
>(VD
->getType()->getAs
<RecordType
>()->getDecl());
1092 // Itanium C++ ABI 5.1.2:
1094 // For the purposes of mangling, the name of an anonymous union is
1095 // considered to be the name of the first named data member found by a
1096 // pre-order, depth-first, declaration-order walk of the data members of
1097 // the anonymous union. If there is no such data member (i.e., if all of
1098 // the data members in the union are unnamed), then there is no way for
1099 // a program to refer to the anonymous union, and there is therefore no
1100 // need to mangle its name.
1101 assert(RD
->isAnonymousStructOrUnion()
1102 && "Expected anonymous struct or union!");
1103 const FieldDecl
*FD
= RD
->findFirstNamedDataMember();
1105 // It's actually possible for various reasons for us to get here
1106 // with an empty anonymous struct / union. Fortunately, it
1107 // doesn't really matter what name we generate.
1109 assert(FD
->getIdentifier() && "Data member name isn't an identifier!");
1111 mangleSourceName(FD
->getIdentifier());
1115 // Class extensions have no name as a category, and it's possible
1116 // for them to be the semantic parent of certain declarations
1117 // (primarily, tag decls defined within declarations). Such
1118 // declarations will always have internal linkage, so the name
1119 // doesn't really matter, but we shouldn't crash on them. For
1120 // safety, just handle all ObjC containers here.
1121 if (isa
<ObjCContainerDecl
>(ND
))
1124 // We must have an anonymous struct.
1125 const TagDecl
*TD
= cast
<TagDecl
>(ND
);
1126 if (const TypedefNameDecl
*D
= TD
->getTypedefNameForAnonDecl()) {
1127 assert(TD
->getDeclContext() == D
->getDeclContext() &&
1128 "Typedef should not be in another decl context!");
1129 assert(D
->getDeclName().getAsIdentifierInfo() &&
1130 "Typedef was not named!");
1131 mangleSourceName(D
->getDeclName().getAsIdentifierInfo());
1135 // <unnamed-type-name> ::= <closure-type-name>
1137 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1138 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1139 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(TD
)) {
1140 if (Record
->isLambda() && Record
->getLambdaManglingNumber()) {
1141 mangleLambda(Record
);
1146 if (TD
->isExternallyVisible()) {
1147 unsigned UnnamedMangle
= getASTContext().getManglingNumber(TD
);
1149 if (UnnamedMangle
> 1)
1150 Out
<< llvm::utostr(UnnamedMangle
- 2);
1155 // Get a unique id for the anonymous struct.
1156 unsigned AnonStructId
= Context
.getAnonymousStructId(TD
);
1158 // Mangle it as a source name in the form
1160 // where n is the length of the string.
1163 Str
+= llvm::utostr(AnonStructId
);
1170 case DeclarationName::ObjCZeroArgSelector
:
1171 case DeclarationName::ObjCOneArgSelector
:
1172 case DeclarationName::ObjCMultiArgSelector
:
1173 llvm_unreachable("Can't mangle Objective-C selector names here!");
1175 case DeclarationName::CXXConstructorName
:
1177 // If the named decl is the C++ constructor we're mangling, use the type
1179 mangleCXXCtorType(static_cast<CXXCtorType
>(StructorType
));
1181 // Otherwise, use the complete constructor name. This is relevant if a
1182 // class with a constructor is declared within a constructor.
1183 mangleCXXCtorType(Ctor_Complete
);
1186 case DeclarationName::CXXDestructorName
:
1188 // If the named decl is the C++ destructor we're mangling, use the type we
1190 mangleCXXDtorType(static_cast<CXXDtorType
>(StructorType
));
1192 // Otherwise, use the complete destructor name. This is relevant if a
1193 // class with a destructor is declared within a destructor.
1194 mangleCXXDtorType(Dtor_Complete
);
1197 case DeclarationName::CXXConversionFunctionName
:
1198 // <operator-name> ::= cv <type> # (cast)
1200 mangleType(Name
.getCXXNameType());
1203 case DeclarationName::CXXOperatorName
: {
1206 Arity
= cast
<FunctionDecl
>(ND
)->getNumParams();
1208 // If we have a C++ member function, we need to include the 'this' pointer.
1209 // FIXME: This does not make sense for operators that are static, but their
1210 // names stay the same regardless of the arity (operator new for instance).
1211 if (isa
<CXXMethodDecl
>(ND
))
1216 mangleOperatorName(Name
.getCXXOverloadedOperator(), Arity
);
1220 case DeclarationName::CXXLiteralOperatorName
:
1221 // FIXME: This mangling is not yet official.
1223 mangleSourceName(Name
.getCXXLiteralIdentifier());
1226 case DeclarationName::CXXUsingDirective
:
1227 llvm_unreachable("Can't mangle a using directive name!");
1231 void CXXNameMangler::mangleSourceName(const IdentifierInfo
*II
) {
1232 // <source-name> ::= <positive length number> <identifier>
1233 // <number> ::= [n] <non-negative decimal integer>
1234 // <identifier> ::= <unqualified source code identifier>
1235 Out
<< II
->getLength() << II
->getName();
1238 void CXXNameMangler::mangleNestedName(const NamedDecl
*ND
,
1239 const DeclContext
*DC
,
1242 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1243 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1244 // <template-args> E
1247 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(ND
)) {
1248 Qualifiers MethodQuals
=
1249 Qualifiers::fromCVRMask(Method
->getTypeQualifiers());
1250 // We do not consider restrict a distinguishing attribute for overloading
1251 // purposes so we must not mangle it.
1252 MethodQuals
.removeRestrict();
1253 mangleQualifiers(MethodQuals
);
1254 mangleRefQualifier(Method
->getRefQualifier());
1257 // Check if we have a template.
1258 const TemplateArgumentList
*TemplateArgs
= nullptr;
1259 if (const TemplateDecl
*TD
= isTemplate(ND
, TemplateArgs
)) {
1260 mangleTemplatePrefix(TD
, NoFunction
);
1261 mangleTemplateArgs(*TemplateArgs
);
1264 manglePrefix(DC
, NoFunction
);
1265 mangleUnqualifiedName(ND
);
1270 void CXXNameMangler::mangleNestedName(const TemplateDecl
*TD
,
1271 const TemplateArgument
*TemplateArgs
,
1272 unsigned NumTemplateArgs
) {
1273 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1277 mangleTemplatePrefix(TD
);
1278 mangleTemplateArgs(TemplateArgs
, NumTemplateArgs
);
1283 void CXXNameMangler::mangleLocalName(const Decl
*D
) {
1284 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1285 // := Z <function encoding> E s [<discriminator>]
1286 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1288 // <discriminator> := _ <non-negative number>
1289 assert(isa
<NamedDecl
>(D
) || isa
<BlockDecl
>(D
));
1290 const RecordDecl
*RD
= GetLocalClassDecl(D
);
1291 const DeclContext
*DC
= getEffectiveDeclContext(RD
? RD
: D
);
1295 if (const ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(DC
))
1296 mangleObjCMethodName(MD
);
1297 else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(DC
))
1298 mangleBlockForPrefix(BD
);
1300 mangleFunctionEncoding(cast
<FunctionDecl
>(DC
));
1305 // The parameter number is omitted for the last parameter, 0 for the
1306 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1307 // <entity name> will of course contain a <closure-type-name>: Its
1308 // numbering will be local to the particular argument in which it appears
1309 // -- other default arguments do not affect its encoding.
1310 const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
);
1311 if (CXXRD
->isLambda()) {
1312 if (const ParmVarDecl
*Parm
1313 = dyn_cast_or_null
<ParmVarDecl
>(CXXRD
->getLambdaContextDecl())) {
1314 if (const FunctionDecl
*Func
1315 = dyn_cast
<FunctionDecl
>(Parm
->getDeclContext())) {
1317 unsigned Num
= Func
->getNumParams() - Parm
->getFunctionScopeIndex();
1319 mangleNumber(Num
- 2);
1325 // Mangle the name relative to the closest enclosing function.
1326 // equality ok because RD derived from ND above
1328 mangleUnqualifiedName(RD
);
1329 } else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(D
)) {
1330 manglePrefix(getEffectiveDeclContext(BD
), true /*NoFunction*/);
1331 mangleUnqualifiedBlock(BD
);
1333 const NamedDecl
*ND
= cast
<NamedDecl
>(D
);
1334 mangleNestedName(ND
, getEffectiveDeclContext(ND
), true /*NoFunction*/);
1336 } else if (const BlockDecl
*BD
= dyn_cast
<BlockDecl
>(D
)) {
1337 // Mangle a block in a default parameter; see above explanation for
1339 if (const ParmVarDecl
*Parm
1340 = dyn_cast_or_null
<ParmVarDecl
>(BD
->getBlockManglingContextDecl())) {
1341 if (const FunctionDecl
*Func
1342 = dyn_cast
<FunctionDecl
>(Parm
->getDeclContext())) {
1344 unsigned Num
= Func
->getNumParams() - Parm
->getFunctionScopeIndex();
1346 mangleNumber(Num
- 2);
1351 mangleUnqualifiedBlock(BD
);
1353 mangleUnqualifiedName(cast
<NamedDecl
>(D
));
1356 if (const NamedDecl
*ND
= dyn_cast
<NamedDecl
>(RD
? RD
: D
)) {
1358 if (Context
.getNextDiscriminator(ND
, disc
)) {
1362 Out
<< "__" << disc
<< '_';
1367 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl
*Block
) {
1368 if (GetLocalClassDecl(Block
)) {
1369 mangleLocalName(Block
);
1372 const DeclContext
*DC
= getEffectiveDeclContext(Block
);
1373 if (isLocalContainerContext(DC
)) {
1374 mangleLocalName(Block
);
1377 manglePrefix(getEffectiveDeclContext(Block
));
1378 mangleUnqualifiedBlock(Block
);
1381 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl
*Block
) {
1382 if (Decl
*Context
= Block
->getBlockManglingContextDecl()) {
1383 if ((isa
<VarDecl
>(Context
) || isa
<FieldDecl
>(Context
)) &&
1384 Context
->getDeclContext()->isRecord()) {
1385 if (const IdentifierInfo
*Name
1386 = cast
<NamedDecl
>(Context
)->getIdentifier()) {
1387 mangleSourceName(Name
);
1393 // If we have a block mangling number, use it.
1394 unsigned Number
= Block
->getBlockManglingNumber();
1395 // Otherwise, just make up a number. It doesn't matter what it is because
1396 // the symbol in question isn't externally visible.
1398 Number
= Context
.getBlockId(Block
, false);
1405 void CXXNameMangler::mangleLambda(const CXXRecordDecl
*Lambda
) {
1406 // If the context of a closure type is an initializer for a class member
1407 // (static or nonstatic), it is encoded in a qualified name with a final
1408 // <prefix> of the form:
1410 // <data-member-prefix> := <member source-name> M
1412 // Technically, the data-member-prefix is part of the <prefix>. However,
1413 // since a closure type will always be mangled with a prefix, it's easier
1414 // to emit that last part of the prefix here.
1415 if (Decl
*Context
= Lambda
->getLambdaContextDecl()) {
1416 if ((isa
<VarDecl
>(Context
) || isa
<FieldDecl
>(Context
)) &&
1417 Context
->getDeclContext()->isRecord()) {
1418 if (const IdentifierInfo
*Name
1419 = cast
<NamedDecl
>(Context
)->getIdentifier()) {
1420 mangleSourceName(Name
);
1427 const FunctionProtoType
*Proto
= Lambda
->getLambdaTypeInfo()->getType()->
1428 getAs
<FunctionProtoType
>();
1429 mangleBareFunctionType(Proto
, /*MangleReturnType=*/false);
1432 // The number is omitted for the first closure type with a given
1433 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1434 // (in lexical order) with that same <lambda-sig> and context.
1436 // The AST keeps track of the number for us.
1437 unsigned Number
= Lambda
->getLambdaManglingNumber();
1438 assert(Number
> 0 && "Lambda should be mangled as an unnamed class");
1440 mangleNumber(Number
- 2);
1444 void CXXNameMangler::manglePrefix(NestedNameSpecifier
*qualifier
) {
1445 switch (qualifier
->getKind()) {
1446 case NestedNameSpecifier::Global
:
1450 case NestedNameSpecifier::Super
:
1451 llvm_unreachable("Can't mangle __super specifier");
1453 case NestedNameSpecifier::Namespace
:
1454 mangleName(qualifier
->getAsNamespace());
1457 case NestedNameSpecifier::NamespaceAlias
:
1458 mangleName(qualifier
->getAsNamespaceAlias()->getNamespace());
1461 case NestedNameSpecifier::TypeSpec
:
1462 case NestedNameSpecifier::TypeSpecWithTemplate
:
1463 manglePrefix(QualType(qualifier
->getAsType(), 0));
1466 case NestedNameSpecifier::Identifier
:
1467 // Member expressions can have these without prefixes, but that
1468 // should end up in mangleUnresolvedPrefix instead.
1469 assert(qualifier
->getPrefix());
1470 manglePrefix(qualifier
->getPrefix());
1472 mangleSourceName(qualifier
->getAsIdentifier());
1476 llvm_unreachable("unexpected nested name specifier");
1479 void CXXNameMangler::manglePrefix(const DeclContext
*DC
, bool NoFunction
) {
1480 // <prefix> ::= <prefix> <unqualified-name>
1481 // ::= <template-prefix> <template-args>
1482 // ::= <template-param>
1484 // ::= <substitution>
1486 DC
= IgnoreLinkageSpecDecls(DC
);
1488 if (DC
->isTranslationUnit())
1491 if (NoFunction
&& isLocalContainerContext(DC
))
1494 assert(!isLocalContainerContext(DC
));
1496 const NamedDecl
*ND
= cast
<NamedDecl
>(DC
);
1497 if (mangleSubstitution(ND
))
1500 // Check if we have a template.
1501 const TemplateArgumentList
*TemplateArgs
= nullptr;
1502 if (const TemplateDecl
*TD
= isTemplate(ND
, TemplateArgs
)) {
1503 mangleTemplatePrefix(TD
);
1504 mangleTemplateArgs(*TemplateArgs
);
1506 manglePrefix(getEffectiveDeclContext(ND
), NoFunction
);
1507 mangleUnqualifiedName(ND
);
1510 addSubstitution(ND
);
1513 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template
) {
1514 // <template-prefix> ::= <prefix> <template unqualified-name>
1515 // ::= <template-param>
1516 // ::= <substitution>
1517 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
1518 return mangleTemplatePrefix(TD
);
1520 if (QualifiedTemplateName
*Qualified
= Template
.getAsQualifiedTemplateName())
1521 manglePrefix(Qualified
->getQualifier());
1523 if (OverloadedTemplateStorage
*Overloaded
1524 = Template
.getAsOverloadedTemplate()) {
1525 mangleUnqualifiedName(nullptr, (*Overloaded
->begin())->getDeclName(),
1530 DependentTemplateName
*Dependent
= Template
.getAsDependentTemplateName();
1531 assert(Dependent
&& "Unknown template name kind?");
1532 manglePrefix(Dependent
->getQualifier());
1533 mangleUnscopedTemplateName(Template
);
1536 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl
*ND
,
1538 // <template-prefix> ::= <prefix> <template unqualified-name>
1539 // ::= <template-param>
1540 // ::= <substitution>
1541 // <template-template-param> ::= <template-param>
1544 if (mangleSubstitution(ND
))
1547 // <template-template-param> ::= <template-param>
1548 if (const auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(ND
)) {
1549 mangleTemplateParameter(TTP
->getIndex());
1551 manglePrefix(getEffectiveDeclContext(ND
), NoFunction
);
1552 mangleUnqualifiedName(ND
->getTemplatedDecl());
1555 addSubstitution(ND
);
1558 /// Mangles a template name under the production <type>. Required for
1559 /// template template arguments.
1560 /// <type> ::= <class-enum-type>
1561 /// ::= <template-param>
1562 /// ::= <substitution>
1563 void CXXNameMangler::mangleType(TemplateName TN
) {
1564 if (mangleSubstitution(TN
))
1567 TemplateDecl
*TD
= nullptr;
1569 switch (TN
.getKind()) {
1570 case TemplateName::QualifiedTemplate
:
1571 TD
= TN
.getAsQualifiedTemplateName()->getTemplateDecl();
1574 case TemplateName::Template
:
1575 TD
= TN
.getAsTemplateDecl();
1579 if (isa
<TemplateTemplateParmDecl
>(TD
))
1580 mangleTemplateParameter(cast
<TemplateTemplateParmDecl
>(TD
)->getIndex());
1585 case TemplateName::OverloadedTemplate
:
1586 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1588 case TemplateName::DependentTemplate
: {
1589 const DependentTemplateName
*Dependent
= TN
.getAsDependentTemplateName();
1590 assert(Dependent
->isIdentifier());
1592 // <class-enum-type> ::= <name>
1593 // <name> ::= <nested-name>
1594 mangleUnresolvedPrefix(Dependent
->getQualifier(), nullptr);
1595 mangleSourceName(Dependent
->getIdentifier());
1599 case TemplateName::SubstTemplateTemplateParm
: {
1600 // Substituted template parameters are mangled as the substituted
1601 // template. This will check for the substitution twice, which is
1602 // fine, but we have to return early so that we don't try to *add*
1603 // the substitution twice.
1604 SubstTemplateTemplateParmStorage
*subst
1605 = TN
.getAsSubstTemplateTemplateParm();
1606 mangleType(subst
->getReplacement());
1610 case TemplateName::SubstTemplateTemplateParmPack
: {
1611 // FIXME: not clear how to mangle this!
1612 // template <template <class> class T...> class A {
1613 // template <template <class> class U...> void foo(B<T,U> x...);
1615 Out
<< "_SUBSTPACK_";
1620 addSubstitution(TN
);
1624 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO
, unsigned Arity
) {
1626 // <operator-name> ::= nw # new
1627 case OO_New
: Out
<< "nw"; break;
1629 case OO_Array_New
: Out
<< "na"; break;
1631 case OO_Delete
: Out
<< "dl"; break;
1632 // ::= da # delete[]
1633 case OO_Array_Delete
: Out
<< "da"; break;
1634 // ::= ps # + (unary)
1635 // ::= pl # + (binary or unknown)
1637 Out
<< (Arity
== 1? "ps" : "pl"); break;
1638 // ::= ng # - (unary)
1639 // ::= mi # - (binary or unknown)
1641 Out
<< (Arity
== 1? "ng" : "mi"); break;
1642 // ::= ad # & (unary)
1643 // ::= an # & (binary or unknown)
1645 Out
<< (Arity
== 1? "ad" : "an"); break;
1646 // ::= de # * (unary)
1647 // ::= ml # * (binary or unknown)
1649 // Use binary when unknown.
1650 Out
<< (Arity
== 1? "de" : "ml"); break;
1652 case OO_Tilde
: Out
<< "co"; break;
1654 case OO_Slash
: Out
<< "dv"; break;
1656 case OO_Percent
: Out
<< "rm"; break;
1658 case OO_Pipe
: Out
<< "or"; break;
1660 case OO_Caret
: Out
<< "eo"; break;
1662 case OO_Equal
: Out
<< "aS"; break;
1664 case OO_PlusEqual
: Out
<< "pL"; break;
1666 case OO_MinusEqual
: Out
<< "mI"; break;
1668 case OO_StarEqual
: Out
<< "mL"; break;
1670 case OO_SlashEqual
: Out
<< "dV"; break;
1672 case OO_PercentEqual
: Out
<< "rM"; break;
1674 case OO_AmpEqual
: Out
<< "aN"; break;
1676 case OO_PipeEqual
: Out
<< "oR"; break;
1678 case OO_CaretEqual
: Out
<< "eO"; break;
1680 case OO_LessLess
: Out
<< "ls"; break;
1682 case OO_GreaterGreater
: Out
<< "rs"; break;
1684 case OO_LessLessEqual
: Out
<< "lS"; break;
1686 case OO_GreaterGreaterEqual
: Out
<< "rS"; break;
1688 case OO_EqualEqual
: Out
<< "eq"; break;
1690 case OO_ExclaimEqual
: Out
<< "ne"; break;
1692 case OO_Less
: Out
<< "lt"; break;
1694 case OO_Greater
: Out
<< "gt"; break;
1696 case OO_LessEqual
: Out
<< "le"; break;
1698 case OO_GreaterEqual
: Out
<< "ge"; break;
1700 case OO_Exclaim
: Out
<< "nt"; break;
1702 case OO_AmpAmp
: Out
<< "aa"; break;
1704 case OO_PipePipe
: Out
<< "oo"; break;
1706 case OO_PlusPlus
: Out
<< "pp"; break;
1708 case OO_MinusMinus
: Out
<< "mm"; break;
1710 case OO_Comma
: Out
<< "cm"; break;
1712 case OO_ArrowStar
: Out
<< "pm"; break;
1714 case OO_Arrow
: Out
<< "pt"; break;
1716 case OO_Call
: Out
<< "cl"; break;
1718 case OO_Subscript
: Out
<< "ix"; break;
1721 // The conditional operator can't be overloaded, but we still handle it when
1722 // mangling expressions.
1723 case OO_Conditional
: Out
<< "qu"; break;
1726 case NUM_OVERLOADED_OPERATORS
:
1727 llvm_unreachable("Not an overloaded operator");
1731 void CXXNameMangler::mangleQualifiers(Qualifiers Quals
) {
1732 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1733 if (Quals
.hasRestrict())
1735 if (Quals
.hasVolatile())
1737 if (Quals
.hasConst())
1740 if (Quals
.hasAddressSpace()) {
1741 // Address space extension:
1743 // <type> ::= U <target-addrspace>
1744 // <type> ::= U <OpenCL-addrspace>
1745 // <type> ::= U <CUDA-addrspace>
1747 SmallString
<64> ASString
;
1748 unsigned AS
= Quals
.getAddressSpace();
1750 if (Context
.getASTContext().addressSpaceMapManglingFor(AS
)) {
1751 // <target-addrspace> ::= "AS" <address-space-number>
1752 unsigned TargetAS
= Context
.getASTContext().getTargetAddressSpace(AS
);
1753 ASString
= "AS" + llvm::utostr_32(TargetAS
);
1756 default: llvm_unreachable("Not a language specific address space");
1757 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1758 case LangAS::opencl_global
: ASString
= "CLglobal"; break;
1759 case LangAS::opencl_local
: ASString
= "CLlocal"; break;
1760 case LangAS::opencl_constant
: ASString
= "CLconstant"; break;
1761 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1762 case LangAS::cuda_device
: ASString
= "CUdevice"; break;
1763 case LangAS::cuda_constant
: ASString
= "CUconstant"; break;
1764 case LangAS::cuda_shared
: ASString
= "CUshared"; break;
1767 Out
<< 'U' << ASString
.size() << ASString
;
1770 StringRef LifetimeName
;
1771 switch (Quals
.getObjCLifetime()) {
1772 // Objective-C ARC Extension:
1774 // <type> ::= U "__strong"
1775 // <type> ::= U "__weak"
1776 // <type> ::= U "__autoreleasing"
1777 case Qualifiers::OCL_None
:
1780 case Qualifiers::OCL_Weak
:
1781 LifetimeName
= "__weak";
1784 case Qualifiers::OCL_Strong
:
1785 LifetimeName
= "__strong";
1788 case Qualifiers::OCL_Autoreleasing
:
1789 LifetimeName
= "__autoreleasing";
1792 case Qualifiers::OCL_ExplicitNone
:
1793 // The __unsafe_unretained qualifier is *not* mangled, so that
1794 // __unsafe_unretained types in ARC produce the same manglings as the
1795 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1796 // better ABI compatibility.
1798 // It's safe to do this because unqualified 'id' won't show up
1799 // in any type signatures that need to be mangled.
1802 if (!LifetimeName
.empty())
1803 Out
<< 'U' << LifetimeName
.size() << LifetimeName
;
1806 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier
) {
1807 // <ref-qualifier> ::= R # lvalue reference
1808 // ::= O # rvalue-reference
1809 switch (RefQualifier
) {
1823 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl
*MD
) {
1824 Context
.mangleObjCMethodName(MD
, Out
);
1827 static bool isTypeSubstitutable(Qualifiers Quals
, const Type
*Ty
) {
1830 if (Ty
->isSpecificBuiltinType(BuiltinType::ObjCSel
))
1832 if (Ty
->isOpenCLSpecificType())
1834 if (Ty
->isBuiltinType())
1840 void CXXNameMangler::mangleType(QualType T
) {
1841 // If our type is instantiation-dependent but not dependent, we mangle
1842 // it as it was written in the source, removing any top-level sugar.
1843 // Otherwise, use the canonical type.
1845 // FIXME: This is an approximation of the instantiation-dependent name
1846 // mangling rules, since we should really be using the type as written and
1847 // augmented via semantic analysis (i.e., with implicit conversions and
1848 // default template arguments) for any instantiation-dependent type.
1849 // Unfortunately, that requires several changes to our AST:
1850 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1851 // uniqued, so that we can handle substitutions properly
1852 // - Default template arguments will need to be represented in the
1853 // TemplateSpecializationType, since they need to be mangled even though
1854 // they aren't written.
1855 // - Conversions on non-type template arguments need to be expressed, since
1856 // they can affect the mangling of sizeof/alignof.
1857 if (!T
->isInstantiationDependentType() || T
->isDependentType())
1858 T
= T
.getCanonicalType();
1860 // Desugar any types that are purely sugar.
1862 // Don't desugar through template specialization types that aren't
1863 // type aliases. We need to mangle the template arguments as written.
1864 if (const TemplateSpecializationType
*TST
1865 = dyn_cast
<TemplateSpecializationType
>(T
))
1866 if (!TST
->isTypeAlias())
1870 = T
.getSingleStepDesugaredType(Context
.getASTContext());
1877 SplitQualType split
= T
.split();
1878 Qualifiers quals
= split
.Quals
;
1879 const Type
*ty
= split
.Ty
;
1881 bool isSubstitutable
= isTypeSubstitutable(quals
, ty
);
1882 if (isSubstitutable
&& mangleSubstitution(T
))
1885 // If we're mangling a qualified array type, push the qualifiers to
1886 // the element type.
1887 if (quals
&& isa
<ArrayType
>(T
)) {
1888 ty
= Context
.getASTContext().getAsArrayType(T
);
1889 quals
= Qualifiers();
1891 // Note that we don't update T: we want to add the
1892 // substitution at the original type.
1896 mangleQualifiers(quals
);
1897 // Recurse: even if the qualified type isn't yet substitutable,
1898 // the unqualified type might be.
1899 mangleType(QualType(ty
, 0));
1901 switch (ty
->getTypeClass()) {
1902 #define ABSTRACT_TYPE(CLASS, PARENT)
1903 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1905 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1907 #define TYPE(CLASS, PARENT) \
1909 mangleType(static_cast<const CLASS##Type*>(ty)); \
1911 #include "clang/AST/TypeNodes.def"
1915 // Add the substitution.
1916 if (isSubstitutable
)
1920 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl
*ND
) {
1921 if (!mangleStandardSubstitution(ND
))
1925 void CXXNameMangler::mangleType(const BuiltinType
*T
) {
1926 // <type> ::= <builtin-type>
1927 // <builtin-type> ::= v # void
1931 // ::= a # signed char
1932 // ::= h # unsigned char
1934 // ::= t # unsigned short
1936 // ::= j # unsigned int
1938 // ::= m # unsigned long
1939 // ::= x # long long, __int64
1940 // ::= y # unsigned long long, __int64
1942 // ::= o # unsigned __int128
1945 // ::= e # long double, __float80
1946 // UNSUPPORTED: ::= g # __float128
1947 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1948 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1949 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1950 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1951 // ::= Di # char32_t
1952 // ::= Ds # char16_t
1953 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1954 // ::= u <source-name> # vendor extended type
1955 switch (T
->getKind()) {
1956 case BuiltinType::Void
: Out
<< 'v'; break;
1957 case BuiltinType::Bool
: Out
<< 'b'; break;
1958 case BuiltinType::Char_U
: case BuiltinType::Char_S
: Out
<< 'c'; break;
1959 case BuiltinType::UChar
: Out
<< 'h'; break;
1960 case BuiltinType::UShort
: Out
<< 't'; break;
1961 case BuiltinType::UInt
: Out
<< 'j'; break;
1962 case BuiltinType::ULong
: Out
<< 'm'; break;
1963 case BuiltinType::ULongLong
: Out
<< 'y'; break;
1964 case BuiltinType::UInt128
: Out
<< 'o'; break;
1965 case BuiltinType::SChar
: Out
<< 'a'; break;
1966 case BuiltinType::WChar_S
:
1967 case BuiltinType::WChar_U
: Out
<< 'w'; break;
1968 case BuiltinType::Char16
: Out
<< "Ds"; break;
1969 case BuiltinType::Char32
: Out
<< "Di"; break;
1970 case BuiltinType::Short
: Out
<< 's'; break;
1971 case BuiltinType::Int
: Out
<< 'i'; break;
1972 case BuiltinType::Long
: Out
<< 'l'; break;
1973 case BuiltinType::LongLong
: Out
<< 'x'; break;
1974 case BuiltinType::Int128
: Out
<< 'n'; break;
1975 case BuiltinType::Half
: Out
<< "Dh"; break;
1976 case BuiltinType::Float
: Out
<< 'f'; break;
1977 case BuiltinType::Double
: Out
<< 'd'; break;
1978 case BuiltinType::LongDouble
: Out
<< 'e'; break;
1979 case BuiltinType::NullPtr
: Out
<< "Dn"; break;
1981 #define BUILTIN_TYPE(Id, SingletonId)
1982 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1983 case BuiltinType::Id:
1984 #include "clang/AST/BuiltinTypes.def"
1985 case BuiltinType::Dependent
:
1986 llvm_unreachable("mangling a placeholder type");
1987 case BuiltinType::ObjCId
: Out
<< "11objc_object"; break;
1988 case BuiltinType::ObjCClass
: Out
<< "10objc_class"; break;
1989 case BuiltinType::ObjCSel
: Out
<< "13objc_selector"; break;
1990 case BuiltinType::OCLImage1d
: Out
<< "11ocl_image1d"; break;
1991 case BuiltinType::OCLImage1dArray
: Out
<< "16ocl_image1darray"; break;
1992 case BuiltinType::OCLImage1dBuffer
: Out
<< "17ocl_image1dbuffer"; break;
1993 case BuiltinType::OCLImage2d
: Out
<< "11ocl_image2d"; break;
1994 case BuiltinType::OCLImage2dArray
: Out
<< "16ocl_image2darray"; break;
1995 case BuiltinType::OCLImage3d
: Out
<< "11ocl_image3d"; break;
1996 case BuiltinType::OCLSampler
: Out
<< "11ocl_sampler"; break;
1997 case BuiltinType::OCLEvent
: Out
<< "9ocl_event"; break;
2001 // <type> ::= <function-type>
2002 // <function-type> ::= [<CV-qualifiers>] F [Y]
2003 // <bare-function-type> [<ref-qualifier>] E
2004 void CXXNameMangler::mangleType(const FunctionProtoType
*T
) {
2005 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2006 // e.g. "const" in "int (A::*)() const".
2007 mangleQualifiers(Qualifiers::fromCVRMask(T
->getTypeQuals()));
2011 // FIXME: We don't have enough information in the AST to produce the 'Y'
2012 // encoding for extern "C" function types.
2013 mangleBareFunctionType(T
, /*MangleReturnType=*/true);
2015 // Mangle the ref-qualifier, if present.
2016 mangleRefQualifier(T
->getRefQualifier());
2020 void CXXNameMangler::mangleType(const FunctionNoProtoType
*T
) {
2021 llvm_unreachable("Can't mangle K&R function prototypes");
2023 void CXXNameMangler::mangleBareFunctionType(const FunctionType
*T
,
2024 bool MangleReturnType
) {
2025 // We should never be mangling something without a prototype.
2026 const FunctionProtoType
*Proto
= cast
<FunctionProtoType
>(T
);
2028 // Record that we're in a function type. See mangleFunctionParam
2029 // for details on what we're trying to achieve here.
2030 FunctionTypeDepthState saved
= FunctionTypeDepth
.push();
2032 // <bare-function-type> ::= <signature type>+
2033 if (MangleReturnType
) {
2034 FunctionTypeDepth
.enterResultType();
2035 mangleType(Proto
->getReturnType());
2036 FunctionTypeDepth
.leaveResultType();
2039 if (Proto
->getNumParams() == 0 && !Proto
->isVariadic()) {
2040 // <builtin-type> ::= v # void
2043 FunctionTypeDepth
.pop(saved
);
2047 for (const auto &Arg
: Proto
->param_types())
2048 mangleType(Context
.getASTContext().getSignatureParameterType(Arg
));
2050 FunctionTypeDepth
.pop(saved
);
2052 // <builtin-type> ::= z # ellipsis
2053 if (Proto
->isVariadic())
2057 // <type> ::= <class-enum-type>
2058 // <class-enum-type> ::= <name>
2059 void CXXNameMangler::mangleType(const UnresolvedUsingType
*T
) {
2060 mangleName(T
->getDecl());
2063 // <type> ::= <class-enum-type>
2064 // <class-enum-type> ::= <name>
2065 void CXXNameMangler::mangleType(const EnumType
*T
) {
2066 mangleType(static_cast<const TagType
*>(T
));
2068 void CXXNameMangler::mangleType(const RecordType
*T
) {
2069 mangleType(static_cast<const TagType
*>(T
));
2071 void CXXNameMangler::mangleType(const TagType
*T
) {
2072 mangleName(T
->getDecl());
2075 // <type> ::= <array-type>
2076 // <array-type> ::= A <positive dimension number> _ <element type>
2077 // ::= A [<dimension expression>] _ <element type>
2078 void CXXNameMangler::mangleType(const ConstantArrayType
*T
) {
2079 Out
<< 'A' << T
->getSize() << '_';
2080 mangleType(T
->getElementType());
2082 void CXXNameMangler::mangleType(const VariableArrayType
*T
) {
2084 // decayed vla types (size 0) will just be skipped.
2085 if (T
->getSizeExpr())
2086 mangleExpression(T
->getSizeExpr());
2088 mangleType(T
->getElementType());
2090 void CXXNameMangler::mangleType(const DependentSizedArrayType
*T
) {
2092 mangleExpression(T
->getSizeExpr());
2094 mangleType(T
->getElementType());
2096 void CXXNameMangler::mangleType(const IncompleteArrayType
*T
) {
2098 mangleType(T
->getElementType());
2101 // <type> ::= <pointer-to-member-type>
2102 // <pointer-to-member-type> ::= M <class type> <member type>
2103 void CXXNameMangler::mangleType(const MemberPointerType
*T
) {
2105 mangleType(QualType(T
->getClass(), 0));
2106 QualType PointeeType
= T
->getPointeeType();
2107 if (const FunctionProtoType
*FPT
= dyn_cast
<FunctionProtoType
>(PointeeType
)) {
2110 // Itanium C++ ABI 5.1.8:
2112 // The type of a non-static member function is considered to be different,
2113 // for the purposes of substitution, from the type of a namespace-scope or
2114 // static member function whose type appears similar. The types of two
2115 // non-static member functions are considered to be different, for the
2116 // purposes of substitution, if the functions are members of different
2117 // classes. In other words, for the purposes of substitution, the class of
2118 // which the function is a member is considered part of the type of
2121 // Given that we already substitute member function pointers as a
2122 // whole, the net effect of this rule is just to unconditionally
2123 // suppress substitution on the function type in a member pointer.
2124 // We increment the SeqID here to emulate adding an entry to the
2125 // substitution table.
2128 mangleType(PointeeType
);
2131 // <type> ::= <template-param>
2132 void CXXNameMangler::mangleType(const TemplateTypeParmType
*T
) {
2133 mangleTemplateParameter(T
->getIndex());
2136 // <type> ::= <template-param>
2137 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType
*T
) {
2138 // FIXME: not clear how to mangle this!
2139 // template <class T...> class A {
2140 // template <class U...> void foo(T(*)(U) x...);
2142 Out
<< "_SUBSTPACK_";
2145 // <type> ::= P <type> # pointer-to
2146 void CXXNameMangler::mangleType(const PointerType
*T
) {
2148 mangleType(T
->getPointeeType());
2150 void CXXNameMangler::mangleType(const ObjCObjectPointerType
*T
) {
2152 mangleType(T
->getPointeeType());
2155 // <type> ::= R <type> # reference-to
2156 void CXXNameMangler::mangleType(const LValueReferenceType
*T
) {
2158 mangleType(T
->getPointeeType());
2161 // <type> ::= O <type> # rvalue reference-to (C++0x)
2162 void CXXNameMangler::mangleType(const RValueReferenceType
*T
) {
2164 mangleType(T
->getPointeeType());
2167 // <type> ::= C <type> # complex pair (C 2000)
2168 void CXXNameMangler::mangleType(const ComplexType
*T
) {
2170 mangleType(T
->getElementType());
2173 // ARM's ABI for Neon vector types specifies that they should be mangled as
2174 // if they are structs (to match ARM's initial implementation). The
2175 // vector type must be one of the special types predefined by ARM.
2176 void CXXNameMangler::mangleNeonVectorType(const VectorType
*T
) {
2177 QualType EltType
= T
->getElementType();
2178 assert(EltType
->isBuiltinType() && "Neon vector element not a BuiltinType");
2179 const char *EltName
= nullptr;
2180 if (T
->getVectorKind() == VectorType::NeonPolyVector
) {
2181 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
2182 case BuiltinType::SChar
:
2183 case BuiltinType::UChar
:
2184 EltName
= "poly8_t";
2186 case BuiltinType::Short
:
2187 case BuiltinType::UShort
:
2188 EltName
= "poly16_t";
2190 case BuiltinType::ULongLong
:
2191 EltName
= "poly64_t";
2193 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2196 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
2197 case BuiltinType::SChar
: EltName
= "int8_t"; break;
2198 case BuiltinType::UChar
: EltName
= "uint8_t"; break;
2199 case BuiltinType::Short
: EltName
= "int16_t"; break;
2200 case BuiltinType::UShort
: EltName
= "uint16_t"; break;
2201 case BuiltinType::Int
: EltName
= "int32_t"; break;
2202 case BuiltinType::UInt
: EltName
= "uint32_t"; break;
2203 case BuiltinType::LongLong
: EltName
= "int64_t"; break;
2204 case BuiltinType::ULongLong
: EltName
= "uint64_t"; break;
2205 case BuiltinType::Double
: EltName
= "float64_t"; break;
2206 case BuiltinType::Float
: EltName
= "float32_t"; break;
2207 case BuiltinType::Half
: EltName
= "float16_t";break;
2209 llvm_unreachable("unexpected Neon vector element type");
2212 const char *BaseName
= nullptr;
2213 unsigned BitSize
= (T
->getNumElements() *
2214 getASTContext().getTypeSize(EltType
));
2216 BaseName
= "__simd64_";
2218 assert(BitSize
== 128 && "Neon vector type not 64 or 128 bits");
2219 BaseName
= "__simd128_";
2221 Out
<< strlen(BaseName
) + strlen(EltName
);
2222 Out
<< BaseName
<< EltName
;
2225 static StringRef
mangleAArch64VectorBase(const BuiltinType
*EltType
) {
2226 switch (EltType
->getKind()) {
2227 case BuiltinType::SChar
:
2229 case BuiltinType::Short
:
2231 case BuiltinType::Int
:
2233 case BuiltinType::Long
:
2234 case BuiltinType::LongLong
:
2236 case BuiltinType::UChar
:
2238 case BuiltinType::UShort
:
2240 case BuiltinType::UInt
:
2242 case BuiltinType::ULong
:
2243 case BuiltinType::ULongLong
:
2245 case BuiltinType::Half
:
2247 case BuiltinType::Float
:
2249 case BuiltinType::Double
:
2252 llvm_unreachable("Unexpected vector element base type");
2256 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2257 // the equivalent internal name. The vector type must be one of the special
2258 // types predefined by ARM.
2259 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType
*T
) {
2260 QualType EltType
= T
->getElementType();
2261 assert(EltType
->isBuiltinType() && "Neon vector element not a BuiltinType");
2263 (T
->getNumElements() * getASTContext().getTypeSize(EltType
));
2264 (void)BitSize
; // Silence warning.
2266 assert((BitSize
== 64 || BitSize
== 128) &&
2267 "Neon vector type not 64 or 128 bits");
2270 if (T
->getVectorKind() == VectorType::NeonPolyVector
) {
2271 switch (cast
<BuiltinType
>(EltType
)->getKind()) {
2272 case BuiltinType::UChar
:
2275 case BuiltinType::UShort
:
2278 case BuiltinType::ULong
:
2282 llvm_unreachable("unexpected Neon polynomial vector element type");
2285 EltName
= mangleAArch64VectorBase(cast
<BuiltinType
>(EltType
));
2287 std::string TypeName
=
2288 ("__" + EltName
+ "x" + llvm::utostr(T
->getNumElements()) + "_t").str();
2289 Out
<< TypeName
.length() << TypeName
;
2292 // GNU extension: vector types
2293 // <type> ::= <vector-type>
2294 // <vector-type> ::= Dv <positive dimension number> _
2295 // <extended element type>
2296 // ::= Dv [<dimension expression>] _ <element type>
2297 // <extended element type> ::= <element type>
2298 // ::= p # AltiVec vector pixel
2299 // ::= b # Altivec vector bool
2300 void CXXNameMangler::mangleType(const VectorType
*T
) {
2301 if ((T
->getVectorKind() == VectorType::NeonVector
||
2302 T
->getVectorKind() == VectorType::NeonPolyVector
)) {
2303 llvm::Triple Target
= getASTContext().getTargetInfo().getTriple();
2304 llvm::Triple::ArchType Arch
=
2305 getASTContext().getTargetInfo().getTriple().getArch();
2306 if ((Arch
== llvm::Triple::aarch64
||
2307 Arch
== llvm::Triple::aarch64_be
) && !Target
.isOSDarwin())
2308 mangleAArch64NeonVectorType(T
);
2310 mangleNeonVectorType(T
);
2313 Out
<< "Dv" << T
->getNumElements() << '_';
2314 if (T
->getVectorKind() == VectorType::AltiVecPixel
)
2316 else if (T
->getVectorKind() == VectorType::AltiVecBool
)
2319 mangleType(T
->getElementType());
2321 void CXXNameMangler::mangleType(const ExtVectorType
*T
) {
2322 mangleType(static_cast<const VectorType
*>(T
));
2324 void CXXNameMangler::mangleType(const DependentSizedExtVectorType
*T
) {
2326 mangleExpression(T
->getSizeExpr());
2328 mangleType(T
->getElementType());
2331 void CXXNameMangler::mangleType(const PackExpansionType
*T
) {
2332 // <type> ::= Dp <type> # pack expansion (C++0x)
2334 mangleType(T
->getPattern());
2337 void CXXNameMangler::mangleType(const ObjCInterfaceType
*T
) {
2338 mangleSourceName(T
->getDecl()->getIdentifier());
2341 void CXXNameMangler::mangleType(const ObjCObjectType
*T
) {
2342 if (!T
->qual_empty()) {
2343 // Mangle protocol qualifiers.
2344 SmallString
<64> QualStr
;
2345 llvm::raw_svector_ostream
QualOS(QualStr
);
2346 QualOS
<< "objcproto";
2347 for (const auto *I
: T
->quals()) {
2348 StringRef name
= I
->getName();
2349 QualOS
<< name
.size() << name
;
2352 Out
<< 'U' << QualStr
.size() << QualStr
;
2354 mangleType(T
->getBaseType());
2357 void CXXNameMangler::mangleType(const BlockPointerType
*T
) {
2358 Out
<< "U13block_pointer";
2359 mangleType(T
->getPointeeType());
2362 void CXXNameMangler::mangleType(const InjectedClassNameType
*T
) {
2363 // Mangle injected class name types as if the user had written the
2364 // specialization out fully. It may not actually be possible to see
2365 // this mangling, though.
2366 mangleType(T
->getInjectedSpecializationType());
2369 void CXXNameMangler::mangleType(const TemplateSpecializationType
*T
) {
2370 if (TemplateDecl
*TD
= T
->getTemplateName().getAsTemplateDecl()) {
2371 mangleName(TD
, T
->getArgs(), T
->getNumArgs());
2373 if (mangleSubstitution(QualType(T
, 0)))
2376 mangleTemplatePrefix(T
->getTemplateName());
2378 // FIXME: GCC does not appear to mangle the template arguments when
2379 // the template in question is a dependent template name. Should we
2380 // emulate that badness?
2381 mangleTemplateArgs(T
->getArgs(), T
->getNumArgs());
2382 addSubstitution(QualType(T
, 0));
2386 void CXXNameMangler::mangleType(const DependentNameType
*T
) {
2387 // Proposal by cxx-abi-dev, 2014-03-26
2388 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2389 // # dependent elaborated type specifier using
2391 // ::= Ts <name> # dependent elaborated type specifier using
2392 // # 'struct' or 'class'
2393 // ::= Tu <name> # dependent elaborated type specifier using
2395 // ::= Te <name> # dependent elaborated type specifier using
2397 switch (T
->getKeyword()) {
2412 llvm_unreachable("unexpected keyword for dependent type name");
2414 // Typename types are always nested
2416 manglePrefix(T
->getQualifier());
2417 mangleSourceName(T
->getIdentifier());
2421 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType
*T
) {
2422 // Dependently-scoped template types are nested if they have a prefix.
2425 // TODO: avoid making this TemplateName.
2426 TemplateName Prefix
=
2427 getASTContext().getDependentTemplateName(T
->getQualifier(),
2428 T
->getIdentifier());
2429 mangleTemplatePrefix(Prefix
);
2431 // FIXME: GCC does not appear to mangle the template arguments when
2432 // the template in question is a dependent template name. Should we
2433 // emulate that badness?
2434 mangleTemplateArgs(T
->getArgs(), T
->getNumArgs());
2438 void CXXNameMangler::mangleType(const TypeOfType
*T
) {
2439 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2440 // "extension with parameters" mangling.
2444 void CXXNameMangler::mangleType(const TypeOfExprType
*T
) {
2445 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2446 // "extension with parameters" mangling.
2450 void CXXNameMangler::mangleType(const DecltypeType
*T
) {
2451 Expr
*E
= T
->getUnderlyingExpr();
2453 // type ::= Dt <expression> E # decltype of an id-expression
2454 // # or class member access
2455 // ::= DT <expression> E # decltype of an expression
2457 // This purports to be an exhaustive list of id-expressions and
2458 // class member accesses. Note that we do not ignore parentheses;
2459 // parentheses change the semantics of decltype for these
2460 // expressions (and cause the mangler to use the other form).
2461 if (isa
<DeclRefExpr
>(E
) ||
2462 isa
<MemberExpr
>(E
) ||
2463 isa
<UnresolvedLookupExpr
>(E
) ||
2464 isa
<DependentScopeDeclRefExpr
>(E
) ||
2465 isa
<CXXDependentScopeMemberExpr
>(E
) ||
2466 isa
<UnresolvedMemberExpr
>(E
))
2470 mangleExpression(E
);
2474 void CXXNameMangler::mangleType(const UnaryTransformType
*T
) {
2475 // If this is dependent, we need to record that. If not, we simply
2476 // mangle it as the underlying type since they are equivalent.
2477 if (T
->isDependentType()) {
2480 switch (T
->getUTTKind()) {
2481 case UnaryTransformType::EnumUnderlyingType
:
2487 mangleType(T
->getUnderlyingType());
2490 void CXXNameMangler::mangleType(const AutoType
*T
) {
2491 QualType D
= T
->getDeducedType();
2492 // <builtin-type> ::= Da # dependent auto
2494 Out
<< (T
->isDecltypeAuto() ? "Dc" : "Da");
2499 void CXXNameMangler::mangleType(const AtomicType
*T
) {
2500 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2501 // (Until there's a standardized mangling...)
2503 mangleType(T
->getValueType());
2506 void CXXNameMangler::mangleIntegerLiteral(QualType T
,
2507 const llvm::APSInt
&Value
) {
2508 // <expr-primary> ::= L <type> <value number> E # integer literal
2512 if (T
->isBooleanType()) {
2513 // Boolean values are encoded as 0/1.
2514 Out
<< (Value
.getBoolValue() ? '1' : '0');
2516 mangleNumber(Value
);
2522 /// Mangles a member expression.
2523 void CXXNameMangler::mangleMemberExpr(const Expr
*base
,
2525 NestedNameSpecifier
*qualifier
,
2526 NamedDecl
*firstQualifierLookup
,
2527 DeclarationName member
,
2529 // <expression> ::= dt <expression> <unresolved-name>
2530 // ::= pt <expression> <unresolved-name>
2533 // Ignore member expressions involving anonymous unions.
2534 while (const auto *RT
= base
->getType()->getAs
<RecordType
>()) {
2535 if (!RT
->getDecl()->isAnonymousStructOrUnion())
2537 const auto *ME
= dyn_cast
<MemberExpr
>(base
);
2540 base
= ME
->getBase();
2541 isArrow
= ME
->isArrow();
2544 if (base
->isImplicitCXXThis()) {
2545 // Note: GCC mangles member expressions to the implicit 'this' as
2546 // *this., whereas we represent them as this->. The Itanium C++ ABI
2547 // does not specify anything here, so we follow GCC.
2550 Out
<< (isArrow
? "pt" : "dt");
2551 mangleExpression(base
);
2554 mangleUnresolvedName(qualifier
, firstQualifierLookup
, member
, arity
);
2557 /// Look at the callee of the given call expression and determine if
2558 /// it's a parenthesized id-expression which would have triggered ADL
2560 static bool isParenthesizedADLCallee(const CallExpr
*call
) {
2561 const Expr
*callee
= call
->getCallee();
2562 const Expr
*fn
= callee
->IgnoreParens();
2564 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2565 // too, but for those to appear in the callee, it would have to be
2567 if (callee
== fn
) return false;
2569 // Must be an unresolved lookup.
2570 const UnresolvedLookupExpr
*lookup
= dyn_cast
<UnresolvedLookupExpr
>(fn
);
2571 if (!lookup
) return false;
2573 assert(!lookup
->requiresADL());
2575 // Must be an unqualified lookup.
2576 if (lookup
->getQualifier()) return false;
2578 // Must not have found a class member. Note that if one is a class
2579 // member, they're all class members.
2580 if (lookup
->getNumDecls() > 0 &&
2581 (*lookup
->decls_begin())->isCXXClassMember())
2584 // Otherwise, ADL would have been triggered.
2588 void CXXNameMangler::mangleCastExpression(const Expr
*E
, StringRef CastEncoding
) {
2589 const ExplicitCastExpr
*ECE
= cast
<ExplicitCastExpr
>(E
);
2590 Out
<< CastEncoding
;
2591 mangleType(ECE
->getType());
2592 mangleExpression(ECE
->getSubExpr());
2595 void CXXNameMangler::mangleExpression(const Expr
*E
, unsigned Arity
) {
2596 // <expression> ::= <unary operator-name> <expression>
2597 // ::= <binary operator-name> <expression> <expression>
2598 // ::= <trinary operator-name> <expression> <expression> <expression>
2599 // ::= cv <type> expression # conversion with one argument
2600 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2601 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2602 // ::= sc <type> <expression> # static_cast<type> (expression)
2603 // ::= cc <type> <expression> # const_cast<type> (expression)
2604 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
2605 // ::= st <type> # sizeof (a type)
2606 // ::= at <type> # alignof (a type)
2607 // ::= <template-param>
2608 // ::= <function-param>
2609 // ::= sr <type> <unqualified-name> # dependent name
2610 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2611 // ::= ds <expression> <expression> # expr.*expr
2612 // ::= sZ <template-param> # size of a parameter pack
2613 // ::= sZ <function-param> # size of a function parameter pack
2614 // ::= <expr-primary>
2615 // <expr-primary> ::= L <type> <value number> E # integer literal
2616 // ::= L <type <value float> E # floating literal
2617 // ::= L <mangled-name> E # external name
2618 // ::= fpT # 'this' expression
2619 QualType ImplicitlyConvertedToType
;
2622 switch (E
->getStmtClass()) {
2623 case Expr::NoStmtClass
:
2624 #define ABSTRACT_STMT(Type)
2625 #define EXPR(Type, Base)
2626 #define STMT(Type, Base) \
2627 case Expr::Type##Class:
2628 #include "clang/AST/StmtNodes.inc"
2631 // These all can only appear in local or variable-initialization
2632 // contexts and so should never appear in a mangling.
2633 case Expr::AddrLabelExprClass
:
2634 case Expr::DesignatedInitExprClass
:
2635 case Expr::ImplicitValueInitExprClass
:
2636 case Expr::ParenListExprClass
:
2637 case Expr::LambdaExprClass
:
2638 case Expr::MSPropertyRefExprClass
:
2639 case Expr::TypoExprClass
: // This should no longer exist in the AST by now.
2640 llvm_unreachable("unexpected statement kind");
2642 // FIXME: invent manglings for all these.
2643 case Expr::BlockExprClass
:
2644 case Expr::CXXPseudoDestructorExprClass
:
2645 case Expr::ChooseExprClass
:
2646 case Expr::CompoundLiteralExprClass
:
2647 case Expr::ExtVectorElementExprClass
:
2648 case Expr::GenericSelectionExprClass
:
2649 case Expr::ObjCEncodeExprClass
:
2650 case Expr::ObjCIsaExprClass
:
2651 case Expr::ObjCIvarRefExprClass
:
2652 case Expr::ObjCMessageExprClass
:
2653 case Expr::ObjCPropertyRefExprClass
:
2654 case Expr::ObjCProtocolExprClass
:
2655 case Expr::ObjCSelectorExprClass
:
2656 case Expr::ObjCStringLiteralClass
:
2657 case Expr::ObjCBoxedExprClass
:
2658 case Expr::ObjCArrayLiteralClass
:
2659 case Expr::ObjCDictionaryLiteralClass
:
2660 case Expr::ObjCSubscriptRefExprClass
:
2661 case Expr::ObjCIndirectCopyRestoreExprClass
:
2662 case Expr::OffsetOfExprClass
:
2663 case Expr::PredefinedExprClass
:
2664 case Expr::ShuffleVectorExprClass
:
2665 case Expr::ConvertVectorExprClass
:
2666 case Expr::StmtExprClass
:
2667 case Expr::TypeTraitExprClass
:
2668 case Expr::ArrayTypeTraitExprClass
:
2669 case Expr::ExpressionTraitExprClass
:
2670 case Expr::VAArgExprClass
:
2671 case Expr::CUDAKernelCallExprClass
:
2672 case Expr::AsTypeExprClass
:
2673 case Expr::PseudoObjectExprClass
:
2674 case Expr::AtomicExprClass
:
2676 // As bad as this diagnostic is, it's better than crashing.
2677 DiagnosticsEngine
&Diags
= Context
.getDiags();
2678 unsigned DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
2679 "cannot yet mangle expression type %0");
2680 Diags
.Report(E
->getExprLoc(), DiagID
)
2681 << E
->getStmtClassName() << E
->getSourceRange();
2685 case Expr::CXXUuidofExprClass
: {
2686 const CXXUuidofExpr
*UE
= cast
<CXXUuidofExpr
>(E
);
2687 if (UE
->isTypeOperand()) {
2688 QualType UuidT
= UE
->getTypeOperand(Context
.getASTContext());
2689 Out
<< "u8__uuidoft";
2692 Expr
*UuidExp
= UE
->getExprOperand();
2693 Out
<< "u8__uuidofz";
2694 mangleExpression(UuidExp
, Arity
);
2699 // Even gcc-4.5 doesn't mangle this.
2700 case Expr::BinaryConditionalOperatorClass
: {
2701 DiagnosticsEngine
&Diags
= Context
.getDiags();
2703 Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
2704 "?: operator with omitted middle operand cannot be mangled");
2705 Diags
.Report(E
->getExprLoc(), DiagID
)
2706 << E
->getStmtClassName() << E
->getSourceRange();
2710 // These are used for internal purposes and cannot be meaningfully mangled.
2711 case Expr::OpaqueValueExprClass
:
2712 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2714 case Expr::InitListExprClass
: {
2716 const InitListExpr
*InitList
= cast
<InitListExpr
>(E
);
2717 for (unsigned i
= 0, e
= InitList
->getNumInits(); i
!= e
; ++i
)
2718 mangleExpression(InitList
->getInit(i
));
2723 case Expr::CXXDefaultArgExprClass
:
2724 mangleExpression(cast
<CXXDefaultArgExpr
>(E
)->getExpr(), Arity
);
2727 case Expr::CXXDefaultInitExprClass
:
2728 mangleExpression(cast
<CXXDefaultInitExpr
>(E
)->getExpr(), Arity
);
2731 case Expr::CXXStdInitializerListExprClass
:
2732 mangleExpression(cast
<CXXStdInitializerListExpr
>(E
)->getSubExpr(), Arity
);
2735 case Expr::SubstNonTypeTemplateParmExprClass
:
2736 mangleExpression(cast
<SubstNonTypeTemplateParmExpr
>(E
)->getReplacement(),
2740 case Expr::UserDefinedLiteralClass
:
2741 // We follow g++'s approach of mangling a UDL as a call to the literal
2743 case Expr::CXXMemberCallExprClass
: // fallthrough
2744 case Expr::CallExprClass
: {
2745 const CallExpr
*CE
= cast
<CallExpr
>(E
);
2747 // <expression> ::= cp <simple-id> <expression>* E
2748 // We use this mangling only when the call would use ADL except
2749 // for being parenthesized. Per discussion with David
2750 // Vandervoorde, 2011.04.25.
2751 if (isParenthesizedADLCallee(CE
)) {
2753 // The callee here is a parenthesized UnresolvedLookupExpr with
2754 // no qualifier and should always get mangled as a <simple-id>
2757 // <expression> ::= cl <expression>* E
2762 mangleExpression(CE
->getCallee(), CE
->getNumArgs());
2763 for (unsigned I
= 0, N
= CE
->getNumArgs(); I
!= N
; ++I
)
2764 mangleExpression(CE
->getArg(I
));
2769 case Expr::CXXNewExprClass
: {
2770 const CXXNewExpr
*New
= cast
<CXXNewExpr
>(E
);
2771 if (New
->isGlobalNew()) Out
<< "gs";
2772 Out
<< (New
->isArray() ? "na" : "nw");
2773 for (CXXNewExpr::const_arg_iterator I
= New
->placement_arg_begin(),
2774 E
= New
->placement_arg_end(); I
!= E
; ++I
)
2775 mangleExpression(*I
);
2777 mangleType(New
->getAllocatedType());
2778 if (New
->hasInitializer()) {
2779 if (New
->getInitializationStyle() == CXXNewExpr::ListInit
)
2783 const Expr
*Init
= New
->getInitializer();
2784 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(Init
)) {
2785 // Directly inline the initializers.
2786 for (CXXConstructExpr::const_arg_iterator I
= CCE
->arg_begin(),
2789 mangleExpression(*I
);
2790 } else if (const ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(Init
)) {
2791 for (unsigned i
= 0, e
= PLE
->getNumExprs(); i
!= e
; ++i
)
2792 mangleExpression(PLE
->getExpr(i
));
2793 } else if (New
->getInitializationStyle() == CXXNewExpr::ListInit
&&
2794 isa
<InitListExpr
>(Init
)) {
2795 // Only take InitListExprs apart for list-initialization.
2796 const InitListExpr
*InitList
= cast
<InitListExpr
>(Init
);
2797 for (unsigned i
= 0, e
= InitList
->getNumInits(); i
!= e
; ++i
)
2798 mangleExpression(InitList
->getInit(i
));
2800 mangleExpression(Init
);
2806 case Expr::MemberExprClass
: {
2807 const MemberExpr
*ME
= cast
<MemberExpr
>(E
);
2808 mangleMemberExpr(ME
->getBase(), ME
->isArrow(),
2809 ME
->getQualifier(), nullptr,
2810 ME
->getMemberDecl()->getDeclName(), Arity
);
2814 case Expr::UnresolvedMemberExprClass
: {
2815 const UnresolvedMemberExpr
*ME
= cast
<UnresolvedMemberExpr
>(E
);
2816 mangleMemberExpr(ME
->getBase(), ME
->isArrow(),
2817 ME
->getQualifier(), nullptr, ME
->getMemberName(),
2819 if (ME
->hasExplicitTemplateArgs())
2820 mangleTemplateArgs(ME
->getExplicitTemplateArgs());
2824 case Expr::CXXDependentScopeMemberExprClass
: {
2825 const CXXDependentScopeMemberExpr
*ME
2826 = cast
<CXXDependentScopeMemberExpr
>(E
);
2827 mangleMemberExpr(ME
->getBase(), ME
->isArrow(),
2828 ME
->getQualifier(), ME
->getFirstQualifierFoundInScope(),
2829 ME
->getMember(), Arity
);
2830 if (ME
->hasExplicitTemplateArgs())
2831 mangleTemplateArgs(ME
->getExplicitTemplateArgs());
2835 case Expr::UnresolvedLookupExprClass
: {
2836 const UnresolvedLookupExpr
*ULE
= cast
<UnresolvedLookupExpr
>(E
);
2837 mangleUnresolvedName(ULE
->getQualifier(), nullptr, ULE
->getName(), Arity
);
2839 // All the <unresolved-name> productions end in a
2840 // base-unresolved-name, where <template-args> are just tacked
2842 if (ULE
->hasExplicitTemplateArgs())
2843 mangleTemplateArgs(ULE
->getExplicitTemplateArgs());
2847 case Expr::CXXUnresolvedConstructExprClass
: {
2848 const CXXUnresolvedConstructExpr
*CE
= cast
<CXXUnresolvedConstructExpr
>(E
);
2849 unsigned N
= CE
->arg_size();
2852 mangleType(CE
->getType());
2853 if (N
!= 1) Out
<< '_';
2854 for (unsigned I
= 0; I
!= N
; ++I
) mangleExpression(CE
->getArg(I
));
2855 if (N
!= 1) Out
<< 'E';
2859 case Expr::CXXTemporaryObjectExprClass
:
2860 case Expr::CXXConstructExprClass
: {
2861 const CXXConstructExpr
*CE
= cast
<CXXConstructExpr
>(E
);
2862 unsigned N
= CE
->getNumArgs();
2864 if (CE
->isListInitialization())
2868 mangleType(CE
->getType());
2869 if (N
!= 1) Out
<< '_';
2870 for (unsigned I
= 0; I
!= N
; ++I
) mangleExpression(CE
->getArg(I
));
2871 if (N
!= 1) Out
<< 'E';
2875 case Expr::CXXScalarValueInitExprClass
:
2877 mangleType(E
->getType());
2881 case Expr::CXXNoexceptExprClass
:
2883 mangleExpression(cast
<CXXNoexceptExpr
>(E
)->getOperand());
2886 case Expr::UnaryExprOrTypeTraitExprClass
: {
2887 const UnaryExprOrTypeTraitExpr
*SAE
= cast
<UnaryExprOrTypeTraitExpr
>(E
);
2889 if (!SAE
->isInstantiationDependent()) {
2891 // If the operand of a sizeof or alignof operator is not
2892 // instantiation-dependent it is encoded as an integer literal
2893 // reflecting the result of the operator.
2895 // If the result of the operator is implicitly converted to a known
2896 // integer type, that type is used for the literal; otherwise, the type
2897 // of std::size_t or std::ptrdiff_t is used.
2898 QualType T
= (ImplicitlyConvertedToType
.isNull() ||
2899 !ImplicitlyConvertedToType
->isIntegerType())? SAE
->getType()
2900 : ImplicitlyConvertedToType
;
2901 llvm::APSInt V
= SAE
->EvaluateKnownConstInt(Context
.getASTContext());
2902 mangleIntegerLiteral(T
, V
);
2906 switch(SAE
->getKind()) {
2914 DiagnosticsEngine
&Diags
= Context
.getDiags();
2915 unsigned DiagID
= Diags
.getCustomDiagID(DiagnosticsEngine::Error
,
2916 "cannot yet mangle vec_step expression");
2917 Diags
.Report(DiagID
);
2920 if (SAE
->isArgumentType()) {
2922 mangleType(SAE
->getArgumentType());
2925 mangleExpression(SAE
->getArgumentExpr());
2930 case Expr::CXXThrowExprClass
: {
2931 const CXXThrowExpr
*TE
= cast
<CXXThrowExpr
>(E
);
2932 // <expression> ::= tw <expression> # throw expression
2934 if (TE
->getSubExpr()) {
2936 mangleExpression(TE
->getSubExpr());
2943 case Expr::CXXTypeidExprClass
: {
2944 const CXXTypeidExpr
*TIE
= cast
<CXXTypeidExpr
>(E
);
2945 // <expression> ::= ti <type> # typeid (type)
2946 // ::= te <expression> # typeid (expression)
2947 if (TIE
->isTypeOperand()) {
2949 mangleType(TIE
->getTypeOperand(Context
.getASTContext()));
2952 mangleExpression(TIE
->getExprOperand());
2957 case Expr::CXXDeleteExprClass
: {
2958 const CXXDeleteExpr
*DE
= cast
<CXXDeleteExpr
>(E
);
2959 // <expression> ::= [gs] dl <expression> # [::] delete expr
2960 // ::= [gs] da <expression> # [::] delete [] expr
2961 if (DE
->isGlobalDelete()) Out
<< "gs";
2962 Out
<< (DE
->isArrayForm() ? "da" : "dl");
2963 mangleExpression(DE
->getArgument());
2967 case Expr::UnaryOperatorClass
: {
2968 const UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
2969 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO
->getOpcode()),
2971 mangleExpression(UO
->getSubExpr());
2975 case Expr::ArraySubscriptExprClass
: {
2976 const ArraySubscriptExpr
*AE
= cast
<ArraySubscriptExpr
>(E
);
2978 // Array subscript is treated as a syntactically weird form of
2981 mangleExpression(AE
->getLHS());
2982 mangleExpression(AE
->getRHS());
2986 case Expr::CompoundAssignOperatorClass
: // fallthrough
2987 case Expr::BinaryOperatorClass
: {
2988 const BinaryOperator
*BO
= cast
<BinaryOperator
>(E
);
2989 if (BO
->getOpcode() == BO_PtrMemD
)
2992 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO
->getOpcode()),
2994 mangleExpression(BO
->getLHS());
2995 mangleExpression(BO
->getRHS());
2999 case Expr::ConditionalOperatorClass
: {
3000 const ConditionalOperator
*CO
= cast
<ConditionalOperator
>(E
);
3001 mangleOperatorName(OO_Conditional
, /*Arity=*/3);
3002 mangleExpression(CO
->getCond());
3003 mangleExpression(CO
->getLHS(), Arity
);
3004 mangleExpression(CO
->getRHS(), Arity
);
3008 case Expr::ImplicitCastExprClass
: {
3009 ImplicitlyConvertedToType
= E
->getType();
3010 E
= cast
<ImplicitCastExpr
>(E
)->getSubExpr();
3014 case Expr::ObjCBridgedCastExprClass
: {
3015 // Mangle ownership casts as a vendor extended operator __bridge,
3016 // __bridge_transfer, or __bridge_retain.
3017 StringRef Kind
= cast
<ObjCBridgedCastExpr
>(E
)->getBridgeKindName();
3018 Out
<< "v1U" << Kind
.size() << Kind
;
3020 // Fall through to mangle the cast itself.
3022 case Expr::CStyleCastExprClass
:
3023 case Expr::CXXFunctionalCastExprClass
:
3024 mangleCastExpression(E
, "cv");
3027 case Expr::CXXStaticCastExprClass
:
3028 mangleCastExpression(E
, "sc");
3030 case Expr::CXXDynamicCastExprClass
:
3031 mangleCastExpression(E
, "dc");
3033 case Expr::CXXReinterpretCastExprClass
:
3034 mangleCastExpression(E
, "rc");
3036 case Expr::CXXConstCastExprClass
:
3037 mangleCastExpression(E
, "cc");
3040 case Expr::CXXOperatorCallExprClass
: {
3041 const CXXOperatorCallExpr
*CE
= cast
<CXXOperatorCallExpr
>(E
);
3042 unsigned NumArgs
= CE
->getNumArgs();
3043 mangleOperatorName(CE
->getOperator(), /*Arity=*/NumArgs
);
3044 // Mangle the arguments.
3045 for (unsigned i
= 0; i
!= NumArgs
; ++i
)
3046 mangleExpression(CE
->getArg(i
));
3050 case Expr::ParenExprClass
:
3051 mangleExpression(cast
<ParenExpr
>(E
)->getSubExpr(), Arity
);
3054 case Expr::DeclRefExprClass
: {
3055 const NamedDecl
*D
= cast
<DeclRefExpr
>(E
)->getDecl();
3057 switch (D
->getKind()) {
3059 // <expr-primary> ::= L <mangled-name> E # external name
3066 mangleFunctionParam(cast
<ParmVarDecl
>(D
));
3069 case Decl::EnumConstant
: {
3070 const EnumConstantDecl
*ED
= cast
<EnumConstantDecl
>(D
);
3071 mangleIntegerLiteral(ED
->getType(), ED
->getInitVal());
3075 case Decl::NonTypeTemplateParm
: {
3076 const NonTypeTemplateParmDecl
*PD
= cast
<NonTypeTemplateParmDecl
>(D
);
3077 mangleTemplateParameter(PD
->getIndex());
3086 case Expr::SubstNonTypeTemplateParmPackExprClass
:
3087 // FIXME: not clear how to mangle this!
3088 // template <unsigned N...> class A {
3089 // template <class U...> void foo(U (&x)[N]...);
3091 Out
<< "_SUBSTPACK_";
3094 case Expr::FunctionParmPackExprClass
: {
3095 // FIXME: not clear how to mangle this!
3096 const FunctionParmPackExpr
*FPPE
= cast
<FunctionParmPackExpr
>(E
);
3097 Out
<< "v110_SUBSTPACK";
3098 mangleFunctionParam(FPPE
->getParameterPack());
3102 case Expr::DependentScopeDeclRefExprClass
: {
3103 const DependentScopeDeclRefExpr
*DRE
= cast
<DependentScopeDeclRefExpr
>(E
);
3104 mangleUnresolvedName(DRE
->getQualifier(), nullptr, DRE
->getDeclName(),
3107 // All the <unresolved-name> productions end in a
3108 // base-unresolved-name, where <template-args> are just tacked
3110 if (DRE
->hasExplicitTemplateArgs())
3111 mangleTemplateArgs(DRE
->getExplicitTemplateArgs());
3115 case Expr::CXXBindTemporaryExprClass
:
3116 mangleExpression(cast
<CXXBindTemporaryExpr
>(E
)->getSubExpr());
3119 case Expr::ExprWithCleanupsClass
:
3120 mangleExpression(cast
<ExprWithCleanups
>(E
)->getSubExpr(), Arity
);
3123 case Expr::FloatingLiteralClass
: {
3124 const FloatingLiteral
*FL
= cast
<FloatingLiteral
>(E
);
3126 mangleType(FL
->getType());
3127 mangleFloat(FL
->getValue());
3132 case Expr::CharacterLiteralClass
:
3134 mangleType(E
->getType());
3135 Out
<< cast
<CharacterLiteral
>(E
)->getValue();
3139 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3140 case Expr::ObjCBoolLiteralExprClass
:
3142 Out
<< (cast
<ObjCBoolLiteralExpr
>(E
)->getValue() ? '1' : '0');
3146 case Expr::CXXBoolLiteralExprClass
:
3148 Out
<< (cast
<CXXBoolLiteralExpr
>(E
)->getValue() ? '1' : '0');
3152 case Expr::IntegerLiteralClass
: {
3153 llvm::APSInt
Value(cast
<IntegerLiteral
>(E
)->getValue());
3154 if (E
->getType()->isSignedIntegerType())
3155 Value
.setIsSigned(true);
3156 mangleIntegerLiteral(E
->getType(), Value
);
3160 case Expr::ImaginaryLiteralClass
: {
3161 const ImaginaryLiteral
*IE
= cast
<ImaginaryLiteral
>(E
);
3162 // Mangle as if a complex literal.
3163 // Proposal from David Vandevoorde, 2010.06.30.
3165 mangleType(E
->getType());
3166 if (const FloatingLiteral
*Imag
=
3167 dyn_cast
<FloatingLiteral
>(IE
->getSubExpr())) {
3168 // Mangle a floating-point zero of the appropriate type.
3169 mangleFloat(llvm::APFloat(Imag
->getValue().getSemantics()));
3171 mangleFloat(Imag
->getValue());
3174 llvm::APSInt
Value(cast
<IntegerLiteral
>(IE
->getSubExpr())->getValue());
3175 if (IE
->getSubExpr()->getType()->isSignedIntegerType())
3176 Value
.setIsSigned(true);
3177 mangleNumber(Value
);
3183 case Expr::StringLiteralClass
: {
3184 // Revised proposal from David Vandervoorde, 2010.07.15.
3186 assert(isa
<ConstantArrayType
>(E
->getType()));
3187 mangleType(E
->getType());
3192 case Expr::GNUNullExprClass
:
3193 // FIXME: should this really be mangled the same as nullptr?
3196 case Expr::CXXNullPtrLiteralExprClass
: {
3201 case Expr::PackExpansionExprClass
:
3203 mangleExpression(cast
<PackExpansionExpr
>(E
)->getPattern());
3206 case Expr::SizeOfPackExprClass
: {
3208 const NamedDecl
*Pack
= cast
<SizeOfPackExpr
>(E
)->getPack();
3209 if (const TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Pack
))
3210 mangleTemplateParameter(TTP
->getIndex());
3211 else if (const NonTypeTemplateParmDecl
*NTTP
3212 = dyn_cast
<NonTypeTemplateParmDecl
>(Pack
))
3213 mangleTemplateParameter(NTTP
->getIndex());
3214 else if (const TemplateTemplateParmDecl
*TempTP
3215 = dyn_cast
<TemplateTemplateParmDecl
>(Pack
))
3216 mangleTemplateParameter(TempTP
->getIndex());
3218 mangleFunctionParam(cast
<ParmVarDecl
>(Pack
));
3222 case Expr::MaterializeTemporaryExprClass
: {
3223 mangleExpression(cast
<MaterializeTemporaryExpr
>(E
)->GetTemporaryExpr());
3227 case Expr::CXXFoldExprClass
: {
3228 auto *FE
= cast
<CXXFoldExpr
>(E
);
3229 if (FE
->isLeftFold())
3230 Out
<< (FE
->getInit() ? "fL" : "fl");
3232 Out
<< (FE
->getInit() ? "fR" : "fr");
3234 if (FE
->getOperator() == BO_PtrMemD
)
3238 BinaryOperator::getOverloadedOperator(FE
->getOperator()),
3242 mangleExpression(FE
->getLHS());
3244 mangleExpression(FE
->getRHS());
3248 case Expr::CXXThisExprClass
:
3254 /// Mangle an expression which refers to a parameter variable.
3256 /// <expression> ::= <function-param>
3257 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3258 /// <function-param> ::= fp <top-level CV-qualifiers>
3259 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3260 /// <function-param> ::= fL <L-1 non-negative number>
3261 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3262 /// <function-param> ::= fL <L-1 non-negative number>
3263 /// p <top-level CV-qualifiers>
3264 /// <I-1 non-negative number> _ # L > 0, I > 0
3266 /// L is the nesting depth of the parameter, defined as 1 if the
3267 /// parameter comes from the innermost function prototype scope
3268 /// enclosing the current context, 2 if from the next enclosing
3269 /// function prototype scope, and so on, with one special case: if
3270 /// we've processed the full parameter clause for the innermost
3271 /// function type, then L is one less. This definition conveniently
3272 /// makes it irrelevant whether a function's result type was written
3273 /// trailing or leading, but is otherwise overly complicated; the
3274 /// numbering was first designed without considering references to
3275 /// parameter in locations other than return types, and then the
3276 /// mangling had to be generalized without changing the existing
3279 /// I is the zero-based index of the parameter within its parameter
3280 /// declaration clause. Note that the original ABI document describes
3281 /// this using 1-based ordinals.
3282 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl
*parm
) {
3283 unsigned parmDepth
= parm
->getFunctionScopeDepth();
3284 unsigned parmIndex
= parm
->getFunctionScopeIndex();
3287 // parmDepth does not include the declaring function prototype.
3288 // FunctionTypeDepth does account for that.
3289 assert(parmDepth
< FunctionTypeDepth
.getDepth());
3290 unsigned nestingDepth
= FunctionTypeDepth
.getDepth() - parmDepth
;
3291 if (FunctionTypeDepth
.isInResultType())
3294 if (nestingDepth
== 0) {
3297 Out
<< "fL" << (nestingDepth
- 1) << 'p';
3300 // Top-level qualifiers. We don't have to worry about arrays here,
3301 // because parameters declared as arrays should already have been
3302 // transformed to have pointer type. FIXME: apparently these don't
3303 // get mangled if used as an rvalue of a known non-class type?
3304 assert(!parm
->getType()->isArrayType()
3305 && "parameter's type is still an array type?");
3306 mangleQualifiers(parm
->getType().getQualifiers());
3309 if (parmIndex
!= 0) {
3310 Out
<< (parmIndex
- 1);
3315 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T
) {
3316 // <ctor-dtor-name> ::= C1 # complete object constructor
3317 // ::= C2 # base object constructor
3319 // In addition, C5 is a comdat name with C1 and C2 in it.
3333 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T
) {
3334 // <ctor-dtor-name> ::= D0 # deleting destructor
3335 // ::= D1 # complete object destructor
3336 // ::= D2 # base object destructor
3338 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
3355 void CXXNameMangler::mangleTemplateArgs(
3356 const ASTTemplateArgumentListInfo
&TemplateArgs
) {
3357 // <template-args> ::= I <template-arg>+ E
3359 for (unsigned i
= 0, e
= TemplateArgs
.NumTemplateArgs
; i
!= e
; ++i
)
3360 mangleTemplateArg(TemplateArgs
.getTemplateArgs()[i
].getArgument());
3364 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList
&AL
) {
3365 // <template-args> ::= I <template-arg>+ E
3367 for (unsigned i
= 0, e
= AL
.size(); i
!= e
; ++i
)
3368 mangleTemplateArg(AL
[i
]);
3372 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument
*TemplateArgs
,
3373 unsigned NumTemplateArgs
) {
3374 // <template-args> ::= I <template-arg>+ E
3376 for (unsigned i
= 0; i
!= NumTemplateArgs
; ++i
)
3377 mangleTemplateArg(TemplateArgs
[i
]);
3381 void CXXNameMangler::mangleTemplateArg(TemplateArgument A
) {
3382 // <template-arg> ::= <type> # type or template
3383 // ::= X <expression> E # expression
3384 // ::= <expr-primary> # simple expressions
3385 // ::= J <template-arg>* E # argument pack
3386 if (!A
.isInstantiationDependent() || A
.isDependent())
3387 A
= Context
.getASTContext().getCanonicalTemplateArgument(A
);
3389 switch (A
.getKind()) {
3390 case TemplateArgument::Null
:
3391 llvm_unreachable("Cannot mangle NULL template argument");
3393 case TemplateArgument::Type
:
3394 mangleType(A
.getAsType());
3396 case TemplateArgument::Template
:
3397 // This is mangled as <type>.
3398 mangleType(A
.getAsTemplate());
3400 case TemplateArgument::TemplateExpansion
:
3401 // <type> ::= Dp <type> # pack expansion (C++0x)
3403 mangleType(A
.getAsTemplateOrTemplatePattern());
3405 case TemplateArgument::Expression
: {
3406 // It's possible to end up with a DeclRefExpr here in certain
3407 // dependent cases, in which case we should mangle as a
3409 const Expr
*E
= A
.getAsExpr()->IgnoreParens();
3410 if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
3411 const ValueDecl
*D
= DRE
->getDecl();
3412 if (isa
<VarDecl
>(D
) || isa
<FunctionDecl
>(D
)) {
3421 mangleExpression(E
);
3425 case TemplateArgument::Integral
:
3426 mangleIntegerLiteral(A
.getIntegralType(), A
.getAsIntegral());
3428 case TemplateArgument::Declaration
: {
3429 // <expr-primary> ::= L <mangled-name> E # external name
3430 // Clang produces AST's where pointer-to-member-function expressions
3431 // and pointer-to-function expressions are represented as a declaration not
3432 // an expression. We compensate for it here to produce the correct mangling.
3433 ValueDecl
*D
= A
.getAsDecl();
3434 bool compensateMangling
= !A
.getParamTypeForDecl()->isReferenceType();
3435 if (compensateMangling
) {
3437 mangleOperatorName(OO_Amp
, 1);
3441 // References to external entities use the mangled name; if the name would
3442 // not normally be manged then mangle it as unqualified.
3444 // FIXME: The ABI specifies that external names here should have _Z, but
3445 // gcc leaves this off.
3446 if (compensateMangling
)
3452 if (compensateMangling
)
3457 case TemplateArgument::NullPtr
: {
3458 // <expr-primary> ::= L <type> 0 E
3460 mangleType(A
.getNullPtrType());
3464 case TemplateArgument::Pack
: {
3465 // <template-arg> ::= J <template-arg>* E
3467 for (const auto &P
: A
.pack_elements())
3468 mangleTemplateArg(P
);
3474 void CXXNameMangler::mangleTemplateParameter(unsigned Index
) {
3475 // <template-param> ::= T_ # first template parameter
3476 // ::= T <parameter-2 non-negative number> _
3480 Out
<< 'T' << (Index
- 1) << '_';
3483 void CXXNameMangler::mangleSeqID(unsigned SeqID
) {
3486 else if (SeqID
> 1) {
3489 // <seq-id> is encoded in base-36, using digits and upper case letters.
3490 char Buffer
[7]; // log(2**32) / log(36) ~= 7
3491 MutableArrayRef
<char> BufferRef(Buffer
);
3492 MutableArrayRef
<char>::reverse_iterator I
= BufferRef
.rbegin();
3494 for (; SeqID
!= 0; SeqID
/= 36) {
3495 unsigned C
= SeqID
% 36;
3496 *I
++ = (C
< 10 ? '0' + C
: 'A' + C
- 10);
3499 Out
.write(I
.base(), I
- BufferRef
.rbegin());
3504 void CXXNameMangler::mangleExistingSubstitution(QualType type
) {
3505 bool result
= mangleSubstitution(type
);
3506 assert(result
&& "no existing substitution for type");
3510 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname
) {
3511 bool result
= mangleSubstitution(tname
);
3512 assert(result
&& "no existing substitution for template name");
3516 // <substitution> ::= S <seq-id> _
3518 bool CXXNameMangler::mangleSubstitution(const NamedDecl
*ND
) {
3519 // Try one of the standard substitutions first.
3520 if (mangleStandardSubstitution(ND
))
3523 ND
= cast
<NamedDecl
>(ND
->getCanonicalDecl());
3524 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND
));
3527 /// \brief Determine whether the given type has any qualifiers that are
3528 /// relevant for substitutions.
3529 static bool hasMangledSubstitutionQualifiers(QualType T
) {
3530 Qualifiers Qs
= T
.getQualifiers();
3531 return Qs
.getCVRQualifiers() || Qs
.hasAddressSpace();
3534 bool CXXNameMangler::mangleSubstitution(QualType T
) {
3535 if (!hasMangledSubstitutionQualifiers(T
)) {
3536 if (const RecordType
*RT
= T
->getAs
<RecordType
>())
3537 return mangleSubstitution(RT
->getDecl());
3540 uintptr_t TypePtr
= reinterpret_cast<uintptr_t>(T
.getAsOpaquePtr());
3542 return mangleSubstitution(TypePtr
);
3545 bool CXXNameMangler::mangleSubstitution(TemplateName Template
) {
3546 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
3547 return mangleSubstitution(TD
);
3549 Template
= Context
.getASTContext().getCanonicalTemplateName(Template
);
3550 return mangleSubstitution(
3551 reinterpret_cast<uintptr_t>(Template
.getAsVoidPointer()));
3554 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr
) {
3555 llvm::DenseMap
<uintptr_t, unsigned>::iterator I
= Substitutions
.find(Ptr
);
3556 if (I
== Substitutions
.end())
3559 unsigned SeqID
= I
->second
;
3566 static bool isCharType(QualType T
) {
3570 return T
->isSpecificBuiltinType(BuiltinType::Char_S
) ||
3571 T
->isSpecificBuiltinType(BuiltinType::Char_U
);
3574 /// isCharSpecialization - Returns whether a given type is a template
3575 /// specialization of a given name with a single argument of type char.
3576 static bool isCharSpecialization(QualType T
, const char *Name
) {
3580 const RecordType
*RT
= T
->getAs
<RecordType
>();
3584 const ClassTemplateSpecializationDecl
*SD
=
3585 dyn_cast
<ClassTemplateSpecializationDecl
>(RT
->getDecl());
3589 if (!isStdNamespace(getEffectiveDeclContext(SD
)))
3592 const TemplateArgumentList
&TemplateArgs
= SD
->getTemplateArgs();
3593 if (TemplateArgs
.size() != 1)
3596 if (!isCharType(TemplateArgs
[0].getAsType()))
3599 return SD
->getIdentifier()->getName() == Name
;
3602 template <std::size_t StrLen
>
3603 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl
*SD
,
3604 const char (&Str
)[StrLen
]) {
3605 if (!SD
->getIdentifier()->isStr(Str
))
3608 const TemplateArgumentList
&TemplateArgs
= SD
->getTemplateArgs();
3609 if (TemplateArgs
.size() != 2)
3612 if (!isCharType(TemplateArgs
[0].getAsType()))
3615 if (!isCharSpecialization(TemplateArgs
[1].getAsType(), "char_traits"))
3621 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl
*ND
) {
3622 // <substitution> ::= St # ::std::
3623 if (const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(ND
)) {
3630 if (const ClassTemplateDecl
*TD
= dyn_cast
<ClassTemplateDecl
>(ND
)) {
3631 if (!isStdNamespace(getEffectiveDeclContext(TD
)))
3634 // <substitution> ::= Sa # ::std::allocator
3635 if (TD
->getIdentifier()->isStr("allocator")) {
3640 // <<substitution> ::= Sb # ::std::basic_string
3641 if (TD
->getIdentifier()->isStr("basic_string")) {
3647 if (const ClassTemplateSpecializationDecl
*SD
=
3648 dyn_cast
<ClassTemplateSpecializationDecl
>(ND
)) {
3649 if (!isStdNamespace(getEffectiveDeclContext(SD
)))
3652 // <substitution> ::= Ss # ::std::basic_string<char,
3653 // ::std::char_traits<char>,
3654 // ::std::allocator<char> >
3655 if (SD
->getIdentifier()->isStr("basic_string")) {
3656 const TemplateArgumentList
&TemplateArgs
= SD
->getTemplateArgs();
3658 if (TemplateArgs
.size() != 3)
3661 if (!isCharType(TemplateArgs
[0].getAsType()))
3664 if (!isCharSpecialization(TemplateArgs
[1].getAsType(), "char_traits"))
3667 if (!isCharSpecialization(TemplateArgs
[2].getAsType(), "allocator"))
3674 // <substitution> ::= Si # ::std::basic_istream<char,
3675 // ::std::char_traits<char> >
3676 if (isStreamCharSpecialization(SD
, "basic_istream")) {
3681 // <substitution> ::= So # ::std::basic_ostream<char,
3682 // ::std::char_traits<char> >
3683 if (isStreamCharSpecialization(SD
, "basic_ostream")) {
3688 // <substitution> ::= Sd # ::std::basic_iostream<char,
3689 // ::std::char_traits<char> >
3690 if (isStreamCharSpecialization(SD
, "basic_iostream")) {
3698 void CXXNameMangler::addSubstitution(QualType T
) {
3699 if (!hasMangledSubstitutionQualifiers(T
)) {
3700 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
3701 addSubstitution(RT
->getDecl());
3706 uintptr_t TypePtr
= reinterpret_cast<uintptr_t>(T
.getAsOpaquePtr());
3707 addSubstitution(TypePtr
);
3710 void CXXNameMangler::addSubstitution(TemplateName Template
) {
3711 if (TemplateDecl
*TD
= Template
.getAsTemplateDecl())
3712 return addSubstitution(TD
);
3714 Template
= Context
.getASTContext().getCanonicalTemplateName(Template
);
3715 addSubstitution(reinterpret_cast<uintptr_t>(Template
.getAsVoidPointer()));
3718 void CXXNameMangler::addSubstitution(uintptr_t Ptr
) {
3719 assert(!Substitutions
.count(Ptr
) && "Substitution already exists!");
3720 Substitutions
[Ptr
] = SeqID
++;
3725 /// \brief Mangles the name of the declaration D and emits that name to the
3726 /// given output stream.
3728 /// If the declaration D requires a mangled name, this routine will emit that
3729 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3730 /// and this routine will return false. In this case, the caller should just
3731 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3733 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl
*D
,
3735 assert((isa
<FunctionDecl
>(D
) || isa
<VarDecl
>(D
)) &&
3736 "Invalid mangleName() call, argument is not a variable or function!");
3737 assert(!isa
<CXXConstructorDecl
>(D
) && !isa
<CXXDestructorDecl
>(D
) &&
3738 "Invalid mangleName() call on 'structor decl!");
3740 PrettyStackTraceDecl
CrashInfo(D
, SourceLocation(),
3741 getASTContext().getSourceManager(),
3742 "Mangling declaration");
3744 CXXNameMangler
Mangler(*this, Out
, D
);
3748 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl
*D
,
3751 CXXNameMangler
Mangler(*this, Out
, D
, Type
);
3755 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl
*D
,
3758 CXXNameMangler
Mangler(*this, Out
, D
, Type
);
3762 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl
*D
,
3764 CXXNameMangler
Mangler(*this, Out
, D
, Ctor_Comdat
);
3768 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl
*D
,
3770 CXXNameMangler
Mangler(*this, Out
, D
, Dtor_Comdat
);
3774 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl
*MD
,
3775 const ThunkInfo
&Thunk
,
3777 // <special-name> ::= T <call-offset> <base encoding>
3778 // # base is the nominal target function of thunk
3779 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3780 // # base is the nominal target function of thunk
3781 // # first call-offset is 'this' adjustment
3782 // # second call-offset is result adjustment
3784 assert(!isa
<CXXDestructorDecl
>(MD
) &&
3785 "Use mangleCXXDtor for destructor decls!");
3786 CXXNameMangler
Mangler(*this, Out
);
3787 Mangler
.getStream() << "_ZT";
3788 if (!Thunk
.Return
.isEmpty())
3789 Mangler
.getStream() << 'c';
3791 // Mangle the 'this' pointer adjustment.
3792 Mangler
.mangleCallOffset(Thunk
.This
.NonVirtual
,
3793 Thunk
.This
.Virtual
.Itanium
.VCallOffsetOffset
);
3795 // Mangle the return pointer adjustment if there is one.
3796 if (!Thunk
.Return
.isEmpty())
3797 Mangler
.mangleCallOffset(Thunk
.Return
.NonVirtual
,
3798 Thunk
.Return
.Virtual
.Itanium
.VBaseOffsetOffset
);
3800 Mangler
.mangleFunctionEncoding(MD
);
3803 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3804 const CXXDestructorDecl
*DD
, CXXDtorType Type
,
3805 const ThisAdjustment
&ThisAdjustment
, raw_ostream
&Out
) {
3806 // <special-name> ::= T <call-offset> <base encoding>
3807 // # base is the nominal target function of thunk
3808 CXXNameMangler
Mangler(*this, Out
, DD
, Type
);
3809 Mangler
.getStream() << "_ZT";
3811 // Mangle the 'this' pointer adjustment.
3812 Mangler
.mangleCallOffset(ThisAdjustment
.NonVirtual
,
3813 ThisAdjustment
.Virtual
.Itanium
.VCallOffsetOffset
);
3815 Mangler
.mangleFunctionEncoding(DD
);
3818 /// mangleGuardVariable - Returns the mangled name for a guard variable
3819 /// for the passed in VarDecl.
3820 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl
*D
,
3822 // <special-name> ::= GV <object name> # Guard variable for one-time
3824 CXXNameMangler
Mangler(*this, Out
);
3825 Mangler
.getStream() << "_ZGV";
3826 Mangler
.mangleName(D
);
3829 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl
*MD
,
3831 // These symbols are internal in the Itanium ABI, so the names don't matter.
3832 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3833 // avoid duplicate symbols.
3834 Out
<< "__cxx_global_var_init";
3837 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl
*D
,
3839 // Prefix the mangling of D with __dtor_.
3840 CXXNameMangler
Mangler(*this, Out
);
3841 Mangler
.getStream() << "__dtor_";
3842 if (shouldMangleDeclName(D
))
3845 Mangler
.getStream() << D
->getName();
3848 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl
*D
,
3850 // <special-name> ::= TH <object name>
3851 CXXNameMangler
Mangler(*this, Out
);
3852 Mangler
.getStream() << "_ZTH";
3853 Mangler
.mangleName(D
);
3857 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl
*D
,
3859 // <special-name> ::= TW <object name>
3860 CXXNameMangler
Mangler(*this, Out
);
3861 Mangler
.getStream() << "_ZTW";
3862 Mangler
.mangleName(D
);
3865 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl
*D
,
3866 unsigned ManglingNumber
,
3868 // We match the GCC mangling here.
3869 // <special-name> ::= GR <object name>
3870 CXXNameMangler
Mangler(*this, Out
);
3871 Mangler
.getStream() << "_ZGR";
3872 Mangler
.mangleName(D
);
3873 assert(ManglingNumber
> 0 && "Reference temporary mangling number is zero!");
3874 Mangler
.mangleSeqID(ManglingNumber
- 1);
3877 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl
*RD
,
3879 // <special-name> ::= TV <type> # virtual table
3880 CXXNameMangler
Mangler(*this, Out
);
3881 Mangler
.getStream() << "_ZTV";
3882 Mangler
.mangleNameOrStandardSubstitution(RD
);
3885 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl
*RD
,
3887 // <special-name> ::= TT <type> # VTT structure
3888 CXXNameMangler
Mangler(*this, Out
);
3889 Mangler
.getStream() << "_ZTT";
3890 Mangler
.mangleNameOrStandardSubstitution(RD
);
3893 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl
*RD
,
3895 const CXXRecordDecl
*Type
,
3897 // <special-name> ::= TC <type> <offset number> _ <base type>
3898 CXXNameMangler
Mangler(*this, Out
);
3899 Mangler
.getStream() << "_ZTC";
3900 Mangler
.mangleNameOrStandardSubstitution(RD
);
3901 Mangler
.getStream() << Offset
;
3902 Mangler
.getStream() << '_';
3903 Mangler
.mangleNameOrStandardSubstitution(Type
);
3906 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty
, raw_ostream
&Out
) {
3907 // <special-name> ::= TI <type> # typeinfo structure
3908 assert(!Ty
.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3909 CXXNameMangler
Mangler(*this, Out
);
3910 Mangler
.getStream() << "_ZTI";
3911 Mangler
.mangleType(Ty
);
3914 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty
,
3916 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3917 CXXNameMangler
Mangler(*this, Out
);
3918 Mangler
.getStream() << "_ZTS";
3919 Mangler
.mangleType(Ty
);
3922 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty
, raw_ostream
&Out
) {
3923 mangleCXXRTTIName(Ty
, Out
);
3926 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral
*, raw_ostream
&) {
3927 llvm_unreachable("Can't mangle string literals");
3930 ItaniumMangleContext
*
3931 ItaniumMangleContext::create(ASTContext
&Context
, DiagnosticsEngine
&Diags
) {
3932 return new ItaniumMangleContextImpl(Context
, Diags
);