//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements C++ name mangling according to the Itanium C++ ABI, // which is used in GCC 3.2 and newer (and many compilers that are // ABI-compatible with GCC): // // http://www.codesourcery.com/public/cxx-abi/abi.html // //===----------------------------------------------------------------------===// #include "clang/AST/Mangle.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/ABI.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #define MANGLE_CHECKER 0 #if MANGLE_CHECKER #include #endif using namespace clang; namespace { static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) { const DeclContext *DC = dyn_cast(ND); if (!DC) DC = ND->getDeclContext(); while (!DC->isNamespace() && !DC->isTranslationUnit()) { if (isa(DC->getParent())) return dyn_cast(DC); DC = DC->getParent(); } return 0; } static const FunctionDecl *getStructor(const FunctionDecl *fn) { if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate()) return ftd->getTemplatedDecl(); return fn; } static const NamedDecl *getStructor(const NamedDecl *decl) { const FunctionDecl *fn = dyn_cast_or_null(decl); return (fn ? getStructor(fn) : decl); } static const unsigned UnknownArity = ~0U; class ItaniumMangleContext : public MangleContext { llvm::DenseMap AnonStructIds; unsigned Discriminator; llvm::DenseMap Uniquifier; public: explicit ItaniumMangleContext(ASTContext &Context, Diagnostic &Diags) : MangleContext(Context, Diags) { } uint64_t getAnonymousStructId(const TagDecl *TD) { std::pair::iterator, bool> Result = AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size())); return Result.first->second; } void startNewFunction() { MangleContext::startNewFunction(); mangleInitDiscriminator(); } /// @name Mangler Entry Points /// @{ bool shouldMangleDeclName(const NamedDecl *D); void mangleName(const NamedDecl *D, llvm::raw_ostream &); void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, llvm::raw_ostream &); void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, const ThisAdjustment &ThisAdjustment, llvm::raw_ostream &); void mangleReferenceTemporary(const VarDecl *D, llvm::raw_ostream &); void mangleCXXVTable(const CXXRecordDecl *RD, llvm::raw_ostream &); void mangleCXXVTT(const CXXRecordDecl *RD, llvm::raw_ostream &); void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset, const CXXRecordDecl *Type, llvm::raw_ostream &); void mangleCXXRTTI(QualType T, llvm::raw_ostream &); void mangleCXXRTTIName(QualType T, llvm::raw_ostream &); void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, llvm::raw_ostream &); void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, llvm::raw_ostream &); void mangleItaniumGuardVariable(const VarDecl *D, llvm::raw_ostream &); void mangleInitDiscriminator() { Discriminator = 0; } bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { unsigned &discriminator = Uniquifier[ND]; if (!discriminator) discriminator = ++Discriminator; if (discriminator == 1) return false; disc = discriminator-2; return true; } /// @} }; /// CXXNameMangler - Manage the mangling of a single name. class CXXNameMangler { ItaniumMangleContext &Context; llvm::raw_ostream &Out; /// The "structor" is the top-level declaration being mangled, if /// that's not a template specialization; otherwise it's the pattern /// for that specialization. const NamedDecl *Structor; unsigned StructorType; /// SeqID - The next subsitution sequence number. unsigned SeqID; class FunctionTypeDepthState { unsigned Bits; enum { InResultTypeMask = 1 }; public: FunctionTypeDepthState() : Bits(0) {} /// The number of function types we're inside. unsigned getDepth() const { return Bits >> 1; } /// True if we're in the return type of the innermost function type. bool isInResultType() const { return Bits & InResultTypeMask; } FunctionTypeDepthState push() { FunctionTypeDepthState tmp = *this; Bits = (Bits & ~InResultTypeMask) + 2; return tmp; } void enterResultType() { Bits |= InResultTypeMask; } void leaveResultType() { Bits &= ~InResultTypeMask; } void pop(FunctionTypeDepthState saved) { assert(getDepth() == saved.getDepth() + 1); Bits = saved.Bits; } } FunctionTypeDepth; llvm::DenseMap Substitutions; ASTContext &getASTContext() const { return Context.getASTContext(); } public: CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_, const NamedDecl *D = 0) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0), SeqID(0) { // These can't be mangled without a ctor type or dtor type. assert(!D || (!isa(D) && !isa(D))); } CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_, const CXXConstructorDecl *D, CXXCtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), SeqID(0) { } CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_, const CXXDestructorDecl *D, CXXDtorType Type) : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), SeqID(0) { } #if MANGLE_CHECKER ~CXXNameMangler() { if (Out.str()[0] == '\01') return; int status = 0; char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status); assert(status == 0 && "Could not demangle mangled name!"); free(result); } #endif llvm::raw_ostream &getStream() { return Out; } void mangle(const NamedDecl *D, llvm::StringRef Prefix = "_Z"); void mangleCallOffset(int64_t NonVirtual, int64_t Virtual); void mangleNumber(const llvm::APSInt &I); void mangleNumber(int64_t Number); void mangleFloat(const llvm::APFloat &F); void mangleFunctionEncoding(const FunctionDecl *FD); void mangleName(const NamedDecl *ND); void mangleType(QualType T); void mangleNameOrStandardSubstitution(const NamedDecl *ND); private: bool mangleSubstitution(const NamedDecl *ND); bool mangleSubstitution(QualType T); bool mangleSubstitution(TemplateName Template); bool mangleSubstitution(uintptr_t Ptr); bool mangleStandardSubstitution(const NamedDecl *ND); void addSubstitution(const NamedDecl *ND) { ND = cast(ND->getCanonicalDecl()); addSubstitution(reinterpret_cast(ND)); } void addSubstitution(QualType T); void addSubstitution(TemplateName Template); void addSubstitution(uintptr_t Ptr); void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, bool recursive = false); void mangleUnresolvedName(NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, DeclarationName name, unsigned KnownArity = UnknownArity); static bool isUnresolvedType(const Type *type); void mangleUnresolvedType(const Type *type); void mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleUnqualifiedName(const NamedDecl *ND) { mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity); } void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name, unsigned KnownArity); void mangleUnscopedName(const NamedDecl *ND); void mangleUnscopedTemplateName(const TemplateDecl *ND); void mangleUnscopedTemplateName(TemplateName); void mangleSourceName(const IdentifierInfo *II); void mangleLocalName(const NamedDecl *ND); void mangleNestedName(const NamedDecl *ND, const DeclContext *DC, bool NoFunction=false); void mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void manglePrefix(NestedNameSpecifier *qualifier); void manglePrefix(const DeclContext *DC, bool NoFunction=false); void manglePrefix(QualType type); void mangleTemplatePrefix(const TemplateDecl *ND); void mangleTemplatePrefix(TemplateName Template); void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); void mangleQualifiers(Qualifiers Quals); void mangleRefQualifier(RefQualifierKind RefQualifier); void mangleObjCMethodName(const ObjCMethodDecl *MD); // Declare manglers for every type class. #define ABSTRACT_TYPE(CLASS, PARENT) #define NON_CANONICAL_TYPE(CLASS, PARENT) #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T); #include "clang/AST/TypeNodes.def" void mangleType(const TagType*); void mangleType(TemplateName); void mangleBareFunctionType(const FunctionType *T, bool MangleReturnType); void mangleNeonVectorType(const VectorType *T); void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); void mangleMemberExpr(const Expr *base, bool isArrow, NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, DeclarationName name, unsigned knownArity); void mangleExpression(const Expr *E, unsigned Arity = UnknownArity); void mangleCXXCtorType(CXXCtorType T); void mangleCXXDtorType(CXXDtorType T); void mangleTemplateArgs(const ExplicitTemplateArgumentList &TemplateArgs); void mangleTemplateArgs(TemplateName Template, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleTemplateArgs(const TemplateParameterList &PL, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleTemplateArgs(const TemplateParameterList &PL, const TemplateArgumentList &AL); void mangleTemplateArg(const NamedDecl *P, const TemplateArgument &A); void mangleUnresolvedTemplateArgs(const TemplateArgument *args, unsigned numArgs); void mangleTemplateParameter(unsigned Index); void mangleFunctionParam(const ParmVarDecl *parm); }; } static bool isInCLinkageSpecification(const Decl *D) { D = D->getCanonicalDecl(); for (const DeclContext *DC = D->getDeclContext(); !DC->isTranslationUnit(); DC = DC->getParent()) { if (const LinkageSpecDecl *Linkage = dyn_cast(DC)) return Linkage->getLanguage() == LinkageSpecDecl::lang_c; } return false; } bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) { // In C, functions with no attributes never need to be mangled. Fastpath them. if (!getASTContext().getLangOptions().CPlusPlus && !D->hasAttrs()) return false; // Any decl can be declared with __asm("foo") on it, and this takes precedence // over all other naming in the .o file. if (D->hasAttr()) return true; // Clang's "overloadable" attribute extension to C/C++ implies name mangling // (always) as does passing a C++ member function and a function // whose name is not a simple identifier. const FunctionDecl *FD = dyn_cast(D); if (FD && (FD->hasAttr() || isa(FD) || !FD->getDeclName().isIdentifier())) return true; // Otherwise, no mangling is done outside C++ mode. if (!getASTContext().getLangOptions().CPlusPlus) return false; // Variables at global scope with non-internal linkage are not mangled if (!FD) { const DeclContext *DC = D->getDeclContext(); // Check for extern variable declared locally. if (DC->isFunctionOrMethod() && D->hasLinkage()) while (!DC->isNamespace() && !DC->isTranslationUnit()) DC = DC->getParent(); if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage) return false; } // Class members are always mangled. if (D->getDeclContext()->isRecord()) return true; // C functions and "main" are not mangled. if ((FD && FD->isMain()) || isInCLinkageSpecification(D)) return false; return true; } void CXXNameMangler::mangle(const NamedDecl *D, llvm::StringRef Prefix) { // Any decl can be declared with __asm("foo") on it, and this takes precedence // over all other naming in the .o file. if (const AsmLabelAttr *ALA = D->getAttr()) { // If we have an asm name, then we use it as the mangling. // Adding the prefix can cause problems when one file has a "foo" and // another has a "\01foo". That is known to happen on ELF with the // tricks normally used for producing aliases (PR9177). Fortunately the // llvm mangler on ELF is a nop, so we can just avoid adding the \01 // marker. We also avoid adding the marker if this is an alias for an // LLVM intrinsic. llvm::StringRef UserLabelPrefix = getASTContext().Target.getUserLabelPrefix(); if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm.")) Out << '\01'; // LLVM IR Marker for __asm("foo") Out << ALA->getLabel(); return; } // ::= _Z // ::= // ::= Out << Prefix; if (const FunctionDecl *FD = dyn_cast(D)) mangleFunctionEncoding(FD); else if (const VarDecl *VD = dyn_cast(D)) mangleName(VD); else mangleName(cast(D)); } void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) { // ::= mangleName(FD); // Don't mangle in the type if this isn't a decl we should typically mangle. if (!Context.shouldMangleDeclName(FD)) return; // Whether the mangling of a function type includes the return type depends on // the context and the nature of the function. The rules for deciding whether // the return type is included are: // // 1. Template functions (names or types) have return types encoded, with // the exceptions listed below. // 2. Function types not appearing as part of a function name mangling, // e.g. parameters, pointer types, etc., have return type encoded, with the // exceptions listed below. // 3. Non-template function names do not have return types encoded. // // The exceptions mentioned in (1) and (2) above, for which the return type is // never included, are // 1. Constructors. // 2. Destructors. // 3. Conversion operator functions, e.g. operator int. bool MangleReturnType = false; if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) { if (!(isa(FD) || isa(FD) || isa(FD))) MangleReturnType = true; // Mangle the type of the primary template. FD = PrimaryTemplate->getTemplatedDecl(); } // Do the canonicalization out here because parameter types can // undergo additional canonicalization (e.g. array decay). const FunctionType *FT = cast(Context.getASTContext() .getCanonicalType(FD->getType())); mangleBareFunctionType(FT, MangleReturnType); } static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) { while (isa(DC)) { DC = DC->getParent(); } return DC; } /// isStd - Return whether a given namespace is the 'std' namespace. static bool isStd(const NamespaceDecl *NS) { if (!IgnoreLinkageSpecDecls(NS->getParent())->isTranslationUnit()) return false; const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } // isStdNamespace - Return whether a given decl context is a toplevel 'std' // namespace. static bool isStdNamespace(const DeclContext *DC) { if (!DC->isNamespace()) return false; return isStd(cast(DC)); } static const TemplateDecl * isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) { // Check if we have a function template. if (const FunctionDecl *FD = dyn_cast(ND)){ if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { TemplateArgs = FD->getTemplateSpecializationArgs(); return TD; } } // Check if we have a class template. if (const ClassTemplateSpecializationDecl *Spec = dyn_cast(ND)) { TemplateArgs = &Spec->getTemplateArgs(); return Spec->getSpecializedTemplate(); } return 0; } void CXXNameMangler::mangleName(const NamedDecl *ND) { // ::= // ::= // ::= // ::= // const DeclContext *DC = ND->getDeclContext(); // If this is an extern variable declared locally, the relevant DeclContext // is that of the containing namespace, or the translation unit. if (isa(DC) && ND->hasLinkage()) while (!DC->isNamespace() && !DC->isTranslationUnit()) DC = DC->getParent(); else if (GetLocalClassDecl(ND)) { mangleLocalName(ND); return; } while (isa(DC)) DC = DC->getParent(); if (DC->isTranslationUnit() || isStdNamespace(DC)) { // Check if we have a template. const TemplateArgumentList *TemplateArgs = 0; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleUnscopedTemplateName(TD); TemplateParameterList *TemplateParameters = TD->getTemplateParameters(); mangleTemplateArgs(*TemplateParameters, *TemplateArgs); return; } mangleUnscopedName(ND); return; } if (isa(DC) || isa(DC)) { mangleLocalName(ND); return; } mangleNestedName(ND, DC); } void CXXNameMangler::mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { const DeclContext *DC = IgnoreLinkageSpecDecls(TD->getDeclContext()); if (DC->isTranslationUnit() || isStdNamespace(DC)) { mangleUnscopedTemplateName(TD); TemplateParameterList *TemplateParameters = TD->getTemplateParameters(); mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs); } else { mangleNestedName(TD, TemplateArgs, NumTemplateArgs); } } void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) { // ::= // ::= St # ::std:: if (isStdNamespace(ND->getDeclContext())) Out << "St"; mangleUnqualifiedName(ND); } void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) { // ::= // ::= if (mangleSubstitution(ND)) return; // ::= if (const TemplateTemplateParmDecl *TTP = dyn_cast(ND)) { mangleTemplateParameter(TTP->getIndex()); return; } mangleUnscopedName(ND->getTemplatedDecl()); addSubstitution(ND); } void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) { // ::= // ::= if (TemplateDecl *TD = Template.getAsTemplateDecl()) return mangleUnscopedTemplateName(TD); if (mangleSubstitution(Template)) return; // FIXME: How to cope with operators here? DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); assert(Dependent && "Not a dependent template name?"); if (!Dependent->isIdentifier()) { // FIXME: We can't possibly know the arity of the operator here! Diagnostic &Diags = Context.getDiags(); unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error, "cannot mangle dependent operator name"); Diags.Report(DiagID); return; } mangleSourceName(Dependent->getIdentifier()); addSubstitution(Template); } void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { // ABI: // Floating-point literals are encoded using a fixed-length // lowercase hexadecimal string corresponding to the internal // representation (IEEE on Itanium), high-order bytes first, // without leading zeroes. For example: "Lf bf800000 E" is -1.0f // on Itanium. // APInt::toString uses uppercase hexadecimal, and it's not really // worth embellishing that interface for this use case, so we just // do a second pass to lowercase things. typedef llvm::SmallString<20> buffer_t; buffer_t buffer; f.bitcastToAPInt().toString(buffer, 16, false); for (buffer_t::iterator i = buffer.begin(), e = buffer.end(); i != e; ++i) if (isupper(*i)) *i = tolower(*i); Out.write(buffer.data(), buffer.size()); } void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { if (Value.isSigned() && Value.isNegative()) { Out << 'n'; Value.abs().print(Out, true); } else Value.print(Out, Value.isSigned()); } void CXXNameMangler::mangleNumber(int64_t Number) { // ::= [n] if (Number < 0) { Out << 'n'; Number = -Number; } Out << Number; } void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { // ::= h _ // ::= v _ // ::= # non-virtual base override // ::= _ // # virtual base override, with vcall offset if (!Virtual) { Out << 'h'; mangleNumber(NonVirtual); Out << '_'; return; } Out << 'v'; mangleNumber(NonVirtual); Out << '_'; mangleNumber(Virtual); Out << '_'; } void CXXNameMangler::manglePrefix(QualType type) { if (const TemplateSpecializationType *TST = type->getAs()) { if (!mangleSubstitution(QualType(TST, 0))) { mangleTemplatePrefix(TST->getTemplateName()); // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(), TST->getNumArgs()); addSubstitution(QualType(TST, 0)); } } else if (const DependentTemplateSpecializationType *DTST = type->getAs()) { TemplateName Template = getASTContext().getDependentTemplateName(DTST->getQualifier(), DTST->getIdentifier()); mangleTemplatePrefix(Template); // FIXME: GCC does not appear to mangle the template arguments when // the template in question is a dependent template name. Should we // emulate that badness? mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs()); } else { // We use the QualType mangle type variant here because it handles // substitutions. mangleType(type); } } /// Returns true if the given type, appearing within an /// unresolved-name, should be mangled as an unresolved-type. bool CXXNameMangler::isUnresolvedType(const Type *type) { // ::= // ::= // ::= // (this last is not official yet) if (isa(type)) return true; if (isa(type)) return true; // typeof? if (const TemplateSpecializationType *tst = dyn_cast(type)) { TemplateDecl *temp = tst->getTemplateName().getAsTemplateDecl(); if (temp && isa(temp)) return true; } return false; } void CXXNameMangler::mangleUnresolvedType(const Type *type) { // This seems to be do everything we want. mangleType(QualType(type, 0)); } /// Mangle everything prior to the base-unresolved-name in an unresolved-name. /// /// \param firstQualifierLookup - the entity found by unqualified lookup /// for the first name in the qualifier, if this is for a member expression /// \param recursive - true if this is being called recursively, /// i.e. if there is more prefix "to the right". void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, bool recursive) { // x, ::x // ::= [gs] // T::x / decltype(p)::x // ::= sr // T::N::x /decltype(p)::N::x // ::= srN + E // // A::x, N::y, A::z; "gs" means leading "::" // ::= [gs] sr + E // switch (qualifier->getKind()) { case NestedNameSpecifier::Global: Out << "gs"; // We want an 'sr' unless this is the entire NNS. if (recursive) Out << "sr"; // We never want an 'E' here. return; case NestedNameSpecifier::Namespace: if (qualifier->getPrefix()) mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, /*recursive*/ true); else Out << "sr"; mangleSourceName(qualifier->getAsNamespace()->getIdentifier()); break; case NestedNameSpecifier::NamespaceAlias: if (qualifier->getPrefix()) mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, /*recursive*/ true); else Out << "sr"; mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier()); break; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { const Type *type = qualifier->getAsType(); // We only want to use an unresolved-type encoding if this is one of: // - a decltype // - a template type parameter // - a template template parameter with arguments // In all of these cases, we should have no prefix. if (qualifier->getPrefix()) { mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, /*recursive*/ true); } else { // Otherwise, all the cases want this. Out << "sr"; if (isUnresolvedType(type)) { // We only get here recursively if we're followed by identifiers. if (recursive) Out << 'N'; mangleUnresolvedType(type); // We never want to print 'E' directly after an unresolved-type, // so we return directly. return; } } assert(!isUnresolvedType(type)); // Only certain other types are valid as prefixes; enumerate them. // FIXME: can we get ElaboratedTypes here? // FIXME: SubstTemplateTypeParmType? if (const TagType *t = dyn_cast(type)) { mangleSourceName(t->getDecl()->getIdentifier()); } else if (const TypedefType *t = dyn_cast(type)) { mangleSourceName(t->getDecl()->getIdentifier()); } else if (const UnresolvedUsingType *t = dyn_cast(type)) { mangleSourceName(t->getDecl()->getIdentifier()); } else if (const DependentNameType *t = dyn_cast(type)) { mangleSourceName(t->getIdentifier()); } else if (const TemplateSpecializationType *tst = dyn_cast(type)) { TemplateDecl *temp = tst->getTemplateName().getAsTemplateDecl(); assert(temp && "no template for template specialization type"); mangleSourceName(temp->getIdentifier()); mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs()); } else if (const DependentTemplateSpecializationType *tst = dyn_cast(type)) { mangleSourceName(tst->getIdentifier()); mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs()); } else { llvm_unreachable("unexpected type in nested name specifier!"); } break; } case NestedNameSpecifier::Identifier: // Member expressions can have these without prefixes. if (qualifier->getPrefix()) { mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, /*recursive*/ true); } else if (firstQualifierLookup) { // Try to make a proper qualifier out of the lookup result, and // then just recurse on that. NestedNameSpecifier *newQualifier; if (TypeDecl *typeDecl = dyn_cast(firstQualifierLookup)) { QualType type = getASTContext().getTypeDeclType(typeDecl); // Pretend we had a different nested name specifier. newQualifier = NestedNameSpecifier::Create(getASTContext(), /*prefix*/ 0, /*template*/ false, type.getTypePtr()); } else if (NamespaceDecl *nspace = dyn_cast(firstQualifierLookup)) { newQualifier = NestedNameSpecifier::Create(getASTContext(), /*prefix*/ 0, nspace); } else if (NamespaceAliasDecl *alias = dyn_cast(firstQualifierLookup)) { newQualifier = NestedNameSpecifier::Create(getASTContext(), /*prefix*/ 0, alias); } else { // No sensible mangling to do here. newQualifier = 0; } if (newQualifier) return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive); } else { Out << "sr"; } mangleSourceName(qualifier->getAsIdentifier()); break; } // If this was the innermost part of the NNS, and we fell out to // here, append an 'E'. if (!recursive) Out << 'E'; } /// Mangle an unresolved-name, which is generally used for names which /// weren't resolved to specific entities. void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier, NamedDecl *firstQualifierLookup, DeclarationName name, unsigned knownArity) { if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup); mangleUnqualifiedName(0, name, knownArity); } static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) { assert(RD->isAnonymousStructOrUnion() && "Expected anonymous struct or union!"); for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); I != E; ++I) { const FieldDecl *FD = *I; if (FD->getIdentifier()) return FD; if (const RecordType *RT = FD->getType()->getAs()) { if (const FieldDecl *NamedDataMember = FindFirstNamedDataMember(RT->getDecl())) return NamedDataMember; } } // We didn't find a named data member. return 0; } void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name, unsigned KnownArity) { // ::= // ::= // ::= switch (Name.getNameKind()) { case DeclarationName::Identifier: { if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { // We must avoid conflicts between internally- and externally- // linked variable and function declaration names in the same TU: // void test() { extern void foo(); } // static void foo(); // This naming convention is the same as that followed by GCC, // though it shouldn't actually matter. if (ND && ND->getLinkage() == InternalLinkage && ND->getDeclContext()->isFileContext()) Out << 'L'; mangleSourceName(II); break; } // Otherwise, an anonymous entity. We must have a declaration. assert(ND && "mangling empty name without declaration"); if (const NamespaceDecl *NS = dyn_cast(ND)) { if (NS->isAnonymousNamespace()) { // This is how gcc mangles these names. Out << "12_GLOBAL__N_1"; break; } } if (const VarDecl *VD = dyn_cast(ND)) { // We must have an anonymous union or struct declaration. const RecordDecl *RD = cast(VD->getType()->getAs()->getDecl()); // Itanium C++ ABI 5.1.2: // // For the purposes of mangling, the name of an anonymous union is // considered to be the name of the first named data member found by a // pre-order, depth-first, declaration-order walk of the data members of // the anonymous union. If there is no such data member (i.e., if all of // the data members in the union are unnamed), then there is no way for // a program to refer to the anonymous union, and there is therefore no // need to mangle its name. const FieldDecl *FD = FindFirstNamedDataMember(RD); // It's actually possible for various reasons for us to get here // with an empty anonymous struct / union. Fortunately, it // doesn't really matter what name we generate. if (!FD) break; assert(FD->getIdentifier() && "Data member name isn't an identifier!"); mangleSourceName(FD->getIdentifier()); break; } // We must have an anonymous struct. const TagDecl *TD = cast(ND); if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { assert(TD->getDeclContext() == D->getDeclContext() && "Typedef should not be in another decl context!"); assert(D->getDeclName().getAsIdentifierInfo() && "Typedef was not named!"); mangleSourceName(D->getDeclName().getAsIdentifierInfo()); break; } // Get a unique id for the anonymous struct. uint64_t AnonStructId = Context.getAnonymousStructId(TD); // Mangle it as a source name in the form // [n] $_ // where n is the length of the string. llvm::SmallString<8> Str; Str += "$_"; Str += llvm::utostr(AnonStructId); Out << Str.size(); Out << Str.str(); break; } case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: assert(false && "Can't mangle Objective-C selector names here!"); break; case DeclarationName::CXXConstructorName: if (ND == Structor) // If the named decl is the C++ constructor we're mangling, use the type // we were given. mangleCXXCtorType(static_cast(StructorType)); else // Otherwise, use the complete constructor name. This is relevant if a // class with a constructor is declared within a constructor. mangleCXXCtorType(Ctor_Complete); break; case DeclarationName::CXXDestructorName: if (ND == Structor) // If the named decl is the C++ destructor we're mangling, use the type we // were given. mangleCXXDtorType(static_cast(StructorType)); else // Otherwise, use the complete destructor name. This is relevant if a // class with a destructor is declared within a destructor. mangleCXXDtorType(Dtor_Complete); break; case DeclarationName::CXXConversionFunctionName: // ::= cv # (cast) Out << "cv"; mangleType(Context.getASTContext().getCanonicalType(Name.getCXXNameType())); break; case DeclarationName::CXXOperatorName: { unsigned Arity; if (ND) { Arity = cast(ND)->getNumParams(); // If we have a C++ member function, we need to include the 'this' pointer. // FIXME: This does not make sense for operators that are static, but their // names stay the same regardless of the arity (operator new for instance). if (isa(ND)) Arity++; } else Arity = KnownArity; mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); break; } case DeclarationName::CXXLiteralOperatorName: // FIXME: This mangling is not yet official. Out << "li"; mangleSourceName(Name.getCXXLiteralIdentifier()); break; case DeclarationName::CXXUsingDirective: assert(false && "Can't mangle a using directive name!"); break; } } void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { // ::= // ::= [n] // ::= Out << II->getLength() << II->getName(); } void CXXNameMangler::mangleNestedName(const NamedDecl *ND, const DeclContext *DC, bool NoFunction) { // // ::= N [] [] E // ::= N [] [] // E Out << 'N'; if (const CXXMethodDecl *Method = dyn_cast(ND)) { mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers())); mangleRefQualifier(Method->getRefQualifier()); } // Check if we have a template. const TemplateArgumentList *TemplateArgs = 0; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleTemplatePrefix(TD); TemplateParameterList *TemplateParameters = TD->getTemplateParameters(); mangleTemplateArgs(*TemplateParameters, *TemplateArgs); } else { manglePrefix(DC, NoFunction); mangleUnqualifiedName(ND); } Out << 'E'; } void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { // ::= N [] E Out << 'N'; mangleTemplatePrefix(TD); TemplateParameterList *TemplateParameters = TD->getTemplateParameters(); mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs); Out << 'E'; } void CXXNameMangler::mangleLocalName(const NamedDecl *ND) { // := Z E [] // := Z E s [] // := _ const DeclContext *DC = ND->getDeclContext(); if (isa(DC) && isa(ND)) { // Don't add objc method name mangling to locally declared function mangleUnqualifiedName(ND); return; } Out << 'Z'; if (const ObjCMethodDecl *MD = dyn_cast(DC)) { mangleObjCMethodName(MD); } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) { mangleFunctionEncoding(cast(RD->getDeclContext())); Out << 'E'; // Mangle the name relative to the closest enclosing function. if (ND == RD) // equality ok because RD derived from ND above mangleUnqualifiedName(ND); else mangleNestedName(ND, DC, true /*NoFunction*/); unsigned disc; if (Context.getNextDiscriminator(RD, disc)) { if (disc < 10) Out << '_' << disc; else Out << "__" << disc << '_'; } return; } else mangleFunctionEncoding(cast(DC)); Out << 'E'; mangleUnqualifiedName(ND); } void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { switch (qualifier->getKind()) { case NestedNameSpecifier::Global: // nothing return; case NestedNameSpecifier::Namespace: mangleName(qualifier->getAsNamespace()); return; case NestedNameSpecifier::NamespaceAlias: mangleName(qualifier->getAsNamespaceAlias()->getNamespace()); return; case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: manglePrefix(QualType(qualifier->getAsType(), 0)); return; case NestedNameSpecifier::Identifier: // Member expressions can have these without prefixes, but that // should end up in mangleUnresolvedPrefix instead. assert(qualifier->getPrefix()); manglePrefix(qualifier->getPrefix()); mangleSourceName(qualifier->getAsIdentifier()); return; } llvm_unreachable("unexpected nested name specifier"); } void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { // ::= // ::= // ::= // ::= # empty // ::= while (isa(DC)) DC = DC->getParent(); if (DC->isTranslationUnit()) return; if (const BlockDecl *Block = dyn_cast(DC)) { manglePrefix(DC->getParent(), NoFunction); llvm::SmallString<64> Name; llvm::raw_svector_ostream NameStream(Name); Context.mangleBlock(Block, NameStream); NameStream.flush(); Out << Name.size() << Name; return; } if (mangleSubstitution(cast(DC))) return; // Check if we have a template. const TemplateArgumentList *TemplateArgs = 0; if (const TemplateDecl *TD = isTemplate(cast(DC), TemplateArgs)) { mangleTemplatePrefix(TD); TemplateParameterList *TemplateParameters = TD->getTemplateParameters(); mangleTemplateArgs(*TemplateParameters, *TemplateArgs); } else if(NoFunction && (isa(DC) || isa(DC))) return; else if (const ObjCMethodDecl *Method = dyn_cast(DC)) mangleObjCMethodName(Method); else { manglePrefix(DC->getParent(), NoFunction); mangleUnqualifiedName(cast(DC)); } addSubstitution(cast(DC)); } void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { // ::=