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://www.codesourcery.com/public/cxx-abi/abi.html
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/ErrorHandling.h"
33 #define MANGLE_CHECKER 0
39 using namespace clang;
43 /// \brief Retrieve the declaration context that should be used when mangling
44 /// the given declaration.
45 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
46 // The ABI assumes that lambda closure types that occur within
47 // default arguments live in the context of the function. However, due to
48 // the way in which Clang parses and creates function declarations, this is
49 // not the case: the lambda closure type ends up living in the context
50 // where the function itself resides, because the function declaration itself
51 // had not yet been created. Fix the context here.
52 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
54 if (ParmVarDecl *ContextParam
55 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
56 return ContextParam->getDeclContext();
59 return D->getDeclContext();
62 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
63 return getEffectiveDeclContext(cast<Decl>(DC));
66 static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
67 const DeclContext *DC = dyn_cast<DeclContext>(ND);
69 DC = getEffectiveDeclContext(ND);
70 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
71 const DeclContext *Parent = getEffectiveDeclContext(cast<Decl>(DC));
72 if (isa<FunctionDecl>(Parent))
73 return dyn_cast<CXXRecordDecl>(DC);
79 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
80 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
81 return ftd->getTemplatedDecl();
86 static const NamedDecl *getStructor(const NamedDecl *decl) {
87 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
88 return (fn ? getStructor(fn) : decl);
91 static const unsigned UnknownArity = ~0U;
93 class ItaniumMangleContext : public MangleContext {
94 llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
95 unsigned Discriminator;
96 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
99 explicit ItaniumMangleContext(ASTContext &Context,
100 DiagnosticsEngine &Diags)
101 : MangleContext(Context, Diags) { }
103 uint64_t getAnonymousStructId(const TagDecl *TD) {
104 std::pair<llvm::DenseMap<const TagDecl *,
105 uint64_t>::iterator, bool> Result =
106 AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
107 return Result.first->second;
110 void startNewFunction() {
111 MangleContext::startNewFunction();
112 mangleInitDiscriminator();
115 /// @name Mangler Entry Points
118 bool shouldMangleDeclName(const NamedDecl *D);
119 void mangleName(const NamedDecl *D, raw_ostream &);
120 void mangleThunk(const CXXMethodDecl *MD,
121 const ThunkInfo &Thunk,
123 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
124 const ThisAdjustment &ThisAdjustment,
126 void mangleReferenceTemporary(const VarDecl *D,
128 void mangleCXXVTable(const CXXRecordDecl *RD,
130 void mangleCXXVTT(const CXXRecordDecl *RD,
132 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
133 const CXXRecordDecl *Type,
135 void mangleCXXRTTI(QualType T, raw_ostream &);
136 void mangleCXXRTTIName(QualType T, raw_ostream &);
137 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
139 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
142 void mangleItaniumGuardVariable(const VarDecl *D, raw_ostream &);
144 void mangleInitDiscriminator() {
148 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
149 // Lambda closure types with external linkage (indicated by a
150 // non-zero lambda mangling number) have their own numbering scheme, so
151 // they do not need a discriminator.
152 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND))
153 if (RD->isLambda() && RD->getLambdaManglingNumber() > 0)
156 unsigned &discriminator = Uniquifier[ND];
158 discriminator = ++Discriminator;
159 if (discriminator == 1)
161 disc = discriminator-2;
167 /// CXXNameMangler - Manage the mangling of a single name.
168 class CXXNameMangler {
169 ItaniumMangleContext &Context;
172 /// The "structor" is the top-level declaration being mangled, if
173 /// that's not a template specialization; otherwise it's the pattern
174 /// for that specialization.
175 const NamedDecl *Structor;
176 unsigned StructorType;
178 /// SeqID - The next subsitution sequence number.
181 class FunctionTypeDepthState {
184 enum { InResultTypeMask = 1 };
187 FunctionTypeDepthState() : Bits(0) {}
189 /// The number of function types we're inside.
190 unsigned getDepth() const {
194 /// True if we're in the return type of the innermost function type.
195 bool isInResultType() const {
196 return Bits & InResultTypeMask;
199 FunctionTypeDepthState push() {
200 FunctionTypeDepthState tmp = *this;
201 Bits = (Bits & ~InResultTypeMask) + 2;
205 void enterResultType() {
206 Bits |= InResultTypeMask;
209 void leaveResultType() {
210 Bits &= ~InResultTypeMask;
213 void pop(FunctionTypeDepthState saved) {
214 assert(getDepth() == saved.getDepth() + 1);
220 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
222 ASTContext &getASTContext() const { return Context.getASTContext(); }
225 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
226 const NamedDecl *D = 0)
227 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
229 // These can't be mangled without a ctor type or dtor type.
230 assert(!D || (!isa<CXXDestructorDecl>(D) &&
231 !isa<CXXConstructorDecl>(D)));
233 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
234 const CXXConstructorDecl *D, CXXCtorType Type)
235 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
237 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
238 const CXXDestructorDecl *D, CXXDtorType Type)
239 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
244 if (Out.str()[0] == '\01')
248 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
249 assert(status == 0 && "Could not demangle mangled name!");
253 raw_ostream &getStream() { return Out; }
255 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
256 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
257 void mangleNumber(const llvm::APSInt &I);
258 void mangleNumber(int64_t Number);
259 void mangleFloat(const llvm::APFloat &F);
260 void mangleFunctionEncoding(const FunctionDecl *FD);
261 void mangleName(const NamedDecl *ND);
262 void mangleType(QualType T);
263 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
266 bool mangleSubstitution(const NamedDecl *ND);
267 bool mangleSubstitution(QualType T);
268 bool mangleSubstitution(TemplateName Template);
269 bool mangleSubstitution(uintptr_t Ptr);
271 void mangleExistingSubstitution(QualType type);
272 void mangleExistingSubstitution(TemplateName name);
274 bool mangleStandardSubstitution(const NamedDecl *ND);
276 void addSubstitution(const NamedDecl *ND) {
277 ND = cast<NamedDecl>(ND->getCanonicalDecl());
279 addSubstitution(reinterpret_cast<uintptr_t>(ND));
281 void addSubstitution(QualType T);
282 void addSubstitution(TemplateName Template);
283 void addSubstitution(uintptr_t Ptr);
285 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
286 NamedDecl *firstQualifierLookup,
287 bool recursive = false);
288 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
289 NamedDecl *firstQualifierLookup,
290 DeclarationName name,
291 unsigned KnownArity = UnknownArity);
293 void mangleName(const TemplateDecl *TD,
294 const TemplateArgument *TemplateArgs,
295 unsigned NumTemplateArgs);
296 void mangleUnqualifiedName(const NamedDecl *ND) {
297 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
299 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
300 unsigned KnownArity);
301 void mangleUnscopedName(const NamedDecl *ND);
302 void mangleUnscopedTemplateName(const TemplateDecl *ND);
303 void mangleUnscopedTemplateName(TemplateName);
304 void mangleSourceName(const IdentifierInfo *II);
305 void mangleLocalName(const NamedDecl *ND);
306 void mangleLambda(const CXXRecordDecl *Lambda);
307 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
308 bool NoFunction=false);
309 void mangleNestedName(const TemplateDecl *TD,
310 const TemplateArgument *TemplateArgs,
311 unsigned NumTemplateArgs);
312 void manglePrefix(NestedNameSpecifier *qualifier);
313 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
314 void manglePrefix(QualType type);
315 void mangleTemplatePrefix(const TemplateDecl *ND);
316 void mangleTemplatePrefix(TemplateName Template);
317 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
318 void mangleQualifiers(Qualifiers Quals);
319 void mangleRefQualifier(RefQualifierKind RefQualifier);
321 void mangleObjCMethodName(const ObjCMethodDecl *MD);
323 // Declare manglers for every type class.
324 #define ABSTRACT_TYPE(CLASS, PARENT)
325 #define NON_CANONICAL_TYPE(CLASS, PARENT)
326 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
327 #include "clang/AST/TypeNodes.def"
329 void mangleType(const TagType*);
330 void mangleType(TemplateName);
331 void mangleBareFunctionType(const FunctionType *T,
332 bool MangleReturnType);
333 void mangleNeonVectorType(const VectorType *T);
335 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
336 void mangleMemberExpr(const Expr *base, bool isArrow,
337 NestedNameSpecifier *qualifier,
338 NamedDecl *firstQualifierLookup,
339 DeclarationName name,
340 unsigned knownArity);
341 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
342 void mangleCXXCtorType(CXXCtorType T);
343 void mangleCXXDtorType(CXXDtorType T);
345 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
346 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
347 unsigned NumTemplateArgs);
348 void mangleTemplateArgs(const TemplateArgumentList &AL);
349 void mangleTemplateArg(TemplateArgument A);
351 void mangleTemplateParameter(unsigned Index);
353 void mangleFunctionParam(const ParmVarDecl *parm);
358 static bool isInCLinkageSpecification(const Decl *D) {
359 D = D->getCanonicalDecl();
360 for (const DeclContext *DC = getEffectiveDeclContext(D);
361 !DC->isTranslationUnit(); DC = getEffectiveParentContext(DC)) {
362 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
363 return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
369 bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
370 // In C, functions with no attributes never need to be mangled. Fastpath them.
371 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
374 // Any decl can be declared with __asm("foo") on it, and this takes precedence
375 // over all other naming in the .o file.
376 if (D->hasAttr<AsmLabelAttr>())
379 // Clang's "overloadable" attribute extension to C/C++ implies name mangling
380 // (always) as does passing a C++ member function and a function
381 // whose name is not a simple identifier.
382 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
383 if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
384 !FD->getDeclName().isIdentifier()))
387 // Otherwise, no mangling is done outside C++ mode.
388 if (!getASTContext().getLangOpts().CPlusPlus)
391 // Variables at global scope with non-internal linkage are not mangled
393 const DeclContext *DC = getEffectiveDeclContext(D);
394 // Check for extern variable declared locally.
395 if (DC->isFunctionOrMethod() && D->hasLinkage())
396 while (!DC->isNamespace() && !DC->isTranslationUnit())
397 DC = getEffectiveParentContext(DC);
398 if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage)
402 // Class members are always mangled.
403 if (getEffectiveDeclContext(D)->isRecord())
406 // C functions and "main" are not mangled.
407 if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
413 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
414 // Any decl can be declared with __asm("foo") on it, and this takes precedence
415 // over all other naming in the .o file.
416 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
417 // If we have an asm name, then we use it as the mangling.
419 // Adding the prefix can cause problems when one file has a "foo" and
420 // another has a "\01foo". That is known to happen on ELF with the
421 // tricks normally used for producing aliases (PR9177). Fortunately the
422 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
423 // marker. We also avoid adding the marker if this is an alias for an
425 StringRef UserLabelPrefix =
426 getASTContext().getTargetInfo().getUserLabelPrefix();
427 if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
428 Out << '\01'; // LLVM IR Marker for __asm("foo")
430 Out << ALA->getLabel();
434 // <mangled-name> ::= _Z <encoding>
436 // ::= <special-name>
438 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
439 mangleFunctionEncoding(FD);
440 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
443 mangleName(cast<FieldDecl>(D));
446 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
447 // <encoding> ::= <function name> <bare-function-type>
450 // Don't mangle in the type if this isn't a decl we should typically mangle.
451 if (!Context.shouldMangleDeclName(FD))
454 // Whether the mangling of a function type includes the return type depends on
455 // the context and the nature of the function. The rules for deciding whether
456 // the return type is included are:
458 // 1. Template functions (names or types) have return types encoded, with
459 // the exceptions listed below.
460 // 2. Function types not appearing as part of a function name mangling,
461 // e.g. parameters, pointer types, etc., have return type encoded, with the
462 // exceptions listed below.
463 // 3. Non-template function names do not have return types encoded.
465 // The exceptions mentioned in (1) and (2) above, for which the return type is
466 // never included, are
469 // 3. Conversion operator functions, e.g. operator int.
470 bool MangleReturnType = false;
471 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
472 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
473 isa<CXXConversionDecl>(FD)))
474 MangleReturnType = true;
476 // Mangle the type of the primary template.
477 FD = PrimaryTemplate->getTemplatedDecl();
480 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
484 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
485 while (isa<LinkageSpecDecl>(DC)) {
486 DC = getEffectiveParentContext(DC);
492 /// isStd - Return whether a given namespace is the 'std' namespace.
493 static bool isStd(const NamespaceDecl *NS) {
494 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
495 ->isTranslationUnit())
498 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
499 return II && II->isStr("std");
502 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
504 static bool isStdNamespace(const DeclContext *DC) {
505 if (!DC->isNamespace())
508 return isStd(cast<NamespaceDecl>(DC));
511 static const TemplateDecl *
512 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
513 // Check if we have a function template.
514 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
515 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
516 TemplateArgs = FD->getTemplateSpecializationArgs();
521 // Check if we have a class template.
522 if (const ClassTemplateSpecializationDecl *Spec =
523 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
524 TemplateArgs = &Spec->getTemplateArgs();
525 return Spec->getSpecializedTemplate();
531 static bool isLambda(const NamedDecl *ND) {
532 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
536 return Record->isLambda();
539 void CXXNameMangler::mangleName(const NamedDecl *ND) {
540 // <name> ::= <nested-name>
541 // ::= <unscoped-name>
542 // ::= <unscoped-template-name> <template-args>
545 const DeclContext *DC = getEffectiveDeclContext(ND);
547 // If this is an extern variable declared locally, the relevant DeclContext
548 // is that of the containing namespace, or the translation unit.
549 // FIXME: This is a hack; extern variables declared locally should have
550 // a proper semantic declaration context!
551 if (isa<FunctionDecl>(DC) && ND->hasLinkage() && !isLambda(ND))
552 while (!DC->isNamespace() && !DC->isTranslationUnit())
553 DC = getEffectiveParentContext(DC);
554 else if (GetLocalClassDecl(ND)) {
559 DC = IgnoreLinkageSpecDecls(DC);
561 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
562 // Check if we have a template.
563 const TemplateArgumentList *TemplateArgs = 0;
564 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
565 mangleUnscopedTemplateName(TD);
566 mangleTemplateArgs(*TemplateArgs);
570 mangleUnscopedName(ND);
574 if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) {
579 mangleNestedName(ND, DC);
581 void CXXNameMangler::mangleName(const TemplateDecl *TD,
582 const TemplateArgument *TemplateArgs,
583 unsigned NumTemplateArgs) {
584 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
586 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
587 mangleUnscopedTemplateName(TD);
588 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
590 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
594 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
595 // <unscoped-name> ::= <unqualified-name>
596 // ::= St <unqualified-name> # ::std::
598 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
601 mangleUnqualifiedName(ND);
604 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
605 // <unscoped-template-name> ::= <unscoped-name>
606 // ::= <substitution>
607 if (mangleSubstitution(ND))
610 // <template-template-param> ::= <template-param>
611 if (const TemplateTemplateParmDecl *TTP
612 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
613 mangleTemplateParameter(TTP->getIndex());
617 mangleUnscopedName(ND->getTemplatedDecl());
621 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
622 // <unscoped-template-name> ::= <unscoped-name>
623 // ::= <substitution>
624 if (TemplateDecl *TD = Template.getAsTemplateDecl())
625 return mangleUnscopedTemplateName(TD);
627 if (mangleSubstitution(Template))
630 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
631 assert(Dependent && "Not a dependent template name?");
632 if (const IdentifierInfo *Id = Dependent->getIdentifier())
633 mangleSourceName(Id);
635 mangleOperatorName(Dependent->getOperator(), UnknownArity);
637 addSubstitution(Template);
640 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
642 // Floating-point literals are encoded using a fixed-length
643 // lowercase hexadecimal string corresponding to the internal
644 // representation (IEEE on Itanium), high-order bytes first,
645 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
647 // The 'without leading zeroes' thing seems to be an editorial
648 // mistake; see the discussion on cxx-abi-dev beginning on
651 // Our requirements here are just barely weird enough to justify
652 // using a custom algorithm instead of post-processing APInt::toString().
654 llvm::APInt valueBits = f.bitcastToAPInt();
655 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
656 assert(numCharacters != 0);
658 // Allocate a buffer of the right number of characters.
659 llvm::SmallVector<char, 20> buffer;
660 buffer.set_size(numCharacters);
662 // Fill the buffer left-to-right.
663 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
664 // The bit-index of the next hex digit.
665 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
667 // Project out 4 bits starting at 'digitIndex'.
668 llvm::integerPart hexDigit
669 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
670 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
673 // Map that over to a lowercase hex digit.
674 static const char charForHex[16] = {
675 '0', '1', '2', '3', '4', '5', '6', '7',
676 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
678 buffer[stringIndex] = charForHex[hexDigit];
681 Out.write(buffer.data(), numCharacters);
684 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
685 if (Value.isSigned() && Value.isNegative()) {
687 Value.abs().print(Out, /*signed*/ false);
689 Value.print(Out, /*signed*/ false);
693 void CXXNameMangler::mangleNumber(int64_t Number) {
694 // <number> ::= [n] <non-negative decimal integer>
703 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
704 // <call-offset> ::= h <nv-offset> _
705 // ::= v <v-offset> _
706 // <nv-offset> ::= <offset number> # non-virtual base override
707 // <v-offset> ::= <offset number> _ <virtual offset number>
708 // # virtual base override, with vcall offset
711 mangleNumber(NonVirtual);
717 mangleNumber(NonVirtual);
719 mangleNumber(Virtual);
723 void CXXNameMangler::manglePrefix(QualType type) {
724 if (const TemplateSpecializationType *TST =
725 type->getAs<TemplateSpecializationType>()) {
726 if (!mangleSubstitution(QualType(TST, 0))) {
727 mangleTemplatePrefix(TST->getTemplateName());
729 // FIXME: GCC does not appear to mangle the template arguments when
730 // the template in question is a dependent template name. Should we
731 // emulate that badness?
732 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
733 addSubstitution(QualType(TST, 0));
735 } else if (const DependentTemplateSpecializationType *DTST
736 = type->getAs<DependentTemplateSpecializationType>()) {
737 TemplateName Template
738 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
739 DTST->getIdentifier());
740 mangleTemplatePrefix(Template);
742 // FIXME: GCC does not appear to mangle the template arguments when
743 // the template in question is a dependent template name. Should we
744 // emulate that badness?
745 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
747 // We use the QualType mangle type variant here because it handles
753 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
755 /// \param firstQualifierLookup - the entity found by unqualified lookup
756 /// for the first name in the qualifier, if this is for a member expression
757 /// \param recursive - true if this is being called recursively,
758 /// i.e. if there is more prefix "to the right".
759 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
760 NamedDecl *firstQualifierLookup,
764 // <unresolved-name> ::= [gs] <base-unresolved-name>
766 // T::x / decltype(p)::x
767 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
769 // T::N::x /decltype(p)::N::x
770 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
771 // <base-unresolved-name>
773 // A::x, N::y, A<T>::z; "gs" means leading "::"
774 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
775 // <base-unresolved-name>
777 switch (qualifier->getKind()) {
778 case NestedNameSpecifier::Global:
781 // We want an 'sr' unless this is the entire NNS.
785 // We never want an 'E' here.
788 case NestedNameSpecifier::Namespace:
789 if (qualifier->getPrefix())
790 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
794 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
796 case NestedNameSpecifier::NamespaceAlias:
797 if (qualifier->getPrefix())
798 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
802 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
805 case NestedNameSpecifier::TypeSpec:
806 case NestedNameSpecifier::TypeSpecWithTemplate: {
807 const Type *type = qualifier->getAsType();
809 // We only want to use an unresolved-type encoding if this is one of:
811 // - a template type parameter
812 // - a template template parameter with arguments
813 // In all of these cases, we should have no prefix.
814 if (qualifier->getPrefix()) {
815 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
818 // Otherwise, all the cases want this.
822 // Only certain other types are valid as prefixes; enumerate them.
823 switch (type->getTypeClass()) {
827 case Type::BlockPointer:
828 case Type::LValueReference:
829 case Type::RValueReference:
830 case Type::MemberPointer:
831 case Type::ConstantArray:
832 case Type::IncompleteArray:
833 case Type::VariableArray:
834 case Type::DependentSizedArray:
835 case Type::DependentSizedExtVector:
837 case Type::ExtVector:
838 case Type::FunctionProto:
839 case Type::FunctionNoProto:
842 case Type::Elaborated:
843 case Type::Attributed:
845 case Type::PackExpansion:
846 case Type::ObjCObject:
847 case Type::ObjCInterface:
848 case Type::ObjCObjectPointer:
850 llvm_unreachable("type is illegal as a nested name specifier");
852 case Type::SubstTemplateTypeParmPack:
853 // FIXME: not clear how to mangle this!
854 // template <class T...> class A {
855 // template <class U...> void foo(decltype(T::foo(U())) x...);
857 Out << "_SUBSTPACK_";
860 // <unresolved-type> ::= <template-param>
862 // ::= <template-template-param> <template-args>
863 // (this last is not official yet)
864 case Type::TypeOfExpr:
867 case Type::TemplateTypeParm:
868 case Type::UnaryTransform:
869 case Type::SubstTemplateTypeParm:
871 assert(!qualifier->getPrefix());
873 // We only get here recursively if we're followed by identifiers.
874 if (recursive) Out << 'N';
876 // This seems to do everything we want. It's not really
877 // sanctioned for a substituted template parameter, though.
878 mangleType(QualType(type, 0));
880 // We never want to print 'E' directly after an unresolved-type,
881 // so we return directly.
885 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
888 case Type::UnresolvedUsing:
889 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
894 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
897 case Type::TemplateSpecialization: {
898 const TemplateSpecializationType *tst
899 = cast<TemplateSpecializationType>(type);
900 TemplateName name = tst->getTemplateName();
901 switch (name.getKind()) {
902 case TemplateName::Template:
903 case TemplateName::QualifiedTemplate: {
904 TemplateDecl *temp = name.getAsTemplateDecl();
906 // If the base is a template template parameter, this is an
908 assert(temp && "no template for template specialization type");
909 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
911 mangleSourceName(temp->getIdentifier());
915 case TemplateName::OverloadedTemplate:
916 case TemplateName::DependentTemplate:
917 llvm_unreachable("invalid base for a template specialization type");
919 case TemplateName::SubstTemplateTemplateParm: {
920 SubstTemplateTemplateParmStorage *subst
921 = name.getAsSubstTemplateTemplateParm();
922 mangleExistingSubstitution(subst->getReplacement());
926 case TemplateName::SubstTemplateTemplateParmPack: {
927 // FIXME: not clear how to mangle this!
928 // template <template <class U> class T...> class A {
929 // template <class U...> void foo(decltype(T<U>::foo) x...);
931 Out << "_SUBSTPACK_";
936 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
940 case Type::InjectedClassName:
941 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
945 case Type::DependentName:
946 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
949 case Type::DependentTemplateSpecialization: {
950 const DependentTemplateSpecializationType *tst
951 = cast<DependentTemplateSpecializationType>(type);
952 mangleSourceName(tst->getIdentifier());
953 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
960 case NestedNameSpecifier::Identifier:
961 // Member expressions can have these without prefixes.
962 if (qualifier->getPrefix()) {
963 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
965 } else if (firstQualifierLookup) {
967 // Try to make a proper qualifier out of the lookup result, and
968 // then just recurse on that.
969 NestedNameSpecifier *newQualifier;
970 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
971 QualType type = getASTContext().getTypeDeclType(typeDecl);
973 // Pretend we had a different nested name specifier.
974 newQualifier = NestedNameSpecifier::Create(getASTContext(),
978 } else if (NamespaceDecl *nspace =
979 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
980 newQualifier = NestedNameSpecifier::Create(getASTContext(),
983 } else if (NamespaceAliasDecl *alias =
984 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
985 newQualifier = NestedNameSpecifier::Create(getASTContext(),
989 // No sensible mangling to do here.
994 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
1000 mangleSourceName(qualifier->getAsIdentifier());
1004 // If this was the innermost part of the NNS, and we fell out to
1005 // here, append an 'E'.
1010 /// Mangle an unresolved-name, which is generally used for names which
1011 /// weren't resolved to specific entities.
1012 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1013 NamedDecl *firstQualifierLookup,
1014 DeclarationName name,
1015 unsigned knownArity) {
1016 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1017 mangleUnqualifiedName(0, name, knownArity);
1020 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1021 assert(RD->isAnonymousStructOrUnion() &&
1022 "Expected anonymous struct or union!");
1024 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1026 if (I->getIdentifier())
1029 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1030 if (const FieldDecl *NamedDataMember =
1031 FindFirstNamedDataMember(RT->getDecl()))
1032 return NamedDataMember;
1035 // We didn't find a named data member.
1039 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1040 DeclarationName Name,
1041 unsigned KnownArity) {
1042 // <unqualified-name> ::= <operator-name>
1043 // ::= <ctor-dtor-name>
1044 // ::= <source-name>
1045 switch (Name.getNameKind()) {
1046 case DeclarationName::Identifier: {
1047 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1048 // We must avoid conflicts between internally- and externally-
1049 // linked variable and function declaration names in the same TU:
1050 // void test() { extern void foo(); }
1051 // static void foo();
1052 // This naming convention is the same as that followed by GCC,
1053 // though it shouldn't actually matter.
1054 if (ND && ND->getLinkage() == InternalLinkage &&
1055 getEffectiveDeclContext(ND)->isFileContext())
1058 mangleSourceName(II);
1062 // Otherwise, an anonymous entity. We must have a declaration.
1063 assert(ND && "mangling empty name without declaration");
1065 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1066 if (NS->isAnonymousNamespace()) {
1067 // This is how gcc mangles these names.
1068 Out << "12_GLOBAL__N_1";
1073 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1074 // We must have an anonymous union or struct declaration.
1075 const RecordDecl *RD =
1076 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1078 // Itanium C++ ABI 5.1.2:
1080 // For the purposes of mangling, the name of an anonymous union is
1081 // considered to be the name of the first named data member found by a
1082 // pre-order, depth-first, declaration-order walk of the data members of
1083 // the anonymous union. If there is no such data member (i.e., if all of
1084 // the data members in the union are unnamed), then there is no way for
1085 // a program to refer to the anonymous union, and there is therefore no
1086 // need to mangle its name.
1087 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1089 // It's actually possible for various reasons for us to get here
1090 // with an empty anonymous struct / union. Fortunately, it
1091 // doesn't really matter what name we generate.
1093 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1095 mangleSourceName(FD->getIdentifier());
1099 // We must have an anonymous struct.
1100 const TagDecl *TD = cast<TagDecl>(ND);
1101 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1102 assert(TD->getDeclContext() == D->getDeclContext() &&
1103 "Typedef should not be in another decl context!");
1104 assert(D->getDeclName().getAsIdentifierInfo() &&
1105 "Typedef was not named!");
1106 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1110 // <unnamed-type-name> ::= <closure-type-name>
1112 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1113 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1114 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1115 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1116 mangleLambda(Record);
1121 // Get a unique id for the anonymous struct.
1122 uint64_t AnonStructId = Context.getAnonymousStructId(TD);
1124 // Mangle it as a source name in the form
1126 // where n is the length of the string.
1129 Str += llvm::utostr(AnonStructId);
1136 case DeclarationName::ObjCZeroArgSelector:
1137 case DeclarationName::ObjCOneArgSelector:
1138 case DeclarationName::ObjCMultiArgSelector:
1139 llvm_unreachable("Can't mangle Objective-C selector names here!");
1141 case DeclarationName::CXXConstructorName:
1143 // If the named decl is the C++ constructor we're mangling, use the type
1145 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1147 // Otherwise, use the complete constructor name. This is relevant if a
1148 // class with a constructor is declared within a constructor.
1149 mangleCXXCtorType(Ctor_Complete);
1152 case DeclarationName::CXXDestructorName:
1154 // If the named decl is the C++ destructor we're mangling, use the type we
1156 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1158 // Otherwise, use the complete destructor name. This is relevant if a
1159 // class with a destructor is declared within a destructor.
1160 mangleCXXDtorType(Dtor_Complete);
1163 case DeclarationName::CXXConversionFunctionName:
1164 // <operator-name> ::= cv <type> # (cast)
1166 mangleType(Name.getCXXNameType());
1169 case DeclarationName::CXXOperatorName: {
1172 Arity = cast<FunctionDecl>(ND)->getNumParams();
1174 // If we have a C++ member function, we need to include the 'this' pointer.
1175 // FIXME: This does not make sense for operators that are static, but their
1176 // names stay the same regardless of the arity (operator new for instance).
1177 if (isa<CXXMethodDecl>(ND))
1182 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1186 case DeclarationName::CXXLiteralOperatorName:
1187 // FIXME: This mangling is not yet official.
1189 mangleSourceName(Name.getCXXLiteralIdentifier());
1192 case DeclarationName::CXXUsingDirective:
1193 llvm_unreachable("Can't mangle a using directive name!");
1197 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1198 // <source-name> ::= <positive length number> <identifier>
1199 // <number> ::= [n] <non-negative decimal integer>
1200 // <identifier> ::= <unqualified source code identifier>
1201 Out << II->getLength() << II->getName();
1204 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1205 const DeclContext *DC,
1208 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1209 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1210 // <template-args> E
1213 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1214 mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
1215 mangleRefQualifier(Method->getRefQualifier());
1218 // Check if we have a template.
1219 const TemplateArgumentList *TemplateArgs = 0;
1220 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1221 mangleTemplatePrefix(TD);
1222 mangleTemplateArgs(*TemplateArgs);
1225 manglePrefix(DC, NoFunction);
1226 mangleUnqualifiedName(ND);
1231 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1232 const TemplateArgument *TemplateArgs,
1233 unsigned NumTemplateArgs) {
1234 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1238 mangleTemplatePrefix(TD);
1239 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1244 void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
1245 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1246 // := Z <function encoding> E s [<discriminator>]
1247 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1249 // <discriminator> := _ <non-negative number>
1250 const DeclContext *DC = getEffectiveDeclContext(ND);
1251 if (isa<ObjCMethodDecl>(DC) && isa<FunctionDecl>(ND)) {
1252 // Don't add objc method name mangling to locally declared function
1253 mangleUnqualifiedName(ND);
1259 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) {
1260 mangleObjCMethodName(MD);
1261 } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) {
1262 mangleFunctionEncoding(cast<FunctionDecl>(getEffectiveDeclContext(RD)));
1265 // The parameter number is omitted for the last parameter, 0 for the
1266 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1267 // <entity name> will of course contain a <closure-type-name>: Its
1268 // numbering will be local to the particular argument in which it appears
1269 // -- other default arguments do not affect its encoding.
1270 bool SkipDiscriminator = false;
1271 if (RD->isLambda()) {
1272 if (const ParmVarDecl *Parm
1273 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) {
1274 if (const FunctionDecl *Func
1275 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1277 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1279 mangleNumber(Num - 2);
1281 SkipDiscriminator = true;
1286 // Mangle the name relative to the closest enclosing function.
1287 if (ND == RD) // equality ok because RD derived from ND above
1288 mangleUnqualifiedName(ND);
1290 mangleNestedName(ND, DC, true /*NoFunction*/);
1292 if (!SkipDiscriminator) {
1294 if (Context.getNextDiscriminator(RD, disc)) {
1298 Out << "__" << disc << '_';
1305 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1308 mangleUnqualifiedName(ND);
1311 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1312 // If the context of a closure type is an initializer for a class member
1313 // (static or nonstatic), it is encoded in a qualified name with a final
1314 // <prefix> of the form:
1316 // <data-member-prefix> := <member source-name> M
1318 // Technically, the data-member-prefix is part of the <prefix>. However,
1319 // since a closure type will always be mangled with a prefix, it's easier
1320 // to emit that last part of the prefix here.
1321 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1322 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1323 Context->getDeclContext()->isRecord()) {
1324 if (const IdentifierInfo *Name
1325 = cast<NamedDecl>(Context)->getIdentifier()) {
1326 mangleSourceName(Name);
1333 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1334 getAs<FunctionProtoType>();
1335 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1338 // The number is omitted for the first closure type with a given
1339 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1340 // (in lexical order) with that same <lambda-sig> and context.
1342 // The AST keeps track of the number for us.
1343 unsigned Number = Lambda->getLambdaManglingNumber();
1344 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1346 mangleNumber(Number - 2);
1350 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1351 switch (qualifier->getKind()) {
1352 case NestedNameSpecifier::Global:
1356 case NestedNameSpecifier::Namespace:
1357 mangleName(qualifier->getAsNamespace());
1360 case NestedNameSpecifier::NamespaceAlias:
1361 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1364 case NestedNameSpecifier::TypeSpec:
1365 case NestedNameSpecifier::TypeSpecWithTemplate:
1366 manglePrefix(QualType(qualifier->getAsType(), 0));
1369 case NestedNameSpecifier::Identifier:
1370 // Member expressions can have these without prefixes, but that
1371 // should end up in mangleUnresolvedPrefix instead.
1372 assert(qualifier->getPrefix());
1373 manglePrefix(qualifier->getPrefix());
1375 mangleSourceName(qualifier->getAsIdentifier());
1379 llvm_unreachable("unexpected nested name specifier");
1382 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1383 // <prefix> ::= <prefix> <unqualified-name>
1384 // ::= <template-prefix> <template-args>
1385 // ::= <template-param>
1387 // ::= <substitution>
1389 DC = IgnoreLinkageSpecDecls(DC);
1391 if (DC->isTranslationUnit())
1394 if (const BlockDecl *Block = dyn_cast<BlockDecl>(DC)) {
1395 manglePrefix(getEffectiveParentContext(DC), NoFunction);
1396 SmallString<64> Name;
1397 llvm::raw_svector_ostream NameStream(Name);
1398 Context.mangleBlock(Block, NameStream);
1400 Out << Name.size() << Name;
1404 const NamedDecl *ND = cast<NamedDecl>(DC);
1405 if (mangleSubstitution(ND))
1408 // Check if we have a template.
1409 const TemplateArgumentList *TemplateArgs = 0;
1410 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1411 mangleTemplatePrefix(TD);
1412 mangleTemplateArgs(*TemplateArgs);
1414 else if(NoFunction && (isa<FunctionDecl>(ND) || isa<ObjCMethodDecl>(ND)))
1416 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1417 mangleObjCMethodName(Method);
1419 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1420 mangleUnqualifiedName(ND);
1423 addSubstitution(ND);
1426 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1427 // <template-prefix> ::= <prefix> <template unqualified-name>
1428 // ::= <template-param>
1429 // ::= <substitution>
1430 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1431 return mangleTemplatePrefix(TD);
1433 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1434 manglePrefix(Qualified->getQualifier());
1436 if (OverloadedTemplateStorage *Overloaded
1437 = Template.getAsOverloadedTemplate()) {
1438 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1443 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1444 assert(Dependent && "Unknown template name kind?");
1445 manglePrefix(Dependent->getQualifier());
1446 mangleUnscopedTemplateName(Template);
1449 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
1450 // <template-prefix> ::= <prefix> <template unqualified-name>
1451 // ::= <template-param>
1452 // ::= <substitution>
1453 // <template-template-param> ::= <template-param>
1456 if (mangleSubstitution(ND))
1459 // <template-template-param> ::= <template-param>
1460 if (const TemplateTemplateParmDecl *TTP
1461 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1462 mangleTemplateParameter(TTP->getIndex());
1466 manglePrefix(getEffectiveDeclContext(ND));
1467 mangleUnqualifiedName(ND->getTemplatedDecl());
1468 addSubstitution(ND);
1471 /// Mangles a template name under the production <type>. Required for
1472 /// template template arguments.
1473 /// <type> ::= <class-enum-type>
1474 /// ::= <template-param>
1475 /// ::= <substitution>
1476 void CXXNameMangler::mangleType(TemplateName TN) {
1477 if (mangleSubstitution(TN))
1480 TemplateDecl *TD = 0;
1482 switch (TN.getKind()) {
1483 case TemplateName::QualifiedTemplate:
1484 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1487 case TemplateName::Template:
1488 TD = TN.getAsTemplateDecl();
1492 if (isa<TemplateTemplateParmDecl>(TD))
1493 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1498 case TemplateName::OverloadedTemplate:
1499 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1501 case TemplateName::DependentTemplate: {
1502 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1503 assert(Dependent->isIdentifier());
1505 // <class-enum-type> ::= <name>
1506 // <name> ::= <nested-name>
1507 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1508 mangleSourceName(Dependent->getIdentifier());
1512 case TemplateName::SubstTemplateTemplateParm: {
1513 // Substituted template parameters are mangled as the substituted
1514 // template. This will check for the substitution twice, which is
1515 // fine, but we have to return early so that we don't try to *add*
1516 // the substitution twice.
1517 SubstTemplateTemplateParmStorage *subst
1518 = TN.getAsSubstTemplateTemplateParm();
1519 mangleType(subst->getReplacement());
1523 case TemplateName::SubstTemplateTemplateParmPack: {
1524 // FIXME: not clear how to mangle this!
1525 // template <template <class> class T...> class A {
1526 // template <template <class> class U...> void foo(B<T,U> x...);
1528 Out << "_SUBSTPACK_";
1533 addSubstitution(TN);
1537 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1539 // <operator-name> ::= nw # new
1540 case OO_New: Out << "nw"; break;
1542 case OO_Array_New: Out << "na"; break;
1544 case OO_Delete: Out << "dl"; break;
1545 // ::= da # delete[]
1546 case OO_Array_Delete: Out << "da"; break;
1547 // ::= ps # + (unary)
1548 // ::= pl # + (binary or unknown)
1550 Out << (Arity == 1? "ps" : "pl"); break;
1551 // ::= ng # - (unary)
1552 // ::= mi # - (binary or unknown)
1554 Out << (Arity == 1? "ng" : "mi"); break;
1555 // ::= ad # & (unary)
1556 // ::= an # & (binary or unknown)
1558 Out << (Arity == 1? "ad" : "an"); break;
1559 // ::= de # * (unary)
1560 // ::= ml # * (binary or unknown)
1562 // Use binary when unknown.
1563 Out << (Arity == 1? "de" : "ml"); break;
1565 case OO_Tilde: Out << "co"; break;
1567 case OO_Slash: Out << "dv"; break;
1569 case OO_Percent: Out << "rm"; break;
1571 case OO_Pipe: Out << "or"; break;
1573 case OO_Caret: Out << "eo"; break;
1575 case OO_Equal: Out << "aS"; break;
1577 case OO_PlusEqual: Out << "pL"; break;
1579 case OO_MinusEqual: Out << "mI"; break;
1581 case OO_StarEqual: Out << "mL"; break;
1583 case OO_SlashEqual: Out << "dV"; break;
1585 case OO_PercentEqual: Out << "rM"; break;
1587 case OO_AmpEqual: Out << "aN"; break;
1589 case OO_PipeEqual: Out << "oR"; break;
1591 case OO_CaretEqual: Out << "eO"; break;
1593 case OO_LessLess: Out << "ls"; break;
1595 case OO_GreaterGreater: Out << "rs"; break;
1597 case OO_LessLessEqual: Out << "lS"; break;
1599 case OO_GreaterGreaterEqual: Out << "rS"; break;
1601 case OO_EqualEqual: Out << "eq"; break;
1603 case OO_ExclaimEqual: Out << "ne"; break;
1605 case OO_Less: Out << "lt"; break;
1607 case OO_Greater: Out << "gt"; break;
1609 case OO_LessEqual: Out << "le"; break;
1611 case OO_GreaterEqual: Out << "ge"; break;
1613 case OO_Exclaim: Out << "nt"; break;
1615 case OO_AmpAmp: Out << "aa"; break;
1617 case OO_PipePipe: Out << "oo"; break;
1619 case OO_PlusPlus: Out << "pp"; break;
1621 case OO_MinusMinus: Out << "mm"; break;
1623 case OO_Comma: Out << "cm"; break;
1625 case OO_ArrowStar: Out << "pm"; break;
1627 case OO_Arrow: Out << "pt"; break;
1629 case OO_Call: Out << "cl"; break;
1631 case OO_Subscript: Out << "ix"; break;
1634 // The conditional operator can't be overloaded, but we still handle it when
1635 // mangling expressions.
1636 case OO_Conditional: Out << "qu"; break;
1639 case NUM_OVERLOADED_OPERATORS:
1640 llvm_unreachable("Not an overloaded operator");
1644 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1645 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1646 if (Quals.hasRestrict())
1648 if (Quals.hasVolatile())
1650 if (Quals.hasConst())
1653 if (Quals.hasAddressSpace()) {
1656 // <type> ::= U <address-space-number>
1658 // where <address-space-number> is a source name consisting of 'AS'
1659 // followed by the address space <number>.
1660 SmallString<64> ASString;
1661 ASString = "AS" + llvm::utostr_32(Quals.getAddressSpace());
1662 Out << 'U' << ASString.size() << ASString;
1665 StringRef LifetimeName;
1666 switch (Quals.getObjCLifetime()) {
1667 // Objective-C ARC Extension:
1669 // <type> ::= U "__strong"
1670 // <type> ::= U "__weak"
1671 // <type> ::= U "__autoreleasing"
1672 case Qualifiers::OCL_None:
1675 case Qualifiers::OCL_Weak:
1676 LifetimeName = "__weak";
1679 case Qualifiers::OCL_Strong:
1680 LifetimeName = "__strong";
1683 case Qualifiers::OCL_Autoreleasing:
1684 LifetimeName = "__autoreleasing";
1687 case Qualifiers::OCL_ExplicitNone:
1688 // The __unsafe_unretained qualifier is *not* mangled, so that
1689 // __unsafe_unretained types in ARC produce the same manglings as the
1690 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1691 // better ABI compatibility.
1693 // It's safe to do this because unqualified 'id' won't show up
1694 // in any type signatures that need to be mangled.
1697 if (!LifetimeName.empty())
1698 Out << 'U' << LifetimeName.size() << LifetimeName;
1701 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1702 // <ref-qualifier> ::= R # lvalue reference
1703 // ::= O # rvalue-reference
1704 // Proposal to Itanium C++ ABI list on 1/26/11
1705 switch (RefQualifier) {
1719 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1720 Context.mangleObjCMethodName(MD, Out);
1723 void CXXNameMangler::mangleType(QualType T) {
1724 // If our type is instantiation-dependent but not dependent, we mangle
1725 // it as it was written in the source, removing any top-level sugar.
1726 // Otherwise, use the canonical type.
1728 // FIXME: This is an approximation of the instantiation-dependent name
1729 // mangling rules, since we should really be using the type as written and
1730 // augmented via semantic analysis (i.e., with implicit conversions and
1731 // default template arguments) for any instantiation-dependent type.
1732 // Unfortunately, that requires several changes to our AST:
1733 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1734 // uniqued, so that we can handle substitutions properly
1735 // - Default template arguments will need to be represented in the
1736 // TemplateSpecializationType, since they need to be mangled even though
1737 // they aren't written.
1738 // - Conversions on non-type template arguments need to be expressed, since
1739 // they can affect the mangling of sizeof/alignof.
1740 if (!T->isInstantiationDependentType() || T->isDependentType())
1741 T = T.getCanonicalType();
1743 // Desugar any types that are purely sugar.
1745 // Don't desugar through template specialization types that aren't
1746 // type aliases. We need to mangle the template arguments as written.
1747 if (const TemplateSpecializationType *TST
1748 = dyn_cast<TemplateSpecializationType>(T))
1749 if (!TST->isTypeAlias())
1753 = T.getSingleStepDesugaredType(Context.getASTContext());
1760 SplitQualType split = T.split();
1761 Qualifiers quals = split.Quals;
1762 const Type *ty = split.Ty;
1764 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1765 if (isSubstitutable && mangleSubstitution(T))
1768 // If we're mangling a qualified array type, push the qualifiers to
1769 // the element type.
1770 if (quals && isa<ArrayType>(T)) {
1771 ty = Context.getASTContext().getAsArrayType(T);
1772 quals = Qualifiers();
1774 // Note that we don't update T: we want to add the
1775 // substitution at the original type.
1779 mangleQualifiers(quals);
1780 // Recurse: even if the qualified type isn't yet substitutable,
1781 // the unqualified type might be.
1782 mangleType(QualType(ty, 0));
1784 switch (ty->getTypeClass()) {
1785 #define ABSTRACT_TYPE(CLASS, PARENT)
1786 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1788 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1790 #define TYPE(CLASS, PARENT) \
1792 mangleType(static_cast<const CLASS##Type*>(ty)); \
1794 #include "clang/AST/TypeNodes.def"
1798 // Add the substitution.
1799 if (isSubstitutable)
1803 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1804 if (!mangleStandardSubstitution(ND))
1808 void CXXNameMangler::mangleType(const BuiltinType *T) {
1809 // <type> ::= <builtin-type>
1810 // <builtin-type> ::= v # void
1814 // ::= a # signed char
1815 // ::= h # unsigned char
1817 // ::= t # unsigned short
1819 // ::= j # unsigned int
1821 // ::= m # unsigned long
1822 // ::= x # long long, __int64
1823 // ::= y # unsigned long long, __int64
1825 // UNSUPPORTED: ::= o # unsigned __int128
1828 // ::= e # long double, __float80
1829 // UNSUPPORTED: ::= g # __float128
1830 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1831 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1832 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1833 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1834 // ::= Di # char32_t
1835 // ::= Ds # char16_t
1836 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1837 // ::= u <source-name> # vendor extended type
1838 switch (T->getKind()) {
1839 case BuiltinType::Void: Out << 'v'; break;
1840 case BuiltinType::Bool: Out << 'b'; break;
1841 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1842 case BuiltinType::UChar: Out << 'h'; break;
1843 case BuiltinType::UShort: Out << 't'; break;
1844 case BuiltinType::UInt: Out << 'j'; break;
1845 case BuiltinType::ULong: Out << 'm'; break;
1846 case BuiltinType::ULongLong: Out << 'y'; break;
1847 case BuiltinType::UInt128: Out << 'o'; break;
1848 case BuiltinType::SChar: Out << 'a'; break;
1849 case BuiltinType::WChar_S:
1850 case BuiltinType::WChar_U: Out << 'w'; break;
1851 case BuiltinType::Char16: Out << "Ds"; break;
1852 case BuiltinType::Char32: Out << "Di"; break;
1853 case BuiltinType::Short: Out << 's'; break;
1854 case BuiltinType::Int: Out << 'i'; break;
1855 case BuiltinType::Long: Out << 'l'; break;
1856 case BuiltinType::LongLong: Out << 'x'; break;
1857 case BuiltinType::Int128: Out << 'n'; break;
1858 case BuiltinType::Half: Out << "Dh"; break;
1859 case BuiltinType::Float: Out << 'f'; break;
1860 case BuiltinType::Double: Out << 'd'; break;
1861 case BuiltinType::LongDouble: Out << 'e'; break;
1862 case BuiltinType::NullPtr: Out << "Dn"; break;
1864 #define BUILTIN_TYPE(Id, SingletonId)
1865 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1866 case BuiltinType::Id:
1867 #include "clang/AST/BuiltinTypes.def"
1868 case BuiltinType::Dependent:
1869 llvm_unreachable("mangling a placeholder type");
1870 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1871 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1872 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
1876 // <type> ::= <function-type>
1877 // <function-type> ::= [<CV-qualifiers>] F [Y]
1878 // <bare-function-type> [<ref-qualifier>] E
1879 // (Proposal to cxx-abi-dev, 2012-05-11)
1880 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1881 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1882 // e.g. "const" in "int (A::*)() const".
1883 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1887 // FIXME: We don't have enough information in the AST to produce the 'Y'
1888 // encoding for extern "C" function types.
1889 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1891 // Mangle the ref-qualifier, if present.
1892 mangleRefQualifier(T->getRefQualifier());
1896 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1897 llvm_unreachable("Can't mangle K&R function prototypes");
1899 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1900 bool MangleReturnType) {
1901 // We should never be mangling something without a prototype.
1902 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1904 // Record that we're in a function type. See mangleFunctionParam
1905 // for details on what we're trying to achieve here.
1906 FunctionTypeDepthState saved = FunctionTypeDepth.push();
1908 // <bare-function-type> ::= <signature type>+
1909 if (MangleReturnType) {
1910 FunctionTypeDepth.enterResultType();
1911 mangleType(Proto->getResultType());
1912 FunctionTypeDepth.leaveResultType();
1915 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1916 // <builtin-type> ::= v # void
1919 FunctionTypeDepth.pop(saved);
1923 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1924 ArgEnd = Proto->arg_type_end();
1925 Arg != ArgEnd; ++Arg)
1926 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
1928 FunctionTypeDepth.pop(saved);
1930 // <builtin-type> ::= z # ellipsis
1931 if (Proto->isVariadic())
1935 // <type> ::= <class-enum-type>
1936 // <class-enum-type> ::= <name>
1937 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1938 mangleName(T->getDecl());
1941 // <type> ::= <class-enum-type>
1942 // <class-enum-type> ::= <name>
1943 void CXXNameMangler::mangleType(const EnumType *T) {
1944 mangleType(static_cast<const TagType*>(T));
1946 void CXXNameMangler::mangleType(const RecordType *T) {
1947 mangleType(static_cast<const TagType*>(T));
1949 void CXXNameMangler::mangleType(const TagType *T) {
1950 mangleName(T->getDecl());
1953 // <type> ::= <array-type>
1954 // <array-type> ::= A <positive dimension number> _ <element type>
1955 // ::= A [<dimension expression>] _ <element type>
1956 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
1957 Out << 'A' << T->getSize() << '_';
1958 mangleType(T->getElementType());
1960 void CXXNameMangler::mangleType(const VariableArrayType *T) {
1962 // decayed vla types (size 0) will just be skipped.
1963 if (T->getSizeExpr())
1964 mangleExpression(T->getSizeExpr());
1966 mangleType(T->getElementType());
1968 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1970 mangleExpression(T->getSizeExpr());
1972 mangleType(T->getElementType());
1974 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
1976 mangleType(T->getElementType());
1979 // <type> ::= <pointer-to-member-type>
1980 // <pointer-to-member-type> ::= M <class type> <member type>
1981 void CXXNameMangler::mangleType(const MemberPointerType *T) {
1983 mangleType(QualType(T->getClass(), 0));
1984 QualType PointeeType = T->getPointeeType();
1985 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
1988 // Itanium C++ ABI 5.1.8:
1990 // The type of a non-static member function is considered to be different,
1991 // for the purposes of substitution, from the type of a namespace-scope or
1992 // static member function whose type appears similar. The types of two
1993 // non-static member functions are considered to be different, for the
1994 // purposes of substitution, if the functions are members of different
1995 // classes. In other words, for the purposes of substitution, the class of
1996 // which the function is a member is considered part of the type of
1999 // Given that we already substitute member function pointers as a
2000 // whole, the net effect of this rule is just to unconditionally
2001 // suppress substitution on the function type in a member pointer.
2002 // We increment the SeqID here to emulate adding an entry to the
2003 // substitution table.
2006 mangleType(PointeeType);
2009 // <type> ::= <template-param>
2010 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2011 mangleTemplateParameter(T->getIndex());
2014 // <type> ::= <template-param>
2015 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2016 // FIXME: not clear how to mangle this!
2017 // template <class T...> class A {
2018 // template <class U...> void foo(T(*)(U) x...);
2020 Out << "_SUBSTPACK_";
2023 // <type> ::= P <type> # pointer-to
2024 void CXXNameMangler::mangleType(const PointerType *T) {
2026 mangleType(T->getPointeeType());
2028 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2030 mangleType(T->getPointeeType());
2033 // <type> ::= R <type> # reference-to
2034 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2036 mangleType(T->getPointeeType());
2039 // <type> ::= O <type> # rvalue reference-to (C++0x)
2040 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2042 mangleType(T->getPointeeType());
2045 // <type> ::= C <type> # complex pair (C 2000)
2046 void CXXNameMangler::mangleType(const ComplexType *T) {
2048 mangleType(T->getElementType());
2051 // ARM's ABI for Neon vector types specifies that they should be mangled as
2052 // if they are structs (to match ARM's initial implementation). The
2053 // vector type must be one of the special types predefined by ARM.
2054 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2055 QualType EltType = T->getElementType();
2056 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2057 const char *EltName = 0;
2058 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2059 switch (cast<BuiltinType>(EltType)->getKind()) {
2060 case BuiltinType::SChar: EltName = "poly8_t"; break;
2061 case BuiltinType::Short: EltName = "poly16_t"; break;
2062 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2065 switch (cast<BuiltinType>(EltType)->getKind()) {
2066 case BuiltinType::SChar: EltName = "int8_t"; break;
2067 case BuiltinType::UChar: EltName = "uint8_t"; break;
2068 case BuiltinType::Short: EltName = "int16_t"; break;
2069 case BuiltinType::UShort: EltName = "uint16_t"; break;
2070 case BuiltinType::Int: EltName = "int32_t"; break;
2071 case BuiltinType::UInt: EltName = "uint32_t"; break;
2072 case BuiltinType::LongLong: EltName = "int64_t"; break;
2073 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2074 case BuiltinType::Float: EltName = "float32_t"; break;
2075 default: llvm_unreachable("unexpected Neon vector element type");
2078 const char *BaseName = 0;
2079 unsigned BitSize = (T->getNumElements() *
2080 getASTContext().getTypeSize(EltType));
2082 BaseName = "__simd64_";
2084 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2085 BaseName = "__simd128_";
2087 Out << strlen(BaseName) + strlen(EltName);
2088 Out << BaseName << EltName;
2091 // GNU extension: vector types
2092 // <type> ::= <vector-type>
2093 // <vector-type> ::= Dv <positive dimension number> _
2094 // <extended element type>
2095 // ::= Dv [<dimension expression>] _ <element type>
2096 // <extended element type> ::= <element type>
2097 // ::= p # AltiVec vector pixel
2098 // ::= b # Altivec vector bool
2099 void CXXNameMangler::mangleType(const VectorType *T) {
2100 if ((T->getVectorKind() == VectorType::NeonVector ||
2101 T->getVectorKind() == VectorType::NeonPolyVector)) {
2102 mangleNeonVectorType(T);
2105 Out << "Dv" << T->getNumElements() << '_';
2106 if (T->getVectorKind() == VectorType::AltiVecPixel)
2108 else if (T->getVectorKind() == VectorType::AltiVecBool)
2111 mangleType(T->getElementType());
2113 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2114 mangleType(static_cast<const VectorType*>(T));
2116 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2118 mangleExpression(T->getSizeExpr());
2120 mangleType(T->getElementType());
2123 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2124 // <type> ::= Dp <type> # pack expansion (C++0x)
2126 mangleType(T->getPattern());
2129 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2130 mangleSourceName(T->getDecl()->getIdentifier());
2133 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2134 // We don't allow overloading by different protocol qualification,
2135 // so mangling them isn't necessary.
2136 mangleType(T->getBaseType());
2139 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2140 Out << "U13block_pointer";
2141 mangleType(T->getPointeeType());
2144 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2145 // Mangle injected class name types as if the user had written the
2146 // specialization out fully. It may not actually be possible to see
2147 // this mangling, though.
2148 mangleType(T->getInjectedSpecializationType());
2151 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2152 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2153 mangleName(TD, T->getArgs(), T->getNumArgs());
2155 if (mangleSubstitution(QualType(T, 0)))
2158 mangleTemplatePrefix(T->getTemplateName());
2160 // FIXME: GCC does not appear to mangle the template arguments when
2161 // the template in question is a dependent template name. Should we
2162 // emulate that badness?
2163 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2164 addSubstitution(QualType(T, 0));
2168 void CXXNameMangler::mangleType(const DependentNameType *T) {
2169 // Typename types are always nested
2171 manglePrefix(T->getQualifier());
2172 mangleSourceName(T->getIdentifier());
2176 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2177 // Dependently-scoped template types are nested if they have a prefix.
2180 // TODO: avoid making this TemplateName.
2181 TemplateName Prefix =
2182 getASTContext().getDependentTemplateName(T->getQualifier(),
2183 T->getIdentifier());
2184 mangleTemplatePrefix(Prefix);
2186 // FIXME: GCC does not appear to mangle the template arguments when
2187 // the template in question is a dependent template name. Should we
2188 // emulate that badness?
2189 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2193 void CXXNameMangler::mangleType(const TypeOfType *T) {
2194 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2195 // "extension with parameters" mangling.
2199 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2200 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2201 // "extension with parameters" mangling.
2205 void CXXNameMangler::mangleType(const DecltypeType *T) {
2206 Expr *E = T->getUnderlyingExpr();
2208 // type ::= Dt <expression> E # decltype of an id-expression
2209 // # or class member access
2210 // ::= DT <expression> E # decltype of an expression
2212 // This purports to be an exhaustive list of id-expressions and
2213 // class member accesses. Note that we do not ignore parentheses;
2214 // parentheses change the semantics of decltype for these
2215 // expressions (and cause the mangler to use the other form).
2216 if (isa<DeclRefExpr>(E) ||
2217 isa<MemberExpr>(E) ||
2218 isa<UnresolvedLookupExpr>(E) ||
2219 isa<DependentScopeDeclRefExpr>(E) ||
2220 isa<CXXDependentScopeMemberExpr>(E) ||
2221 isa<UnresolvedMemberExpr>(E))
2225 mangleExpression(E);
2229 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2230 // If this is dependent, we need to record that. If not, we simply
2231 // mangle it as the underlying type since they are equivalent.
2232 if (T->isDependentType()) {
2235 switch (T->getUTTKind()) {
2236 case UnaryTransformType::EnumUnderlyingType:
2242 mangleType(T->getUnderlyingType());
2245 void CXXNameMangler::mangleType(const AutoType *T) {
2246 QualType D = T->getDeducedType();
2247 // <builtin-type> ::= Da # dependent auto
2254 void CXXNameMangler::mangleType(const AtomicType *T) {
2255 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2256 // (Until there's a standardized mangling...)
2258 mangleType(T->getValueType());
2261 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2262 const llvm::APSInt &Value) {
2263 // <expr-primary> ::= L <type> <value number> E # integer literal
2267 if (T->isBooleanType()) {
2268 // Boolean values are encoded as 0/1.
2269 Out << (Value.getBoolValue() ? '1' : '0');
2271 mangleNumber(Value);
2277 /// Mangles a member expression.
2278 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2280 NestedNameSpecifier *qualifier,
2281 NamedDecl *firstQualifierLookup,
2282 DeclarationName member,
2284 // <expression> ::= dt <expression> <unresolved-name>
2285 // ::= pt <expression> <unresolved-name>
2287 if (base->isImplicitCXXThis()) {
2288 // Note: GCC mangles member expressions to the implicit 'this' as
2289 // *this., whereas we represent them as this->. The Itanium C++ ABI
2290 // does not specify anything here, so we follow GCC.
2293 Out << (isArrow ? "pt" : "dt");
2294 mangleExpression(base);
2297 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2300 /// Look at the callee of the given call expression and determine if
2301 /// it's a parenthesized id-expression which would have triggered ADL
2303 static bool isParenthesizedADLCallee(const CallExpr *call) {
2304 const Expr *callee = call->getCallee();
2305 const Expr *fn = callee->IgnoreParens();
2307 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2308 // too, but for those to appear in the callee, it would have to be
2310 if (callee == fn) return false;
2312 // Must be an unresolved lookup.
2313 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2314 if (!lookup) return false;
2316 assert(!lookup->requiresADL());
2318 // Must be an unqualified lookup.
2319 if (lookup->getQualifier()) return false;
2321 // Must not have found a class member. Note that if one is a class
2322 // member, they're all class members.
2323 if (lookup->getNumDecls() > 0 &&
2324 (*lookup->decls_begin())->isCXXClassMember())
2327 // Otherwise, ADL would have been triggered.
2331 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2332 // <expression> ::= <unary operator-name> <expression>
2333 // ::= <binary operator-name> <expression> <expression>
2334 // ::= <trinary operator-name> <expression> <expression> <expression>
2335 // ::= cv <type> expression # conversion with one argument
2336 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2337 // ::= st <type> # sizeof (a type)
2338 // ::= at <type> # alignof (a type)
2339 // ::= <template-param>
2340 // ::= <function-param>
2341 // ::= sr <type> <unqualified-name> # dependent name
2342 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2343 // ::= ds <expression> <expression> # expr.*expr
2344 // ::= sZ <template-param> # size of a parameter pack
2345 // ::= sZ <function-param> # size of a function parameter pack
2346 // ::= <expr-primary>
2347 // <expr-primary> ::= L <type> <value number> E # integer literal
2348 // ::= L <type <value float> E # floating literal
2349 // ::= L <mangled-name> E # external name
2350 // ::= fpT # 'this' expression
2351 QualType ImplicitlyConvertedToType;
2354 switch (E->getStmtClass()) {
2355 case Expr::NoStmtClass:
2356 #define ABSTRACT_STMT(Type)
2357 #define EXPR(Type, Base)
2358 #define STMT(Type, Base) \
2359 case Expr::Type##Class:
2360 #include "clang/AST/StmtNodes.inc"
2363 // These all can only appear in local or variable-initialization
2364 // contexts and so should never appear in a mangling.
2365 case Expr::AddrLabelExprClass:
2366 case Expr::DesignatedInitExprClass:
2367 case Expr::ImplicitValueInitExprClass:
2368 case Expr::ParenListExprClass:
2369 case Expr::LambdaExprClass:
2370 llvm_unreachable("unexpected statement kind");
2372 // FIXME: invent manglings for all these.
2373 case Expr::BlockExprClass:
2374 case Expr::CXXPseudoDestructorExprClass:
2375 case Expr::ChooseExprClass:
2376 case Expr::CompoundLiteralExprClass:
2377 case Expr::ExtVectorElementExprClass:
2378 case Expr::GenericSelectionExprClass:
2379 case Expr::ObjCEncodeExprClass:
2380 case Expr::ObjCIsaExprClass:
2381 case Expr::ObjCIvarRefExprClass:
2382 case Expr::ObjCMessageExprClass:
2383 case Expr::ObjCPropertyRefExprClass:
2384 case Expr::ObjCProtocolExprClass:
2385 case Expr::ObjCSelectorExprClass:
2386 case Expr::ObjCStringLiteralClass:
2387 case Expr::ObjCBoxedExprClass:
2388 case Expr::ObjCArrayLiteralClass:
2389 case Expr::ObjCDictionaryLiteralClass:
2390 case Expr::ObjCSubscriptRefExprClass:
2391 case Expr::ObjCIndirectCopyRestoreExprClass:
2392 case Expr::OffsetOfExprClass:
2393 case Expr::PredefinedExprClass:
2394 case Expr::ShuffleVectorExprClass:
2395 case Expr::StmtExprClass:
2396 case Expr::UnaryTypeTraitExprClass:
2397 case Expr::BinaryTypeTraitExprClass:
2398 case Expr::TypeTraitExprClass:
2399 case Expr::ArrayTypeTraitExprClass:
2400 case Expr::ExpressionTraitExprClass:
2401 case Expr::VAArgExprClass:
2402 case Expr::CXXUuidofExprClass:
2403 case Expr::CUDAKernelCallExprClass:
2404 case Expr::AsTypeExprClass:
2405 case Expr::PseudoObjectExprClass:
2406 case Expr::AtomicExprClass:
2408 // As bad as this diagnostic is, it's better than crashing.
2409 DiagnosticsEngine &Diags = Context.getDiags();
2410 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2411 "cannot yet mangle expression type %0");
2412 Diags.Report(E->getExprLoc(), DiagID)
2413 << E->getStmtClassName() << E->getSourceRange();
2417 // Even gcc-4.5 doesn't mangle this.
2418 case Expr::BinaryConditionalOperatorClass: {
2419 DiagnosticsEngine &Diags = Context.getDiags();
2421 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2422 "?: operator with omitted middle operand cannot be mangled");
2423 Diags.Report(E->getExprLoc(), DiagID)
2424 << E->getStmtClassName() << E->getSourceRange();
2428 // These are used for internal purposes and cannot be meaningfully mangled.
2429 case Expr::OpaqueValueExprClass:
2430 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2432 case Expr::InitListExprClass: {
2433 // Proposal by Jason Merrill, 2012-01-03
2435 const InitListExpr *InitList = cast<InitListExpr>(E);
2436 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2437 mangleExpression(InitList->getInit(i));
2442 case Expr::CXXDefaultArgExprClass:
2443 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2446 case Expr::SubstNonTypeTemplateParmExprClass:
2447 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2451 case Expr::UserDefinedLiteralClass:
2452 // We follow g++'s approach of mangling a UDL as a call to the literal
2454 case Expr::CXXMemberCallExprClass: // fallthrough
2455 case Expr::CallExprClass: {
2456 const CallExpr *CE = cast<CallExpr>(E);
2458 // <expression> ::= cp <simple-id> <expression>* E
2459 // We use this mangling only when the call would use ADL except
2460 // for being parenthesized. Per discussion with David
2461 // Vandervoorde, 2011.04.25.
2462 if (isParenthesizedADLCallee(CE)) {
2464 // The callee here is a parenthesized UnresolvedLookupExpr with
2465 // no qualifier and should always get mangled as a <simple-id>
2468 // <expression> ::= cl <expression>* E
2473 mangleExpression(CE->getCallee(), CE->getNumArgs());
2474 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2475 mangleExpression(CE->getArg(I));
2480 case Expr::CXXNewExprClass: {
2481 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2482 if (New->isGlobalNew()) Out << "gs";
2483 Out << (New->isArray() ? "na" : "nw");
2484 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2485 E = New->placement_arg_end(); I != E; ++I)
2486 mangleExpression(*I);
2488 mangleType(New->getAllocatedType());
2489 if (New->hasInitializer()) {
2490 // Proposal by Jason Merrill, 2012-01-03
2491 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2495 const Expr *Init = New->getInitializer();
2496 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2497 // Directly inline the initializers.
2498 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2501 mangleExpression(*I);
2502 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2503 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2504 mangleExpression(PLE->getExpr(i));
2505 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2506 isa<InitListExpr>(Init)) {
2507 // Only take InitListExprs apart for list-initialization.
2508 const InitListExpr *InitList = cast<InitListExpr>(Init);
2509 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2510 mangleExpression(InitList->getInit(i));
2512 mangleExpression(Init);
2518 case Expr::MemberExprClass: {
2519 const MemberExpr *ME = cast<MemberExpr>(E);
2520 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2521 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2526 case Expr::UnresolvedMemberExprClass: {
2527 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2528 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2529 ME->getQualifier(), 0, ME->getMemberName(),
2531 if (ME->hasExplicitTemplateArgs())
2532 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2536 case Expr::CXXDependentScopeMemberExprClass: {
2537 const CXXDependentScopeMemberExpr *ME
2538 = cast<CXXDependentScopeMemberExpr>(E);
2539 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2540 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2541 ME->getMember(), Arity);
2542 if (ME->hasExplicitTemplateArgs())
2543 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2547 case Expr::UnresolvedLookupExprClass: {
2548 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2549 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2551 // All the <unresolved-name> productions end in a
2552 // base-unresolved-name, where <template-args> are just tacked
2554 if (ULE->hasExplicitTemplateArgs())
2555 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2559 case Expr::CXXUnresolvedConstructExprClass: {
2560 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2561 unsigned N = CE->arg_size();
2564 mangleType(CE->getType());
2565 if (N != 1) Out << '_';
2566 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2567 if (N != 1) Out << 'E';
2571 case Expr::CXXTemporaryObjectExprClass:
2572 case Expr::CXXConstructExprClass: {
2573 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2574 unsigned N = CE->getNumArgs();
2576 // Proposal by Jason Merrill, 2012-01-03
2577 if (CE->isListInitialization())
2581 mangleType(CE->getType());
2582 if (N != 1) Out << '_';
2583 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2584 if (N != 1) Out << 'E';
2588 case Expr::CXXScalarValueInitExprClass:
2590 mangleType(E->getType());
2594 case Expr::CXXNoexceptExprClass:
2596 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2599 case Expr::UnaryExprOrTypeTraitExprClass: {
2600 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2602 if (!SAE->isInstantiationDependent()) {
2604 // If the operand of a sizeof or alignof operator is not
2605 // instantiation-dependent it is encoded as an integer literal
2606 // reflecting the result of the operator.
2608 // If the result of the operator is implicitly converted to a known
2609 // integer type, that type is used for the literal; otherwise, the type
2610 // of std::size_t or std::ptrdiff_t is used.
2611 QualType T = (ImplicitlyConvertedToType.isNull() ||
2612 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2613 : ImplicitlyConvertedToType;
2614 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2615 mangleIntegerLiteral(T, V);
2619 switch(SAE->getKind()) {
2627 DiagnosticsEngine &Diags = Context.getDiags();
2628 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2629 "cannot yet mangle vec_step expression");
2630 Diags.Report(DiagID);
2633 if (SAE->isArgumentType()) {
2635 mangleType(SAE->getArgumentType());
2638 mangleExpression(SAE->getArgumentExpr());
2643 case Expr::CXXThrowExprClass: {
2644 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2646 // Proposal from David Vandervoorde, 2010.06.30
2647 if (TE->getSubExpr()) {
2649 mangleExpression(TE->getSubExpr());
2656 case Expr::CXXTypeidExprClass: {
2657 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2659 // Proposal from David Vandervoorde, 2010.06.30
2660 if (TIE->isTypeOperand()) {
2662 mangleType(TIE->getTypeOperand());
2665 mangleExpression(TIE->getExprOperand());
2670 case Expr::CXXDeleteExprClass: {
2671 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2673 // Proposal from David Vandervoorde, 2010.06.30
2674 if (DE->isGlobalDelete()) Out << "gs";
2675 Out << (DE->isArrayForm() ? "da" : "dl");
2676 mangleExpression(DE->getArgument());
2680 case Expr::UnaryOperatorClass: {
2681 const UnaryOperator *UO = cast<UnaryOperator>(E);
2682 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2684 mangleExpression(UO->getSubExpr());
2688 case Expr::ArraySubscriptExprClass: {
2689 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2691 // Array subscript is treated as a syntactically weird form of
2694 mangleExpression(AE->getLHS());
2695 mangleExpression(AE->getRHS());
2699 case Expr::CompoundAssignOperatorClass: // fallthrough
2700 case Expr::BinaryOperatorClass: {
2701 const BinaryOperator *BO = cast<BinaryOperator>(E);
2702 if (BO->getOpcode() == BO_PtrMemD)
2705 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2707 mangleExpression(BO->getLHS());
2708 mangleExpression(BO->getRHS());
2712 case Expr::ConditionalOperatorClass: {
2713 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2714 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2715 mangleExpression(CO->getCond());
2716 mangleExpression(CO->getLHS(), Arity);
2717 mangleExpression(CO->getRHS(), Arity);
2721 case Expr::ImplicitCastExprClass: {
2722 ImplicitlyConvertedToType = E->getType();
2723 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2727 case Expr::ObjCBridgedCastExprClass: {
2728 // Mangle ownership casts as a vendor extended operator __bridge,
2729 // __bridge_transfer, or __bridge_retain.
2730 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2731 Out << "v1U" << Kind.size() << Kind;
2733 // Fall through to mangle the cast itself.
2735 case Expr::CStyleCastExprClass:
2736 case Expr::CXXStaticCastExprClass:
2737 case Expr::CXXDynamicCastExprClass:
2738 case Expr::CXXReinterpretCastExprClass:
2739 case Expr::CXXConstCastExprClass:
2740 case Expr::CXXFunctionalCastExprClass: {
2741 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2743 mangleType(ECE->getType());
2744 mangleExpression(ECE->getSubExpr());
2748 case Expr::CXXOperatorCallExprClass: {
2749 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2750 unsigned NumArgs = CE->getNumArgs();
2751 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2752 // Mangle the arguments.
2753 for (unsigned i = 0; i != NumArgs; ++i)
2754 mangleExpression(CE->getArg(i));
2758 case Expr::ParenExprClass:
2759 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2762 case Expr::DeclRefExprClass: {
2763 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2765 switch (D->getKind()) {
2767 // <expr-primary> ::= L <mangled-name> E # external name
2774 mangleFunctionParam(cast<ParmVarDecl>(D));
2777 case Decl::EnumConstant: {
2778 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2779 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2783 case Decl::NonTypeTemplateParm: {
2784 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2785 mangleTemplateParameter(PD->getIndex());
2794 case Expr::SubstNonTypeTemplateParmPackExprClass:
2795 // FIXME: not clear how to mangle this!
2796 // template <unsigned N...> class A {
2797 // template <class U...> void foo(U (&x)[N]...);
2799 Out << "_SUBSTPACK_";
2802 case Expr::FunctionParmPackExprClass: {
2803 // FIXME: not clear how to mangle this!
2804 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
2805 Out << "v110_SUBSTPACK";
2806 mangleFunctionParam(FPPE->getParameterPack());
2810 case Expr::DependentScopeDeclRefExprClass: {
2811 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2812 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2814 // All the <unresolved-name> productions end in a
2815 // base-unresolved-name, where <template-args> are just tacked
2817 if (DRE->hasExplicitTemplateArgs())
2818 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2822 case Expr::CXXBindTemporaryExprClass:
2823 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2826 case Expr::ExprWithCleanupsClass:
2827 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2830 case Expr::FloatingLiteralClass: {
2831 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2833 mangleType(FL->getType());
2834 mangleFloat(FL->getValue());
2839 case Expr::CharacterLiteralClass:
2841 mangleType(E->getType());
2842 Out << cast<CharacterLiteral>(E)->getValue();
2846 // FIXME. __objc_yes/__objc_no are mangled same as true/false
2847 case Expr::ObjCBoolLiteralExprClass:
2849 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2853 case Expr::CXXBoolLiteralExprClass:
2855 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2859 case Expr::IntegerLiteralClass: {
2860 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2861 if (E->getType()->isSignedIntegerType())
2862 Value.setIsSigned(true);
2863 mangleIntegerLiteral(E->getType(), Value);
2867 case Expr::ImaginaryLiteralClass: {
2868 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2869 // Mangle as if a complex literal.
2870 // Proposal from David Vandevoorde, 2010.06.30.
2872 mangleType(E->getType());
2873 if (const FloatingLiteral *Imag =
2874 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2875 // Mangle a floating-point zero of the appropriate type.
2876 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2878 mangleFloat(Imag->getValue());
2881 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2882 if (IE->getSubExpr()->getType()->isSignedIntegerType())
2883 Value.setIsSigned(true);
2884 mangleNumber(Value);
2890 case Expr::StringLiteralClass: {
2891 // Revised proposal from David Vandervoorde, 2010.07.15.
2893 assert(isa<ConstantArrayType>(E->getType()));
2894 mangleType(E->getType());
2899 case Expr::GNUNullExprClass:
2900 // FIXME: should this really be mangled the same as nullptr?
2903 case Expr::CXXNullPtrLiteralExprClass: {
2904 // Proposal from David Vandervoorde, 2010.06.30, as
2905 // modified by ABI list discussion.
2910 case Expr::PackExpansionExprClass:
2912 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
2915 case Expr::SizeOfPackExprClass: {
2917 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
2918 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
2919 mangleTemplateParameter(TTP->getIndex());
2920 else if (const NonTypeTemplateParmDecl *NTTP
2921 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
2922 mangleTemplateParameter(NTTP->getIndex());
2923 else if (const TemplateTemplateParmDecl *TempTP
2924 = dyn_cast<TemplateTemplateParmDecl>(Pack))
2925 mangleTemplateParameter(TempTP->getIndex());
2927 mangleFunctionParam(cast<ParmVarDecl>(Pack));
2931 case Expr::MaterializeTemporaryExprClass: {
2932 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
2936 case Expr::CXXThisExprClass:
2942 /// Mangle an expression which refers to a parameter variable.
2944 /// <expression> ::= <function-param>
2945 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
2946 /// <function-param> ::= fp <top-level CV-qualifiers>
2947 /// <parameter-2 non-negative number> _ # L == 0, I > 0
2948 /// <function-param> ::= fL <L-1 non-negative number>
2949 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
2950 /// <function-param> ::= fL <L-1 non-negative number>
2951 /// p <top-level CV-qualifiers>
2952 /// <I-1 non-negative number> _ # L > 0, I > 0
2954 /// L is the nesting depth of the parameter, defined as 1 if the
2955 /// parameter comes from the innermost function prototype scope
2956 /// enclosing the current context, 2 if from the next enclosing
2957 /// function prototype scope, and so on, with one special case: if
2958 /// we've processed the full parameter clause for the innermost
2959 /// function type, then L is one less. This definition conveniently
2960 /// makes it irrelevant whether a function's result type was written
2961 /// trailing or leading, but is otherwise overly complicated; the
2962 /// numbering was first designed without considering references to
2963 /// parameter in locations other than return types, and then the
2964 /// mangling had to be generalized without changing the existing
2967 /// I is the zero-based index of the parameter within its parameter
2968 /// declaration clause. Note that the original ABI document describes
2969 /// this using 1-based ordinals.
2970 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
2971 unsigned parmDepth = parm->getFunctionScopeDepth();
2972 unsigned parmIndex = parm->getFunctionScopeIndex();
2975 // parmDepth does not include the declaring function prototype.
2976 // FunctionTypeDepth does account for that.
2977 assert(parmDepth < FunctionTypeDepth.getDepth());
2978 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
2979 if (FunctionTypeDepth.isInResultType())
2982 if (nestingDepth == 0) {
2985 Out << "fL" << (nestingDepth - 1) << 'p';
2988 // Top-level qualifiers. We don't have to worry about arrays here,
2989 // because parameters declared as arrays should already have been
2990 // transformed to have pointer type. FIXME: apparently these don't
2991 // get mangled if used as an rvalue of a known non-class type?
2992 assert(!parm->getType()->isArrayType()
2993 && "parameter's type is still an array type?");
2994 mangleQualifiers(parm->getType().getQualifiers());
2997 if (parmIndex != 0) {
2998 Out << (parmIndex - 1);
3003 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3004 // <ctor-dtor-name> ::= C1 # complete object constructor
3005 // ::= C2 # base object constructor
3006 // ::= C3 # complete object allocating constructor
3015 case Ctor_CompleteAllocating:
3021 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3022 // <ctor-dtor-name> ::= D0 # deleting destructor
3023 // ::= D1 # complete object destructor
3024 // ::= D2 # base object destructor
3039 void CXXNameMangler::mangleTemplateArgs(
3040 const ASTTemplateArgumentListInfo &TemplateArgs) {
3041 // <template-args> ::= I <template-arg>+ E
3043 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3044 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3048 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3049 // <template-args> ::= I <template-arg>+ E
3051 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3052 mangleTemplateArg(AL[i]);
3056 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3057 unsigned NumTemplateArgs) {
3058 // <template-args> ::= I <template-arg>+ E
3060 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3061 mangleTemplateArg(TemplateArgs[i]);
3065 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3066 // <template-arg> ::= <type> # type or template
3067 // ::= X <expression> E # expression
3068 // ::= <expr-primary> # simple expressions
3069 // ::= J <template-arg>* E # argument pack
3070 // ::= sp <expression> # pack expansion of (C++0x)
3071 if (!A.isInstantiationDependent() || A.isDependent())
3072 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3074 switch (A.getKind()) {
3075 case TemplateArgument::Null:
3076 llvm_unreachable("Cannot mangle NULL template argument");
3078 case TemplateArgument::Type:
3079 mangleType(A.getAsType());
3081 case TemplateArgument::Template:
3082 // This is mangled as <type>.
3083 mangleType(A.getAsTemplate());
3085 case TemplateArgument::TemplateExpansion:
3086 // <type> ::= Dp <type> # pack expansion (C++0x)
3088 mangleType(A.getAsTemplateOrTemplatePattern());
3090 case TemplateArgument::Expression: {
3091 // It's possible to end up with a DeclRefExpr here in certain
3092 // dependent cases, in which case we should mangle as a
3094 const Expr *E = A.getAsExpr()->IgnoreParens();
3095 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3096 const ValueDecl *D = DRE->getDecl();
3097 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3106 mangleExpression(E);
3110 case TemplateArgument::Integral:
3111 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3113 case TemplateArgument::Declaration: {
3114 // <expr-primary> ::= L <mangled-name> E # external name
3115 // Clang produces AST's where pointer-to-member-function expressions
3116 // and pointer-to-function expressions are represented as a declaration not
3117 // an expression. We compensate for it here to produce the correct mangling.
3118 ValueDecl *D = A.getAsDecl();
3119 bool compensateMangling = !A.isDeclForReferenceParam();
3120 if (compensateMangling) {
3122 mangleOperatorName(OO_Amp, 1);
3126 // References to external entities use the mangled name; if the name would
3127 // not normally be manged then mangle it as unqualified.
3129 // FIXME: The ABI specifies that external names here should have _Z, but
3130 // gcc leaves this off.
3131 if (compensateMangling)
3137 if (compensateMangling)
3142 case TemplateArgument::NullPtr: {
3143 // <expr-primary> ::= L <type> 0 E
3145 mangleType(A.getNullPtrType());
3149 case TemplateArgument::Pack: {
3150 // Note: proposal by Mike Herrick on 12/20/10
3152 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
3153 PAEnd = A.pack_end();
3155 mangleTemplateArg(*PA);
3161 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3162 // <template-param> ::= T_ # first template parameter
3163 // ::= T <parameter-2 non-negative number> _
3167 Out << 'T' << (Index - 1) << '_';
3170 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3171 bool result = mangleSubstitution(type);
3172 assert(result && "no existing substitution for type");
3176 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3177 bool result = mangleSubstitution(tname);
3178 assert(result && "no existing substitution for template name");
3182 // <substitution> ::= S <seq-id> _
3184 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3185 // Try one of the standard substitutions first.
3186 if (mangleStandardSubstitution(ND))
3189 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3190 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3193 /// \brief Determine whether the given type has any qualifiers that are
3194 /// relevant for substitutions.
3195 static bool hasMangledSubstitutionQualifiers(QualType T) {
3196 Qualifiers Qs = T.getQualifiers();
3197 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3200 bool CXXNameMangler::mangleSubstitution(QualType T) {
3201 if (!hasMangledSubstitutionQualifiers(T)) {
3202 if (const RecordType *RT = T->getAs<RecordType>())
3203 return mangleSubstitution(RT->getDecl());
3206 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3208 return mangleSubstitution(TypePtr);
3211 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3212 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3213 return mangleSubstitution(TD);
3215 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3216 return mangleSubstitution(
3217 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3220 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3221 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3222 if (I == Substitutions.end())
3225 unsigned SeqID = I->second;
3231 // <seq-id> is encoded in base-36, using digits and upper case letters.
3233 char *BufferPtr = llvm::array_endof(Buffer);
3235 if (SeqID == 0) *--BufferPtr = '0';
3238 assert(BufferPtr > Buffer && "Buffer overflow!");
3240 char c = static_cast<char>(SeqID % 36);
3242 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3247 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3254 static bool isCharType(QualType T) {
3258 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3259 T->isSpecificBuiltinType(BuiltinType::Char_U);
3262 /// isCharSpecialization - Returns whether a given type is a template
3263 /// specialization of a given name with a single argument of type char.
3264 static bool isCharSpecialization(QualType T, const char *Name) {
3268 const RecordType *RT = T->getAs<RecordType>();
3272 const ClassTemplateSpecializationDecl *SD =
3273 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3277 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3280 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3281 if (TemplateArgs.size() != 1)
3284 if (!isCharType(TemplateArgs[0].getAsType()))
3287 return SD->getIdentifier()->getName() == Name;
3290 template <std::size_t StrLen>
3291 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3292 const char (&Str)[StrLen]) {
3293 if (!SD->getIdentifier()->isStr(Str))
3296 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3297 if (TemplateArgs.size() != 2)
3300 if (!isCharType(TemplateArgs[0].getAsType()))
3303 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3309 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3310 // <substitution> ::= St # ::std::
3311 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3318 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3319 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3322 // <substitution> ::= Sa # ::std::allocator
3323 if (TD->getIdentifier()->isStr("allocator")) {
3328 // <<substitution> ::= Sb # ::std::basic_string
3329 if (TD->getIdentifier()->isStr("basic_string")) {
3335 if (const ClassTemplateSpecializationDecl *SD =
3336 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3337 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3340 // <substitution> ::= Ss # ::std::basic_string<char,
3341 // ::std::char_traits<char>,
3342 // ::std::allocator<char> >
3343 if (SD->getIdentifier()->isStr("basic_string")) {
3344 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3346 if (TemplateArgs.size() != 3)
3349 if (!isCharType(TemplateArgs[0].getAsType()))
3352 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3355 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3362 // <substitution> ::= Si # ::std::basic_istream<char,
3363 // ::std::char_traits<char> >
3364 if (isStreamCharSpecialization(SD, "basic_istream")) {
3369 // <substitution> ::= So # ::std::basic_ostream<char,
3370 // ::std::char_traits<char> >
3371 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3376 // <substitution> ::= Sd # ::std::basic_iostream<char,
3377 // ::std::char_traits<char> >
3378 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3386 void CXXNameMangler::addSubstitution(QualType T) {
3387 if (!hasMangledSubstitutionQualifiers(T)) {
3388 if (const RecordType *RT = T->getAs<RecordType>()) {
3389 addSubstitution(RT->getDecl());
3394 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3395 addSubstitution(TypePtr);
3398 void CXXNameMangler::addSubstitution(TemplateName Template) {
3399 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3400 return addSubstitution(TD);
3402 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3403 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3406 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3407 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3408 Substitutions[Ptr] = SeqID++;
3413 /// \brief Mangles the name of the declaration D and emits that name to the
3414 /// given output stream.
3416 /// If the declaration D requires a mangled name, this routine will emit that
3417 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3418 /// and this routine will return false. In this case, the caller should just
3419 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3421 void ItaniumMangleContext::mangleName(const NamedDecl *D,
3423 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3424 "Invalid mangleName() call, argument is not a variable or function!");
3425 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3426 "Invalid mangleName() call on 'structor decl!");
3428 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3429 getASTContext().getSourceManager(),
3430 "Mangling declaration");
3432 CXXNameMangler Mangler(*this, Out, D);
3433 return Mangler.mangle(D);
3436 void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3439 CXXNameMangler Mangler(*this, Out, D, Type);
3443 void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3446 CXXNameMangler Mangler(*this, Out, D, Type);
3450 void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3451 const ThunkInfo &Thunk,
3453 // <special-name> ::= T <call-offset> <base encoding>
3454 // # base is the nominal target function of thunk
3455 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3456 // # base is the nominal target function of thunk
3457 // # first call-offset is 'this' adjustment
3458 // # second call-offset is result adjustment
3460 assert(!isa<CXXDestructorDecl>(MD) &&
3461 "Use mangleCXXDtor for destructor decls!");
3462 CXXNameMangler Mangler(*this, Out);
3463 Mangler.getStream() << "_ZT";
3464 if (!Thunk.Return.isEmpty())
3465 Mangler.getStream() << 'c';
3467 // Mangle the 'this' pointer adjustment.
3468 Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3470 // Mangle the return pointer adjustment if there is one.
3471 if (!Thunk.Return.isEmpty())
3472 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3473 Thunk.Return.VBaseOffsetOffset);
3475 Mangler.mangleFunctionEncoding(MD);
3479 ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3481 const ThisAdjustment &ThisAdjustment,
3483 // <special-name> ::= T <call-offset> <base encoding>
3484 // # base is the nominal target function of thunk
3485 CXXNameMangler Mangler(*this, Out, DD, Type);
3486 Mangler.getStream() << "_ZT";
3488 // Mangle the 'this' pointer adjustment.
3489 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3490 ThisAdjustment.VCallOffsetOffset);
3492 Mangler.mangleFunctionEncoding(DD);
3495 /// mangleGuardVariable - Returns the mangled name for a guard variable
3496 /// for the passed in VarDecl.
3497 void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
3499 // <special-name> ::= GV <object name> # Guard variable for one-time
3501 CXXNameMangler Mangler(*this, Out);
3502 Mangler.getStream() << "_ZGV";
3503 Mangler.mangleName(D);
3506 void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3508 // We match the GCC mangling here.
3509 // <special-name> ::= GR <object name>
3510 CXXNameMangler Mangler(*this, Out);
3511 Mangler.getStream() << "_ZGR";
3512 Mangler.mangleName(D);
3515 void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3517 // <special-name> ::= TV <type> # virtual table
3518 CXXNameMangler Mangler(*this, Out);
3519 Mangler.getStream() << "_ZTV";
3520 Mangler.mangleNameOrStandardSubstitution(RD);
3523 void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3525 // <special-name> ::= TT <type> # VTT structure
3526 CXXNameMangler Mangler(*this, Out);
3527 Mangler.getStream() << "_ZTT";
3528 Mangler.mangleNameOrStandardSubstitution(RD);
3531 void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3533 const CXXRecordDecl *Type,
3535 // <special-name> ::= TC <type> <offset number> _ <base type>
3536 CXXNameMangler Mangler(*this, Out);
3537 Mangler.getStream() << "_ZTC";
3538 Mangler.mangleNameOrStandardSubstitution(RD);
3539 Mangler.getStream() << Offset;
3540 Mangler.getStream() << '_';
3541 Mangler.mangleNameOrStandardSubstitution(Type);
3544 void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3546 // <special-name> ::= TI <type> # typeinfo structure
3547 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3548 CXXNameMangler Mangler(*this, Out);
3549 Mangler.getStream() << "_ZTI";
3550 Mangler.mangleType(Ty);
3553 void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3555 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3556 CXXNameMangler Mangler(*this, Out);
3557 Mangler.getStream() << "_ZTS";
3558 Mangler.mangleType(Ty);
3561 MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3562 DiagnosticsEngine &Diags) {
3563 return new ItaniumMangleContext(Context, Diags);