1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
14 // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
35 #define MANGLE_CHECKER 0
41 using namespace clang;
45 /// \brief Retrieve the declaration context that should be used when mangling
46 /// the given declaration.
47 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
68 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
75 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
76 return getEffectiveDeclContext(cast<Decl>(DC));
79 static bool isLocalContainerContext(const DeclContext *DC) {
80 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
83 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
84 const DeclContext *DC = getEffectiveDeclContext(D);
85 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
86 if (isLocalContainerContext(DC))
87 return dyn_cast<RecordDecl>(D);
89 DC = getEffectiveDeclContext(D);
94 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
95 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
96 return ftd->getTemplatedDecl();
101 static const NamedDecl *getStructor(const NamedDecl *decl) {
102 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
103 return (fn ? getStructor(fn) : decl);
106 static bool isLambda(const NamedDecl *ND) {
107 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
111 return Record->isLambda();
114 static const unsigned UnknownArity = ~0U;
116 class ItaniumMangleContextImpl : public ItaniumMangleContext {
117 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
118 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
119 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
122 explicit ItaniumMangleContextImpl(ASTContext &Context,
123 DiagnosticsEngine &Diags)
124 : ItaniumMangleContext(Context, Diags) {}
126 /// @name Mangler Entry Points
129 bool shouldMangleCXXName(const NamedDecl *D) override;
130 bool shouldMangleStringLiteral(const StringLiteral *) override {
133 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
134 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
135 raw_ostream &) override;
136 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
137 const ThisAdjustment &ThisAdjustment,
138 raw_ostream &) override;
139 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
140 raw_ostream &) override;
141 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
142 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
143 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
144 const CXXRecordDecl *Type, raw_ostream &) override;
145 void mangleCXXRTTI(QualType T, raw_ostream &) override;
146 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
147 void mangleTypeName(QualType T, raw_ostream &) override;
148 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
149 raw_ostream &) override;
150 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
151 raw_ostream &) override;
153 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
154 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
155 void mangleDynamicAtExitDestructor(const VarDecl *D,
156 raw_ostream &Out) override;
157 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
158 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
159 raw_ostream &) override;
161 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
163 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
164 // Lambda closure types are already numbered.
168 // Anonymous tags are already numbered.
169 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
170 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
174 // Use the canonical number for externally visible decls.
175 if (ND->isExternallyVisible()) {
176 unsigned discriminator = getASTContext().getManglingNumber(ND);
177 if (discriminator == 1)
179 disc = discriminator - 2;
183 // Make up a reasonable number for internal decls.
184 unsigned &discriminator = Uniquifier[ND];
185 if (!discriminator) {
186 const DeclContext *DC = getEffectiveDeclContext(ND);
187 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
189 if (discriminator == 1)
191 disc = discriminator-2;
197 /// CXXNameMangler - Manage the mangling of a single name.
198 class CXXNameMangler {
199 ItaniumMangleContextImpl &Context;
202 /// The "structor" is the top-level declaration being mangled, if
203 /// that's not a template specialization; otherwise it's the pattern
204 /// for that specialization.
205 const NamedDecl *Structor;
206 unsigned StructorType;
208 /// SeqID - The next subsitution sequence number.
211 class FunctionTypeDepthState {
214 enum { InResultTypeMask = 1 };
217 FunctionTypeDepthState() : Bits(0) {}
219 /// The number of function types we're inside.
220 unsigned getDepth() const {
224 /// True if we're in the return type of the innermost function type.
225 bool isInResultType() const {
226 return Bits & InResultTypeMask;
229 FunctionTypeDepthState push() {
230 FunctionTypeDepthState tmp = *this;
231 Bits = (Bits & ~InResultTypeMask) + 2;
235 void enterResultType() {
236 Bits |= InResultTypeMask;
239 void leaveResultType() {
240 Bits &= ~InResultTypeMask;
243 void pop(FunctionTypeDepthState saved) {
244 assert(getDepth() == saved.getDepth() + 1);
250 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
252 ASTContext &getASTContext() const { return Context.getASTContext(); }
255 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
256 const NamedDecl *D = nullptr)
257 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
259 // These can't be mangled without a ctor type or dtor type.
260 assert(!D || (!isa<CXXDestructorDecl>(D) &&
261 !isa<CXXConstructorDecl>(D)));
263 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
264 const CXXConstructorDecl *D, CXXCtorType Type)
265 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
267 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
268 const CXXDestructorDecl *D, CXXDtorType Type)
269 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
274 if (Out.str()[0] == '\01')
278 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
279 assert(status == 0 && "Could not demangle mangled name!");
283 raw_ostream &getStream() { return Out; }
285 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
286 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
287 void mangleNumber(const llvm::APSInt &I);
288 void mangleNumber(int64_t Number);
289 void mangleFloat(const llvm::APFloat &F);
290 void mangleFunctionEncoding(const FunctionDecl *FD);
291 void mangleSeqID(unsigned SeqID);
292 void mangleName(const NamedDecl *ND);
293 void mangleType(QualType T);
294 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
298 bool mangleSubstitution(const NamedDecl *ND);
299 bool mangleSubstitution(QualType T);
300 bool mangleSubstitution(TemplateName Template);
301 bool mangleSubstitution(uintptr_t Ptr);
303 void mangleExistingSubstitution(QualType type);
304 void mangleExistingSubstitution(TemplateName name);
306 bool mangleStandardSubstitution(const NamedDecl *ND);
308 void addSubstitution(const NamedDecl *ND) {
309 ND = cast<NamedDecl>(ND->getCanonicalDecl());
311 addSubstitution(reinterpret_cast<uintptr_t>(ND));
313 void addSubstitution(QualType T);
314 void addSubstitution(TemplateName Template);
315 void addSubstitution(uintptr_t Ptr);
317 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
318 NamedDecl *firstQualifierLookup,
319 bool recursive = false);
320 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
321 NamedDecl *firstQualifierLookup,
322 DeclarationName name,
323 unsigned KnownArity = UnknownArity);
325 void mangleName(const TemplateDecl *TD,
326 const TemplateArgument *TemplateArgs,
327 unsigned NumTemplateArgs);
328 void mangleUnqualifiedName(const NamedDecl *ND) {
329 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
331 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
332 unsigned KnownArity);
333 void mangleUnscopedName(const NamedDecl *ND);
334 void mangleUnscopedTemplateName(const TemplateDecl *ND);
335 void mangleUnscopedTemplateName(TemplateName);
336 void mangleSourceName(const IdentifierInfo *II);
337 void mangleLocalName(const Decl *D);
338 void mangleBlockForPrefix(const BlockDecl *Block);
339 void mangleUnqualifiedBlock(const BlockDecl *Block);
340 void mangleLambda(const CXXRecordDecl *Lambda);
341 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
342 bool NoFunction=false);
343 void mangleNestedName(const TemplateDecl *TD,
344 const TemplateArgument *TemplateArgs,
345 unsigned NumTemplateArgs);
346 void manglePrefix(NestedNameSpecifier *qualifier);
347 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
348 void manglePrefix(QualType type);
349 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
350 void mangleTemplatePrefix(TemplateName Template);
351 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
352 void mangleQualifiers(Qualifiers Quals);
353 void mangleRefQualifier(RefQualifierKind RefQualifier);
355 void mangleObjCMethodName(const ObjCMethodDecl *MD);
357 // Declare manglers for every type class.
358 #define ABSTRACT_TYPE(CLASS, PARENT)
359 #define NON_CANONICAL_TYPE(CLASS, PARENT)
360 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
361 #include "clang/AST/TypeNodes.def"
363 void mangleType(const TagType*);
364 void mangleType(TemplateName);
365 void mangleBareFunctionType(const FunctionType *T,
366 bool MangleReturnType);
367 void mangleNeonVectorType(const VectorType *T);
368 void mangleAArch64NeonVectorType(const VectorType *T);
370 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
371 void mangleMemberExpr(const Expr *base, bool isArrow,
372 NestedNameSpecifier *qualifier,
373 NamedDecl *firstQualifierLookup,
374 DeclarationName name,
375 unsigned knownArity);
376 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
377 void mangleCXXCtorType(CXXCtorType T);
378 void mangleCXXDtorType(CXXDtorType T);
380 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
381 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
382 unsigned NumTemplateArgs);
383 void mangleTemplateArgs(const TemplateArgumentList &AL);
384 void mangleTemplateArg(TemplateArgument A);
386 void mangleTemplateParameter(unsigned Index);
388 void mangleFunctionParam(const ParmVarDecl *parm);
393 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
394 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
396 LanguageLinkage L = FD->getLanguageLinkage();
397 // Overloadable functions need mangling.
398 if (FD->hasAttr<OverloadableAttr>())
401 // "main" is not mangled.
405 // C++ functions and those whose names are not a simple identifier need
407 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
410 // C functions are not mangled.
411 if (L == CLanguageLinkage)
415 // Otherwise, no mangling is done outside C++ mode.
416 if (!getASTContext().getLangOpts().CPlusPlus)
419 const VarDecl *VD = dyn_cast<VarDecl>(D);
421 // C variables are not mangled.
425 // Variables at global scope with non-internal linkage are not mangled
426 const DeclContext *DC = getEffectiveDeclContext(D);
427 // Check for extern variable declared locally.
428 if (DC->isFunctionOrMethod() && D->hasLinkage())
429 while (!DC->isNamespace() && !DC->isTranslationUnit())
430 DC = getEffectiveParentContext(DC);
431 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
432 !isa<VarTemplateSpecializationDecl>(D))
439 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
440 // <mangled-name> ::= _Z <encoding>
442 // ::= <special-name>
444 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
445 mangleFunctionEncoding(FD);
446 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
448 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
449 mangleName(IFD->getAnonField());
451 mangleName(cast<FieldDecl>(D));
454 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
455 // <encoding> ::= <function name> <bare-function-type>
458 // Don't mangle in the type if this isn't a decl we should typically mangle.
459 if (!Context.shouldMangleDeclName(FD))
462 if (FD->hasAttr<EnableIfAttr>()) {
463 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
464 Out << "Ua9enable_ifI";
465 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
467 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
468 E = FD->getAttrs().rend();
470 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
474 mangleExpression(EIA->getCond());
478 FunctionTypeDepth.pop(Saved);
481 // Whether the mangling of a function type includes the return type depends on
482 // the context and the nature of the function. The rules for deciding whether
483 // the return type is included are:
485 // 1. Template functions (names or types) have return types encoded, with
486 // the exceptions listed below.
487 // 2. Function types not appearing as part of a function name mangling,
488 // e.g. parameters, pointer types, etc., have return type encoded, with the
489 // exceptions listed below.
490 // 3. Non-template function names do not have return types encoded.
492 // The exceptions mentioned in (1) and (2) above, for which the return type is
493 // never included, are
496 // 3. Conversion operator functions, e.g. operator int.
497 bool MangleReturnType = false;
498 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
499 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
500 isa<CXXConversionDecl>(FD)))
501 MangleReturnType = true;
503 // Mangle the type of the primary template.
504 FD = PrimaryTemplate->getTemplatedDecl();
507 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
511 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
512 while (isa<LinkageSpecDecl>(DC)) {
513 DC = getEffectiveParentContext(DC);
519 /// isStd - Return whether a given namespace is the 'std' namespace.
520 static bool isStd(const NamespaceDecl *NS) {
521 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
522 ->isTranslationUnit())
525 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
526 return II && II->isStr("std");
529 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
531 static bool isStdNamespace(const DeclContext *DC) {
532 if (!DC->isNamespace())
535 return isStd(cast<NamespaceDecl>(DC));
538 static const TemplateDecl *
539 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
540 // Check if we have a function template.
541 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
542 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
543 TemplateArgs = FD->getTemplateSpecializationArgs();
548 // Check if we have a class template.
549 if (const ClassTemplateSpecializationDecl *Spec =
550 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
551 TemplateArgs = &Spec->getTemplateArgs();
552 return Spec->getSpecializedTemplate();
555 // Check if we have a variable template.
556 if (const VarTemplateSpecializationDecl *Spec =
557 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
558 TemplateArgs = &Spec->getTemplateArgs();
559 return Spec->getSpecializedTemplate();
565 void CXXNameMangler::mangleName(const NamedDecl *ND) {
566 // <name> ::= <nested-name>
567 // ::= <unscoped-name>
568 // ::= <unscoped-template-name> <template-args>
571 const DeclContext *DC = getEffectiveDeclContext(ND);
573 // If this is an extern variable declared locally, the relevant DeclContext
574 // is that of the containing namespace, or the translation unit.
575 // FIXME: This is a hack; extern variables declared locally should have
576 // a proper semantic declaration context!
577 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
578 while (!DC->isNamespace() && !DC->isTranslationUnit())
579 DC = getEffectiveParentContext(DC);
580 else if (GetLocalClassDecl(ND)) {
585 DC = IgnoreLinkageSpecDecls(DC);
587 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
588 // Check if we have a template.
589 const TemplateArgumentList *TemplateArgs = nullptr;
590 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
591 mangleUnscopedTemplateName(TD);
592 mangleTemplateArgs(*TemplateArgs);
596 mangleUnscopedName(ND);
600 if (isLocalContainerContext(DC)) {
605 mangleNestedName(ND, DC);
607 void CXXNameMangler::mangleName(const TemplateDecl *TD,
608 const TemplateArgument *TemplateArgs,
609 unsigned NumTemplateArgs) {
610 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
612 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
613 mangleUnscopedTemplateName(TD);
614 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
616 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
620 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
621 // <unscoped-name> ::= <unqualified-name>
622 // ::= St <unqualified-name> # ::std::
624 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
627 mangleUnqualifiedName(ND);
630 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
631 // <unscoped-template-name> ::= <unscoped-name>
632 // ::= <substitution>
633 if (mangleSubstitution(ND))
636 // <template-template-param> ::= <template-param>
637 if (const TemplateTemplateParmDecl *TTP
638 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
639 mangleTemplateParameter(TTP->getIndex());
643 mangleUnscopedName(ND->getTemplatedDecl());
647 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
648 // <unscoped-template-name> ::= <unscoped-name>
649 // ::= <substitution>
650 if (TemplateDecl *TD = Template.getAsTemplateDecl())
651 return mangleUnscopedTemplateName(TD);
653 if (mangleSubstitution(Template))
656 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
657 assert(Dependent && "Not a dependent template name?");
658 if (const IdentifierInfo *Id = Dependent->getIdentifier())
659 mangleSourceName(Id);
661 mangleOperatorName(Dependent->getOperator(), UnknownArity);
663 addSubstitution(Template);
666 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
668 // Floating-point literals are encoded using a fixed-length
669 // lowercase hexadecimal string corresponding to the internal
670 // representation (IEEE on Itanium), high-order bytes first,
671 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
673 // The 'without leading zeroes' thing seems to be an editorial
674 // mistake; see the discussion on cxx-abi-dev beginning on
677 // Our requirements here are just barely weird enough to justify
678 // using a custom algorithm instead of post-processing APInt::toString().
680 llvm::APInt valueBits = f.bitcastToAPInt();
681 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
682 assert(numCharacters != 0);
684 // Allocate a buffer of the right number of characters.
685 SmallVector<char, 20> buffer;
686 buffer.set_size(numCharacters);
688 // Fill the buffer left-to-right.
689 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
690 // The bit-index of the next hex digit.
691 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
693 // Project out 4 bits starting at 'digitIndex'.
694 llvm::integerPart hexDigit
695 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
696 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
699 // Map that over to a lowercase hex digit.
700 static const char charForHex[16] = {
701 '0', '1', '2', '3', '4', '5', '6', '7',
702 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
704 buffer[stringIndex] = charForHex[hexDigit];
707 Out.write(buffer.data(), numCharacters);
710 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
711 if (Value.isSigned() && Value.isNegative()) {
713 Value.abs().print(Out, /*signed*/ false);
715 Value.print(Out, /*signed*/ false);
719 void CXXNameMangler::mangleNumber(int64_t Number) {
720 // <number> ::= [n] <non-negative decimal integer>
729 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
730 // <call-offset> ::= h <nv-offset> _
731 // ::= v <v-offset> _
732 // <nv-offset> ::= <offset number> # non-virtual base override
733 // <v-offset> ::= <offset number> _ <virtual offset number>
734 // # virtual base override, with vcall offset
737 mangleNumber(NonVirtual);
743 mangleNumber(NonVirtual);
745 mangleNumber(Virtual);
749 void CXXNameMangler::manglePrefix(QualType type) {
750 if (const TemplateSpecializationType *TST =
751 type->getAs<TemplateSpecializationType>()) {
752 if (!mangleSubstitution(QualType(TST, 0))) {
753 mangleTemplatePrefix(TST->getTemplateName());
755 // FIXME: GCC does not appear to mangle the template arguments when
756 // the template in question is a dependent template name. Should we
757 // emulate that badness?
758 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
759 addSubstitution(QualType(TST, 0));
761 } else if (const DependentTemplateSpecializationType *DTST
762 = type->getAs<DependentTemplateSpecializationType>()) {
763 TemplateName Template
764 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
765 DTST->getIdentifier());
766 mangleTemplatePrefix(Template);
768 // FIXME: GCC does not appear to mangle the template arguments when
769 // the template in question is a dependent template name. Should we
770 // emulate that badness?
771 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
773 // We use the QualType mangle type variant here because it handles
779 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
781 /// \param firstQualifierLookup - the entity found by unqualified lookup
782 /// for the first name in the qualifier, if this is for a member expression
783 /// \param recursive - true if this is being called recursively,
784 /// i.e. if there is more prefix "to the right".
785 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
786 NamedDecl *firstQualifierLookup,
790 // <unresolved-name> ::= [gs] <base-unresolved-name>
792 // T::x / decltype(p)::x
793 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
795 // T::N::x /decltype(p)::N::x
796 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
797 // <base-unresolved-name>
799 // A::x, N::y, A<T>::z; "gs" means leading "::"
800 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
801 // <base-unresolved-name>
803 switch (qualifier->getKind()) {
804 case NestedNameSpecifier::Global:
807 // We want an 'sr' unless this is the entire NNS.
811 // We never want an 'E' here.
814 case NestedNameSpecifier::Namespace:
815 if (qualifier->getPrefix())
816 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
820 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
822 case NestedNameSpecifier::NamespaceAlias:
823 if (qualifier->getPrefix())
824 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
828 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
831 case NestedNameSpecifier::TypeSpec:
832 case NestedNameSpecifier::TypeSpecWithTemplate: {
833 const Type *type = qualifier->getAsType();
835 // We only want to use an unresolved-type encoding if this is one of:
837 // - a template type parameter
838 // - a template template parameter with arguments
839 // In all of these cases, we should have no prefix.
840 if (qualifier->getPrefix()) {
841 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
844 // Otherwise, all the cases want this.
848 // Only certain other types are valid as prefixes; enumerate them.
849 switch (type->getTypeClass()) {
855 case Type::BlockPointer:
856 case Type::LValueReference:
857 case Type::RValueReference:
858 case Type::MemberPointer:
859 case Type::ConstantArray:
860 case Type::IncompleteArray:
861 case Type::VariableArray:
862 case Type::DependentSizedArray:
863 case Type::DependentSizedExtVector:
865 case Type::ExtVector:
866 case Type::FunctionProto:
867 case Type::FunctionNoProto:
870 case Type::Elaborated:
871 case Type::Attributed:
873 case Type::PackExpansion:
874 case Type::ObjCObject:
875 case Type::ObjCInterface:
876 case Type::ObjCObjectPointer:
878 llvm_unreachable("type is illegal as a nested name specifier");
880 case Type::SubstTemplateTypeParmPack:
881 // FIXME: not clear how to mangle this!
882 // template <class T...> class A {
883 // template <class U...> void foo(decltype(T::foo(U())) x...);
885 Out << "_SUBSTPACK_";
888 // <unresolved-type> ::= <template-param>
890 // ::= <template-template-param> <template-args>
891 // (this last is not official yet)
892 case Type::TypeOfExpr:
895 case Type::TemplateTypeParm:
896 case Type::UnaryTransform:
897 case Type::SubstTemplateTypeParm:
899 assert(!qualifier->getPrefix());
901 // We only get here recursively if we're followed by identifiers.
902 if (recursive) Out << 'N';
904 // This seems to do everything we want. It's not really
905 // sanctioned for a substituted template parameter, though.
906 mangleType(QualType(type, 0));
908 // We never want to print 'E' directly after an unresolved-type,
909 // so we return directly.
913 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
916 case Type::UnresolvedUsing:
917 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
922 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
925 case Type::TemplateSpecialization: {
926 const TemplateSpecializationType *tst
927 = cast<TemplateSpecializationType>(type);
928 TemplateName name = tst->getTemplateName();
929 switch (name.getKind()) {
930 case TemplateName::Template:
931 case TemplateName::QualifiedTemplate: {
932 TemplateDecl *temp = name.getAsTemplateDecl();
934 // If the base is a template template parameter, this is an
936 assert(temp && "no template for template specialization type");
937 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
939 mangleSourceName(temp->getIdentifier());
943 case TemplateName::OverloadedTemplate:
944 case TemplateName::DependentTemplate:
945 llvm_unreachable("invalid base for a template specialization type");
947 case TemplateName::SubstTemplateTemplateParm: {
948 SubstTemplateTemplateParmStorage *subst
949 = name.getAsSubstTemplateTemplateParm();
950 mangleExistingSubstitution(subst->getReplacement());
954 case TemplateName::SubstTemplateTemplateParmPack: {
955 // FIXME: not clear how to mangle this!
956 // template <template <class U> class T...> class A {
957 // template <class U...> void foo(decltype(T<U>::foo) x...);
959 Out << "_SUBSTPACK_";
964 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
968 case Type::InjectedClassName:
969 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
973 case Type::DependentName:
974 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
977 case Type::DependentTemplateSpecialization: {
978 const DependentTemplateSpecializationType *tst
979 = cast<DependentTemplateSpecializationType>(type);
980 mangleSourceName(tst->getIdentifier());
981 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
988 case NestedNameSpecifier::Identifier:
989 // Member expressions can have these without prefixes.
990 if (qualifier->getPrefix()) {
991 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
993 } else if (firstQualifierLookup) {
995 // Try to make a proper qualifier out of the lookup result, and
996 // then just recurse on that.
997 NestedNameSpecifier *newQualifier;
998 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
999 QualType type = getASTContext().getTypeDeclType(typeDecl);
1001 // Pretend we had a different nested name specifier.
1002 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1006 } else if (NamespaceDecl *nspace =
1007 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
1008 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1011 } else if (NamespaceAliasDecl *alias =
1012 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
1013 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1017 // No sensible mangling to do here.
1018 newQualifier = nullptr;
1022 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
1029 mangleSourceName(qualifier->getAsIdentifier());
1033 // If this was the innermost part of the NNS, and we fell out to
1034 // here, append an 'E'.
1039 /// Mangle an unresolved-name, which is generally used for names which
1040 /// weren't resolved to specific entities.
1041 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1042 NamedDecl *firstQualifierLookup,
1043 DeclarationName name,
1044 unsigned knownArity) {
1045 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1046 mangleUnqualifiedName(nullptr, name, knownArity);
1049 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1050 assert(RD->isAnonymousStructOrUnion() &&
1051 "Expected anonymous struct or union!");
1053 for (const auto *I : RD->fields()) {
1054 if (I->getIdentifier())
1057 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1058 if (const FieldDecl *NamedDataMember =
1059 FindFirstNamedDataMember(RT->getDecl()))
1060 return NamedDataMember;
1063 // We didn't find a named data member.
1067 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1068 DeclarationName Name,
1069 unsigned KnownArity) {
1070 // <unqualified-name> ::= <operator-name>
1071 // ::= <ctor-dtor-name>
1072 // ::= <source-name>
1073 switch (Name.getNameKind()) {
1074 case DeclarationName::Identifier: {
1075 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1076 // We must avoid conflicts between internally- and externally-
1077 // linked variable and function declaration names in the same TU:
1078 // void test() { extern void foo(); }
1079 // static void foo();
1080 // This naming convention is the same as that followed by GCC,
1081 // though it shouldn't actually matter.
1082 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1083 getEffectiveDeclContext(ND)->isFileContext())
1086 mangleSourceName(II);
1090 // Otherwise, an anonymous entity. We must have a declaration.
1091 assert(ND && "mangling empty name without declaration");
1093 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1094 if (NS->isAnonymousNamespace()) {
1095 // This is how gcc mangles these names.
1096 Out << "12_GLOBAL__N_1";
1101 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1102 // We must have an anonymous union or struct declaration.
1103 const RecordDecl *RD =
1104 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1106 // Itanium C++ ABI 5.1.2:
1108 // For the purposes of mangling, the name of an anonymous union is
1109 // considered to be the name of the first named data member found by a
1110 // pre-order, depth-first, declaration-order walk of the data members of
1111 // the anonymous union. If there is no such data member (i.e., if all of
1112 // the data members in the union are unnamed), then there is no way for
1113 // a program to refer to the anonymous union, and there is therefore no
1114 // need to mangle its name.
1115 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1117 // It's actually possible for various reasons for us to get here
1118 // with an empty anonymous struct / union. Fortunately, it
1119 // doesn't really matter what name we generate.
1121 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1123 mangleSourceName(FD->getIdentifier());
1127 // Class extensions have no name as a category, and it's possible
1128 // for them to be the semantic parent of certain declarations
1129 // (primarily, tag decls defined within declarations). Such
1130 // declarations will always have internal linkage, so the name
1131 // doesn't really matter, but we shouldn't crash on them. For
1132 // safety, just handle all ObjC containers here.
1133 if (isa<ObjCContainerDecl>(ND))
1136 // We must have an anonymous struct.
1137 const TagDecl *TD = cast<TagDecl>(ND);
1138 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1139 assert(TD->getDeclContext() == D->getDeclContext() &&
1140 "Typedef should not be in another decl context!");
1141 assert(D->getDeclName().getAsIdentifierInfo() &&
1142 "Typedef was not named!");
1143 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1147 // <unnamed-type-name> ::= <closure-type-name>
1149 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1150 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1151 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1152 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1153 mangleLambda(Record);
1158 if (TD->isExternallyVisible()) {
1159 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1161 if (UnnamedMangle > 1)
1162 Out << llvm::utostr(UnnamedMangle - 2);
1167 // Get a unique id for the anonymous struct.
1168 unsigned AnonStructId = Context.getAnonymousStructId(TD);
1170 // Mangle it as a source name in the form
1172 // where n is the length of the string.
1175 Str += llvm::utostr(AnonStructId);
1182 case DeclarationName::ObjCZeroArgSelector:
1183 case DeclarationName::ObjCOneArgSelector:
1184 case DeclarationName::ObjCMultiArgSelector:
1185 llvm_unreachable("Can't mangle Objective-C selector names here!");
1187 case DeclarationName::CXXConstructorName:
1189 // If the named decl is the C++ constructor we're mangling, use the type
1191 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1193 // Otherwise, use the complete constructor name. This is relevant if a
1194 // class with a constructor is declared within a constructor.
1195 mangleCXXCtorType(Ctor_Complete);
1198 case DeclarationName::CXXDestructorName:
1200 // If the named decl is the C++ destructor we're mangling, use the type we
1202 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1204 // Otherwise, use the complete destructor name. This is relevant if a
1205 // class with a destructor is declared within a destructor.
1206 mangleCXXDtorType(Dtor_Complete);
1209 case DeclarationName::CXXConversionFunctionName:
1210 // <operator-name> ::= cv <type> # (cast)
1212 mangleType(Name.getCXXNameType());
1215 case DeclarationName::CXXOperatorName: {
1218 Arity = cast<FunctionDecl>(ND)->getNumParams();
1220 // If we have a C++ member function, we need to include the 'this' pointer.
1221 // FIXME: This does not make sense for operators that are static, but their
1222 // names stay the same regardless of the arity (operator new for instance).
1223 if (isa<CXXMethodDecl>(ND))
1228 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1232 case DeclarationName::CXXLiteralOperatorName:
1233 // FIXME: This mangling is not yet official.
1235 mangleSourceName(Name.getCXXLiteralIdentifier());
1238 case DeclarationName::CXXUsingDirective:
1239 llvm_unreachable("Can't mangle a using directive name!");
1243 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1244 // <source-name> ::= <positive length number> <identifier>
1245 // <number> ::= [n] <non-negative decimal integer>
1246 // <identifier> ::= <unqualified source code identifier>
1247 Out << II->getLength() << II->getName();
1250 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1251 const DeclContext *DC,
1254 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1255 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1256 // <template-args> E
1259 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1260 Qualifiers MethodQuals =
1261 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1262 // We do not consider restrict a distinguishing attribute for overloading
1263 // purposes so we must not mangle it.
1264 MethodQuals.removeRestrict();
1265 mangleQualifiers(MethodQuals);
1266 mangleRefQualifier(Method->getRefQualifier());
1269 // Check if we have a template.
1270 const TemplateArgumentList *TemplateArgs = nullptr;
1271 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1272 mangleTemplatePrefix(TD, NoFunction);
1273 mangleTemplateArgs(*TemplateArgs);
1276 manglePrefix(DC, NoFunction);
1277 mangleUnqualifiedName(ND);
1282 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1283 const TemplateArgument *TemplateArgs,
1284 unsigned NumTemplateArgs) {
1285 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1289 mangleTemplatePrefix(TD);
1290 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1295 void CXXNameMangler::mangleLocalName(const Decl *D) {
1296 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1297 // := Z <function encoding> E s [<discriminator>]
1298 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1300 // <discriminator> := _ <non-negative number>
1301 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1302 const RecordDecl *RD = GetLocalClassDecl(D);
1303 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1307 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1308 mangleObjCMethodName(MD);
1309 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1310 mangleBlockForPrefix(BD);
1312 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1317 // The parameter number is omitted for the last parameter, 0 for the
1318 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1319 // <entity name> will of course contain a <closure-type-name>: Its
1320 // numbering will be local to the particular argument in which it appears
1321 // -- other default arguments do not affect its encoding.
1322 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1323 if (CXXRD->isLambda()) {
1324 if (const ParmVarDecl *Parm
1325 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1326 if (const FunctionDecl *Func
1327 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1329 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1331 mangleNumber(Num - 2);
1337 // Mangle the name relative to the closest enclosing function.
1338 // equality ok because RD derived from ND above
1340 mangleUnqualifiedName(RD);
1341 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1342 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1343 mangleUnqualifiedBlock(BD);
1345 const NamedDecl *ND = cast<NamedDecl>(D);
1346 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
1348 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1349 // Mangle a block in a default parameter; see above explanation for
1351 if (const ParmVarDecl *Parm
1352 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1353 if (const FunctionDecl *Func
1354 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1356 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1358 mangleNumber(Num - 2);
1363 mangleUnqualifiedBlock(BD);
1365 mangleUnqualifiedName(cast<NamedDecl>(D));
1368 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1370 if (Context.getNextDiscriminator(ND, disc)) {
1374 Out << "__" << disc << '_';
1379 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1380 if (GetLocalClassDecl(Block)) {
1381 mangleLocalName(Block);
1384 const DeclContext *DC = getEffectiveDeclContext(Block);
1385 if (isLocalContainerContext(DC)) {
1386 mangleLocalName(Block);
1389 manglePrefix(getEffectiveDeclContext(Block));
1390 mangleUnqualifiedBlock(Block);
1393 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1394 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1395 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1396 Context->getDeclContext()->isRecord()) {
1397 if (const IdentifierInfo *Name
1398 = cast<NamedDecl>(Context)->getIdentifier()) {
1399 mangleSourceName(Name);
1405 // If we have a block mangling number, use it.
1406 unsigned Number = Block->getBlockManglingNumber();
1407 // Otherwise, just make up a number. It doesn't matter what it is because
1408 // the symbol in question isn't externally visible.
1410 Number = Context.getBlockId(Block, false);
1417 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1418 // If the context of a closure type is an initializer for a class member
1419 // (static or nonstatic), it is encoded in a qualified name with a final
1420 // <prefix> of the form:
1422 // <data-member-prefix> := <member source-name> M
1424 // Technically, the data-member-prefix is part of the <prefix>. However,
1425 // since a closure type will always be mangled with a prefix, it's easier
1426 // to emit that last part of the prefix here.
1427 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1428 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1429 Context->getDeclContext()->isRecord()) {
1430 if (const IdentifierInfo *Name
1431 = cast<NamedDecl>(Context)->getIdentifier()) {
1432 mangleSourceName(Name);
1439 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1440 getAs<FunctionProtoType>();
1441 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1444 // The number is omitted for the first closure type with a given
1445 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1446 // (in lexical order) with that same <lambda-sig> and context.
1448 // The AST keeps track of the number for us.
1449 unsigned Number = Lambda->getLambdaManglingNumber();
1450 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1452 mangleNumber(Number - 2);
1456 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1457 switch (qualifier->getKind()) {
1458 case NestedNameSpecifier::Global:
1462 case NestedNameSpecifier::Namespace:
1463 mangleName(qualifier->getAsNamespace());
1466 case NestedNameSpecifier::NamespaceAlias:
1467 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1470 case NestedNameSpecifier::TypeSpec:
1471 case NestedNameSpecifier::TypeSpecWithTemplate:
1472 manglePrefix(QualType(qualifier->getAsType(), 0));
1475 case NestedNameSpecifier::Identifier:
1476 // Member expressions can have these without prefixes, but that
1477 // should end up in mangleUnresolvedPrefix instead.
1478 assert(qualifier->getPrefix());
1479 manglePrefix(qualifier->getPrefix());
1481 mangleSourceName(qualifier->getAsIdentifier());
1485 llvm_unreachable("unexpected nested name specifier");
1488 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1489 // <prefix> ::= <prefix> <unqualified-name>
1490 // ::= <template-prefix> <template-args>
1491 // ::= <template-param>
1493 // ::= <substitution>
1495 DC = IgnoreLinkageSpecDecls(DC);
1497 if (DC->isTranslationUnit())
1500 if (NoFunction && isLocalContainerContext(DC))
1503 assert(!isLocalContainerContext(DC));
1505 const NamedDecl *ND = cast<NamedDecl>(DC);
1506 if (mangleSubstitution(ND))
1509 // Check if we have a template.
1510 const TemplateArgumentList *TemplateArgs = nullptr;
1511 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1512 mangleTemplatePrefix(TD);
1513 mangleTemplateArgs(*TemplateArgs);
1515 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1516 mangleUnqualifiedName(ND);
1519 addSubstitution(ND);
1522 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1523 // <template-prefix> ::= <prefix> <template unqualified-name>
1524 // ::= <template-param>
1525 // ::= <substitution>
1526 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1527 return mangleTemplatePrefix(TD);
1529 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1530 manglePrefix(Qualified->getQualifier());
1532 if (OverloadedTemplateStorage *Overloaded
1533 = Template.getAsOverloadedTemplate()) {
1534 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1539 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1540 assert(Dependent && "Unknown template name kind?");
1541 manglePrefix(Dependent->getQualifier());
1542 mangleUnscopedTemplateName(Template);
1545 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1547 // <template-prefix> ::= <prefix> <template unqualified-name>
1548 // ::= <template-param>
1549 // ::= <substitution>
1550 // <template-template-param> ::= <template-param>
1553 if (mangleSubstitution(ND))
1556 // <template-template-param> ::= <template-param>
1557 if (const TemplateTemplateParmDecl *TTP
1558 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1559 mangleTemplateParameter(TTP->getIndex());
1563 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1564 mangleUnqualifiedName(ND->getTemplatedDecl());
1565 addSubstitution(ND);
1568 /// Mangles a template name under the production <type>. Required for
1569 /// template template arguments.
1570 /// <type> ::= <class-enum-type>
1571 /// ::= <template-param>
1572 /// ::= <substitution>
1573 void CXXNameMangler::mangleType(TemplateName TN) {
1574 if (mangleSubstitution(TN))
1577 TemplateDecl *TD = nullptr;
1579 switch (TN.getKind()) {
1580 case TemplateName::QualifiedTemplate:
1581 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1584 case TemplateName::Template:
1585 TD = TN.getAsTemplateDecl();
1589 if (isa<TemplateTemplateParmDecl>(TD))
1590 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1595 case TemplateName::OverloadedTemplate:
1596 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1598 case TemplateName::DependentTemplate: {
1599 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1600 assert(Dependent->isIdentifier());
1602 // <class-enum-type> ::= <name>
1603 // <name> ::= <nested-name>
1604 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
1605 mangleSourceName(Dependent->getIdentifier());
1609 case TemplateName::SubstTemplateTemplateParm: {
1610 // Substituted template parameters are mangled as the substituted
1611 // template. This will check for the substitution twice, which is
1612 // fine, but we have to return early so that we don't try to *add*
1613 // the substitution twice.
1614 SubstTemplateTemplateParmStorage *subst
1615 = TN.getAsSubstTemplateTemplateParm();
1616 mangleType(subst->getReplacement());
1620 case TemplateName::SubstTemplateTemplateParmPack: {
1621 // FIXME: not clear how to mangle this!
1622 // template <template <class> class T...> class A {
1623 // template <template <class> class U...> void foo(B<T,U> x...);
1625 Out << "_SUBSTPACK_";
1630 addSubstitution(TN);
1634 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1636 // <operator-name> ::= nw # new
1637 case OO_New: Out << "nw"; break;
1639 case OO_Array_New: Out << "na"; break;
1641 case OO_Delete: Out << "dl"; break;
1642 // ::= da # delete[]
1643 case OO_Array_Delete: Out << "da"; break;
1644 // ::= ps # + (unary)
1645 // ::= pl # + (binary or unknown)
1647 Out << (Arity == 1? "ps" : "pl"); break;
1648 // ::= ng # - (unary)
1649 // ::= mi # - (binary or unknown)
1651 Out << (Arity == 1? "ng" : "mi"); break;
1652 // ::= ad # & (unary)
1653 // ::= an # & (binary or unknown)
1655 Out << (Arity == 1? "ad" : "an"); break;
1656 // ::= de # * (unary)
1657 // ::= ml # * (binary or unknown)
1659 // Use binary when unknown.
1660 Out << (Arity == 1? "de" : "ml"); break;
1662 case OO_Tilde: Out << "co"; break;
1664 case OO_Slash: Out << "dv"; break;
1666 case OO_Percent: Out << "rm"; break;
1668 case OO_Pipe: Out << "or"; break;
1670 case OO_Caret: Out << "eo"; break;
1672 case OO_Equal: Out << "aS"; break;
1674 case OO_PlusEqual: Out << "pL"; break;
1676 case OO_MinusEqual: Out << "mI"; break;
1678 case OO_StarEqual: Out << "mL"; break;
1680 case OO_SlashEqual: Out << "dV"; break;
1682 case OO_PercentEqual: Out << "rM"; break;
1684 case OO_AmpEqual: Out << "aN"; break;
1686 case OO_PipeEqual: Out << "oR"; break;
1688 case OO_CaretEqual: Out << "eO"; break;
1690 case OO_LessLess: Out << "ls"; break;
1692 case OO_GreaterGreater: Out << "rs"; break;
1694 case OO_LessLessEqual: Out << "lS"; break;
1696 case OO_GreaterGreaterEqual: Out << "rS"; break;
1698 case OO_EqualEqual: Out << "eq"; break;
1700 case OO_ExclaimEqual: Out << "ne"; break;
1702 case OO_Less: Out << "lt"; break;
1704 case OO_Greater: Out << "gt"; break;
1706 case OO_LessEqual: Out << "le"; break;
1708 case OO_GreaterEqual: Out << "ge"; break;
1710 case OO_Exclaim: Out << "nt"; break;
1712 case OO_AmpAmp: Out << "aa"; break;
1714 case OO_PipePipe: Out << "oo"; break;
1716 case OO_PlusPlus: Out << "pp"; break;
1718 case OO_MinusMinus: Out << "mm"; break;
1720 case OO_Comma: Out << "cm"; break;
1722 case OO_ArrowStar: Out << "pm"; break;
1724 case OO_Arrow: Out << "pt"; break;
1726 case OO_Call: Out << "cl"; break;
1728 case OO_Subscript: Out << "ix"; break;
1731 // The conditional operator can't be overloaded, but we still handle it when
1732 // mangling expressions.
1733 case OO_Conditional: Out << "qu"; break;
1736 case NUM_OVERLOADED_OPERATORS:
1737 llvm_unreachable("Not an overloaded operator");
1741 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1742 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1743 if (Quals.hasRestrict())
1745 if (Quals.hasVolatile())
1747 if (Quals.hasConst())
1750 if (Quals.hasAddressSpace()) {
1751 // Address space extension:
1753 // <type> ::= U <target-addrspace>
1754 // <type> ::= U <OpenCL-addrspace>
1755 // <type> ::= U <CUDA-addrspace>
1757 SmallString<64> ASString;
1758 unsigned AS = Quals.getAddressSpace();
1760 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1761 // <target-addrspace> ::= "AS" <address-space-number>
1762 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1763 ASString = "AS" + llvm::utostr_32(TargetAS);
1766 default: llvm_unreachable("Not a language specific address space");
1767 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1768 case LangAS::opencl_global: ASString = "CLglobal"; break;
1769 case LangAS::opencl_local: ASString = "CLlocal"; break;
1770 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1771 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1772 case LangAS::cuda_device: ASString = "CUdevice"; break;
1773 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1774 case LangAS::cuda_shared: ASString = "CUshared"; break;
1777 Out << 'U' << ASString.size() << ASString;
1780 StringRef LifetimeName;
1781 switch (Quals.getObjCLifetime()) {
1782 // Objective-C ARC Extension:
1784 // <type> ::= U "__strong"
1785 // <type> ::= U "__weak"
1786 // <type> ::= U "__autoreleasing"
1787 case Qualifiers::OCL_None:
1790 case Qualifiers::OCL_Weak:
1791 LifetimeName = "__weak";
1794 case Qualifiers::OCL_Strong:
1795 LifetimeName = "__strong";
1798 case Qualifiers::OCL_Autoreleasing:
1799 LifetimeName = "__autoreleasing";
1802 case Qualifiers::OCL_ExplicitNone:
1803 // The __unsafe_unretained qualifier is *not* mangled, so that
1804 // __unsafe_unretained types in ARC produce the same manglings as the
1805 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1806 // better ABI compatibility.
1808 // It's safe to do this because unqualified 'id' won't show up
1809 // in any type signatures that need to be mangled.
1812 if (!LifetimeName.empty())
1813 Out << 'U' << LifetimeName.size() << LifetimeName;
1816 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1817 // <ref-qualifier> ::= R # lvalue reference
1818 // ::= O # rvalue-reference
1819 switch (RefQualifier) {
1833 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1834 Context.mangleObjCMethodName(MD, Out);
1837 void CXXNameMangler::mangleType(QualType T) {
1838 // If our type is instantiation-dependent but not dependent, we mangle
1839 // it as it was written in the source, removing any top-level sugar.
1840 // Otherwise, use the canonical type.
1842 // FIXME: This is an approximation of the instantiation-dependent name
1843 // mangling rules, since we should really be using the type as written and
1844 // augmented via semantic analysis (i.e., with implicit conversions and
1845 // default template arguments) for any instantiation-dependent type.
1846 // Unfortunately, that requires several changes to our AST:
1847 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1848 // uniqued, so that we can handle substitutions properly
1849 // - Default template arguments will need to be represented in the
1850 // TemplateSpecializationType, since they need to be mangled even though
1851 // they aren't written.
1852 // - Conversions on non-type template arguments need to be expressed, since
1853 // they can affect the mangling of sizeof/alignof.
1854 if (!T->isInstantiationDependentType() || T->isDependentType())
1855 T = T.getCanonicalType();
1857 // Desugar any types that are purely sugar.
1859 // Don't desugar through template specialization types that aren't
1860 // type aliases. We need to mangle the template arguments as written.
1861 if (const TemplateSpecializationType *TST
1862 = dyn_cast<TemplateSpecializationType>(T))
1863 if (!TST->isTypeAlias())
1867 = T.getSingleStepDesugaredType(Context.getASTContext());
1874 SplitQualType split = T.split();
1875 Qualifiers quals = split.Quals;
1876 const Type *ty = split.Ty;
1878 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1879 if (isSubstitutable && mangleSubstitution(T))
1882 // If we're mangling a qualified array type, push the qualifiers to
1883 // the element type.
1884 if (quals && isa<ArrayType>(T)) {
1885 ty = Context.getASTContext().getAsArrayType(T);
1886 quals = Qualifiers();
1888 // Note that we don't update T: we want to add the
1889 // substitution at the original type.
1893 mangleQualifiers(quals);
1894 // Recurse: even if the qualified type isn't yet substitutable,
1895 // the unqualified type might be.
1896 mangleType(QualType(ty, 0));
1898 switch (ty->getTypeClass()) {
1899 #define ABSTRACT_TYPE(CLASS, PARENT)
1900 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1902 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1904 #define TYPE(CLASS, PARENT) \
1906 mangleType(static_cast<const CLASS##Type*>(ty)); \
1908 #include "clang/AST/TypeNodes.def"
1912 // Add the substitution.
1913 if (isSubstitutable)
1917 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1918 if (!mangleStandardSubstitution(ND))
1922 void CXXNameMangler::mangleType(const BuiltinType *T) {
1923 // <type> ::= <builtin-type>
1924 // <builtin-type> ::= v # void
1928 // ::= a # signed char
1929 // ::= h # unsigned char
1931 // ::= t # unsigned short
1933 // ::= j # unsigned int
1935 // ::= m # unsigned long
1936 // ::= x # long long, __int64
1937 // ::= y # unsigned long long, __int64
1939 // ::= o # unsigned __int128
1942 // ::= e # long double, __float80
1943 // UNSUPPORTED: ::= g # __float128
1944 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1945 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1946 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1947 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1948 // ::= Di # char32_t
1949 // ::= Ds # char16_t
1950 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1951 // ::= u <source-name> # vendor extended type
1952 switch (T->getKind()) {
1953 case BuiltinType::Void: Out << 'v'; break;
1954 case BuiltinType::Bool: Out << 'b'; break;
1955 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1956 case BuiltinType::UChar: Out << 'h'; break;
1957 case BuiltinType::UShort: Out << 't'; break;
1958 case BuiltinType::UInt: Out << 'j'; break;
1959 case BuiltinType::ULong: Out << 'm'; break;
1960 case BuiltinType::ULongLong: Out << 'y'; break;
1961 case BuiltinType::UInt128: Out << 'o'; break;
1962 case BuiltinType::SChar: Out << 'a'; break;
1963 case BuiltinType::WChar_S:
1964 case BuiltinType::WChar_U: Out << 'w'; break;
1965 case BuiltinType::Char16: Out << "Ds"; break;
1966 case BuiltinType::Char32: Out << "Di"; break;
1967 case BuiltinType::Short: Out << 's'; break;
1968 case BuiltinType::Int: Out << 'i'; break;
1969 case BuiltinType::Long: Out << 'l'; break;
1970 case BuiltinType::LongLong: Out << 'x'; break;
1971 case BuiltinType::Int128: Out << 'n'; break;
1972 case BuiltinType::Half: Out << "Dh"; break;
1973 case BuiltinType::Float: Out << 'f'; break;
1974 case BuiltinType::Double: Out << 'd'; break;
1975 case BuiltinType::LongDouble: Out << 'e'; break;
1976 case BuiltinType::NullPtr: Out << "Dn"; break;
1978 #define BUILTIN_TYPE(Id, SingletonId)
1979 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1980 case BuiltinType::Id:
1981 #include "clang/AST/BuiltinTypes.def"
1982 case BuiltinType::Dependent:
1983 llvm_unreachable("mangling a placeholder type");
1984 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1985 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1986 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
1987 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1988 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1989 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1990 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1991 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1992 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
1993 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
1994 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
1998 // <type> ::= <function-type>
1999 // <function-type> ::= [<CV-qualifiers>] F [Y]
2000 // <bare-function-type> [<ref-qualifier>] E
2001 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2002 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2003 // e.g. "const" in "int (A::*)() const".
2004 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2008 // FIXME: We don't have enough information in the AST to produce the 'Y'
2009 // encoding for extern "C" function types.
2010 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2012 // Mangle the ref-qualifier, if present.
2013 mangleRefQualifier(T->getRefQualifier());
2017 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2018 llvm_unreachable("Can't mangle K&R function prototypes");
2020 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2021 bool MangleReturnType) {
2022 // We should never be mangling something without a prototype.
2023 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2025 // Record that we're in a function type. See mangleFunctionParam
2026 // for details on what we're trying to achieve here.
2027 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2029 // <bare-function-type> ::= <signature type>+
2030 if (MangleReturnType) {
2031 FunctionTypeDepth.enterResultType();
2032 mangleType(Proto->getReturnType());
2033 FunctionTypeDepth.leaveResultType();
2036 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2037 // <builtin-type> ::= v # void
2040 FunctionTypeDepth.pop(saved);
2044 for (const auto &Arg : Proto->param_types())
2045 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
2047 FunctionTypeDepth.pop(saved);
2049 // <builtin-type> ::= z # ellipsis
2050 if (Proto->isVariadic())
2054 // <type> ::= <class-enum-type>
2055 // <class-enum-type> ::= <name>
2056 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2057 mangleName(T->getDecl());
2060 // <type> ::= <class-enum-type>
2061 // <class-enum-type> ::= <name>
2062 void CXXNameMangler::mangleType(const EnumType *T) {
2063 mangleType(static_cast<const TagType*>(T));
2065 void CXXNameMangler::mangleType(const RecordType *T) {
2066 mangleType(static_cast<const TagType*>(T));
2068 void CXXNameMangler::mangleType(const TagType *T) {
2069 mangleName(T->getDecl());
2072 // <type> ::= <array-type>
2073 // <array-type> ::= A <positive dimension number> _ <element type>
2074 // ::= A [<dimension expression>] _ <element type>
2075 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2076 Out << 'A' << T->getSize() << '_';
2077 mangleType(T->getElementType());
2079 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2081 // decayed vla types (size 0) will just be skipped.
2082 if (T->getSizeExpr())
2083 mangleExpression(T->getSizeExpr());
2085 mangleType(T->getElementType());
2087 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2089 mangleExpression(T->getSizeExpr());
2091 mangleType(T->getElementType());
2093 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2095 mangleType(T->getElementType());
2098 // <type> ::= <pointer-to-member-type>
2099 // <pointer-to-member-type> ::= M <class type> <member type>
2100 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2102 mangleType(QualType(T->getClass(), 0));
2103 QualType PointeeType = T->getPointeeType();
2104 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2107 // Itanium C++ ABI 5.1.8:
2109 // The type of a non-static member function is considered to be different,
2110 // for the purposes of substitution, from the type of a namespace-scope or
2111 // static member function whose type appears similar. The types of two
2112 // non-static member functions are considered to be different, for the
2113 // purposes of substitution, if the functions are members of different
2114 // classes. In other words, for the purposes of substitution, the class of
2115 // which the function is a member is considered part of the type of
2118 // Given that we already substitute member function pointers as a
2119 // whole, the net effect of this rule is just to unconditionally
2120 // suppress substitution on the function type in a member pointer.
2121 // We increment the SeqID here to emulate adding an entry to the
2122 // substitution table.
2125 mangleType(PointeeType);
2128 // <type> ::= <template-param>
2129 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2130 mangleTemplateParameter(T->getIndex());
2133 // <type> ::= <template-param>
2134 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2135 // FIXME: not clear how to mangle this!
2136 // template <class T...> class A {
2137 // template <class U...> void foo(T(*)(U) x...);
2139 Out << "_SUBSTPACK_";
2142 // <type> ::= P <type> # pointer-to
2143 void CXXNameMangler::mangleType(const PointerType *T) {
2145 mangleType(T->getPointeeType());
2147 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2149 mangleType(T->getPointeeType());
2152 // <type> ::= R <type> # reference-to
2153 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2155 mangleType(T->getPointeeType());
2158 // <type> ::= O <type> # rvalue reference-to (C++0x)
2159 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2161 mangleType(T->getPointeeType());
2164 // <type> ::= C <type> # complex pair (C 2000)
2165 void CXXNameMangler::mangleType(const ComplexType *T) {
2167 mangleType(T->getElementType());
2170 // ARM's ABI for Neon vector types specifies that they should be mangled as
2171 // if they are structs (to match ARM's initial implementation). The
2172 // vector type must be one of the special types predefined by ARM.
2173 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2174 QualType EltType = T->getElementType();
2175 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2176 const char *EltName = nullptr;
2177 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2178 switch (cast<BuiltinType>(EltType)->getKind()) {
2179 case BuiltinType::SChar:
2180 case BuiltinType::UChar:
2181 EltName = "poly8_t";
2183 case BuiltinType::Short:
2184 case BuiltinType::UShort:
2185 EltName = "poly16_t";
2187 case BuiltinType::ULongLong:
2188 EltName = "poly64_t";
2190 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2193 switch (cast<BuiltinType>(EltType)->getKind()) {
2194 case BuiltinType::SChar: EltName = "int8_t"; break;
2195 case BuiltinType::UChar: EltName = "uint8_t"; break;
2196 case BuiltinType::Short: EltName = "int16_t"; break;
2197 case BuiltinType::UShort: EltName = "uint16_t"; break;
2198 case BuiltinType::Int: EltName = "int32_t"; break;
2199 case BuiltinType::UInt: EltName = "uint32_t"; break;
2200 case BuiltinType::LongLong: EltName = "int64_t"; break;
2201 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2202 case BuiltinType::Double: EltName = "float64_t"; break;
2203 case BuiltinType::Float: EltName = "float32_t"; break;
2204 case BuiltinType::Half: EltName = "float16_t";break;
2206 llvm_unreachable("unexpected Neon vector element type");
2209 const char *BaseName = nullptr;
2210 unsigned BitSize = (T->getNumElements() *
2211 getASTContext().getTypeSize(EltType));
2213 BaseName = "__simd64_";
2215 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2216 BaseName = "__simd128_";
2218 Out << strlen(BaseName) + strlen(EltName);
2219 Out << BaseName << EltName;
2222 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2223 switch (EltType->getKind()) {
2224 case BuiltinType::SChar:
2226 case BuiltinType::Short:
2228 case BuiltinType::Int:
2230 case BuiltinType::Long:
2231 case BuiltinType::LongLong:
2233 case BuiltinType::UChar:
2235 case BuiltinType::UShort:
2237 case BuiltinType::UInt:
2239 case BuiltinType::ULong:
2240 case BuiltinType::ULongLong:
2242 case BuiltinType::Half:
2244 case BuiltinType::Float:
2246 case BuiltinType::Double:
2249 llvm_unreachable("Unexpected vector element base type");
2253 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2254 // the equivalent internal name. The vector type must be one of the special
2255 // types predefined by ARM.
2256 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2257 QualType EltType = T->getElementType();
2258 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2260 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2261 (void)BitSize; // Silence warning.
2263 assert((BitSize == 64 || BitSize == 128) &&
2264 "Neon vector type not 64 or 128 bits");
2267 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2268 switch (cast<BuiltinType>(EltType)->getKind()) {
2269 case BuiltinType::UChar:
2272 case BuiltinType::UShort:
2275 case BuiltinType::ULong:
2279 llvm_unreachable("unexpected Neon polynomial vector element type");
2282 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2284 std::string TypeName =
2285 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2286 Out << TypeName.length() << TypeName;
2289 // GNU extension: vector types
2290 // <type> ::= <vector-type>
2291 // <vector-type> ::= Dv <positive dimension number> _
2292 // <extended element type>
2293 // ::= Dv [<dimension expression>] _ <element type>
2294 // <extended element type> ::= <element type>
2295 // ::= p # AltiVec vector pixel
2296 // ::= b # Altivec vector bool
2297 void CXXNameMangler::mangleType(const VectorType *T) {
2298 if ((T->getVectorKind() == VectorType::NeonVector ||
2299 T->getVectorKind() == VectorType::NeonPolyVector)) {
2300 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2301 llvm::Triple::ArchType Arch =
2302 getASTContext().getTargetInfo().getTriple().getArch();
2303 if ((Arch == llvm::Triple::aarch64 ||
2304 Arch == llvm::Triple::aarch64_be ||
2305 Arch == llvm::Triple::arm64_be ||
2306 Arch == llvm::Triple::arm64) && !Target.isOSDarwin())
2307 mangleAArch64NeonVectorType(T);
2309 mangleNeonVectorType(T);
2312 Out << "Dv" << T->getNumElements() << '_';
2313 if (T->getVectorKind() == VectorType::AltiVecPixel)
2315 else if (T->getVectorKind() == VectorType::AltiVecBool)
2318 mangleType(T->getElementType());
2320 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2321 mangleType(static_cast<const VectorType*>(T));
2323 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2325 mangleExpression(T->getSizeExpr());
2327 mangleType(T->getElementType());
2330 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2331 // <type> ::= Dp <type> # pack expansion (C++0x)
2333 mangleType(T->getPattern());
2336 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2337 mangleSourceName(T->getDecl()->getIdentifier());
2340 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2341 if (!T->qual_empty()) {
2342 // Mangle protocol qualifiers.
2343 SmallString<64> QualStr;
2344 llvm::raw_svector_ostream QualOS(QualStr);
2345 QualOS << "objcproto";
2346 for (const auto *I : T->quals()) {
2347 StringRef name = I->getName();
2348 QualOS << name.size() << name;
2351 Out << 'U' << QualStr.size() << QualStr;
2353 mangleType(T->getBaseType());
2356 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2357 Out << "U13block_pointer";
2358 mangleType(T->getPointeeType());
2361 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2362 // Mangle injected class name types as if the user had written the
2363 // specialization out fully. It may not actually be possible to see
2364 // this mangling, though.
2365 mangleType(T->getInjectedSpecializationType());
2368 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2369 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2370 mangleName(TD, T->getArgs(), T->getNumArgs());
2372 if (mangleSubstitution(QualType(T, 0)))
2375 mangleTemplatePrefix(T->getTemplateName());
2377 // FIXME: GCC does not appear to mangle the template arguments when
2378 // the template in question is a dependent template name. Should we
2379 // emulate that badness?
2380 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2381 addSubstitution(QualType(T, 0));
2385 void CXXNameMangler::mangleType(const DependentNameType *T) {
2386 // Proposal by cxx-abi-dev, 2014-03-26
2387 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2388 // # dependent elaborated type specifier using
2390 // ::= Ts <name> # dependent elaborated type specifier using
2391 // # 'struct' or 'class'
2392 // ::= Tu <name> # dependent elaborated type specifier using
2394 // ::= Te <name> # dependent elaborated type specifier using
2396 switch (T->getKeyword()) {
2411 llvm_unreachable("unexpected keyword for dependent type name");
2413 // Typename types are always nested
2415 manglePrefix(T->getQualifier());
2416 mangleSourceName(T->getIdentifier());
2420 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2421 // Dependently-scoped template types are nested if they have a prefix.
2424 // TODO: avoid making this TemplateName.
2425 TemplateName Prefix =
2426 getASTContext().getDependentTemplateName(T->getQualifier(),
2427 T->getIdentifier());
2428 mangleTemplatePrefix(Prefix);
2430 // FIXME: GCC does not appear to mangle the template arguments when
2431 // the template in question is a dependent template name. Should we
2432 // emulate that badness?
2433 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2437 void CXXNameMangler::mangleType(const TypeOfType *T) {
2438 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2439 // "extension with parameters" mangling.
2443 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2444 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2445 // "extension with parameters" mangling.
2449 void CXXNameMangler::mangleType(const DecltypeType *T) {
2450 Expr *E = T->getUnderlyingExpr();
2452 // type ::= Dt <expression> E # decltype of an id-expression
2453 // # or class member access
2454 // ::= DT <expression> E # decltype of an expression
2456 // This purports to be an exhaustive list of id-expressions and
2457 // class member accesses. Note that we do not ignore parentheses;
2458 // parentheses change the semantics of decltype for these
2459 // expressions (and cause the mangler to use the other form).
2460 if (isa<DeclRefExpr>(E) ||
2461 isa<MemberExpr>(E) ||
2462 isa<UnresolvedLookupExpr>(E) ||
2463 isa<DependentScopeDeclRefExpr>(E) ||
2464 isa<CXXDependentScopeMemberExpr>(E) ||
2465 isa<UnresolvedMemberExpr>(E))
2469 mangleExpression(E);
2473 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2474 // If this is dependent, we need to record that. If not, we simply
2475 // mangle it as the underlying type since they are equivalent.
2476 if (T->isDependentType()) {
2479 switch (T->getUTTKind()) {
2480 case UnaryTransformType::EnumUnderlyingType:
2486 mangleType(T->getUnderlyingType());
2489 void CXXNameMangler::mangleType(const AutoType *T) {
2490 QualType D = T->getDeducedType();
2491 // <builtin-type> ::= Da # dependent auto
2493 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
2498 void CXXNameMangler::mangleType(const AtomicType *T) {
2499 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2500 // (Until there's a standardized mangling...)
2502 mangleType(T->getValueType());
2505 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2506 const llvm::APSInt &Value) {
2507 // <expr-primary> ::= L <type> <value number> E # integer literal
2511 if (T->isBooleanType()) {
2512 // Boolean values are encoded as 0/1.
2513 Out << (Value.getBoolValue() ? '1' : '0');
2515 mangleNumber(Value);
2521 /// Mangles a member expression.
2522 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2524 NestedNameSpecifier *qualifier,
2525 NamedDecl *firstQualifierLookup,
2526 DeclarationName member,
2528 // <expression> ::= dt <expression> <unresolved-name>
2529 // ::= pt <expression> <unresolved-name>
2531 if (base->isImplicitCXXThis()) {
2532 // Note: GCC mangles member expressions to the implicit 'this' as
2533 // *this., whereas we represent them as this->. The Itanium C++ ABI
2534 // does not specify anything here, so we follow GCC.
2537 Out << (isArrow ? "pt" : "dt");
2538 mangleExpression(base);
2541 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2544 /// Look at the callee of the given call expression and determine if
2545 /// it's a parenthesized id-expression which would have triggered ADL
2547 static bool isParenthesizedADLCallee(const CallExpr *call) {
2548 const Expr *callee = call->getCallee();
2549 const Expr *fn = callee->IgnoreParens();
2551 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2552 // too, but for those to appear in the callee, it would have to be
2554 if (callee == fn) return false;
2556 // Must be an unresolved lookup.
2557 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2558 if (!lookup) return false;
2560 assert(!lookup->requiresADL());
2562 // Must be an unqualified lookup.
2563 if (lookup->getQualifier()) return false;
2565 // Must not have found a class member. Note that if one is a class
2566 // member, they're all class members.
2567 if (lookup->getNumDecls() > 0 &&
2568 (*lookup->decls_begin())->isCXXClassMember())
2571 // Otherwise, ADL would have been triggered.
2575 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2576 // <expression> ::= <unary operator-name> <expression>
2577 // ::= <binary operator-name> <expression> <expression>
2578 // ::= <trinary operator-name> <expression> <expression> <expression>
2579 // ::= cv <type> expression # conversion with one argument
2580 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2581 // ::= st <type> # sizeof (a type)
2582 // ::= at <type> # alignof (a type)
2583 // ::= <template-param>
2584 // ::= <function-param>
2585 // ::= sr <type> <unqualified-name> # dependent name
2586 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2587 // ::= ds <expression> <expression> # expr.*expr
2588 // ::= sZ <template-param> # size of a parameter pack
2589 // ::= sZ <function-param> # size of a function parameter pack
2590 // ::= <expr-primary>
2591 // <expr-primary> ::= L <type> <value number> E # integer literal
2592 // ::= L <type <value float> E # floating literal
2593 // ::= L <mangled-name> E # external name
2594 // ::= fpT # 'this' expression
2595 QualType ImplicitlyConvertedToType;
2598 switch (E->getStmtClass()) {
2599 case Expr::NoStmtClass:
2600 #define ABSTRACT_STMT(Type)
2601 #define EXPR(Type, Base)
2602 #define STMT(Type, Base) \
2603 case Expr::Type##Class:
2604 #include "clang/AST/StmtNodes.inc"
2607 // These all can only appear in local or variable-initialization
2608 // contexts and so should never appear in a mangling.
2609 case Expr::AddrLabelExprClass:
2610 case Expr::DesignatedInitExprClass:
2611 case Expr::ImplicitValueInitExprClass:
2612 case Expr::ParenListExprClass:
2613 case Expr::LambdaExprClass:
2614 case Expr::MSPropertyRefExprClass:
2615 llvm_unreachable("unexpected statement kind");
2617 // FIXME: invent manglings for all these.
2618 case Expr::BlockExprClass:
2619 case Expr::CXXPseudoDestructorExprClass:
2620 case Expr::ChooseExprClass:
2621 case Expr::CompoundLiteralExprClass:
2622 case Expr::ExtVectorElementExprClass:
2623 case Expr::GenericSelectionExprClass:
2624 case Expr::ObjCEncodeExprClass:
2625 case Expr::ObjCIsaExprClass:
2626 case Expr::ObjCIvarRefExprClass:
2627 case Expr::ObjCMessageExprClass:
2628 case Expr::ObjCPropertyRefExprClass:
2629 case Expr::ObjCProtocolExprClass:
2630 case Expr::ObjCSelectorExprClass:
2631 case Expr::ObjCStringLiteralClass:
2632 case Expr::ObjCBoxedExprClass:
2633 case Expr::ObjCArrayLiteralClass:
2634 case Expr::ObjCDictionaryLiteralClass:
2635 case Expr::ObjCSubscriptRefExprClass:
2636 case Expr::ObjCIndirectCopyRestoreExprClass:
2637 case Expr::OffsetOfExprClass:
2638 case Expr::PredefinedExprClass:
2639 case Expr::ShuffleVectorExprClass:
2640 case Expr::ConvertVectorExprClass:
2641 case Expr::StmtExprClass:
2642 case Expr::TypeTraitExprClass:
2643 case Expr::ArrayTypeTraitExprClass:
2644 case Expr::ExpressionTraitExprClass:
2645 case Expr::VAArgExprClass:
2646 case Expr::CXXUuidofExprClass:
2647 case Expr::CUDAKernelCallExprClass:
2648 case Expr::AsTypeExprClass:
2649 case Expr::PseudoObjectExprClass:
2650 case Expr::AtomicExprClass:
2652 // As bad as this diagnostic is, it's better than crashing.
2653 DiagnosticsEngine &Diags = Context.getDiags();
2654 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2655 "cannot yet mangle expression type %0");
2656 Diags.Report(E->getExprLoc(), DiagID)
2657 << E->getStmtClassName() << E->getSourceRange();
2661 // Even gcc-4.5 doesn't mangle this.
2662 case Expr::BinaryConditionalOperatorClass: {
2663 DiagnosticsEngine &Diags = Context.getDiags();
2665 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2666 "?: operator with omitted middle operand cannot be mangled");
2667 Diags.Report(E->getExprLoc(), DiagID)
2668 << E->getStmtClassName() << E->getSourceRange();
2672 // These are used for internal purposes and cannot be meaningfully mangled.
2673 case Expr::OpaqueValueExprClass:
2674 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2676 case Expr::InitListExprClass: {
2678 const InitListExpr *InitList = cast<InitListExpr>(E);
2679 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2680 mangleExpression(InitList->getInit(i));
2685 case Expr::CXXDefaultArgExprClass:
2686 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2689 case Expr::CXXDefaultInitExprClass:
2690 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2693 case Expr::CXXStdInitializerListExprClass:
2694 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2697 case Expr::SubstNonTypeTemplateParmExprClass:
2698 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2702 case Expr::UserDefinedLiteralClass:
2703 // We follow g++'s approach of mangling a UDL as a call to the literal
2705 case Expr::CXXMemberCallExprClass: // fallthrough
2706 case Expr::CallExprClass: {
2707 const CallExpr *CE = cast<CallExpr>(E);
2709 // <expression> ::= cp <simple-id> <expression>* E
2710 // We use this mangling only when the call would use ADL except
2711 // for being parenthesized. Per discussion with David
2712 // Vandervoorde, 2011.04.25.
2713 if (isParenthesizedADLCallee(CE)) {
2715 // The callee here is a parenthesized UnresolvedLookupExpr with
2716 // no qualifier and should always get mangled as a <simple-id>
2719 // <expression> ::= cl <expression>* E
2724 mangleExpression(CE->getCallee(), CE->getNumArgs());
2725 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2726 mangleExpression(CE->getArg(I));
2731 case Expr::CXXNewExprClass: {
2732 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2733 if (New->isGlobalNew()) Out << "gs";
2734 Out << (New->isArray() ? "na" : "nw");
2735 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2736 E = New->placement_arg_end(); I != E; ++I)
2737 mangleExpression(*I);
2739 mangleType(New->getAllocatedType());
2740 if (New->hasInitializer()) {
2741 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2745 const Expr *Init = New->getInitializer();
2746 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2747 // Directly inline the initializers.
2748 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2751 mangleExpression(*I);
2752 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2753 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2754 mangleExpression(PLE->getExpr(i));
2755 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2756 isa<InitListExpr>(Init)) {
2757 // Only take InitListExprs apart for list-initialization.
2758 const InitListExpr *InitList = cast<InitListExpr>(Init);
2759 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2760 mangleExpression(InitList->getInit(i));
2762 mangleExpression(Init);
2768 case Expr::MemberExprClass: {
2769 const MemberExpr *ME = cast<MemberExpr>(E);
2770 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2771 ME->getQualifier(), nullptr,
2772 ME->getMemberDecl()->getDeclName(), Arity);
2776 case Expr::UnresolvedMemberExprClass: {
2777 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2778 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2779 ME->getQualifier(), nullptr, ME->getMemberName(),
2781 if (ME->hasExplicitTemplateArgs())
2782 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2786 case Expr::CXXDependentScopeMemberExprClass: {
2787 const CXXDependentScopeMemberExpr *ME
2788 = cast<CXXDependentScopeMemberExpr>(E);
2789 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2790 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2791 ME->getMember(), Arity);
2792 if (ME->hasExplicitTemplateArgs())
2793 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2797 case Expr::UnresolvedLookupExprClass: {
2798 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2799 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
2801 // All the <unresolved-name> productions end in a
2802 // base-unresolved-name, where <template-args> are just tacked
2804 if (ULE->hasExplicitTemplateArgs())
2805 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2809 case Expr::CXXUnresolvedConstructExprClass: {
2810 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2811 unsigned N = CE->arg_size();
2814 mangleType(CE->getType());
2815 if (N != 1) Out << '_';
2816 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2817 if (N != 1) Out << 'E';
2821 case Expr::CXXTemporaryObjectExprClass:
2822 case Expr::CXXConstructExprClass: {
2823 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2824 unsigned N = CE->getNumArgs();
2826 if (CE->isListInitialization())
2830 mangleType(CE->getType());
2831 if (N != 1) Out << '_';
2832 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2833 if (N != 1) Out << 'E';
2837 case Expr::CXXScalarValueInitExprClass:
2839 mangleType(E->getType());
2843 case Expr::CXXNoexceptExprClass:
2845 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2848 case Expr::UnaryExprOrTypeTraitExprClass: {
2849 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2851 if (!SAE->isInstantiationDependent()) {
2853 // If the operand of a sizeof or alignof operator is not
2854 // instantiation-dependent it is encoded as an integer literal
2855 // reflecting the result of the operator.
2857 // If the result of the operator is implicitly converted to a known
2858 // integer type, that type is used for the literal; otherwise, the type
2859 // of std::size_t or std::ptrdiff_t is used.
2860 QualType T = (ImplicitlyConvertedToType.isNull() ||
2861 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2862 : ImplicitlyConvertedToType;
2863 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2864 mangleIntegerLiteral(T, V);
2868 switch(SAE->getKind()) {
2876 DiagnosticsEngine &Diags = Context.getDiags();
2877 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2878 "cannot yet mangle vec_step expression");
2879 Diags.Report(DiagID);
2882 if (SAE->isArgumentType()) {
2884 mangleType(SAE->getArgumentType());
2887 mangleExpression(SAE->getArgumentExpr());
2892 case Expr::CXXThrowExprClass: {
2893 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2894 // <expression> ::= tw <expression> # throw expression
2896 if (TE->getSubExpr()) {
2898 mangleExpression(TE->getSubExpr());
2905 case Expr::CXXTypeidExprClass: {
2906 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2907 // <expression> ::= ti <type> # typeid (type)
2908 // ::= te <expression> # typeid (expression)
2909 if (TIE->isTypeOperand()) {
2911 mangleType(TIE->getTypeOperand(Context.getASTContext()));
2914 mangleExpression(TIE->getExprOperand());
2919 case Expr::CXXDeleteExprClass: {
2920 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2921 // <expression> ::= [gs] dl <expression> # [::] delete expr
2922 // ::= [gs] da <expression> # [::] delete [] expr
2923 if (DE->isGlobalDelete()) Out << "gs";
2924 Out << (DE->isArrayForm() ? "da" : "dl");
2925 mangleExpression(DE->getArgument());
2929 case Expr::UnaryOperatorClass: {
2930 const UnaryOperator *UO = cast<UnaryOperator>(E);
2931 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2933 mangleExpression(UO->getSubExpr());
2937 case Expr::ArraySubscriptExprClass: {
2938 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2940 // Array subscript is treated as a syntactically weird form of
2943 mangleExpression(AE->getLHS());
2944 mangleExpression(AE->getRHS());
2948 case Expr::CompoundAssignOperatorClass: // fallthrough
2949 case Expr::BinaryOperatorClass: {
2950 const BinaryOperator *BO = cast<BinaryOperator>(E);
2951 if (BO->getOpcode() == BO_PtrMemD)
2954 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2956 mangleExpression(BO->getLHS());
2957 mangleExpression(BO->getRHS());
2961 case Expr::ConditionalOperatorClass: {
2962 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2963 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2964 mangleExpression(CO->getCond());
2965 mangleExpression(CO->getLHS(), Arity);
2966 mangleExpression(CO->getRHS(), Arity);
2970 case Expr::ImplicitCastExprClass: {
2971 ImplicitlyConvertedToType = E->getType();
2972 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2976 case Expr::ObjCBridgedCastExprClass: {
2977 // Mangle ownership casts as a vendor extended operator __bridge,
2978 // __bridge_transfer, or __bridge_retain.
2979 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2980 Out << "v1U" << Kind.size() << Kind;
2982 // Fall through to mangle the cast itself.
2984 case Expr::CStyleCastExprClass:
2985 case Expr::CXXStaticCastExprClass:
2986 case Expr::CXXDynamicCastExprClass:
2987 case Expr::CXXReinterpretCastExprClass:
2988 case Expr::CXXConstCastExprClass:
2989 case Expr::CXXFunctionalCastExprClass: {
2990 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2992 mangleType(ECE->getType());
2993 mangleExpression(ECE->getSubExpr());
2997 case Expr::CXXOperatorCallExprClass: {
2998 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2999 unsigned NumArgs = CE->getNumArgs();
3000 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3001 // Mangle the arguments.
3002 for (unsigned i = 0; i != NumArgs; ++i)
3003 mangleExpression(CE->getArg(i));
3007 case Expr::ParenExprClass:
3008 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3011 case Expr::DeclRefExprClass: {
3012 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3014 switch (D->getKind()) {
3016 // <expr-primary> ::= L <mangled-name> E # external name
3023 mangleFunctionParam(cast<ParmVarDecl>(D));
3026 case Decl::EnumConstant: {
3027 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3028 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3032 case Decl::NonTypeTemplateParm: {
3033 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3034 mangleTemplateParameter(PD->getIndex());
3043 case Expr::SubstNonTypeTemplateParmPackExprClass:
3044 // FIXME: not clear how to mangle this!
3045 // template <unsigned N...> class A {
3046 // template <class U...> void foo(U (&x)[N]...);
3048 Out << "_SUBSTPACK_";
3051 case Expr::FunctionParmPackExprClass: {
3052 // FIXME: not clear how to mangle this!
3053 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3054 Out << "v110_SUBSTPACK";
3055 mangleFunctionParam(FPPE->getParameterPack());
3059 case Expr::DependentScopeDeclRefExprClass: {
3060 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3061 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
3064 // All the <unresolved-name> productions end in a
3065 // base-unresolved-name, where <template-args> are just tacked
3067 if (DRE->hasExplicitTemplateArgs())
3068 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3072 case Expr::CXXBindTemporaryExprClass:
3073 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3076 case Expr::ExprWithCleanupsClass:
3077 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3080 case Expr::FloatingLiteralClass: {
3081 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3083 mangleType(FL->getType());
3084 mangleFloat(FL->getValue());
3089 case Expr::CharacterLiteralClass:
3091 mangleType(E->getType());
3092 Out << cast<CharacterLiteral>(E)->getValue();
3096 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3097 case Expr::ObjCBoolLiteralExprClass:
3099 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3103 case Expr::CXXBoolLiteralExprClass:
3105 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3109 case Expr::IntegerLiteralClass: {
3110 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3111 if (E->getType()->isSignedIntegerType())
3112 Value.setIsSigned(true);
3113 mangleIntegerLiteral(E->getType(), Value);
3117 case Expr::ImaginaryLiteralClass: {
3118 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3119 // Mangle as if a complex literal.
3120 // Proposal from David Vandevoorde, 2010.06.30.
3122 mangleType(E->getType());
3123 if (const FloatingLiteral *Imag =
3124 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3125 // Mangle a floating-point zero of the appropriate type.
3126 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3128 mangleFloat(Imag->getValue());
3131 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3132 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3133 Value.setIsSigned(true);
3134 mangleNumber(Value);
3140 case Expr::StringLiteralClass: {
3141 // Revised proposal from David Vandervoorde, 2010.07.15.
3143 assert(isa<ConstantArrayType>(E->getType()));
3144 mangleType(E->getType());
3149 case Expr::GNUNullExprClass:
3150 // FIXME: should this really be mangled the same as nullptr?
3153 case Expr::CXXNullPtrLiteralExprClass: {
3158 case Expr::PackExpansionExprClass:
3160 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3163 case Expr::SizeOfPackExprClass: {
3165 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3166 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3167 mangleTemplateParameter(TTP->getIndex());
3168 else if (const NonTypeTemplateParmDecl *NTTP
3169 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3170 mangleTemplateParameter(NTTP->getIndex());
3171 else if (const TemplateTemplateParmDecl *TempTP
3172 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3173 mangleTemplateParameter(TempTP->getIndex());
3175 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3179 case Expr::MaterializeTemporaryExprClass: {
3180 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3184 case Expr::CXXThisExprClass:
3190 /// Mangle an expression which refers to a parameter variable.
3192 /// <expression> ::= <function-param>
3193 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3194 /// <function-param> ::= fp <top-level CV-qualifiers>
3195 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3196 /// <function-param> ::= fL <L-1 non-negative number>
3197 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3198 /// <function-param> ::= fL <L-1 non-negative number>
3199 /// p <top-level CV-qualifiers>
3200 /// <I-1 non-negative number> _ # L > 0, I > 0
3202 /// L is the nesting depth of the parameter, defined as 1 if the
3203 /// parameter comes from the innermost function prototype scope
3204 /// enclosing the current context, 2 if from the next enclosing
3205 /// function prototype scope, and so on, with one special case: if
3206 /// we've processed the full parameter clause for the innermost
3207 /// function type, then L is one less. This definition conveniently
3208 /// makes it irrelevant whether a function's result type was written
3209 /// trailing or leading, but is otherwise overly complicated; the
3210 /// numbering was first designed without considering references to
3211 /// parameter in locations other than return types, and then the
3212 /// mangling had to be generalized without changing the existing
3215 /// I is the zero-based index of the parameter within its parameter
3216 /// declaration clause. Note that the original ABI document describes
3217 /// this using 1-based ordinals.
3218 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3219 unsigned parmDepth = parm->getFunctionScopeDepth();
3220 unsigned parmIndex = parm->getFunctionScopeIndex();
3223 // parmDepth does not include the declaring function prototype.
3224 // FunctionTypeDepth does account for that.
3225 assert(parmDepth < FunctionTypeDepth.getDepth());
3226 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3227 if (FunctionTypeDepth.isInResultType())
3230 if (nestingDepth == 0) {
3233 Out << "fL" << (nestingDepth - 1) << 'p';
3236 // Top-level qualifiers. We don't have to worry about arrays here,
3237 // because parameters declared as arrays should already have been
3238 // transformed to have pointer type. FIXME: apparently these don't
3239 // get mangled if used as an rvalue of a known non-class type?
3240 assert(!parm->getType()->isArrayType()
3241 && "parameter's type is still an array type?");
3242 mangleQualifiers(parm->getType().getQualifiers());
3245 if (parmIndex != 0) {
3246 Out << (parmIndex - 1);
3251 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3252 // <ctor-dtor-name> ::= C1 # complete object constructor
3253 // ::= C2 # base object constructor
3254 // ::= C3 # complete object allocating constructor
3263 case Ctor_CompleteAllocating:
3269 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3270 // <ctor-dtor-name> ::= D0 # deleting destructor
3271 // ::= D1 # complete object destructor
3272 // ::= D2 # base object destructor
3287 void CXXNameMangler::mangleTemplateArgs(
3288 const ASTTemplateArgumentListInfo &TemplateArgs) {
3289 // <template-args> ::= I <template-arg>+ E
3291 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3292 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3296 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3297 // <template-args> ::= I <template-arg>+ E
3299 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3300 mangleTemplateArg(AL[i]);
3304 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3305 unsigned NumTemplateArgs) {
3306 // <template-args> ::= I <template-arg>+ E
3308 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3309 mangleTemplateArg(TemplateArgs[i]);
3313 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3314 // <template-arg> ::= <type> # type or template
3315 // ::= X <expression> E # expression
3316 // ::= <expr-primary> # simple expressions
3317 // ::= J <template-arg>* E # argument pack
3318 if (!A.isInstantiationDependent() || A.isDependent())
3319 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3321 switch (A.getKind()) {
3322 case TemplateArgument::Null:
3323 llvm_unreachable("Cannot mangle NULL template argument");
3325 case TemplateArgument::Type:
3326 mangleType(A.getAsType());
3328 case TemplateArgument::Template:
3329 // This is mangled as <type>.
3330 mangleType(A.getAsTemplate());
3332 case TemplateArgument::TemplateExpansion:
3333 // <type> ::= Dp <type> # pack expansion (C++0x)
3335 mangleType(A.getAsTemplateOrTemplatePattern());
3337 case TemplateArgument::Expression: {
3338 // It's possible to end up with a DeclRefExpr here in certain
3339 // dependent cases, in which case we should mangle as a
3341 const Expr *E = A.getAsExpr()->IgnoreParens();
3342 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3343 const ValueDecl *D = DRE->getDecl();
3344 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3353 mangleExpression(E);
3357 case TemplateArgument::Integral:
3358 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3360 case TemplateArgument::Declaration: {
3361 // <expr-primary> ::= L <mangled-name> E # external name
3362 // Clang produces AST's where pointer-to-member-function expressions
3363 // and pointer-to-function expressions are represented as a declaration not
3364 // an expression. We compensate for it here to produce the correct mangling.
3365 ValueDecl *D = A.getAsDecl();
3366 bool compensateMangling = !A.isDeclForReferenceParam();
3367 if (compensateMangling) {
3369 mangleOperatorName(OO_Amp, 1);
3373 // References to external entities use the mangled name; if the name would
3374 // not normally be manged then mangle it as unqualified.
3376 // FIXME: The ABI specifies that external names here should have _Z, but
3377 // gcc leaves this off.
3378 if (compensateMangling)
3384 if (compensateMangling)
3389 case TemplateArgument::NullPtr: {
3390 // <expr-primary> ::= L <type> 0 E
3392 mangleType(A.getNullPtrType());
3396 case TemplateArgument::Pack: {
3397 // <template-arg> ::= J <template-arg>* E
3399 for (const auto &P : A.pack_elements())
3400 mangleTemplateArg(P);
3406 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3407 // <template-param> ::= T_ # first template parameter
3408 // ::= T <parameter-2 non-negative number> _
3412 Out << 'T' << (Index - 1) << '_';
3415 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3418 else if (SeqID > 1) {
3421 // <seq-id> is encoded in base-36, using digits and upper case letters.
3422 char Buffer[7]; // log(2**32) / log(36) ~= 7
3423 MutableArrayRef<char> BufferRef(Buffer);
3424 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
3426 for (; SeqID != 0; SeqID /= 36) {
3427 unsigned C = SeqID % 36;
3428 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3431 Out.write(I.base(), I - BufferRef.rbegin());
3436 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3437 bool result = mangleSubstitution(type);
3438 assert(result && "no existing substitution for type");
3442 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3443 bool result = mangleSubstitution(tname);
3444 assert(result && "no existing substitution for template name");
3448 // <substitution> ::= S <seq-id> _
3450 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3451 // Try one of the standard substitutions first.
3452 if (mangleStandardSubstitution(ND))
3455 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3456 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3459 /// \brief Determine whether the given type has any qualifiers that are
3460 /// relevant for substitutions.
3461 static bool hasMangledSubstitutionQualifiers(QualType T) {
3462 Qualifiers Qs = T.getQualifiers();
3463 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3466 bool CXXNameMangler::mangleSubstitution(QualType T) {
3467 if (!hasMangledSubstitutionQualifiers(T)) {
3468 if (const RecordType *RT = T->getAs<RecordType>())
3469 return mangleSubstitution(RT->getDecl());
3472 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3474 return mangleSubstitution(TypePtr);
3477 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3478 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3479 return mangleSubstitution(TD);
3481 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3482 return mangleSubstitution(
3483 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3486 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3487 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3488 if (I == Substitutions.end())
3491 unsigned SeqID = I->second;
3498 static bool isCharType(QualType T) {
3502 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3503 T->isSpecificBuiltinType(BuiltinType::Char_U);
3506 /// isCharSpecialization - Returns whether a given type is a template
3507 /// specialization of a given name with a single argument of type char.
3508 static bool isCharSpecialization(QualType T, const char *Name) {
3512 const RecordType *RT = T->getAs<RecordType>();
3516 const ClassTemplateSpecializationDecl *SD =
3517 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3521 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3524 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3525 if (TemplateArgs.size() != 1)
3528 if (!isCharType(TemplateArgs[0].getAsType()))
3531 return SD->getIdentifier()->getName() == Name;
3534 template <std::size_t StrLen>
3535 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3536 const char (&Str)[StrLen]) {
3537 if (!SD->getIdentifier()->isStr(Str))
3540 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3541 if (TemplateArgs.size() != 2)
3544 if (!isCharType(TemplateArgs[0].getAsType()))
3547 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3553 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3554 // <substitution> ::= St # ::std::
3555 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3562 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3563 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3566 // <substitution> ::= Sa # ::std::allocator
3567 if (TD->getIdentifier()->isStr("allocator")) {
3572 // <<substitution> ::= Sb # ::std::basic_string
3573 if (TD->getIdentifier()->isStr("basic_string")) {
3579 if (const ClassTemplateSpecializationDecl *SD =
3580 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3581 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3584 // <substitution> ::= Ss # ::std::basic_string<char,
3585 // ::std::char_traits<char>,
3586 // ::std::allocator<char> >
3587 if (SD->getIdentifier()->isStr("basic_string")) {
3588 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3590 if (TemplateArgs.size() != 3)
3593 if (!isCharType(TemplateArgs[0].getAsType()))
3596 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3599 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3606 // <substitution> ::= Si # ::std::basic_istream<char,
3607 // ::std::char_traits<char> >
3608 if (isStreamCharSpecialization(SD, "basic_istream")) {
3613 // <substitution> ::= So # ::std::basic_ostream<char,
3614 // ::std::char_traits<char> >
3615 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3620 // <substitution> ::= Sd # ::std::basic_iostream<char,
3621 // ::std::char_traits<char> >
3622 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3630 void CXXNameMangler::addSubstitution(QualType T) {
3631 if (!hasMangledSubstitutionQualifiers(T)) {
3632 if (const RecordType *RT = T->getAs<RecordType>()) {
3633 addSubstitution(RT->getDecl());
3638 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3639 addSubstitution(TypePtr);
3642 void CXXNameMangler::addSubstitution(TemplateName Template) {
3643 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3644 return addSubstitution(TD);
3646 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3647 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3650 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3651 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3652 Substitutions[Ptr] = SeqID++;
3657 /// \brief Mangles the name of the declaration D and emits that name to the
3658 /// given output stream.
3660 /// If the declaration D requires a mangled name, this routine will emit that
3661 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3662 /// and this routine will return false. In this case, the caller should just
3663 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3665 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3667 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3668 "Invalid mangleName() call, argument is not a variable or function!");
3669 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3670 "Invalid mangleName() call on 'structor decl!");
3672 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3673 getASTContext().getSourceManager(),
3674 "Mangling declaration");
3676 CXXNameMangler Mangler(*this, Out, D);
3677 return Mangler.mangle(D);
3680 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3683 CXXNameMangler Mangler(*this, Out, D, Type);
3687 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3690 CXXNameMangler Mangler(*this, Out, D, Type);
3694 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3695 const ThunkInfo &Thunk,
3697 // <special-name> ::= T <call-offset> <base encoding>
3698 // # base is the nominal target function of thunk
3699 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3700 // # base is the nominal target function of thunk
3701 // # first call-offset is 'this' adjustment
3702 // # second call-offset is result adjustment
3704 assert(!isa<CXXDestructorDecl>(MD) &&
3705 "Use mangleCXXDtor for destructor decls!");
3706 CXXNameMangler Mangler(*this, Out);
3707 Mangler.getStream() << "_ZT";
3708 if (!Thunk.Return.isEmpty())
3709 Mangler.getStream() << 'c';
3711 // Mangle the 'this' pointer adjustment.
3712 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3713 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3715 // Mangle the return pointer adjustment if there is one.
3716 if (!Thunk.Return.isEmpty())
3717 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3718 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3720 Mangler.mangleFunctionEncoding(MD);
3723 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3724 const CXXDestructorDecl *DD, CXXDtorType Type,
3725 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
3726 // <special-name> ::= T <call-offset> <base encoding>
3727 // # base is the nominal target function of thunk
3728 CXXNameMangler Mangler(*this, Out, DD, Type);
3729 Mangler.getStream() << "_ZT";
3731 // Mangle the 'this' pointer adjustment.
3732 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3733 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
3735 Mangler.mangleFunctionEncoding(DD);
3738 /// mangleGuardVariable - Returns the mangled name for a guard variable
3739 /// for the passed in VarDecl.
3740 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3742 // <special-name> ::= GV <object name> # Guard variable for one-time
3744 CXXNameMangler Mangler(*this, Out);
3745 Mangler.getStream() << "_ZGV";
3746 Mangler.mangleName(D);
3749 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3751 // These symbols are internal in the Itanium ABI, so the names don't matter.
3752 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3753 // avoid duplicate symbols.
3754 Out << "__cxx_global_var_init";
3757 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3759 // Prefix the mangling of D with __dtor_.
3760 CXXNameMangler Mangler(*this, Out);
3761 Mangler.getStream() << "__dtor_";
3762 if (shouldMangleDeclName(D))
3765 Mangler.getStream() << D->getName();
3768 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3770 // <special-name> ::= TH <object name>
3771 CXXNameMangler Mangler(*this, Out);
3772 Mangler.getStream() << "_ZTH";
3773 Mangler.mangleName(D);
3777 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3779 // <special-name> ::= TW <object name>
3780 CXXNameMangler Mangler(*this, Out);
3781 Mangler.getStream() << "_ZTW";
3782 Mangler.mangleName(D);
3785 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
3786 unsigned ManglingNumber,
3788 // We match the GCC mangling here.
3789 // <special-name> ::= GR <object name>
3790 CXXNameMangler Mangler(*this, Out);
3791 Mangler.getStream() << "_ZGR";
3792 Mangler.mangleName(D);
3793 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
3794 Mangler.mangleSeqID(ManglingNumber - 1);
3797 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
3799 // <special-name> ::= TV <type> # virtual table
3800 CXXNameMangler Mangler(*this, Out);
3801 Mangler.getStream() << "_ZTV";
3802 Mangler.mangleNameOrStandardSubstitution(RD);
3805 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
3807 // <special-name> ::= TT <type> # VTT structure
3808 CXXNameMangler Mangler(*this, Out);
3809 Mangler.getStream() << "_ZTT";
3810 Mangler.mangleNameOrStandardSubstitution(RD);
3813 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3815 const CXXRecordDecl *Type,
3817 // <special-name> ::= TC <type> <offset number> _ <base type>
3818 CXXNameMangler Mangler(*this, Out);
3819 Mangler.getStream() << "_ZTC";
3820 Mangler.mangleNameOrStandardSubstitution(RD);
3821 Mangler.getStream() << Offset;
3822 Mangler.getStream() << '_';
3823 Mangler.mangleNameOrStandardSubstitution(Type);
3826 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
3827 // <special-name> ::= TI <type> # typeinfo structure
3828 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3829 CXXNameMangler Mangler(*this, Out);
3830 Mangler.getStream() << "_ZTI";
3831 Mangler.mangleType(Ty);
3834 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
3836 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3837 CXXNameMangler Mangler(*this, Out);
3838 Mangler.getStream() << "_ZTS";
3839 Mangler.mangleType(Ty);
3842 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
3843 mangleCXXRTTIName(Ty, Out);
3846 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
3847 llvm_unreachable("Can't mangle string literals");
3850 ItaniumMangleContext *
3851 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3852 return new ItaniumMangleContextImpl(Context, Diags);