//===--- Mangle.cpp - Mangle C++ Names --------------------------*- 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 "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/Basic/SourceManager.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "CGVtable.h" using namespace clang; using namespace CodeGen; namespace { static const CXXMethodDecl *getStructor(const CXXMethodDecl *MD) { assert((isa(MD) || isa(MD)) && "Passed in decl is not a ctor or dtor!"); if (const TemplateDecl *TD = MD->getPrimaryTemplate()) { MD = cast(TD->getTemplatedDecl()); assert((isa(MD) || isa(MD)) && "Templated decl is not a ctor or dtor!"); } return MD; } /// CXXNameMangler - Manage the mangling of a single name. class CXXNameMangler { MangleContext &Context; llvm::raw_svector_ostream Out; const CXXMethodDecl *Structor; unsigned StructorType; llvm::DenseMap Substitutions; public: CXXNameMangler(MangleContext &C, llvm::SmallVectorImpl &Res) : Context(C), Out(Res), Structor(0), StructorType(0) { } CXXNameMangler(MangleContext &C, llvm::SmallVectorImpl &Res, const CXXConstructorDecl *D, CXXCtorType Type) : Context(C), Out(Res), Structor(getStructor(D)), StructorType(Type) { } CXXNameMangler(MangleContext &C, llvm::SmallVectorImpl &Res, const CXXDestructorDecl *D, CXXDtorType Type) : Context(C), Out(Res), Structor(getStructor(D)), StructorType(Type) { } llvm::raw_svector_ostream &getStream() { return Out; } void mangle(const NamedDecl *D, llvm::StringRef Prefix = "_Z"); void mangleCallOffset(const ThunkAdjustment &Adjustment); void mangleNumber(int64_t Number); void mangleFunctionEncoding(const FunctionDecl *FD); void mangleName(const NamedDecl *ND); void mangleType(QualType T); private: bool mangleSubstitution(const NamedDecl *ND); bool mangleSubstitution(QualType T); 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(uintptr_t Ptr); bool mangleFunctionDecl(const FunctionDecl *FD); void mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleUnqualifiedName(const NamedDecl *ND); void mangleUnscopedName(const NamedDecl *ND); void mangleUnscopedTemplateName(const TemplateDecl *ND); void mangleSourceName(const IdentifierInfo *II); void mangleLocalName(const NamedDecl *ND); void mangleNestedName(const NamedDecl *ND); void mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void manglePrefix(const DeclContext *DC); void mangleTemplatePrefix(const TemplateDecl *ND); void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); void mangleQualifiers(Qualifiers Quals); // 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 mangleBareFunctionType(const FunctionType *T, bool MangleReturnType); void mangleExpression(const Expr *E); void mangleCXXCtorType(CXXCtorType T); void mangleCXXDtorType(CXXDtorType T); void mangleTemplateArgs(const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs); void mangleTemplateArgumentList(const TemplateArgumentList &L); void mangleTemplateArgument(const TemplateArgument &A); void mangleTemplateParameter(unsigned Index); }; } 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 MangleContext::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; // No mangling in an "implicit extern C" header. if (D->getLocation().isValid() && getASTContext().getSourceManager(). isInExternCSystemHeader(D->getLocation())) return false; // C functions, "main", and variables at global scope are not // mangled. if ((FD && FD->isMain()) || (!FD && D->getDeclContext()->isTranslationUnit()) || 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. 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 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). FunctionType *FT = cast(Context.getASTContext() .getCanonicalType(FD->getType())); mangleBareFunctionType(FT, MangleReturnType); } static bool isStdNamespace(const NamespaceDecl *NS) { const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } static bool isStdNamespace(const DeclContext *DC) { return DC->isNamespace() && DC->getParent()->isTranslationUnit() && isStdNamespace(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(); 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); mangleTemplateArgumentList(*TemplateArgs); return; } mangleUnscopedName(ND); return; } if (isa(DC)) { mangleLocalName(ND); return; } mangleNestedName(ND); } void CXXNameMangler::mangleName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { const DeclContext *DC = TD->getDeclContext(); while (isa(DC)) { assert(cast(DC)->getLanguage() == LinkageSpecDecl::lang_cxx && "Unexpected linkage decl!"); DC = DC->getParent(); } if (DC->isTranslationUnit() || isStdNamespace(DC)) { mangleUnscopedTemplateName(TD); mangleTemplateArgs(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; mangleUnscopedName(ND->getTemplatedDecl()); addSubstitution(ND); } void CXXNameMangler::mangleNumber(int64_t Number) { // ::= [n] if (Number < 0) { Out << 'n'; Number = -Number; } Out << Number; } void CXXNameMangler::mangleCallOffset(const ThunkAdjustment &Adjustment) { // ::= h _ // ::= v _ // ::= # non-virtual base override // ::= _ // # virtual base override, with vcall offset if (!Adjustment.Virtual) { Out << 'h'; mangleNumber(Adjustment.NonVirtual); Out << '_'; return; } Out << 'v'; mangleNumber(Adjustment.NonVirtual); Out << '_'; mangleNumber(Adjustment.Virtual); Out << '_'; } void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND) { // ::= // ::= // ::= DeclarationName Name = ND->getDeclName(); switch (Name.getNameKind()) { case DeclarationName::Identifier: { if (const NamespaceDecl *NS = dyn_cast(ND)) { if (NS->isAnonymousNamespace()) { // This is how gcc mangles these names. It's apparently // always '1', no matter how many different anonymous // namespaces appear in a context. Out << "12_GLOBAL__N_1"; break; } } if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { mangleSourceName(II); break; } // We must have an anonymous struct. const TagDecl *TD = cast(ND); if (const TypedefDecl *D = TD->getTypedefForAnonDecl()) { 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: mangleOperatorName(Name.getCXXOverloadedOperator(), cast(ND)->getNumParams()); break; case DeclarationName::CXXLiteralOperatorName: // Guessing based on existing ABI. Out << "ul"; 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) { // ::= N [] E // ::= N [] E Out << 'N'; if (const CXXMethodDecl *Method = dyn_cast(ND)) mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers())); // Check if we have a template. const TemplateArgumentList *TemplateArgs = 0; if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { mangleTemplatePrefix(TD); mangleTemplateArgumentList(*TemplateArgs); } else { manglePrefix(ND->getDeclContext()); mangleUnqualifiedName(ND); } Out << 'E'; } void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs) { // ::= N [] E Out << 'N'; mangleTemplatePrefix(TD); mangleTemplateArgs(TemplateArgs, NumTemplateArgs); Out << 'E'; } void CXXNameMangler::mangleLocalName(const NamedDecl *ND) { // := Z E [] // := Z E s [] // := _ Out << 'Z'; mangleFunctionEncoding(cast(ND->getDeclContext())); Out << 'E'; mangleSourceName(ND->getIdentifier()); } void CXXNameMangler::manglePrefix(const DeclContext *DC) { // ::= // ::= // ::= // ::= # empty // ::= // FIXME: We only handle mangling of namespaces and classes at the moment. while (isa(DC)) DC = DC->getParent(); if (DC->isTranslationUnit()) 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); mangleTemplateArgumentList(*TemplateArgs); } else { manglePrefix(DC->getParent()); mangleUnqualifiedName(cast(DC)); } addSubstitution(cast(DC)); } void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) { // ::=