Home | History | Annotate | Download | only in AST
      1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     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):
     13 //
     14 //   http://www.codesourcery.com/public/cxx-abi/abi.html
     15 //
     16 //===----------------------------------------------------------------------===//
     17 #include "clang/AST/Mangle.h"
     18 #include "clang/AST/ASTContext.h"
     19 #include "clang/AST/Decl.h"
     20 #include "clang/AST/DeclCXX.h"
     21 #include "clang/AST/DeclObjC.h"
     22 #include "clang/AST/DeclTemplate.h"
     23 #include "clang/AST/ExprCXX.h"
     24 #include "clang/AST/ExprObjC.h"
     25 #include "clang/AST/TypeLoc.h"
     26 #include "clang/Basic/ABI.h"
     27 #include "clang/Basic/SourceManager.h"
     28 #include "clang/Basic/TargetInfo.h"
     29 #include "llvm/ADT/StringExtras.h"
     30 #include "llvm/Support/raw_ostream.h"
     31 #include "llvm/Support/ErrorHandling.h"
     32 
     33 #define MANGLE_CHECKER 0
     34 
     35 #if MANGLE_CHECKER
     36 #include <cxxabi.h>
     37 #endif
     38 
     39 using namespace clang;
     40 
     41 namespace {
     42 
     43 /// \brief Retrieve the declaration context that should be used when mangling
     44 /// the given declaration.
     45 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
     46   // The ABI assumes that lambda closure types that occur within
     47   // default arguments live in the context of the function. However, due to
     48   // the way in which Clang parses and creates function declarations, this is
     49   // not the case: the lambda closure type ends up living in the context
     50   // where the function itself resides, because the function declaration itself
     51   // had not yet been created. Fix the context here.
     52   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
     53     if (RD->isLambda())
     54       if (ParmVarDecl *ContextParam
     55             = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
     56         return ContextParam->getDeclContext();
     57   }
     58 
     59   return D->getDeclContext();
     60 }
     61 
     62 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
     63   return getEffectiveDeclContext(cast<Decl>(DC));
     64 }
     65 
     66 static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
     67   const DeclContext *DC = dyn_cast<DeclContext>(ND);
     68   if (!DC)
     69     DC = getEffectiveDeclContext(ND);
     70   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
     71     const DeclContext *Parent = getEffectiveDeclContext(cast<Decl>(DC));
     72     if (isa<FunctionDecl>(Parent))
     73       return dyn_cast<CXXRecordDecl>(DC);
     74     DC = Parent;
     75   }
     76   return 0;
     77 }
     78 
     79 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
     80   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
     81     return ftd->getTemplatedDecl();
     82 
     83   return fn;
     84 }
     85 
     86 static const NamedDecl *getStructor(const NamedDecl *decl) {
     87   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
     88   return (fn ? getStructor(fn) : decl);
     89 }
     90 
     91 static const unsigned UnknownArity = ~0U;
     92 
     93 class ItaniumMangleContext : public MangleContext {
     94   llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
     95   unsigned Discriminator;
     96   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
     97 
     98 public:
     99   explicit ItaniumMangleContext(ASTContext &Context,
    100                                 DiagnosticsEngine &Diags)
    101     : MangleContext(Context, Diags) { }
    102 
    103   uint64_t getAnonymousStructId(const TagDecl *TD) {
    104     std::pair<llvm::DenseMap<const TagDecl *,
    105       uint64_t>::iterator, bool> Result =
    106       AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
    107     return Result.first->second;
    108   }
    109 
    110   void startNewFunction() {
    111     MangleContext::startNewFunction();
    112     mangleInitDiscriminator();
    113   }
    114 
    115   /// @name Mangler Entry Points
    116   /// @{
    117 
    118   bool shouldMangleDeclName(const NamedDecl *D);
    119   void mangleName(const NamedDecl *D, raw_ostream &);
    120   void mangleThunk(const CXXMethodDecl *MD,
    121                    const ThunkInfo &Thunk,
    122                    raw_ostream &);
    123   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
    124                           const ThisAdjustment &ThisAdjustment,
    125                           raw_ostream &);
    126   void mangleReferenceTemporary(const VarDecl *D,
    127                                 raw_ostream &);
    128   void mangleCXXVTable(const CXXRecordDecl *RD,
    129                        raw_ostream &);
    130   void mangleCXXVTT(const CXXRecordDecl *RD,
    131                     raw_ostream &);
    132   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
    133                            const CXXRecordDecl *Type,
    134                            raw_ostream &);
    135   void mangleCXXRTTI(QualType T, raw_ostream &);
    136   void mangleCXXRTTIName(QualType T, raw_ostream &);
    137   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
    138                      raw_ostream &);
    139   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
    140                      raw_ostream &);
    141 
    142   void mangleItaniumGuardVariable(const VarDecl *D, raw_ostream &);
    143 
    144   void mangleInitDiscriminator() {
    145     Discriminator = 0;
    146   }
    147 
    148   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
    149     // Lambda closure types with external linkage (indicated by a
    150     // non-zero lambda mangling number) have their own numbering scheme, so
    151     // they do not need a discriminator.
    152     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND))
    153       if (RD->isLambda() && RD->getLambdaManglingNumber() > 0)
    154         return false;
    155 
    156     unsigned &discriminator = Uniquifier[ND];
    157     if (!discriminator)
    158       discriminator = ++Discriminator;
    159     if (discriminator == 1)
    160       return false;
    161     disc = discriminator-2;
    162     return true;
    163   }
    164   /// @}
    165 };
    166 
    167 /// CXXNameMangler - Manage the mangling of a single name.
    168 class CXXNameMangler {
    169   ItaniumMangleContext &Context;
    170   raw_ostream &Out;
    171 
    172   /// The "structor" is the top-level declaration being mangled, if
    173   /// that's not a template specialization; otherwise it's the pattern
    174   /// for that specialization.
    175   const NamedDecl *Structor;
    176   unsigned StructorType;
    177 
    178   /// SeqID - The next subsitution sequence number.
    179   unsigned SeqID;
    180 
    181   class FunctionTypeDepthState {
    182     unsigned Bits;
    183 
    184     enum { InResultTypeMask = 1 };
    185 
    186   public:
    187     FunctionTypeDepthState() : Bits(0) {}
    188 
    189     /// The number of function types we're inside.
    190     unsigned getDepth() const {
    191       return Bits >> 1;
    192     }
    193 
    194     /// True if we're in the return type of the innermost function type.
    195     bool isInResultType() const {
    196       return Bits & InResultTypeMask;
    197     }
    198 
    199     FunctionTypeDepthState push() {
    200       FunctionTypeDepthState tmp = *this;
    201       Bits = (Bits & ~InResultTypeMask) + 2;
    202       return tmp;
    203     }
    204 
    205     void enterResultType() {
    206       Bits |= InResultTypeMask;
    207     }
    208 
    209     void leaveResultType() {
    210       Bits &= ~InResultTypeMask;
    211     }
    212 
    213     void pop(FunctionTypeDepthState saved) {
    214       assert(getDepth() == saved.getDepth() + 1);
    215       Bits = saved.Bits;
    216     }
    217 
    218   } FunctionTypeDepth;
    219 
    220   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
    221 
    222   ASTContext &getASTContext() const { return Context.getASTContext(); }
    223 
    224 public:
    225   CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
    226                  const NamedDecl *D = 0)
    227     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
    228       SeqID(0) {
    229     // These can't be mangled without a ctor type or dtor type.
    230     assert(!D || (!isa<CXXDestructorDecl>(D) &&
    231                   !isa<CXXConstructorDecl>(D)));
    232   }
    233   CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
    234                  const CXXConstructorDecl *D, CXXCtorType Type)
    235     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    236       SeqID(0) { }
    237   CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
    238                  const CXXDestructorDecl *D, CXXDtorType Type)
    239     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    240       SeqID(0) { }
    241 
    242 #if MANGLE_CHECKER
    243   ~CXXNameMangler() {
    244     if (Out.str()[0] == '\01')
    245       return;
    246 
    247     int status = 0;
    248     char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
    249     assert(status == 0 && "Could not demangle mangled name!");
    250     free(result);
    251   }
    252 #endif
    253   raw_ostream &getStream() { return Out; }
    254 
    255   void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
    256   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
    257   void mangleNumber(const llvm::APSInt &I);
    258   void mangleNumber(int64_t Number);
    259   void mangleFloat(const llvm::APFloat &F);
    260   void mangleFunctionEncoding(const FunctionDecl *FD);
    261   void mangleName(const NamedDecl *ND);
    262   void mangleType(QualType T);
    263   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
    264 
    265 private:
    266   bool mangleSubstitution(const NamedDecl *ND);
    267   bool mangleSubstitution(QualType T);
    268   bool mangleSubstitution(TemplateName Template);
    269   bool mangleSubstitution(uintptr_t Ptr);
    270 
    271   void mangleExistingSubstitution(QualType type);
    272   void mangleExistingSubstitution(TemplateName name);
    273 
    274   bool mangleStandardSubstitution(const NamedDecl *ND);
    275 
    276   void addSubstitution(const NamedDecl *ND) {
    277     ND = cast<NamedDecl>(ND->getCanonicalDecl());
    278 
    279     addSubstitution(reinterpret_cast<uintptr_t>(ND));
    280   }
    281   void addSubstitution(QualType T);
    282   void addSubstitution(TemplateName Template);
    283   void addSubstitution(uintptr_t Ptr);
    284 
    285   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
    286                               NamedDecl *firstQualifierLookup,
    287                               bool recursive = false);
    288   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
    289                             NamedDecl *firstQualifierLookup,
    290                             DeclarationName name,
    291                             unsigned KnownArity = UnknownArity);
    292 
    293   void mangleName(const TemplateDecl *TD,
    294                   const TemplateArgument *TemplateArgs,
    295                   unsigned NumTemplateArgs);
    296   void mangleUnqualifiedName(const NamedDecl *ND) {
    297     mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
    298   }
    299   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
    300                              unsigned KnownArity);
    301   void mangleUnscopedName(const NamedDecl *ND);
    302   void mangleUnscopedTemplateName(const TemplateDecl *ND);
    303   void mangleUnscopedTemplateName(TemplateName);
    304   void mangleSourceName(const IdentifierInfo *II);
    305   void mangleLocalName(const NamedDecl *ND);
    306   void mangleLambda(const CXXRecordDecl *Lambda);
    307   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
    308                         bool NoFunction=false);
    309   void mangleNestedName(const TemplateDecl *TD,
    310                         const TemplateArgument *TemplateArgs,
    311                         unsigned NumTemplateArgs);
    312   void manglePrefix(NestedNameSpecifier *qualifier);
    313   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
    314   void manglePrefix(QualType type);
    315   void mangleTemplatePrefix(const TemplateDecl *ND);
    316   void mangleTemplatePrefix(TemplateName Template);
    317   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
    318   void mangleQualifiers(Qualifiers Quals);
    319   void mangleRefQualifier(RefQualifierKind RefQualifier);
    320 
    321   void mangleObjCMethodName(const ObjCMethodDecl *MD);
    322 
    323   // Declare manglers for every type class.
    324 #define ABSTRACT_TYPE(CLASS, PARENT)
    325 #define NON_CANONICAL_TYPE(CLASS, PARENT)
    326 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
    327 #include "clang/AST/TypeNodes.def"
    328 
    329   void mangleType(const TagType*);
    330   void mangleType(TemplateName);
    331   void mangleBareFunctionType(const FunctionType *T,
    332                               bool MangleReturnType);
    333   void mangleNeonVectorType(const VectorType *T);
    334 
    335   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
    336   void mangleMemberExpr(const Expr *base, bool isArrow,
    337                         NestedNameSpecifier *qualifier,
    338                         NamedDecl *firstQualifierLookup,
    339                         DeclarationName name,
    340                         unsigned knownArity);
    341   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
    342   void mangleCXXCtorType(CXXCtorType T);
    343   void mangleCXXDtorType(CXXDtorType T);
    344 
    345   void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
    346   void mangleTemplateArgs(TemplateName Template,
    347                           const TemplateArgument *TemplateArgs,
    348                           unsigned NumTemplateArgs);
    349   void mangleTemplateArgs(const TemplateParameterList &PL,
    350                           const TemplateArgument *TemplateArgs,
    351                           unsigned NumTemplateArgs);
    352   void mangleTemplateArgs(const TemplateParameterList &PL,
    353                           const TemplateArgumentList &AL);
    354   void mangleTemplateArg(const NamedDecl *P, TemplateArgument A);
    355   void mangleUnresolvedTemplateArgs(const TemplateArgument *args,
    356                                     unsigned numArgs);
    357 
    358   void mangleTemplateParameter(unsigned Index);
    359 
    360   void mangleFunctionParam(const ParmVarDecl *parm);
    361 };
    362 
    363 }
    364 
    365 static bool isInCLinkageSpecification(const Decl *D) {
    366   D = D->getCanonicalDecl();
    367   for (const DeclContext *DC = getEffectiveDeclContext(D);
    368        !DC->isTranslationUnit(); DC = getEffectiveParentContext(DC)) {
    369     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
    370       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
    371   }
    372 
    373   return false;
    374 }
    375 
    376 bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
    377   // In C, functions with no attributes never need to be mangled. Fastpath them.
    378   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
    379     return false;
    380 
    381   // Any decl can be declared with __asm("foo") on it, and this takes precedence
    382   // over all other naming in the .o file.
    383   if (D->hasAttr<AsmLabelAttr>())
    384     return true;
    385 
    386   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
    387   // (always) as does passing a C++ member function and a function
    388   // whose name is not a simple identifier.
    389   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
    390   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
    391              !FD->getDeclName().isIdentifier()))
    392     return true;
    393 
    394   // Otherwise, no mangling is done outside C++ mode.
    395   if (!getASTContext().getLangOpts().CPlusPlus)
    396     return false;
    397 
    398   // Variables at global scope with non-internal linkage are not mangled
    399   if (!FD) {
    400     const DeclContext *DC = getEffectiveDeclContext(D);
    401     // Check for extern variable declared locally.
    402     if (DC->isFunctionOrMethod() && D->hasLinkage())
    403       while (!DC->isNamespace() && !DC->isTranslationUnit())
    404         DC = getEffectiveParentContext(DC);
    405     if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage)
    406       return false;
    407   }
    408 
    409   // Class members are always mangled.
    410   if (getEffectiveDeclContext(D)->isRecord())
    411     return true;
    412 
    413   // C functions and "main" are not mangled.
    414   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
    415     return false;
    416 
    417   return true;
    418 }
    419 
    420 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
    421   // Any decl can be declared with __asm("foo") on it, and this takes precedence
    422   // over all other naming in the .o file.
    423   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
    424     // If we have an asm name, then we use it as the mangling.
    425 
    426     // Adding the prefix can cause problems when one file has a "foo" and
    427     // another has a "\01foo". That is known to happen on ELF with the
    428     // tricks normally used for producing aliases (PR9177). Fortunately the
    429     // llvm mangler on ELF is a nop, so we can just avoid adding the \01
    430     // marker.  We also avoid adding the marker if this is an alias for an
    431     // LLVM intrinsic.
    432     StringRef UserLabelPrefix =
    433       getASTContext().getTargetInfo().getUserLabelPrefix();
    434     if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
    435       Out << '\01';  // LLVM IR Marker for __asm("foo")
    436 
    437     Out << ALA->getLabel();
    438     return;
    439   }
    440 
    441   // <mangled-name> ::= _Z <encoding>
    442   //            ::= <data name>
    443   //            ::= <special-name>
    444   Out << Prefix;
    445   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
    446     mangleFunctionEncoding(FD);
    447   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
    448     mangleName(VD);
    449   else
    450     mangleName(cast<FieldDecl>(D));
    451 }
    452 
    453 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
    454   // <encoding> ::= <function name> <bare-function-type>
    455   mangleName(FD);
    456 
    457   // Don't mangle in the type if this isn't a decl we should typically mangle.
    458   if (!Context.shouldMangleDeclName(FD))
    459     return;
    460 
    461   // Whether the mangling of a function type includes the return type depends on
    462   // the context and the nature of the function. The rules for deciding whether
    463   // the return type is included are:
    464   //
    465   //   1. Template functions (names or types) have return types encoded, with
    466   //   the exceptions listed below.
    467   //   2. Function types not appearing as part of a function name mangling,
    468   //   e.g. parameters, pointer types, etc., have return type encoded, with the
    469   //   exceptions listed below.
    470   //   3. Non-template function names do not have return types encoded.
    471   //
    472   // The exceptions mentioned in (1) and (2) above, for which the return type is
    473   // never included, are
    474   //   1. Constructors.
    475   //   2. Destructors.
    476   //   3. Conversion operator functions, e.g. operator int.
    477   bool MangleReturnType = false;
    478   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
    479     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
    480           isa<CXXConversionDecl>(FD)))
    481       MangleReturnType = true;
    482 
    483     // Mangle the type of the primary template.
    484     FD = PrimaryTemplate->getTemplatedDecl();
    485   }
    486 
    487   mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
    488                          MangleReturnType);
    489 }
    490 
    491 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
    492   while (isa<LinkageSpecDecl>(DC)) {
    493     DC = getEffectiveParentContext(DC);
    494   }
    495 
    496   return DC;
    497 }
    498 
    499 /// isStd - Return whether a given namespace is the 'std' namespace.
    500 static bool isStd(const NamespaceDecl *NS) {
    501   if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
    502                                 ->isTranslationUnit())
    503     return false;
    504 
    505   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
    506   return II && II->isStr("std");
    507 }
    508 
    509 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
    510 // namespace.
    511 static bool isStdNamespace(const DeclContext *DC) {
    512   if (!DC->isNamespace())
    513     return false;
    514 
    515   return isStd(cast<NamespaceDecl>(DC));
    516 }
    517 
    518 static const TemplateDecl *
    519 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
    520   // Check if we have a function template.
    521   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
    522     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
    523       TemplateArgs = FD->getTemplateSpecializationArgs();
    524       return TD;
    525     }
    526   }
    527 
    528   // Check if we have a class template.
    529   if (const ClassTemplateSpecializationDecl *Spec =
    530         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
    531     TemplateArgs = &Spec->getTemplateArgs();
    532     return Spec->getSpecializedTemplate();
    533   }
    534 
    535   return 0;
    536 }
    537 
    538 static bool isLambda(const NamedDecl *ND) {
    539   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
    540   if (!Record)
    541     return false;
    542 
    543   return Record->isLambda();
    544 }
    545 
    546 void CXXNameMangler::mangleName(const NamedDecl *ND) {
    547   //  <name> ::= <nested-name>
    548   //         ::= <unscoped-name>
    549   //         ::= <unscoped-template-name> <template-args>
    550   //         ::= <local-name>
    551   //
    552   const DeclContext *DC = getEffectiveDeclContext(ND);
    553 
    554   // If this is an extern variable declared locally, the relevant DeclContext
    555   // is that of the containing namespace, or the translation unit.
    556   // FIXME: This is a hack; extern variables declared locally should have
    557   // a proper semantic declaration context!
    558   if (isa<FunctionDecl>(DC) && ND->hasLinkage() && !isLambda(ND))
    559     while (!DC->isNamespace() && !DC->isTranslationUnit())
    560       DC = getEffectiveParentContext(DC);
    561   else if (GetLocalClassDecl(ND)) {
    562     mangleLocalName(ND);
    563     return;
    564   }
    565 
    566   DC = IgnoreLinkageSpecDecls(DC);
    567 
    568   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
    569     // Check if we have a template.
    570     const TemplateArgumentList *TemplateArgs = 0;
    571     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
    572       mangleUnscopedTemplateName(TD);
    573       TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
    574       mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
    575       return;
    576     }
    577 
    578     mangleUnscopedName(ND);
    579     return;
    580   }
    581 
    582   if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) {
    583     mangleLocalName(ND);
    584     return;
    585   }
    586 
    587   mangleNestedName(ND, DC);
    588 }
    589 void CXXNameMangler::mangleName(const TemplateDecl *TD,
    590                                 const TemplateArgument *TemplateArgs,
    591                                 unsigned NumTemplateArgs) {
    592   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
    593 
    594   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
    595     mangleUnscopedTemplateName(TD);
    596     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
    597     mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
    598   } else {
    599     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
    600   }
    601 }
    602 
    603 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
    604   //  <unscoped-name> ::= <unqualified-name>
    605   //                  ::= St <unqualified-name>   # ::std::
    606 
    607   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
    608     Out << "St";
    609 
    610   mangleUnqualifiedName(ND);
    611 }
    612 
    613 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
    614   //     <unscoped-template-name> ::= <unscoped-name>
    615   //                              ::= <substitution>
    616   if (mangleSubstitution(ND))
    617     return;
    618 
    619   // <template-template-param> ::= <template-param>
    620   if (const TemplateTemplateParmDecl *TTP
    621                                      = dyn_cast<TemplateTemplateParmDecl>(ND)) {
    622     mangleTemplateParameter(TTP->getIndex());
    623     return;
    624   }
    625 
    626   mangleUnscopedName(ND->getTemplatedDecl());
    627   addSubstitution(ND);
    628 }
    629 
    630 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
    631   //     <unscoped-template-name> ::= <unscoped-name>
    632   //                              ::= <substitution>
    633   if (TemplateDecl *TD = Template.getAsTemplateDecl())
    634     return mangleUnscopedTemplateName(TD);
    635 
    636   if (mangleSubstitution(Template))
    637     return;
    638 
    639   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
    640   assert(Dependent && "Not a dependent template name?");
    641   if (const IdentifierInfo *Id = Dependent->getIdentifier())
    642     mangleSourceName(Id);
    643   else
    644     mangleOperatorName(Dependent->getOperator(), UnknownArity);
    645 
    646   addSubstitution(Template);
    647 }
    648 
    649 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
    650   // ABI:
    651   //   Floating-point literals are encoded using a fixed-length
    652   //   lowercase hexadecimal string corresponding to the internal
    653   //   representation (IEEE on Itanium), high-order bytes first,
    654   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
    655   //   on Itanium.
    656   // The 'without leading zeroes' thing seems to be an editorial
    657   // mistake; see the discussion on cxx-abi-dev beginning on
    658   // 2012-01-16.
    659 
    660   // Our requirements here are just barely wierd enough to justify
    661   // using a custom algorithm instead of post-processing APInt::toString().
    662 
    663   llvm::APInt valueBits = f.bitcastToAPInt();
    664   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
    665   assert(numCharacters != 0);
    666 
    667   // Allocate a buffer of the right number of characters.
    668   llvm::SmallVector<char, 20> buffer;
    669   buffer.set_size(numCharacters);
    670 
    671   // Fill the buffer left-to-right.
    672   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
    673     // The bit-index of the next hex digit.
    674     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
    675 
    676     // Project out 4 bits starting at 'digitIndex'.
    677     llvm::integerPart hexDigit
    678       = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
    679     hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
    680     hexDigit &= 0xF;
    681 
    682     // Map that over to a lowercase hex digit.
    683     static const char charForHex[16] = {
    684       '0', '1', '2', '3', '4', '5', '6', '7',
    685       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    686     };
    687     buffer[stringIndex] = charForHex[hexDigit];
    688   }
    689 
    690   Out.write(buffer.data(), numCharacters);
    691 }
    692 
    693 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
    694   if (Value.isSigned() && Value.isNegative()) {
    695     Out << 'n';
    696     Value.abs().print(Out, true);
    697   } else
    698     Value.print(Out, Value.isSigned());
    699 }
    700 
    701 void CXXNameMangler::mangleNumber(int64_t Number) {
    702   //  <number> ::= [n] <non-negative decimal integer>
    703   if (Number < 0) {
    704     Out << 'n';
    705     Number = -Number;
    706   }
    707 
    708   Out << Number;
    709 }
    710 
    711 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
    712   //  <call-offset>  ::= h <nv-offset> _
    713   //                 ::= v <v-offset> _
    714   //  <nv-offset>    ::= <offset number>        # non-virtual base override
    715   //  <v-offset>     ::= <offset number> _ <virtual offset number>
    716   //                      # virtual base override, with vcall offset
    717   if (!Virtual) {
    718     Out << 'h';
    719     mangleNumber(NonVirtual);
    720     Out << '_';
    721     return;
    722   }
    723 
    724   Out << 'v';
    725   mangleNumber(NonVirtual);
    726   Out << '_';
    727   mangleNumber(Virtual);
    728   Out << '_';
    729 }
    730 
    731 void CXXNameMangler::manglePrefix(QualType type) {
    732   if (const TemplateSpecializationType *TST =
    733         type->getAs<TemplateSpecializationType>()) {
    734     if (!mangleSubstitution(QualType(TST, 0))) {
    735       mangleTemplatePrefix(TST->getTemplateName());
    736 
    737       // FIXME: GCC does not appear to mangle the template arguments when
    738       // the template in question is a dependent template name. Should we
    739       // emulate that badness?
    740       mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
    741                          TST->getNumArgs());
    742       addSubstitution(QualType(TST, 0));
    743     }
    744   } else if (const DependentTemplateSpecializationType *DTST
    745                = type->getAs<DependentTemplateSpecializationType>()) {
    746     TemplateName Template
    747       = getASTContext().getDependentTemplateName(DTST->getQualifier(),
    748                                                  DTST->getIdentifier());
    749     mangleTemplatePrefix(Template);
    750 
    751     // FIXME: GCC does not appear to mangle the template arguments when
    752     // the template in question is a dependent template name. Should we
    753     // emulate that badness?
    754     mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
    755   } else {
    756     // We use the QualType mangle type variant here because it handles
    757     // substitutions.
    758     mangleType(type);
    759   }
    760 }
    761 
    762 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
    763 ///
    764 /// \param firstQualifierLookup - the entity found by unqualified lookup
    765 ///   for the first name in the qualifier, if this is for a member expression
    766 /// \param recursive - true if this is being called recursively,
    767 ///   i.e. if there is more prefix "to the right".
    768 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
    769                                             NamedDecl *firstQualifierLookup,
    770                                             bool recursive) {
    771 
    772   // x, ::x
    773   // <unresolved-name> ::= [gs] <base-unresolved-name>
    774 
    775   // T::x / decltype(p)::x
    776   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
    777 
    778   // T::N::x /decltype(p)::N::x
    779   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
    780   //                       <base-unresolved-name>
    781 
    782   // A::x, N::y, A<T>::z; "gs" means leading "::"
    783   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
    784   //                       <base-unresolved-name>
    785 
    786   switch (qualifier->getKind()) {
    787   case NestedNameSpecifier::Global:
    788     Out << "gs";
    789 
    790     // We want an 'sr' unless this is the entire NNS.
    791     if (recursive)
    792       Out << "sr";
    793 
    794     // We never want an 'E' here.
    795     return;
    796 
    797   case NestedNameSpecifier::Namespace:
    798     if (qualifier->getPrefix())
    799       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
    800                              /*recursive*/ true);
    801     else
    802       Out << "sr";
    803     mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
    804     break;
    805   case NestedNameSpecifier::NamespaceAlias:
    806     if (qualifier->getPrefix())
    807       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
    808                              /*recursive*/ true);
    809     else
    810       Out << "sr";
    811     mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
    812     break;
    813 
    814   case NestedNameSpecifier::TypeSpec:
    815   case NestedNameSpecifier::TypeSpecWithTemplate: {
    816     const Type *type = qualifier->getAsType();
    817 
    818     // We only want to use an unresolved-type encoding if this is one of:
    819     //   - a decltype
    820     //   - a template type parameter
    821     //   - a template template parameter with arguments
    822     // In all of these cases, we should have no prefix.
    823     if (qualifier->getPrefix()) {
    824       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
    825                              /*recursive*/ true);
    826     } else {
    827       // Otherwise, all the cases want this.
    828       Out << "sr";
    829     }
    830 
    831     // Only certain other types are valid as prefixes;  enumerate them.
    832     switch (type->getTypeClass()) {
    833     case Type::Builtin:
    834     case Type::Complex:
    835     case Type::Pointer:
    836     case Type::BlockPointer:
    837     case Type::LValueReference:
    838     case Type::RValueReference:
    839     case Type::MemberPointer:
    840     case Type::ConstantArray:
    841     case Type::IncompleteArray:
    842     case Type::VariableArray:
    843     case Type::DependentSizedArray:
    844     case Type::DependentSizedExtVector:
    845     case Type::Vector:
    846     case Type::ExtVector:
    847     case Type::FunctionProto:
    848     case Type::FunctionNoProto:
    849     case Type::Enum:
    850     case Type::Paren:
    851     case Type::Elaborated:
    852     case Type::Attributed:
    853     case Type::Auto:
    854     case Type::PackExpansion:
    855     case Type::ObjCObject:
    856     case Type::ObjCInterface:
    857     case Type::ObjCObjectPointer:
    858     case Type::Atomic:
    859       llvm_unreachable("type is illegal as a nested name specifier");
    860 
    861     case Type::SubstTemplateTypeParmPack:
    862       // FIXME: not clear how to mangle this!
    863       // template <class T...> class A {
    864       //   template <class U...> void foo(decltype(T::foo(U())) x...);
    865       // };
    866       Out << "_SUBSTPACK_";
    867       break;
    868 
    869     // <unresolved-type> ::= <template-param>
    870     //                   ::= <decltype>
    871     //                   ::= <template-template-param> <template-args>
    872     // (this last is not official yet)
    873     case Type::TypeOfExpr:
    874     case Type::TypeOf:
    875     case Type::Decltype:
    876     case Type::TemplateTypeParm:
    877     case Type::UnaryTransform:
    878     case Type::SubstTemplateTypeParm:
    879     unresolvedType:
    880       assert(!qualifier->getPrefix());
    881 
    882       // We only get here recursively if we're followed by identifiers.
    883       if (recursive) Out << 'N';
    884 
    885       // This seems to do everything we want.  It's not really
    886       // sanctioned for a substituted template parameter, though.
    887       mangleType(QualType(type, 0));
    888 
    889       // We never want to print 'E' directly after an unresolved-type,
    890       // so we return directly.
    891       return;
    892 
    893     case Type::Typedef:
    894       mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
    895       break;
    896 
    897     case Type::UnresolvedUsing:
    898       mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
    899                          ->getIdentifier());
    900       break;
    901 
    902     case Type::Record:
    903       mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
    904       break;
    905 
    906     case Type::TemplateSpecialization: {
    907       const TemplateSpecializationType *tst
    908         = cast<TemplateSpecializationType>(type);
    909       TemplateName name = tst->getTemplateName();
    910       switch (name.getKind()) {
    911       case TemplateName::Template:
    912       case TemplateName::QualifiedTemplate: {
    913         TemplateDecl *temp = name.getAsTemplateDecl();
    914 
    915         // If the base is a template template parameter, this is an
    916         // unresolved type.
    917         assert(temp && "no template for template specialization type");
    918         if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
    919 
    920         mangleSourceName(temp->getIdentifier());
    921         break;
    922       }
    923 
    924       case TemplateName::OverloadedTemplate:
    925       case TemplateName::DependentTemplate:
    926         llvm_unreachable("invalid base for a template specialization type");
    927 
    928       case TemplateName::SubstTemplateTemplateParm: {
    929         SubstTemplateTemplateParmStorage *subst
    930           = name.getAsSubstTemplateTemplateParm();
    931         mangleExistingSubstitution(subst->getReplacement());
    932         break;
    933       }
    934 
    935       case TemplateName::SubstTemplateTemplateParmPack: {
    936         // FIXME: not clear how to mangle this!
    937         // template <template <class U> class T...> class A {
    938         //   template <class U...> void foo(decltype(T<U>::foo) x...);
    939         // };
    940         Out << "_SUBSTPACK_";
    941         break;
    942       }
    943       }
    944 
    945       mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs());
    946       break;
    947     }
    948 
    949     case Type::InjectedClassName:
    950       mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
    951                          ->getIdentifier());
    952       break;
    953 
    954     case Type::DependentName:
    955       mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
    956       break;
    957 
    958     case Type::DependentTemplateSpecialization: {
    959       const DependentTemplateSpecializationType *tst
    960         = cast<DependentTemplateSpecializationType>(type);
    961       mangleSourceName(tst->getIdentifier());
    962       mangleUnresolvedTemplateArgs(tst->getArgs(), tst->getNumArgs());
    963       break;
    964     }
    965     }
    966     break;
    967   }
    968 
    969   case NestedNameSpecifier::Identifier:
    970     // Member expressions can have these without prefixes.
    971     if (qualifier->getPrefix()) {
    972       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
    973                              /*recursive*/ true);
    974     } else if (firstQualifierLookup) {
    975 
    976       // Try to make a proper qualifier out of the lookup result, and
    977       // then just recurse on that.
    978       NestedNameSpecifier *newQualifier;
    979       if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
    980         QualType type = getASTContext().getTypeDeclType(typeDecl);
    981 
    982         // Pretend we had a different nested name specifier.
    983         newQualifier = NestedNameSpecifier::Create(getASTContext(),
    984                                                    /*prefix*/ 0,
    985                                                    /*template*/ false,
    986                                                    type.getTypePtr());
    987       } else if (NamespaceDecl *nspace =
    988                    dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
    989         newQualifier = NestedNameSpecifier::Create(getASTContext(),
    990                                                    /*prefix*/ 0,
    991                                                    nspace);
    992       } else if (NamespaceAliasDecl *alias =
    993                    dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
    994         newQualifier = NestedNameSpecifier::Create(getASTContext(),
    995                                                    /*prefix*/ 0,
    996                                                    alias);
    997       } else {
    998         // No sensible mangling to do here.
    999         newQualifier = 0;
   1000       }
   1001 
   1002       if (newQualifier)
   1003         return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
   1004 
   1005     } else {
   1006       Out << "sr";
   1007     }
   1008 
   1009     mangleSourceName(qualifier->getAsIdentifier());
   1010     break;
   1011   }
   1012 
   1013   // If this was the innermost part of the NNS, and we fell out to
   1014   // here, append an 'E'.
   1015   if (!recursive)
   1016     Out << 'E';
   1017 }
   1018 
   1019 /// Mangle an unresolved-name, which is generally used for names which
   1020 /// weren't resolved to specific entities.
   1021 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
   1022                                           NamedDecl *firstQualifierLookup,
   1023                                           DeclarationName name,
   1024                                           unsigned knownArity) {
   1025   if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
   1026   mangleUnqualifiedName(0, name, knownArity);
   1027 }
   1028 
   1029 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
   1030   assert(RD->isAnonymousStructOrUnion() &&
   1031          "Expected anonymous struct or union!");
   1032 
   1033   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
   1034        I != E; ++I) {
   1035     const FieldDecl *FD = *I;
   1036 
   1037     if (FD->getIdentifier())
   1038       return FD;
   1039 
   1040     if (const RecordType *RT = FD->getType()->getAs<RecordType>()) {
   1041       if (const FieldDecl *NamedDataMember =
   1042           FindFirstNamedDataMember(RT->getDecl()))
   1043         return NamedDataMember;
   1044     }
   1045   }
   1046 
   1047   // We didn't find a named data member.
   1048   return 0;
   1049 }
   1050 
   1051 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
   1052                                            DeclarationName Name,
   1053                                            unsigned KnownArity) {
   1054   //  <unqualified-name> ::= <operator-name>
   1055   //                     ::= <ctor-dtor-name>
   1056   //                     ::= <source-name>
   1057   switch (Name.getNameKind()) {
   1058   case DeclarationName::Identifier: {
   1059     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
   1060       // We must avoid conflicts between internally- and externally-
   1061       // linked variable and function declaration names in the same TU:
   1062       //   void test() { extern void foo(); }
   1063       //   static void foo();
   1064       // This naming convention is the same as that followed by GCC,
   1065       // though it shouldn't actually matter.
   1066       if (ND && ND->getLinkage() == InternalLinkage &&
   1067           getEffectiveDeclContext(ND)->isFileContext())
   1068         Out << 'L';
   1069 
   1070       mangleSourceName(II);
   1071       break;
   1072     }
   1073 
   1074     // Otherwise, an anonymous entity.  We must have a declaration.
   1075     assert(ND && "mangling empty name without declaration");
   1076 
   1077     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
   1078       if (NS->isAnonymousNamespace()) {
   1079         // This is how gcc mangles these names.
   1080         Out << "12_GLOBAL__N_1";
   1081         break;
   1082       }
   1083     }
   1084 
   1085     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
   1086       // We must have an anonymous union or struct declaration.
   1087       const RecordDecl *RD =
   1088         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
   1089 
   1090       // Itanium C++ ABI 5.1.2:
   1091       //
   1092       //   For the purposes of mangling, the name of an anonymous union is
   1093       //   considered to be the name of the first named data member found by a
   1094       //   pre-order, depth-first, declaration-order walk of the data members of
   1095       //   the anonymous union. If there is no such data member (i.e., if all of
   1096       //   the data members in the union are unnamed), then there is no way for
   1097       //   a program to refer to the anonymous union, and there is therefore no
   1098       //   need to mangle its name.
   1099       const FieldDecl *FD = FindFirstNamedDataMember(RD);
   1100 
   1101       // It's actually possible for various reasons for us to get here
   1102       // with an empty anonymous struct / union.  Fortunately, it
   1103       // doesn't really matter what name we generate.
   1104       if (!FD) break;
   1105       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
   1106 
   1107       mangleSourceName(FD->getIdentifier());
   1108       break;
   1109     }
   1110 
   1111     // We must have an anonymous struct.
   1112     const TagDecl *TD = cast<TagDecl>(ND);
   1113     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
   1114       assert(TD->getDeclContext() == D->getDeclContext() &&
   1115              "Typedef should not be in another decl context!");
   1116       assert(D->getDeclName().getAsIdentifierInfo() &&
   1117              "Typedef was not named!");
   1118       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
   1119       break;
   1120     }
   1121 
   1122     // <unnamed-type-name> ::= <closure-type-name>
   1123     //
   1124     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
   1125     // <lambda-sig> ::= <parameter-type>+   # Parameter types or 'v' for 'void'.
   1126     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
   1127       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
   1128         mangleLambda(Record);
   1129         break;
   1130       }
   1131     }
   1132 
   1133     // Get a unique id for the anonymous struct.
   1134     uint64_t AnonStructId = Context.getAnonymousStructId(TD);
   1135 
   1136     // Mangle it as a source name in the form
   1137     // [n] $_<id>
   1138     // where n is the length of the string.
   1139     SmallString<8> Str;
   1140     Str += "$_";
   1141     Str += llvm::utostr(AnonStructId);
   1142 
   1143     Out << Str.size();
   1144     Out << Str.str();
   1145     break;
   1146   }
   1147 
   1148   case DeclarationName::ObjCZeroArgSelector:
   1149   case DeclarationName::ObjCOneArgSelector:
   1150   case DeclarationName::ObjCMultiArgSelector:
   1151     llvm_unreachable("Can't mangle Objective-C selector names here!");
   1152 
   1153   case DeclarationName::CXXConstructorName:
   1154     if (ND == Structor)
   1155       // If the named decl is the C++ constructor we're mangling, use the type
   1156       // we were given.
   1157       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
   1158     else
   1159       // Otherwise, use the complete constructor name. This is relevant if a
   1160       // class with a constructor is declared within a constructor.
   1161       mangleCXXCtorType(Ctor_Complete);
   1162     break;
   1163 
   1164   case DeclarationName::CXXDestructorName:
   1165     if (ND == Structor)
   1166       // If the named decl is the C++ destructor we're mangling, use the type we
   1167       // were given.
   1168       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
   1169     else
   1170       // Otherwise, use the complete destructor name. This is relevant if a
   1171       // class with a destructor is declared within a destructor.
   1172       mangleCXXDtorType(Dtor_Complete);
   1173     break;
   1174 
   1175   case DeclarationName::CXXConversionFunctionName:
   1176     // <operator-name> ::= cv <type>    # (cast)
   1177     Out << "cv";
   1178     mangleType(Name.getCXXNameType());
   1179     break;
   1180 
   1181   case DeclarationName::CXXOperatorName: {
   1182     unsigned Arity;
   1183     if (ND) {
   1184       Arity = cast<FunctionDecl>(ND)->getNumParams();
   1185 
   1186       // If we have a C++ member function, we need to include the 'this' pointer.
   1187       // FIXME: This does not make sense for operators that are static, but their
   1188       // names stay the same regardless of the arity (operator new for instance).
   1189       if (isa<CXXMethodDecl>(ND))
   1190         Arity++;
   1191     } else
   1192       Arity = KnownArity;
   1193 
   1194     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
   1195     break;
   1196   }
   1197 
   1198   case DeclarationName::CXXLiteralOperatorName:
   1199     // FIXME: This mangling is not yet official.
   1200     Out << "li";
   1201     mangleSourceName(Name.getCXXLiteralIdentifier());
   1202     break;
   1203 
   1204   case DeclarationName::CXXUsingDirective:
   1205     llvm_unreachable("Can't mangle a using directive name!");
   1206   }
   1207 }
   1208 
   1209 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
   1210   // <source-name> ::= <positive length number> <identifier>
   1211   // <number> ::= [n] <non-negative decimal integer>
   1212   // <identifier> ::= <unqualified source code identifier>
   1213   Out << II->getLength() << II->getName();
   1214 }
   1215 
   1216 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
   1217                                       const DeclContext *DC,
   1218                                       bool NoFunction) {
   1219   // <nested-name>
   1220   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
   1221   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
   1222   //       <template-args> E
   1223 
   1224   Out << 'N';
   1225   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
   1226     mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
   1227     mangleRefQualifier(Method->getRefQualifier());
   1228   }
   1229 
   1230   // Check if we have a template.
   1231   const TemplateArgumentList *TemplateArgs = 0;
   1232   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
   1233     mangleTemplatePrefix(TD);
   1234     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
   1235     mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
   1236   }
   1237   else {
   1238     manglePrefix(DC, NoFunction);
   1239     mangleUnqualifiedName(ND);
   1240   }
   1241 
   1242   Out << 'E';
   1243 }
   1244 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
   1245                                       const TemplateArgument *TemplateArgs,
   1246                                       unsigned NumTemplateArgs) {
   1247   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
   1248 
   1249   Out << 'N';
   1250 
   1251   mangleTemplatePrefix(TD);
   1252   TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
   1253   mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
   1254 
   1255   Out << 'E';
   1256 }
   1257 
   1258 void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
   1259   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
   1260   //              := Z <function encoding> E s [<discriminator>]
   1261   // <local-name> := Z <function encoding> E d [ <parameter number> ]
   1262   //                 _ <entity name>
   1263   // <discriminator> := _ <non-negative number>
   1264   const DeclContext *DC = getEffectiveDeclContext(ND);
   1265   if (isa<ObjCMethodDecl>(DC) && isa<FunctionDecl>(ND)) {
   1266     // Don't add objc method name mangling to locally declared function
   1267     mangleUnqualifiedName(ND);
   1268     return;
   1269   }
   1270 
   1271   Out << 'Z';
   1272 
   1273   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) {
   1274    mangleObjCMethodName(MD);
   1275   } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) {
   1276     mangleFunctionEncoding(cast<FunctionDecl>(getEffectiveDeclContext(RD)));
   1277     Out << 'E';
   1278 
   1279     // The parameter number is omitted for the last parameter, 0 for the
   1280     // second-to-last parameter, 1 for the third-to-last parameter, etc. The
   1281     // <entity name> will of course contain a <closure-type-name>: Its
   1282     // numbering will be local to the particular argument in which it appears
   1283     // -- other default arguments do not affect its encoding.
   1284     bool SkipDiscriminator = false;
   1285     if (RD->isLambda()) {
   1286       if (const ParmVarDecl *Parm
   1287                  = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) {
   1288         if (const FunctionDecl *Func
   1289               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
   1290           Out << 'd';
   1291           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
   1292           if (Num > 1)
   1293             mangleNumber(Num - 2);
   1294           Out << '_';
   1295           SkipDiscriminator = true;
   1296         }
   1297       }
   1298     }
   1299 
   1300     // Mangle the name relative to the closest enclosing function.
   1301     if (ND == RD) // equality ok because RD derived from ND above
   1302       mangleUnqualifiedName(ND);
   1303     else
   1304       mangleNestedName(ND, DC, true /*NoFunction*/);
   1305 
   1306     if (!SkipDiscriminator) {
   1307       unsigned disc;
   1308       if (Context.getNextDiscriminator(RD, disc)) {
   1309         if (disc < 10)
   1310           Out << '_' << disc;
   1311         else
   1312           Out << "__" << disc << '_';
   1313       }
   1314     }
   1315 
   1316     return;
   1317   }
   1318   else
   1319     mangleFunctionEncoding(cast<FunctionDecl>(DC));
   1320 
   1321   Out << 'E';
   1322   mangleUnqualifiedName(ND);
   1323 }
   1324 
   1325 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
   1326   // If the context of a closure type is an initializer for a class member
   1327   // (static or nonstatic), it is encoded in a qualified name with a final
   1328   // <prefix> of the form:
   1329   //
   1330   //   <data-member-prefix> := <member source-name> M
   1331   //
   1332   // Technically, the data-member-prefix is part of the <prefix>. However,
   1333   // since a closure type will always be mangled with a prefix, it's easier
   1334   // to emit that last part of the prefix here.
   1335   if (Decl *Context = Lambda->getLambdaContextDecl()) {
   1336     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
   1337         Context->getDeclContext()->isRecord()) {
   1338       if (const IdentifierInfo *Name
   1339             = cast<NamedDecl>(Context)->getIdentifier()) {
   1340         mangleSourceName(Name);
   1341         Out << 'M';
   1342       }
   1343     }
   1344   }
   1345 
   1346   Out << "Ul";
   1347   DeclarationName Name
   1348     = getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
   1349   const FunctionProtoType *Proto
   1350     = cast<CXXMethodDecl>(*Lambda->lookup(Name).first)->getType()->
   1351         getAs<FunctionProtoType>();
   1352   mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
   1353   Out << "E";
   1354 
   1355   // The number is omitted for the first closure type with a given
   1356   // <lambda-sig> in a given context; it is n-2 for the nth closure type
   1357   // (in lexical order) with that same <lambda-sig> and context.
   1358   //
   1359   // The AST keeps track of the number for us.
   1360   unsigned Number = Lambda->getLambdaManglingNumber();
   1361   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
   1362   if (Number > 1)
   1363     mangleNumber(Number - 2);
   1364   Out << '_';
   1365 }
   1366 
   1367 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
   1368   switch (qualifier->getKind()) {
   1369   case NestedNameSpecifier::Global:
   1370     // nothing
   1371     return;
   1372 
   1373   case NestedNameSpecifier::Namespace:
   1374     mangleName(qualifier->getAsNamespace());
   1375     return;
   1376 
   1377   case NestedNameSpecifier::NamespaceAlias:
   1378     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
   1379     return;
   1380 
   1381   case NestedNameSpecifier::TypeSpec:
   1382   case NestedNameSpecifier::TypeSpecWithTemplate:
   1383     manglePrefix(QualType(qualifier->getAsType(), 0));
   1384     return;
   1385 
   1386   case NestedNameSpecifier::Identifier:
   1387     // Member expressions can have these without prefixes, but that
   1388     // should end up in mangleUnresolvedPrefix instead.
   1389     assert(qualifier->getPrefix());
   1390     manglePrefix(qualifier->getPrefix());
   1391 
   1392     mangleSourceName(qualifier->getAsIdentifier());
   1393     return;
   1394   }
   1395 
   1396   llvm_unreachable("unexpected nested name specifier");
   1397 }
   1398 
   1399 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
   1400   //  <prefix> ::= <prefix> <unqualified-name>
   1401   //           ::= <template-prefix> <template-args>
   1402   //           ::= <template-param>
   1403   //           ::= # empty
   1404   //           ::= <substitution>
   1405 
   1406   DC = IgnoreLinkageSpecDecls(DC);
   1407 
   1408   if (DC->isTranslationUnit())
   1409     return;
   1410 
   1411   if (const BlockDecl *Block = dyn_cast<BlockDecl>(DC)) {
   1412     manglePrefix(getEffectiveParentContext(DC), NoFunction);
   1413     SmallString<64> Name;
   1414     llvm::raw_svector_ostream NameStream(Name);
   1415     Context.mangleBlock(Block, NameStream);
   1416     NameStream.flush();
   1417     Out << Name.size() << Name;
   1418     return;
   1419   }
   1420 
   1421   const NamedDecl *ND = cast<NamedDecl>(DC);
   1422   if (mangleSubstitution(ND))
   1423     return;
   1424 
   1425   // Check if we have a template.
   1426   const TemplateArgumentList *TemplateArgs = 0;
   1427   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
   1428     mangleTemplatePrefix(TD);
   1429     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
   1430     mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
   1431   }
   1432   else if(NoFunction && (isa<FunctionDecl>(ND) || isa<ObjCMethodDecl>(ND)))
   1433     return;
   1434   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
   1435     mangleObjCMethodName(Method);
   1436   else {
   1437     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
   1438     mangleUnqualifiedName(ND);
   1439   }
   1440 
   1441   addSubstitution(ND);
   1442 }
   1443 
   1444 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
   1445   // <template-prefix> ::= <prefix> <template unqualified-name>
   1446   //                   ::= <template-param>
   1447   //                   ::= <substitution>
   1448   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   1449     return mangleTemplatePrefix(TD);
   1450 
   1451   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
   1452     manglePrefix(Qualified->getQualifier());
   1453 
   1454   if (OverloadedTemplateStorage *Overloaded
   1455                                       = Template.getAsOverloadedTemplate()) {
   1456     mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
   1457                           UnknownArity);
   1458     return;
   1459   }
   1460 
   1461   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
   1462   assert(Dependent && "Unknown template name kind?");
   1463   manglePrefix(Dependent->getQualifier());
   1464   mangleUnscopedTemplateName(Template);
   1465 }
   1466 
   1467 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
   1468   // <template-prefix> ::= <prefix> <template unqualified-name>
   1469   //                   ::= <template-param>
   1470   //                   ::= <substitution>
   1471   // <template-template-param> ::= <template-param>
   1472   //                               <substitution>
   1473 
   1474   if (mangleSubstitution(ND))
   1475     return;
   1476 
   1477   // <template-template-param> ::= <template-param>
   1478   if (const TemplateTemplateParmDecl *TTP
   1479                                      = dyn_cast<TemplateTemplateParmDecl>(ND)) {
   1480     mangleTemplateParameter(TTP->getIndex());
   1481     return;
   1482   }
   1483 
   1484   manglePrefix(getEffectiveDeclContext(ND));
   1485   mangleUnqualifiedName(ND->getTemplatedDecl());
   1486   addSubstitution(ND);
   1487 }
   1488 
   1489 /// Mangles a template name under the production <type>.  Required for
   1490 /// template template arguments.
   1491 ///   <type> ::= <class-enum-type>
   1492 ///          ::= <template-param>
   1493 ///          ::= <substitution>
   1494 void CXXNameMangler::mangleType(TemplateName TN) {
   1495   if (mangleSubstitution(TN))
   1496     return;
   1497 
   1498   TemplateDecl *TD = 0;
   1499 
   1500   switch (TN.getKind()) {
   1501   case TemplateName::QualifiedTemplate:
   1502     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
   1503     goto HaveDecl;
   1504 
   1505   case TemplateName::Template:
   1506     TD = TN.getAsTemplateDecl();
   1507     goto HaveDecl;
   1508 
   1509   HaveDecl:
   1510     if (isa<TemplateTemplateParmDecl>(TD))
   1511       mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
   1512     else
   1513       mangleName(TD);
   1514     break;
   1515 
   1516   case TemplateName::OverloadedTemplate:
   1517     llvm_unreachable("can't mangle an overloaded template name as a <type>");
   1518 
   1519   case TemplateName::DependentTemplate: {
   1520     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
   1521     assert(Dependent->isIdentifier());
   1522 
   1523     // <class-enum-type> ::= <name>
   1524     // <name> ::= <nested-name>
   1525     mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
   1526     mangleSourceName(Dependent->getIdentifier());
   1527     break;
   1528   }
   1529 
   1530   case TemplateName::SubstTemplateTemplateParm: {
   1531     // Substituted template parameters are mangled as the substituted
   1532     // template.  This will check for the substitution twice, which is
   1533     // fine, but we have to return early so that we don't try to *add*
   1534     // the substitution twice.
   1535     SubstTemplateTemplateParmStorage *subst
   1536       = TN.getAsSubstTemplateTemplateParm();
   1537     mangleType(subst->getReplacement());
   1538     return;
   1539   }
   1540 
   1541   case TemplateName::SubstTemplateTemplateParmPack: {
   1542     // FIXME: not clear how to mangle this!
   1543     // template <template <class> class T...> class A {
   1544     //   template <template <class> class U...> void foo(B<T,U> x...);
   1545     // };
   1546     Out << "_SUBSTPACK_";
   1547     break;
   1548   }
   1549   }
   1550 
   1551   addSubstitution(TN);
   1552 }
   1553 
   1554 void
   1555 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
   1556   switch (OO) {
   1557   // <operator-name> ::= nw     # new
   1558   case OO_New: Out << "nw"; break;
   1559   //              ::= na        # new[]
   1560   case OO_Array_New: Out << "na"; break;
   1561   //              ::= dl        # delete
   1562   case OO_Delete: Out << "dl"; break;
   1563   //              ::= da        # delete[]
   1564   case OO_Array_Delete: Out << "da"; break;
   1565   //              ::= ps        # + (unary)
   1566   //              ::= pl        # + (binary or unknown)
   1567   case OO_Plus:
   1568     Out << (Arity == 1? "ps" : "pl"); break;
   1569   //              ::= ng        # - (unary)
   1570   //              ::= mi        # - (binary or unknown)
   1571   case OO_Minus:
   1572     Out << (Arity == 1? "ng" : "mi"); break;
   1573   //              ::= ad        # & (unary)
   1574   //              ::= an        # & (binary or unknown)
   1575   case OO_Amp:
   1576     Out << (Arity == 1? "ad" : "an"); break;
   1577   //              ::= de        # * (unary)
   1578   //              ::= ml        # * (binary or unknown)
   1579   case OO_Star:
   1580     // Use binary when unknown.
   1581     Out << (Arity == 1? "de" : "ml"); break;
   1582   //              ::= co        # ~
   1583   case OO_Tilde: Out << "co"; break;
   1584   //              ::= dv        # /
   1585   case OO_Slash: Out << "dv"; break;
   1586   //              ::= rm        # %
   1587   case OO_Percent: Out << "rm"; break;
   1588   //              ::= or        # |
   1589   case OO_Pipe: Out << "or"; break;
   1590   //              ::= eo        # ^
   1591   case OO_Caret: Out << "eo"; break;
   1592   //              ::= aS        # =
   1593   case OO_Equal: Out << "aS"; break;
   1594   //              ::= pL        # +=
   1595   case OO_PlusEqual: Out << "pL"; break;
   1596   //              ::= mI        # -=
   1597   case OO_MinusEqual: Out << "mI"; break;
   1598   //              ::= mL        # *=
   1599   case OO_StarEqual: Out << "mL"; break;
   1600   //              ::= dV        # /=
   1601   case OO_SlashEqual: Out << "dV"; break;
   1602   //              ::= rM        # %=
   1603   case OO_PercentEqual: Out << "rM"; break;
   1604   //              ::= aN        # &=
   1605   case OO_AmpEqual: Out << "aN"; break;
   1606   //              ::= oR        # |=
   1607   case OO_PipeEqual: Out << "oR"; break;
   1608   //              ::= eO        # ^=
   1609   case OO_CaretEqual: Out << "eO"; break;
   1610   //              ::= ls        # <<
   1611   case OO_LessLess: Out << "ls"; break;
   1612   //              ::= rs        # >>
   1613   case OO_GreaterGreater: Out << "rs"; break;
   1614   //              ::= lS        # <<=
   1615   case OO_LessLessEqual: Out << "lS"; break;
   1616   //              ::= rS        # >>=
   1617   case OO_GreaterGreaterEqual: Out << "rS"; break;
   1618   //              ::= eq        # ==
   1619   case OO_EqualEqual: Out << "eq"; break;
   1620   //              ::= ne        # !=
   1621   case OO_ExclaimEqual: Out << "ne"; break;
   1622   //              ::= lt        # <
   1623   case OO_Less: Out << "lt"; break;
   1624   //              ::= gt        # >
   1625   case OO_Greater: Out << "gt"; break;
   1626   //              ::= le        # <=
   1627   case OO_LessEqual: Out << "le"; break;
   1628   //              ::= ge        # >=
   1629   case OO_GreaterEqual: Out << "ge"; break;
   1630   //              ::= nt        # !
   1631   case OO_Exclaim: Out << "nt"; break;
   1632   //              ::= aa        # &&
   1633   case OO_AmpAmp: Out << "aa"; break;
   1634   //              ::= oo        # ||
   1635   case OO_PipePipe: Out << "oo"; break;
   1636   //              ::= pp        # ++
   1637   case OO_PlusPlus: Out << "pp"; break;
   1638   //              ::= mm        # --
   1639   case OO_MinusMinus: Out << "mm"; break;
   1640   //              ::= cm        # ,
   1641   case OO_Comma: Out << "cm"; break;
   1642   //              ::= pm        # ->*
   1643   case OO_ArrowStar: Out << "pm"; break;
   1644   //              ::= pt        # ->
   1645   case OO_Arrow: Out << "pt"; break;
   1646   //              ::= cl        # ()
   1647   case OO_Call: Out << "cl"; break;
   1648   //              ::= ix        # []
   1649   case OO_Subscript: Out << "ix"; break;
   1650 
   1651   //              ::= qu        # ?
   1652   // The conditional operator can't be overloaded, but we still handle it when
   1653   // mangling expressions.
   1654   case OO_Conditional: Out << "qu"; break;
   1655 
   1656   case OO_None:
   1657   case NUM_OVERLOADED_OPERATORS:
   1658     llvm_unreachable("Not an overloaded operator");
   1659   }
   1660 }
   1661 
   1662 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
   1663   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
   1664   if (Quals.hasRestrict())
   1665     Out << 'r';
   1666   if (Quals.hasVolatile())
   1667     Out << 'V';
   1668   if (Quals.hasConst())
   1669     Out << 'K';
   1670 
   1671   if (Quals.hasAddressSpace()) {
   1672     // Extension:
   1673     //
   1674     //   <type> ::= U <address-space-number>
   1675     //
   1676     // where <address-space-number> is a source name consisting of 'AS'
   1677     // followed by the address space <number>.
   1678     SmallString<64> ASString;
   1679     ASString = "AS" + llvm::utostr_32(Quals.getAddressSpace());
   1680     Out << 'U' << ASString.size() << ASString;
   1681   }
   1682 
   1683   StringRef LifetimeName;
   1684   switch (Quals.getObjCLifetime()) {
   1685   // Objective-C ARC Extension:
   1686   //
   1687   //   <type> ::= U "__strong"
   1688   //   <type> ::= U "__weak"
   1689   //   <type> ::= U "__autoreleasing"
   1690   case Qualifiers::OCL_None:
   1691     break;
   1692 
   1693   case Qualifiers::OCL_Weak:
   1694     LifetimeName = "__weak";
   1695     break;
   1696 
   1697   case Qualifiers::OCL_Strong:
   1698     LifetimeName = "__strong";
   1699     break;
   1700 
   1701   case Qualifiers::OCL_Autoreleasing:
   1702     LifetimeName = "__autoreleasing";
   1703     break;
   1704 
   1705   case Qualifiers::OCL_ExplicitNone:
   1706     // The __unsafe_unretained qualifier is *not* mangled, so that
   1707     // __unsafe_unretained types in ARC produce the same manglings as the
   1708     // equivalent (but, naturally, unqualified) types in non-ARC, providing
   1709     // better ABI compatibility.
   1710     //
   1711     // It's safe to do this because unqualified 'id' won't show up
   1712     // in any type signatures that need to be mangled.
   1713     break;
   1714   }
   1715   if (!LifetimeName.empty())
   1716     Out << 'U' << LifetimeName.size() << LifetimeName;
   1717 }
   1718 
   1719 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
   1720   // <ref-qualifier> ::= R                # lvalue reference
   1721   //                 ::= O                # rvalue-reference
   1722   // Proposal to Itanium C++ ABI list on 1/26/11
   1723   switch (RefQualifier) {
   1724   case RQ_None:
   1725     break;
   1726 
   1727   case RQ_LValue:
   1728     Out << 'R';
   1729     break;
   1730 
   1731   case RQ_RValue:
   1732     Out << 'O';
   1733     break;
   1734   }
   1735 }
   1736 
   1737 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
   1738   Context.mangleObjCMethodName(MD, Out);
   1739 }
   1740 
   1741 void CXXNameMangler::mangleType(QualType T) {
   1742   // If our type is instantiation-dependent but not dependent, we mangle
   1743   // it as it was written in the source, removing any top-level sugar.
   1744   // Otherwise, use the canonical type.
   1745   //
   1746   // FIXME: This is an approximation of the instantiation-dependent name
   1747   // mangling rules, since we should really be using the type as written and
   1748   // augmented via semantic analysis (i.e., with implicit conversions and
   1749   // default template arguments) for any instantiation-dependent type.
   1750   // Unfortunately, that requires several changes to our AST:
   1751   //   - Instantiation-dependent TemplateSpecializationTypes will need to be
   1752   //     uniqued, so that we can handle substitutions properly
   1753   //   - Default template arguments will need to be represented in the
   1754   //     TemplateSpecializationType, since they need to be mangled even though
   1755   //     they aren't written.
   1756   //   - Conversions on non-type template arguments need to be expressed, since
   1757   //     they can affect the mangling of sizeof/alignof.
   1758   if (!T->isInstantiationDependentType() || T->isDependentType())
   1759     T = T.getCanonicalType();
   1760   else {
   1761     // Desugar any types that are purely sugar.
   1762     do {
   1763       // Don't desugar through template specialization types that aren't
   1764       // type aliases. We need to mangle the template arguments as written.
   1765       if (const TemplateSpecializationType *TST
   1766                                       = dyn_cast<TemplateSpecializationType>(T))
   1767         if (!TST->isTypeAlias())
   1768           break;
   1769 
   1770       QualType Desugared
   1771         = T.getSingleStepDesugaredType(Context.getASTContext());
   1772       if (Desugared == T)
   1773         break;
   1774 
   1775       T = Desugared;
   1776     } while (true);
   1777   }
   1778   SplitQualType split = T.split();
   1779   Qualifiers quals = split.Quals;
   1780   const Type *ty = split.Ty;
   1781 
   1782   bool isSubstitutable = quals || !isa<BuiltinType>(T);
   1783   if (isSubstitutable && mangleSubstitution(T))
   1784     return;
   1785 
   1786   // If we're mangling a qualified array type, push the qualifiers to
   1787   // the element type.
   1788   if (quals && isa<ArrayType>(T)) {
   1789     ty = Context.getASTContext().getAsArrayType(T);
   1790     quals = Qualifiers();
   1791 
   1792     // Note that we don't update T: we want to add the
   1793     // substitution at the original type.
   1794   }
   1795 
   1796   if (quals) {
   1797     mangleQualifiers(quals);
   1798     // Recurse:  even if the qualified type isn't yet substitutable,
   1799     // the unqualified type might be.
   1800     mangleType(QualType(ty, 0));
   1801   } else {
   1802     switch (ty->getTypeClass()) {
   1803 #define ABSTRACT_TYPE(CLASS, PARENT)
   1804 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
   1805     case Type::CLASS: \
   1806       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
   1807       return;
   1808 #define TYPE(CLASS, PARENT) \
   1809     case Type::CLASS: \
   1810       mangleType(static_cast<const CLASS##Type*>(ty)); \
   1811       break;
   1812 #include "clang/AST/TypeNodes.def"
   1813     }
   1814   }
   1815 
   1816   // Add the substitution.
   1817   if (isSubstitutable)
   1818     addSubstitution(T);
   1819 }
   1820 
   1821 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
   1822   if (!mangleStandardSubstitution(ND))
   1823     mangleName(ND);
   1824 }
   1825 
   1826 void CXXNameMangler::mangleType(const BuiltinType *T) {
   1827   //  <type>         ::= <builtin-type>
   1828   //  <builtin-type> ::= v  # void
   1829   //                 ::= w  # wchar_t
   1830   //                 ::= b  # bool
   1831   //                 ::= c  # char
   1832   //                 ::= a  # signed char
   1833   //                 ::= h  # unsigned char
   1834   //                 ::= s  # short
   1835   //                 ::= t  # unsigned short
   1836   //                 ::= i  # int
   1837   //                 ::= j  # unsigned int
   1838   //                 ::= l  # long
   1839   //                 ::= m  # unsigned long
   1840   //                 ::= x  # long long, __int64
   1841   //                 ::= y  # unsigned long long, __int64
   1842   //                 ::= n  # __int128
   1843   // UNSUPPORTED:    ::= o  # unsigned __int128
   1844   //                 ::= f  # float
   1845   //                 ::= d  # double
   1846   //                 ::= e  # long double, __float80
   1847   // UNSUPPORTED:    ::= g  # __float128
   1848   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
   1849   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
   1850   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
   1851   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
   1852   //                 ::= Di # char32_t
   1853   //                 ::= Ds # char16_t
   1854   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
   1855   //                 ::= u <source-name>    # vendor extended type
   1856   switch (T->getKind()) {
   1857   case BuiltinType::Void: Out << 'v'; break;
   1858   case BuiltinType::Bool: Out << 'b'; break;
   1859   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
   1860   case BuiltinType::UChar: Out << 'h'; break;
   1861   case BuiltinType::UShort: Out << 't'; break;
   1862   case BuiltinType::UInt: Out << 'j'; break;
   1863   case BuiltinType::ULong: Out << 'm'; break;
   1864   case BuiltinType::ULongLong: Out << 'y'; break;
   1865   case BuiltinType::UInt128: Out << 'o'; break;
   1866   case BuiltinType::SChar: Out << 'a'; break;
   1867   case BuiltinType::WChar_S:
   1868   case BuiltinType::WChar_U: Out << 'w'; break;
   1869   case BuiltinType::Char16: Out << "Ds"; break;
   1870   case BuiltinType::Char32: Out << "Di"; break;
   1871   case BuiltinType::Short: Out << 's'; break;
   1872   case BuiltinType::Int: Out << 'i'; break;
   1873   case BuiltinType::Long: Out << 'l'; break;
   1874   case BuiltinType::LongLong: Out << 'x'; break;
   1875   case BuiltinType::Int128: Out << 'n'; break;
   1876   case BuiltinType::Half: Out << "Dh"; break;
   1877   case BuiltinType::Float: Out << 'f'; break;
   1878   case BuiltinType::Double: Out << 'd'; break;
   1879   case BuiltinType::LongDouble: Out << 'e'; break;
   1880   case BuiltinType::NullPtr: Out << "Dn"; break;
   1881 
   1882 #define BUILTIN_TYPE(Id, SingletonId)
   1883 #define PLACEHOLDER_TYPE(Id, SingletonId) \
   1884   case BuiltinType::Id:
   1885 #include "clang/AST/BuiltinTypes.def"
   1886   case BuiltinType::Dependent:
   1887     llvm_unreachable("mangling a placeholder type");
   1888   case BuiltinType::ObjCId: Out << "11objc_object"; break;
   1889   case BuiltinType::ObjCClass: Out << "10objc_class"; break;
   1890   case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
   1891   }
   1892 }
   1893 
   1894 // <type>          ::= <function-type>
   1895 // <function-type> ::= F [Y] <bare-function-type> E
   1896 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
   1897   Out << 'F';
   1898   // FIXME: We don't have enough information in the AST to produce the 'Y'
   1899   // encoding for extern "C" function types.
   1900   mangleBareFunctionType(T, /*MangleReturnType=*/true);
   1901   Out << 'E';
   1902 }
   1903 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
   1904   llvm_unreachable("Can't mangle K&R function prototypes");
   1905 }
   1906 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
   1907                                             bool MangleReturnType) {
   1908   // We should never be mangling something without a prototype.
   1909   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
   1910 
   1911   // Record that we're in a function type.  See mangleFunctionParam
   1912   // for details on what we're trying to achieve here.
   1913   FunctionTypeDepthState saved = FunctionTypeDepth.push();
   1914 
   1915   // <bare-function-type> ::= <signature type>+
   1916   if (MangleReturnType) {
   1917     FunctionTypeDepth.enterResultType();
   1918     mangleType(Proto->getResultType());
   1919     FunctionTypeDepth.leaveResultType();
   1920   }
   1921 
   1922   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
   1923     //   <builtin-type> ::= v   # void
   1924     Out << 'v';
   1925 
   1926     FunctionTypeDepth.pop(saved);
   1927     return;
   1928   }
   1929 
   1930   for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
   1931                                          ArgEnd = Proto->arg_type_end();
   1932        Arg != ArgEnd; ++Arg)
   1933     mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
   1934 
   1935   FunctionTypeDepth.pop(saved);
   1936 
   1937   // <builtin-type>      ::= z  # ellipsis
   1938   if (Proto->isVariadic())
   1939     Out << 'z';
   1940 }
   1941 
   1942 // <type>            ::= <class-enum-type>
   1943 // <class-enum-type> ::= <name>
   1944 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
   1945   mangleName(T->getDecl());
   1946 }
   1947 
   1948 // <type>            ::= <class-enum-type>
   1949 // <class-enum-type> ::= <name>
   1950 void CXXNameMangler::mangleType(const EnumType *T) {
   1951   mangleType(static_cast<const TagType*>(T));
   1952 }
   1953 void CXXNameMangler::mangleType(const RecordType *T) {
   1954   mangleType(static_cast<const TagType*>(T));
   1955 }
   1956 void CXXNameMangler::mangleType(const TagType *T) {
   1957   mangleName(T->getDecl());
   1958 }
   1959 
   1960 // <type>       ::= <array-type>
   1961 // <array-type> ::= A <positive dimension number> _ <element type>
   1962 //              ::= A [<dimension expression>] _ <element type>
   1963 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
   1964   Out << 'A' << T->getSize() << '_';
   1965   mangleType(T->getElementType());
   1966 }
   1967 void CXXNameMangler::mangleType(const VariableArrayType *T) {
   1968   Out << 'A';
   1969   // decayed vla types (size 0) will just be skipped.
   1970   if (T->getSizeExpr())
   1971     mangleExpression(T->getSizeExpr());
   1972   Out << '_';
   1973   mangleType(T->getElementType());
   1974 }
   1975 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
   1976   Out << 'A';
   1977   mangleExpression(T->getSizeExpr());
   1978   Out << '_';
   1979   mangleType(T->getElementType());
   1980 }
   1981 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
   1982   Out << "A_";
   1983   mangleType(T->getElementType());
   1984 }
   1985 
   1986 // <type>                   ::= <pointer-to-member-type>
   1987 // <pointer-to-member-type> ::= M <class type> <member type>
   1988 void CXXNameMangler::mangleType(const MemberPointerType *T) {
   1989   Out << 'M';
   1990   mangleType(QualType(T->getClass(), 0));
   1991   QualType PointeeType = T->getPointeeType();
   1992   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
   1993     mangleQualifiers(Qualifiers::fromCVRMask(FPT->getTypeQuals()));
   1994     mangleRefQualifier(FPT->getRefQualifier());
   1995     mangleType(FPT);
   1996 
   1997     // Itanium C++ ABI 5.1.8:
   1998     //
   1999     //   The type of a non-static member function is considered to be different,
   2000     //   for the purposes of substitution, from the type of a namespace-scope or
   2001     //   static member function whose type appears similar. The types of two
   2002     //   non-static member functions are considered to be different, for the
   2003     //   purposes of substitution, if the functions are members of different
   2004     //   classes. In other words, for the purposes of substitution, the class of
   2005     //   which the function is a member is considered part of the type of
   2006     //   function.
   2007 
   2008     // We increment the SeqID here to emulate adding an entry to the
   2009     // substitution table. We can't actually add it because we don't want this
   2010     // particular function type to be substituted.
   2011     ++SeqID;
   2012   } else
   2013     mangleType(PointeeType);
   2014 }
   2015 
   2016 // <type>           ::= <template-param>
   2017 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
   2018   mangleTemplateParameter(T->getIndex());
   2019 }
   2020 
   2021 // <type>           ::= <template-param>
   2022 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
   2023   // FIXME: not clear how to mangle this!
   2024   // template <class T...> class A {
   2025   //   template <class U...> void foo(T(*)(U) x...);
   2026   // };
   2027   Out << "_SUBSTPACK_";
   2028 }
   2029 
   2030 // <type> ::= P <type>   # pointer-to
   2031 void CXXNameMangler::mangleType(const PointerType *T) {
   2032   Out << 'P';
   2033   mangleType(T->getPointeeType());
   2034 }
   2035 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
   2036   Out << 'P';
   2037   mangleType(T->getPointeeType());
   2038 }
   2039 
   2040 // <type> ::= R <type>   # reference-to
   2041 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
   2042   Out << 'R';
   2043   mangleType(T->getPointeeType());
   2044 }
   2045 
   2046 // <type> ::= O <type>   # rvalue reference-to (C++0x)
   2047 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
   2048   Out << 'O';
   2049   mangleType(T->getPointeeType());
   2050 }
   2051 
   2052 // <type> ::= C <type>   # complex pair (C 2000)
   2053 void CXXNameMangler::mangleType(const ComplexType *T) {
   2054   Out << 'C';
   2055   mangleType(T->getElementType());
   2056 }
   2057 
   2058 // ARM's ABI for Neon vector types specifies that they should be mangled as
   2059 // if they are structs (to match ARM's initial implementation).  The
   2060 // vector type must be one of the special types predefined by ARM.
   2061 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
   2062   QualType EltType = T->getElementType();
   2063   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
   2064   const char *EltName = 0;
   2065   if (T->getVectorKind() == VectorType::NeonPolyVector) {
   2066     switch (cast<BuiltinType>(EltType)->getKind()) {
   2067     case BuiltinType::SChar:     EltName = "poly8_t"; break;
   2068     case BuiltinType::Short:     EltName = "poly16_t"; break;
   2069     default: llvm_unreachable("unexpected Neon polynomial vector element type");
   2070     }
   2071   } else {
   2072     switch (cast<BuiltinType>(EltType)->getKind()) {
   2073     case BuiltinType::SChar:     EltName = "int8_t"; break;
   2074     case BuiltinType::UChar:     EltName = "uint8_t"; break;
   2075     case BuiltinType::Short:     EltName = "int16_t"; break;
   2076     case BuiltinType::UShort:    EltName = "uint16_t"; break;
   2077     case BuiltinType::Int:       EltName = "int32_t"; break;
   2078     case BuiltinType::UInt:      EltName = "uint32_t"; break;
   2079     case BuiltinType::LongLong:  EltName = "int64_t"; break;
   2080     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
   2081     case BuiltinType::Float:     EltName = "float32_t"; break;
   2082     default: llvm_unreachable("unexpected Neon vector element type");
   2083     }
   2084   }
   2085   const char *BaseName = 0;
   2086   unsigned BitSize = (T->getNumElements() *
   2087                       getASTContext().getTypeSize(EltType));
   2088   if (BitSize == 64)
   2089     BaseName = "__simd64_";
   2090   else {
   2091     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
   2092     BaseName = "__simd128_";
   2093   }
   2094   Out << strlen(BaseName) + strlen(EltName);
   2095   Out << BaseName << EltName;
   2096 }
   2097 
   2098 // GNU extension: vector types
   2099 // <type>                  ::= <vector-type>
   2100 // <vector-type>           ::= Dv <positive dimension number> _
   2101 //                                    <extended element type>
   2102 //                         ::= Dv [<dimension expression>] _ <element type>
   2103 // <extended element type> ::= <element type>
   2104 //                         ::= p # AltiVec vector pixel
   2105 void CXXNameMangler::mangleType(const VectorType *T) {
   2106   if ((T->getVectorKind() == VectorType::NeonVector ||
   2107        T->getVectorKind() == VectorType::NeonPolyVector)) {
   2108     mangleNeonVectorType(T);
   2109     return;
   2110   }
   2111   Out << "Dv" << T->getNumElements() << '_';
   2112   if (T->getVectorKind() == VectorType::AltiVecPixel)
   2113     Out << 'p';
   2114   else if (T->getVectorKind() == VectorType::AltiVecBool)
   2115     Out << 'b';
   2116   else
   2117     mangleType(T->getElementType());
   2118 }
   2119 void CXXNameMangler::mangleType(const ExtVectorType *T) {
   2120   mangleType(static_cast<const VectorType*>(T));
   2121 }
   2122 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
   2123   Out << "Dv";
   2124   mangleExpression(T->getSizeExpr());
   2125   Out << '_';
   2126   mangleType(T->getElementType());
   2127 }
   2128 
   2129 void CXXNameMangler::mangleType(const PackExpansionType *T) {
   2130   // <type>  ::= Dp <type>          # pack expansion (C++0x)
   2131   Out << "Dp";
   2132   mangleType(T->getPattern());
   2133 }
   2134 
   2135 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
   2136   mangleSourceName(T->getDecl()->getIdentifier());
   2137 }
   2138 
   2139 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
   2140   // We don't allow overloading by different protocol qualification,
   2141   // so mangling them isn't necessary.
   2142   mangleType(T->getBaseType());
   2143 }
   2144 
   2145 void CXXNameMangler::mangleType(const BlockPointerType *T) {
   2146   Out << "U13block_pointer";
   2147   mangleType(T->getPointeeType());
   2148 }
   2149 
   2150 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
   2151   // Mangle injected class name types as if the user had written the
   2152   // specialization out fully.  It may not actually be possible to see
   2153   // this mangling, though.
   2154   mangleType(T->getInjectedSpecializationType());
   2155 }
   2156 
   2157 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
   2158   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
   2159     mangleName(TD, T->getArgs(), T->getNumArgs());
   2160   } else {
   2161     if (mangleSubstitution(QualType(T, 0)))
   2162       return;
   2163 
   2164     mangleTemplatePrefix(T->getTemplateName());
   2165 
   2166     // FIXME: GCC does not appear to mangle the template arguments when
   2167     // the template in question is a dependent template name. Should we
   2168     // emulate that badness?
   2169     mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
   2170     addSubstitution(QualType(T, 0));
   2171   }
   2172 }
   2173 
   2174 void CXXNameMangler::mangleType(const DependentNameType *T) {
   2175   // Typename types are always nested
   2176   Out << 'N';
   2177   manglePrefix(T->getQualifier());
   2178   mangleSourceName(T->getIdentifier());
   2179   Out << 'E';
   2180 }
   2181 
   2182 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
   2183   // Dependently-scoped template types are nested if they have a prefix.
   2184   Out << 'N';
   2185 
   2186   // TODO: avoid making this TemplateName.
   2187   TemplateName Prefix =
   2188     getASTContext().getDependentTemplateName(T->getQualifier(),
   2189                                              T->getIdentifier());
   2190   mangleTemplatePrefix(Prefix);
   2191 
   2192   // FIXME: GCC does not appear to mangle the template arguments when
   2193   // the template in question is a dependent template name. Should we
   2194   // emulate that badness?
   2195   mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
   2196   Out << 'E';
   2197 }
   2198 
   2199 void CXXNameMangler::mangleType(const TypeOfType *T) {
   2200   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
   2201   // "extension with parameters" mangling.
   2202   Out << "u6typeof";
   2203 }
   2204 
   2205 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
   2206   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
   2207   // "extension with parameters" mangling.
   2208   Out << "u6typeof";
   2209 }
   2210 
   2211 void CXXNameMangler::mangleType(const DecltypeType *T) {
   2212   Expr *E = T->getUnderlyingExpr();
   2213 
   2214   // type ::= Dt <expression> E  # decltype of an id-expression
   2215   //                             #   or class member access
   2216   //      ::= DT <expression> E  # decltype of an expression
   2217 
   2218   // This purports to be an exhaustive list of id-expressions and
   2219   // class member accesses.  Note that we do not ignore parentheses;
   2220   // parentheses change the semantics of decltype for these
   2221   // expressions (and cause the mangler to use the other form).
   2222   if (isa<DeclRefExpr>(E) ||
   2223       isa<MemberExpr>(E) ||
   2224       isa<UnresolvedLookupExpr>(E) ||
   2225       isa<DependentScopeDeclRefExpr>(E) ||
   2226       isa<CXXDependentScopeMemberExpr>(E) ||
   2227       isa<UnresolvedMemberExpr>(E))
   2228     Out << "Dt";
   2229   else
   2230     Out << "DT";
   2231   mangleExpression(E);
   2232   Out << 'E';
   2233 }
   2234 
   2235 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
   2236   // If this is dependent, we need to record that. If not, we simply
   2237   // mangle it as the underlying type since they are equivalent.
   2238   if (T->isDependentType()) {
   2239     Out << 'U';
   2240 
   2241     switch (T->getUTTKind()) {
   2242       case UnaryTransformType::EnumUnderlyingType:
   2243         Out << "3eut";
   2244         break;
   2245     }
   2246   }
   2247 
   2248   mangleType(T->getUnderlyingType());
   2249 }
   2250 
   2251 void CXXNameMangler::mangleType(const AutoType *T) {
   2252   QualType D = T->getDeducedType();
   2253   // <builtin-type> ::= Da  # dependent auto
   2254   if (D.isNull())
   2255     Out << "Da";
   2256   else
   2257     mangleType(D);
   2258 }
   2259 
   2260 void CXXNameMangler::mangleType(const AtomicType *T) {
   2261   // <type> ::= U <source-name> <type>	# vendor extended type qualifier
   2262   // (Until there's a standardized mangling...)
   2263   Out << "U7_Atomic";
   2264   mangleType(T->getValueType());
   2265 }
   2266 
   2267 void CXXNameMangler::mangleIntegerLiteral(QualType T,
   2268                                           const llvm::APSInt &Value) {
   2269   //  <expr-primary> ::= L <type> <value number> E # integer literal
   2270   Out << 'L';
   2271 
   2272   mangleType(T);
   2273   if (T->isBooleanType()) {
   2274     // Boolean values are encoded as 0/1.
   2275     Out << (Value.getBoolValue() ? '1' : '0');
   2276   } else {
   2277     mangleNumber(Value);
   2278   }
   2279   Out << 'E';
   2280 
   2281 }
   2282 
   2283 /// Mangles a member expression.
   2284 void CXXNameMangler::mangleMemberExpr(const Expr *base,
   2285                                       bool isArrow,
   2286                                       NestedNameSpecifier *qualifier,
   2287                                       NamedDecl *firstQualifierLookup,
   2288                                       DeclarationName member,
   2289                                       unsigned arity) {
   2290   // <expression> ::= dt <expression> <unresolved-name>
   2291   //              ::= pt <expression> <unresolved-name>
   2292   if (base) {
   2293     if (base->isImplicitCXXThis()) {
   2294       // Note: GCC mangles member expressions to the implicit 'this' as
   2295       // *this., whereas we represent them as this->. The Itanium C++ ABI
   2296       // does not specify anything here, so we follow GCC.
   2297       Out << "dtdefpT";
   2298     } else {
   2299       Out << (isArrow ? "pt" : "dt");
   2300       mangleExpression(base);
   2301     }
   2302   }
   2303   mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
   2304 }
   2305 
   2306 /// Look at the callee of the given call expression and determine if
   2307 /// it's a parenthesized id-expression which would have triggered ADL
   2308 /// otherwise.
   2309 static bool isParenthesizedADLCallee(const CallExpr *call) {
   2310   const Expr *callee = call->getCallee();
   2311   const Expr *fn = callee->IgnoreParens();
   2312 
   2313   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
   2314   // too, but for those to appear in the callee, it would have to be
   2315   // parenthesized.
   2316   if (callee == fn) return false;
   2317 
   2318   // Must be an unresolved lookup.
   2319   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
   2320   if (!lookup) return false;
   2321 
   2322   assert(!lookup->requiresADL());
   2323 
   2324   // Must be an unqualified lookup.
   2325   if (lookup->getQualifier()) return false;
   2326 
   2327   // Must not have found a class member.  Note that if one is a class
   2328   // member, they're all class members.
   2329   if (lookup->getNumDecls() > 0 &&
   2330       (*lookup->decls_begin())->isCXXClassMember())
   2331     return false;
   2332 
   2333   // Otherwise, ADL would have been triggered.
   2334   return true;
   2335 }
   2336 
   2337 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
   2338   // <expression> ::= <unary operator-name> <expression>
   2339   //              ::= <binary operator-name> <expression> <expression>
   2340   //              ::= <trinary operator-name> <expression> <expression> <expression>
   2341   //              ::= cv <type> expression           # conversion with one argument
   2342   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
   2343   //              ::= st <type>                      # sizeof (a type)
   2344   //              ::= at <type>                      # alignof (a type)
   2345   //              ::= <template-param>
   2346   //              ::= <function-param>
   2347   //              ::= sr <type> <unqualified-name>                   # dependent name
   2348   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
   2349   //              ::= ds <expression> <expression>                   # expr.*expr
   2350   //              ::= sZ <template-param>                            # size of a parameter pack
   2351   //              ::= sZ <function-param>    # size of a function parameter pack
   2352   //              ::= <expr-primary>
   2353   // <expr-primary> ::= L <type> <value number> E    # integer literal
   2354   //                ::= L <type <value float> E      # floating literal
   2355   //                ::= L <mangled-name> E           # external name
   2356   //                ::= fpT                          # 'this' expression
   2357   QualType ImplicitlyConvertedToType;
   2358 
   2359 recurse:
   2360   switch (E->getStmtClass()) {
   2361   case Expr::NoStmtClass:
   2362 #define ABSTRACT_STMT(Type)
   2363 #define EXPR(Type, Base)
   2364 #define STMT(Type, Base) \
   2365   case Expr::Type##Class:
   2366 #include "clang/AST/StmtNodes.inc"
   2367     // fallthrough
   2368 
   2369   // These all can only appear in local or variable-initialization
   2370   // contexts and so should never appear in a mangling.
   2371   case Expr::AddrLabelExprClass:
   2372   case Expr::DesignatedInitExprClass:
   2373   case Expr::ImplicitValueInitExprClass:
   2374   case Expr::ParenListExprClass:
   2375   case Expr::LambdaExprClass:
   2376     llvm_unreachable("unexpected statement kind");
   2377 
   2378   // FIXME: invent manglings for all these.
   2379   case Expr::BlockExprClass:
   2380   case Expr::CXXPseudoDestructorExprClass:
   2381   case Expr::ChooseExprClass:
   2382   case Expr::CompoundLiteralExprClass:
   2383   case Expr::ExtVectorElementExprClass:
   2384   case Expr::GenericSelectionExprClass:
   2385   case Expr::ObjCEncodeExprClass:
   2386   case Expr::ObjCIsaExprClass:
   2387   case Expr::ObjCIvarRefExprClass:
   2388   case Expr::ObjCMessageExprClass:
   2389   case Expr::ObjCPropertyRefExprClass:
   2390   case Expr::ObjCProtocolExprClass:
   2391   case Expr::ObjCSelectorExprClass:
   2392   case Expr::ObjCStringLiteralClass:
   2393   case Expr::ObjCBoxedExprClass:
   2394   case Expr::ObjCArrayLiteralClass:
   2395   case Expr::ObjCDictionaryLiteralClass:
   2396   case Expr::ObjCSubscriptRefExprClass:
   2397   case Expr::ObjCIndirectCopyRestoreExprClass:
   2398   case Expr::OffsetOfExprClass:
   2399   case Expr::PredefinedExprClass:
   2400   case Expr::ShuffleVectorExprClass:
   2401   case Expr::StmtExprClass:
   2402   case Expr::UnaryTypeTraitExprClass:
   2403   case Expr::BinaryTypeTraitExprClass:
   2404   case Expr::TypeTraitExprClass:
   2405   case Expr::ArrayTypeTraitExprClass:
   2406   case Expr::ExpressionTraitExprClass:
   2407   case Expr::VAArgExprClass:
   2408   case Expr::CXXUuidofExprClass:
   2409   case Expr::CXXNoexceptExprClass:
   2410   case Expr::CUDAKernelCallExprClass:
   2411   case Expr::AsTypeExprClass:
   2412   case Expr::PseudoObjectExprClass:
   2413   case Expr::AtomicExprClass:
   2414   {
   2415     // As bad as this diagnostic is, it's better than crashing.
   2416     DiagnosticsEngine &Diags = Context.getDiags();
   2417     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2418                                      "cannot yet mangle expression type %0");
   2419     Diags.Report(E->getExprLoc(), DiagID)
   2420       << E->getStmtClassName() << E->getSourceRange();
   2421     break;
   2422   }
   2423 
   2424   // Even gcc-4.5 doesn't mangle this.
   2425   case Expr::BinaryConditionalOperatorClass: {
   2426     DiagnosticsEngine &Diags = Context.getDiags();
   2427     unsigned DiagID =
   2428       Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2429                 "?: operator with omitted middle operand cannot be mangled");
   2430     Diags.Report(E->getExprLoc(), DiagID)
   2431       << E->getStmtClassName() << E->getSourceRange();
   2432     break;
   2433   }
   2434 
   2435   // These are used for internal purposes and cannot be meaningfully mangled.
   2436   case Expr::OpaqueValueExprClass:
   2437     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
   2438 
   2439   case Expr::InitListExprClass: {
   2440     // Proposal by Jason Merrill, 2012-01-03
   2441     Out << "il";
   2442     const InitListExpr *InitList = cast<InitListExpr>(E);
   2443     for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
   2444       mangleExpression(InitList->getInit(i));
   2445     Out << "E";
   2446     break;
   2447   }
   2448 
   2449   case Expr::CXXDefaultArgExprClass:
   2450     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
   2451     break;
   2452 
   2453   case Expr::SubstNonTypeTemplateParmExprClass:
   2454     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
   2455                      Arity);
   2456     break;
   2457 
   2458   case Expr::UserDefinedLiteralClass:
   2459     // We follow g++'s approach of mangling a UDL as a call to the literal
   2460     // operator.
   2461   case Expr::CXXMemberCallExprClass: // fallthrough
   2462   case Expr::CallExprClass: {
   2463     const CallExpr *CE = cast<CallExpr>(E);
   2464 
   2465     // <expression> ::= cp <simple-id> <expression>* E
   2466     // We use this mangling only when the call would use ADL except
   2467     // for being parenthesized.  Per discussion with David
   2468     // Vandervoorde, 2011.04.25.
   2469     if (isParenthesizedADLCallee(CE)) {
   2470       Out << "cp";
   2471       // The callee here is a parenthesized UnresolvedLookupExpr with
   2472       // no qualifier and should always get mangled as a <simple-id>
   2473       // anyway.
   2474 
   2475     // <expression> ::= cl <expression>* E
   2476     } else {
   2477       Out << "cl";
   2478     }
   2479 
   2480     mangleExpression(CE->getCallee(), CE->getNumArgs());
   2481     for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
   2482       mangleExpression(CE->getArg(I));
   2483     Out << 'E';
   2484     break;
   2485   }
   2486 
   2487   case Expr::CXXNewExprClass: {
   2488     const CXXNewExpr *New = cast<CXXNewExpr>(E);
   2489     if (New->isGlobalNew()) Out << "gs";
   2490     Out << (New->isArray() ? "na" : "nw");
   2491     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
   2492            E = New->placement_arg_end(); I != E; ++I)
   2493       mangleExpression(*I);
   2494     Out << '_';
   2495     mangleType(New->getAllocatedType());
   2496     if (New->hasInitializer()) {
   2497       // Proposal by Jason Merrill, 2012-01-03
   2498       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
   2499         Out << "il";
   2500       else
   2501         Out << "pi";
   2502       const Expr *Init = New->getInitializer();
   2503       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
   2504         // Directly inline the initializers.
   2505         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
   2506                                                   E = CCE->arg_end();
   2507              I != E; ++I)
   2508           mangleExpression(*I);
   2509       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
   2510         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
   2511           mangleExpression(PLE->getExpr(i));
   2512       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
   2513                  isa<InitListExpr>(Init)) {
   2514         // Only take InitListExprs apart for list-initialization.
   2515         const InitListExpr *InitList = cast<InitListExpr>(Init);
   2516         for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
   2517           mangleExpression(InitList->getInit(i));
   2518       } else
   2519         mangleExpression(Init);
   2520     }
   2521     Out << 'E';
   2522     break;
   2523   }
   2524 
   2525   case Expr::MemberExprClass: {
   2526     const MemberExpr *ME = cast<MemberExpr>(E);
   2527     mangleMemberExpr(ME->getBase(), ME->isArrow(),
   2528                      ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
   2529                      Arity);
   2530     break;
   2531   }
   2532 
   2533   case Expr::UnresolvedMemberExprClass: {
   2534     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
   2535     mangleMemberExpr(ME->getBase(), ME->isArrow(),
   2536                      ME->getQualifier(), 0, ME->getMemberName(),
   2537                      Arity);
   2538     if (ME->hasExplicitTemplateArgs())
   2539       mangleTemplateArgs(ME->getExplicitTemplateArgs());
   2540     break;
   2541   }
   2542 
   2543   case Expr::CXXDependentScopeMemberExprClass: {
   2544     const CXXDependentScopeMemberExpr *ME
   2545       = cast<CXXDependentScopeMemberExpr>(E);
   2546     mangleMemberExpr(ME->getBase(), ME->isArrow(),
   2547                      ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
   2548                      ME->getMember(), Arity);
   2549     if (ME->hasExplicitTemplateArgs())
   2550       mangleTemplateArgs(ME->getExplicitTemplateArgs());
   2551     break;
   2552   }
   2553 
   2554   case Expr::UnresolvedLookupExprClass: {
   2555     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
   2556     mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
   2557 
   2558     // All the <unresolved-name> productions end in a
   2559     // base-unresolved-name, where <template-args> are just tacked
   2560     // onto the end.
   2561     if (ULE->hasExplicitTemplateArgs())
   2562       mangleTemplateArgs(ULE->getExplicitTemplateArgs());
   2563     break;
   2564   }
   2565 
   2566   case Expr::CXXUnresolvedConstructExprClass: {
   2567     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
   2568     unsigned N = CE->arg_size();
   2569 
   2570     Out << "cv";
   2571     mangleType(CE->getType());
   2572     if (N != 1) Out << '_';
   2573     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
   2574     if (N != 1) Out << 'E';
   2575     break;
   2576   }
   2577 
   2578   case Expr::CXXTemporaryObjectExprClass:
   2579   case Expr::CXXConstructExprClass: {
   2580     const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
   2581     unsigned N = CE->getNumArgs();
   2582 
   2583     // Proposal by Jason Merrill, 2012-01-03
   2584     if (CE->isListInitialization())
   2585       Out << "tl";
   2586     else
   2587       Out << "cv";
   2588     mangleType(CE->getType());
   2589     if (N != 1) Out << '_';
   2590     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
   2591     if (N != 1) Out << 'E';
   2592     break;
   2593   }
   2594 
   2595   case Expr::CXXScalarValueInitExprClass:
   2596     Out <<"cv";
   2597     mangleType(E->getType());
   2598     Out <<"_E";
   2599     break;
   2600 
   2601   case Expr::UnaryExprOrTypeTraitExprClass: {
   2602     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
   2603 
   2604     if (!SAE->isInstantiationDependent()) {
   2605       // Itanium C++ ABI:
   2606       //   If the operand of a sizeof or alignof operator is not
   2607       //   instantiation-dependent it is encoded as an integer literal
   2608       //   reflecting the result of the operator.
   2609       //
   2610       //   If the result of the operator is implicitly converted to a known
   2611       //   integer type, that type is used for the literal; otherwise, the type
   2612       //   of std::size_t or std::ptrdiff_t is used.
   2613       QualType T = (ImplicitlyConvertedToType.isNull() ||
   2614                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
   2615                                                     : ImplicitlyConvertedToType;
   2616       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
   2617       mangleIntegerLiteral(T, V);
   2618       break;
   2619     }
   2620 
   2621     switch(SAE->getKind()) {
   2622     case UETT_SizeOf:
   2623       Out << 's';
   2624       break;
   2625     case UETT_AlignOf:
   2626       Out << 'a';
   2627       break;
   2628     case UETT_VecStep:
   2629       DiagnosticsEngine &Diags = Context.getDiags();
   2630       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2631                                      "cannot yet mangle vec_step expression");
   2632       Diags.Report(DiagID);
   2633       return;
   2634     }
   2635     if (SAE->isArgumentType()) {
   2636       Out << 't';
   2637       mangleType(SAE->getArgumentType());
   2638     } else {
   2639       Out << 'z';
   2640       mangleExpression(SAE->getArgumentExpr());
   2641     }
   2642     break;
   2643   }
   2644 
   2645   case Expr::CXXThrowExprClass: {
   2646     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
   2647 
   2648     // Proposal from David Vandervoorde, 2010.06.30
   2649     if (TE->getSubExpr()) {
   2650       Out << "tw";
   2651       mangleExpression(TE->getSubExpr());
   2652     } else {
   2653       Out << "tr";
   2654     }
   2655     break;
   2656   }
   2657 
   2658   case Expr::CXXTypeidExprClass: {
   2659     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
   2660 
   2661     // Proposal from David Vandervoorde, 2010.06.30
   2662     if (TIE->isTypeOperand()) {
   2663       Out << "ti";
   2664       mangleType(TIE->getTypeOperand());
   2665     } else {
   2666       Out << "te";
   2667       mangleExpression(TIE->getExprOperand());
   2668     }
   2669     break;
   2670   }
   2671 
   2672   case Expr::CXXDeleteExprClass: {
   2673     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
   2674 
   2675     // Proposal from David Vandervoorde, 2010.06.30
   2676     if (DE->isGlobalDelete()) Out << "gs";
   2677     Out << (DE->isArrayForm() ? "da" : "dl");
   2678     mangleExpression(DE->getArgument());
   2679     break;
   2680   }
   2681 
   2682   case Expr::UnaryOperatorClass: {
   2683     const UnaryOperator *UO = cast<UnaryOperator>(E);
   2684     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
   2685                        /*Arity=*/1);
   2686     mangleExpression(UO->getSubExpr());
   2687     break;
   2688   }
   2689 
   2690   case Expr::ArraySubscriptExprClass: {
   2691     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
   2692 
   2693     // Array subscript is treated as a syntactically weird form of
   2694     // binary operator.
   2695     Out << "ix";
   2696     mangleExpression(AE->getLHS());
   2697     mangleExpression(AE->getRHS());
   2698     break;
   2699   }
   2700 
   2701   case Expr::CompoundAssignOperatorClass: // fallthrough
   2702   case Expr::BinaryOperatorClass: {
   2703     const BinaryOperator *BO = cast<BinaryOperator>(E);
   2704     if (BO->getOpcode() == BO_PtrMemD)
   2705       Out << "ds";
   2706     else
   2707       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
   2708                          /*Arity=*/2);
   2709     mangleExpression(BO->getLHS());
   2710     mangleExpression(BO->getRHS());
   2711     break;
   2712   }
   2713 
   2714   case Expr::ConditionalOperatorClass: {
   2715     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
   2716     mangleOperatorName(OO_Conditional, /*Arity=*/3);
   2717     mangleExpression(CO->getCond());
   2718     mangleExpression(CO->getLHS(), Arity);
   2719     mangleExpression(CO->getRHS(), Arity);
   2720     break;
   2721   }
   2722 
   2723   case Expr::ImplicitCastExprClass: {
   2724     ImplicitlyConvertedToType = E->getType();
   2725     E = cast<ImplicitCastExpr>(E)->getSubExpr();
   2726     goto recurse;
   2727   }
   2728 
   2729   case Expr::ObjCBridgedCastExprClass: {
   2730     // Mangle ownership casts as a vendor extended operator __bridge,
   2731     // __bridge_transfer, or __bridge_retain.
   2732     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
   2733     Out << "v1U" << Kind.size() << Kind;
   2734   }
   2735   // Fall through to mangle the cast itself.
   2736 
   2737   case Expr::CStyleCastExprClass:
   2738   case Expr::CXXStaticCastExprClass:
   2739   case Expr::CXXDynamicCastExprClass:
   2740   case Expr::CXXReinterpretCastExprClass:
   2741   case Expr::CXXConstCastExprClass:
   2742   case Expr::CXXFunctionalCastExprClass: {
   2743     const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
   2744     Out << "cv";
   2745     mangleType(ECE->getType());
   2746     mangleExpression(ECE->getSubExpr());
   2747     break;
   2748   }
   2749 
   2750   case Expr::CXXOperatorCallExprClass: {
   2751     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
   2752     unsigned NumArgs = CE->getNumArgs();
   2753     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
   2754     // Mangle the arguments.
   2755     for (unsigned i = 0; i != NumArgs; ++i)
   2756       mangleExpression(CE->getArg(i));
   2757     break;
   2758   }
   2759 
   2760   case Expr::ParenExprClass:
   2761     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
   2762     break;
   2763 
   2764   case Expr::DeclRefExprClass: {
   2765     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
   2766 
   2767     switch (D->getKind()) {
   2768     default:
   2769       //  <expr-primary> ::= L <mangled-name> E # external name
   2770       Out << 'L';
   2771       mangle(D, "_Z");
   2772       Out << 'E';
   2773       break;
   2774 
   2775     case Decl::ParmVar:
   2776       mangleFunctionParam(cast<ParmVarDecl>(D));
   2777       break;
   2778 
   2779     case Decl::EnumConstant: {
   2780       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
   2781       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
   2782       break;
   2783     }
   2784 
   2785     case Decl::NonTypeTemplateParm: {
   2786       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
   2787       mangleTemplateParameter(PD->getIndex());
   2788       break;
   2789     }
   2790 
   2791     }
   2792 
   2793     break;
   2794   }
   2795 
   2796   case Expr::SubstNonTypeTemplateParmPackExprClass:
   2797     // FIXME: not clear how to mangle this!
   2798     // template <unsigned N...> class A {
   2799     //   template <class U...> void foo(U (&x)[N]...);
   2800     // };
   2801     Out << "_SUBSTPACK_";
   2802     break;
   2803 
   2804   case Expr::DependentScopeDeclRefExprClass: {
   2805     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
   2806     mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
   2807 
   2808     // All the <unresolved-name> productions end in a
   2809     // base-unresolved-name, where <template-args> are just tacked
   2810     // onto the end.
   2811     if (DRE->hasExplicitTemplateArgs())
   2812       mangleTemplateArgs(DRE->getExplicitTemplateArgs());
   2813     break;
   2814   }
   2815 
   2816   case Expr::CXXBindTemporaryExprClass:
   2817     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
   2818     break;
   2819 
   2820   case Expr::ExprWithCleanupsClass:
   2821     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
   2822     break;
   2823 
   2824   case Expr::FloatingLiteralClass: {
   2825     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
   2826     Out << 'L';
   2827     mangleType(FL->getType());
   2828     mangleFloat(FL->getValue());
   2829     Out << 'E';
   2830     break;
   2831   }
   2832 
   2833   case Expr::CharacterLiteralClass:
   2834     Out << 'L';
   2835     mangleType(E->getType());
   2836     Out << cast<CharacterLiteral>(E)->getValue();
   2837     Out << 'E';
   2838     break;
   2839 
   2840   // FIXME. __objc_yes/__objc_no are mangled same as true/false
   2841   case Expr::ObjCBoolLiteralExprClass:
   2842     Out << "Lb";
   2843     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
   2844     Out << 'E';
   2845     break;
   2846 
   2847   case Expr::CXXBoolLiteralExprClass:
   2848     Out << "Lb";
   2849     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
   2850     Out << 'E';
   2851     break;
   2852 
   2853   case Expr::IntegerLiteralClass: {
   2854     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
   2855     if (E->getType()->isSignedIntegerType())
   2856       Value.setIsSigned(true);
   2857     mangleIntegerLiteral(E->getType(), Value);
   2858     break;
   2859   }
   2860 
   2861   case Expr::ImaginaryLiteralClass: {
   2862     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
   2863     // Mangle as if a complex literal.
   2864     // Proposal from David Vandevoorde, 2010.06.30.
   2865     Out << 'L';
   2866     mangleType(E->getType());
   2867     if (const FloatingLiteral *Imag =
   2868           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
   2869       // Mangle a floating-point zero of the appropriate type.
   2870       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
   2871       Out << '_';
   2872       mangleFloat(Imag->getValue());
   2873     } else {
   2874       Out << "0_";
   2875       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
   2876       if (IE->getSubExpr()->getType()->isSignedIntegerType())
   2877         Value.setIsSigned(true);
   2878       mangleNumber(Value);
   2879     }
   2880     Out << 'E';
   2881     break;
   2882   }
   2883 
   2884   case Expr::StringLiteralClass: {
   2885     // Revised proposal from David Vandervoorde, 2010.07.15.
   2886     Out << 'L';
   2887     assert(isa<ConstantArrayType>(E->getType()));
   2888     mangleType(E->getType());
   2889     Out << 'E';
   2890     break;
   2891   }
   2892 
   2893   case Expr::GNUNullExprClass:
   2894     // FIXME: should this really be mangled the same as nullptr?
   2895     // fallthrough
   2896 
   2897   case Expr::CXXNullPtrLiteralExprClass: {
   2898     // Proposal from David Vandervoorde, 2010.06.30, as
   2899     // modified by ABI list discussion.
   2900     Out << "LDnE";
   2901     break;
   2902   }
   2903 
   2904   case Expr::PackExpansionExprClass:
   2905     Out << "sp";
   2906     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
   2907     break;
   2908 
   2909   case Expr::SizeOfPackExprClass: {
   2910     Out << "sZ";
   2911     const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
   2912     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
   2913       mangleTemplateParameter(TTP->getIndex());
   2914     else if (const NonTypeTemplateParmDecl *NTTP
   2915                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
   2916       mangleTemplateParameter(NTTP->getIndex());
   2917     else if (const TemplateTemplateParmDecl *TempTP
   2918                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
   2919       mangleTemplateParameter(TempTP->getIndex());
   2920     else
   2921       mangleFunctionParam(cast<ParmVarDecl>(Pack));
   2922     break;
   2923   }
   2924 
   2925   case Expr::MaterializeTemporaryExprClass: {
   2926     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
   2927     break;
   2928   }
   2929 
   2930   case Expr::CXXThisExprClass:
   2931     Out << "fpT";
   2932     break;
   2933   }
   2934 }
   2935 
   2936 /// Mangle an expression which refers to a parameter variable.
   2937 ///
   2938 /// <expression>     ::= <function-param>
   2939 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
   2940 /// <function-param> ::= fp <top-level CV-qualifiers>
   2941 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
   2942 /// <function-param> ::= fL <L-1 non-negative number>
   2943 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
   2944 /// <function-param> ::= fL <L-1 non-negative number>
   2945 ///                      p <top-level CV-qualifiers>
   2946 ///                      <I-1 non-negative number> _         # L > 0, I > 0
   2947 ///
   2948 /// L is the nesting depth of the parameter, defined as 1 if the
   2949 /// parameter comes from the innermost function prototype scope
   2950 /// enclosing the current context, 2 if from the next enclosing
   2951 /// function prototype scope, and so on, with one special case: if
   2952 /// we've processed the full parameter clause for the innermost
   2953 /// function type, then L is one less.  This definition conveniently
   2954 /// makes it irrelevant whether a function's result type was written
   2955 /// trailing or leading, but is otherwise overly complicated; the
   2956 /// numbering was first designed without considering references to
   2957 /// parameter in locations other than return types, and then the
   2958 /// mangling had to be generalized without changing the existing
   2959 /// manglings.
   2960 ///
   2961 /// I is the zero-based index of the parameter within its parameter
   2962 /// declaration clause.  Note that the original ABI document describes
   2963 /// this using 1-based ordinals.
   2964 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
   2965   unsigned parmDepth = parm->getFunctionScopeDepth();
   2966   unsigned parmIndex = parm->getFunctionScopeIndex();
   2967 
   2968   // Compute 'L'.
   2969   // parmDepth does not include the declaring function prototype.
   2970   // FunctionTypeDepth does account for that.
   2971   assert(parmDepth < FunctionTypeDepth.getDepth());
   2972   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
   2973   if (FunctionTypeDepth.isInResultType())
   2974     nestingDepth--;
   2975 
   2976   if (nestingDepth == 0) {
   2977     Out << "fp";
   2978   } else {
   2979     Out << "fL" << (nestingDepth - 1) << 'p';
   2980   }
   2981 
   2982   // Top-level qualifiers.  We don't have to worry about arrays here,
   2983   // because parameters declared as arrays should already have been
   2984   // tranformed to have pointer type. FIXME: apparently these don't
   2985   // get mangled if used as an rvalue of a known non-class type?
   2986   assert(!parm->getType()->isArrayType()
   2987          && "parameter's type is still an array type?");
   2988   mangleQualifiers(parm->getType().getQualifiers());
   2989 
   2990   // Parameter index.
   2991   if (parmIndex != 0) {
   2992     Out << (parmIndex - 1);
   2993   }
   2994   Out << '_';
   2995 }
   2996 
   2997 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
   2998   // <ctor-dtor-name> ::= C1  # complete object constructor
   2999   //                  ::= C2  # base object constructor
   3000   //                  ::= C3  # complete object allocating constructor
   3001   //
   3002   switch (T) {
   3003   case Ctor_Complete:
   3004     Out << "C1";
   3005     break;
   3006   case Ctor_Base:
   3007     Out << "C2";
   3008     break;
   3009   case Ctor_CompleteAllocating:
   3010     Out << "C3";
   3011     break;
   3012   }
   3013 }
   3014 
   3015 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
   3016   // <ctor-dtor-name> ::= D0  # deleting destructor
   3017   //                  ::= D1  # complete object destructor
   3018   //                  ::= D2  # base object destructor
   3019   //
   3020   switch (T) {
   3021   case Dtor_Deleting:
   3022     Out << "D0";
   3023     break;
   3024   case Dtor_Complete:
   3025     Out << "D1";
   3026     break;
   3027   case Dtor_Base:
   3028     Out << "D2";
   3029     break;
   3030   }
   3031 }
   3032 
   3033 void CXXNameMangler::mangleTemplateArgs(
   3034                           const ASTTemplateArgumentListInfo &TemplateArgs) {
   3035   // <template-args> ::= I <template-arg>+ E
   3036   Out << 'I';
   3037   for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
   3038     mangleTemplateArg(0, TemplateArgs.getTemplateArgs()[i].getArgument());
   3039   Out << 'E';
   3040 }
   3041 
   3042 void CXXNameMangler::mangleTemplateArgs(TemplateName Template,
   3043                                         const TemplateArgument *TemplateArgs,
   3044                                         unsigned NumTemplateArgs) {
   3045   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   3046     return mangleTemplateArgs(*TD->getTemplateParameters(), TemplateArgs,
   3047                               NumTemplateArgs);
   3048 
   3049   mangleUnresolvedTemplateArgs(TemplateArgs, NumTemplateArgs);
   3050 }
   3051 
   3052 void CXXNameMangler::mangleUnresolvedTemplateArgs(const TemplateArgument *args,
   3053                                                   unsigned numArgs) {
   3054   // <template-args> ::= I <template-arg>+ E
   3055   Out << 'I';
   3056   for (unsigned i = 0; i != numArgs; ++i)
   3057     mangleTemplateArg(0, args[i]);
   3058   Out << 'E';
   3059 }
   3060 
   3061 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
   3062                                         const TemplateArgumentList &AL) {
   3063   // <template-args> ::= I <template-arg>+ E
   3064   Out << 'I';
   3065   for (unsigned i = 0, e = AL.size(); i != e; ++i)
   3066     mangleTemplateArg(PL.getParam(i), AL[i]);
   3067   Out << 'E';
   3068 }
   3069 
   3070 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
   3071                                         const TemplateArgument *TemplateArgs,
   3072                                         unsigned NumTemplateArgs) {
   3073   // <template-args> ::= I <template-arg>+ E
   3074   Out << 'I';
   3075   for (unsigned i = 0; i != NumTemplateArgs; ++i)
   3076     mangleTemplateArg(PL.getParam(i), TemplateArgs[i]);
   3077   Out << 'E';
   3078 }
   3079 
   3080 void CXXNameMangler::mangleTemplateArg(const NamedDecl *P,
   3081                                        TemplateArgument A) {
   3082   // <template-arg> ::= <type>              # type or template
   3083   //                ::= X <expression> E    # expression
   3084   //                ::= <expr-primary>      # simple expressions
   3085   //                ::= J <template-arg>* E # argument pack
   3086   //                ::= sp <expression>     # pack expansion of (C++0x)
   3087   if (!A.isInstantiationDependent() || A.isDependent())
   3088     A = Context.getASTContext().getCanonicalTemplateArgument(A);
   3089 
   3090   switch (A.getKind()) {
   3091   case TemplateArgument::Null:
   3092     llvm_unreachable("Cannot mangle NULL template argument");
   3093 
   3094   case TemplateArgument::Type:
   3095     mangleType(A.getAsType());
   3096     break;
   3097   case TemplateArgument::Template:
   3098     // This is mangled as <type>.
   3099     mangleType(A.getAsTemplate());
   3100     break;
   3101   case TemplateArgument::TemplateExpansion:
   3102     // <type>  ::= Dp <type>          # pack expansion (C++0x)
   3103     Out << "Dp";
   3104     mangleType(A.getAsTemplateOrTemplatePattern());
   3105     break;
   3106   case TemplateArgument::Expression: {
   3107     // It's possible to end up with a DeclRefExpr here in certain
   3108     // dependent cases, in which case we should mangle as a
   3109     // declaration.
   3110     const Expr *E = A.getAsExpr()->IgnoreParens();
   3111     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   3112       const ValueDecl *D = DRE->getDecl();
   3113       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
   3114         Out << "L";
   3115         mangle(D, "_Z");
   3116         Out << 'E';
   3117         break;
   3118       }
   3119     }
   3120 
   3121     Out << 'X';
   3122     mangleExpression(E);
   3123     Out << 'E';
   3124     break;
   3125   }
   3126   case TemplateArgument::Integral:
   3127     mangleIntegerLiteral(A.getIntegralType(), *A.getAsIntegral());
   3128     break;
   3129   case TemplateArgument::Declaration: {
   3130     assert(P && "Missing template parameter for declaration argument");
   3131     //  <expr-primary> ::= L <mangled-name> E # external name
   3132     //  <expr-primary> ::= L <type> 0 E
   3133     // Clang produces AST's where pointer-to-member-function expressions
   3134     // and pointer-to-function expressions are represented as a declaration not
   3135     // an expression. We compensate for it here to produce the correct mangling.
   3136     const NonTypeTemplateParmDecl *Parameter = cast<NonTypeTemplateParmDecl>(P);
   3137 
   3138     // Handle NULL pointer arguments.
   3139     if (!A.getAsDecl()) {
   3140       Out << "L";
   3141       mangleType(Parameter->getType());
   3142       Out << "0E";
   3143       break;
   3144     }
   3145 
   3146 
   3147     NamedDecl *D = cast<NamedDecl>(A.getAsDecl());
   3148     bool compensateMangling = !Parameter->getType()->isReferenceType();
   3149     if (compensateMangling) {
   3150       Out << 'X';
   3151       mangleOperatorName(OO_Amp, 1);
   3152     }
   3153 
   3154     Out << 'L';
   3155     // References to external entities use the mangled name; if the name would
   3156     // not normally be manged then mangle it as unqualified.
   3157     //
   3158     // FIXME: The ABI specifies that external names here should have _Z, but
   3159     // gcc leaves this off.
   3160     if (compensateMangling)
   3161       mangle(D, "_Z");
   3162     else
   3163       mangle(D, "Z");
   3164     Out << 'E';
   3165 
   3166     if (compensateMangling)
   3167       Out << 'E';
   3168 
   3169     break;
   3170   }
   3171 
   3172   case TemplateArgument::Pack: {
   3173     // Note: proposal by Mike Herrick on 12/20/10
   3174     Out << 'J';
   3175     for (TemplateArgument::pack_iterator PA = A.pack_begin(),
   3176                                       PAEnd = A.pack_end();
   3177          PA != PAEnd; ++PA)
   3178       mangleTemplateArg(P, *PA);
   3179     Out << 'E';
   3180   }
   3181   }
   3182 }
   3183 
   3184 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
   3185   // <template-param> ::= T_    # first template parameter
   3186   //                  ::= T <parameter-2 non-negative number> _
   3187   if (Index == 0)
   3188     Out << "T_";
   3189   else
   3190     Out << 'T' << (Index - 1) << '_';
   3191 }
   3192 
   3193 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
   3194   bool result = mangleSubstitution(type);
   3195   assert(result && "no existing substitution for type");
   3196   (void) result;
   3197 }
   3198 
   3199 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
   3200   bool result = mangleSubstitution(tname);
   3201   assert(result && "no existing substitution for template name");
   3202   (void) result;
   3203 }
   3204 
   3205 // <substitution> ::= S <seq-id> _
   3206 //                ::= S_
   3207 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
   3208   // Try one of the standard substitutions first.
   3209   if (mangleStandardSubstitution(ND))
   3210     return true;
   3211 
   3212   ND = cast<NamedDecl>(ND->getCanonicalDecl());
   3213   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
   3214 }
   3215 
   3216 /// \brief Determine whether the given type has any qualifiers that are
   3217 /// relevant for substitutions.
   3218 static bool hasMangledSubstitutionQualifiers(QualType T) {
   3219   Qualifiers Qs = T.getQualifiers();
   3220   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
   3221 }
   3222 
   3223 bool CXXNameMangler::mangleSubstitution(QualType T) {
   3224   if (!hasMangledSubstitutionQualifiers(T)) {
   3225     if (const RecordType *RT = T->getAs<RecordType>())
   3226       return mangleSubstitution(RT->getDecl());
   3227   }
   3228 
   3229   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
   3230 
   3231   return mangleSubstitution(TypePtr);
   3232 }
   3233 
   3234 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
   3235   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   3236     return mangleSubstitution(TD);
   3237 
   3238   Template = Context.getASTContext().getCanonicalTemplateName(Template);
   3239   return mangleSubstitution(
   3240                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
   3241 }
   3242 
   3243 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
   3244   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
   3245   if (I == Substitutions.end())
   3246     return false;
   3247 
   3248   unsigned SeqID = I->second;
   3249   if (SeqID == 0)
   3250     Out << "S_";
   3251   else {
   3252     SeqID--;
   3253 
   3254     // <seq-id> is encoded in base-36, using digits and upper case letters.
   3255     char Buffer[10];
   3256     char *BufferPtr = llvm::array_endof(Buffer);
   3257 
   3258     if (SeqID == 0) *--BufferPtr = '0';
   3259 
   3260     while (SeqID) {
   3261       assert(BufferPtr > Buffer && "Buffer overflow!");
   3262 
   3263       char c = static_cast<char>(SeqID % 36);
   3264 
   3265       *--BufferPtr =  (c < 10 ? '0' + c : 'A' + c - 10);
   3266       SeqID /= 36;
   3267     }
   3268 
   3269     Out << 'S'
   3270         << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
   3271         << '_';
   3272   }
   3273 
   3274   return true;
   3275 }
   3276 
   3277 static bool isCharType(QualType T) {
   3278   if (T.isNull())
   3279     return false;
   3280 
   3281   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
   3282     T->isSpecificBuiltinType(BuiltinType::Char_U);
   3283 }
   3284 
   3285 /// isCharSpecialization - Returns whether a given type is a template
   3286 /// specialization of a given name with a single argument of type char.
   3287 static bool isCharSpecialization(QualType T, const char *Name) {
   3288   if (T.isNull())
   3289     return false;
   3290 
   3291   const RecordType *RT = T->getAs<RecordType>();
   3292   if (!RT)
   3293     return false;
   3294 
   3295   const ClassTemplateSpecializationDecl *SD =
   3296     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
   3297   if (!SD)
   3298     return false;
   3299 
   3300   if (!isStdNamespace(getEffectiveDeclContext(SD)))
   3301     return false;
   3302 
   3303   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   3304   if (TemplateArgs.size() != 1)
   3305     return false;
   3306 
   3307   if (!isCharType(TemplateArgs[0].getAsType()))
   3308     return false;
   3309 
   3310   return SD->getIdentifier()->getName() == Name;
   3311 }
   3312 
   3313 template <std::size_t StrLen>
   3314 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
   3315                                        const char (&Str)[StrLen]) {
   3316   if (!SD->getIdentifier()->isStr(Str))
   3317     return false;
   3318 
   3319   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   3320   if (TemplateArgs.size() != 2)
   3321     return false;
   3322 
   3323   if (!isCharType(TemplateArgs[0].getAsType()))
   3324     return false;
   3325 
   3326   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
   3327     return false;
   3328 
   3329   return true;
   3330 }
   3331 
   3332 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
   3333   // <substitution> ::= St # ::std::
   3334   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
   3335     if (isStd(NS)) {
   3336       Out << "St";
   3337       return true;
   3338     }
   3339   }
   3340 
   3341   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
   3342     if (!isStdNamespace(getEffectiveDeclContext(TD)))
   3343       return false;
   3344 
   3345     // <substitution> ::= Sa # ::std::allocator
   3346     if (TD->getIdentifier()->isStr("allocator")) {
   3347       Out << "Sa";
   3348       return true;
   3349     }
   3350 
   3351     // <<substitution> ::= Sb # ::std::basic_string
   3352     if (TD->getIdentifier()->isStr("basic_string")) {
   3353       Out << "Sb";
   3354       return true;
   3355     }
   3356   }
   3357 
   3358   if (const ClassTemplateSpecializationDecl *SD =
   3359         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
   3360     if (!isStdNamespace(getEffectiveDeclContext(SD)))
   3361       return false;
   3362 
   3363     //    <substitution> ::= Ss # ::std::basic_string<char,
   3364     //                            ::std::char_traits<char>,
   3365     //                            ::std::allocator<char> >
   3366     if (SD->getIdentifier()->isStr("basic_string")) {
   3367       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
   3368 
   3369       if (TemplateArgs.size() != 3)
   3370         return false;
   3371 
   3372       if (!isCharType(TemplateArgs[0].getAsType()))
   3373         return false;
   3374 
   3375       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
   3376         return false;
   3377 
   3378       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
   3379         return false;
   3380 
   3381       Out << "Ss";
   3382       return true;
   3383     }
   3384 
   3385     //    <substitution> ::= Si # ::std::basic_istream<char,
   3386     //                            ::std::char_traits<char> >
   3387     if (isStreamCharSpecialization(SD, "basic_istream")) {
   3388       Out << "Si";
   3389       return true;
   3390     }
   3391 
   3392     //    <substitution> ::= So # ::std::basic_ostream<char,
   3393     //                            ::std::char_traits<char> >
   3394     if (isStreamCharSpecialization(SD, "basic_ostream")) {
   3395       Out << "So";
   3396       return true;
   3397     }
   3398 
   3399     //    <substitution> ::= Sd # ::std::basic_iostream<char,
   3400     //                            ::std::char_traits<char> >
   3401     if (isStreamCharSpecialization(SD, "basic_iostream")) {
   3402       Out << "Sd";
   3403       return true;
   3404     }
   3405   }
   3406   return false;
   3407 }
   3408 
   3409 void CXXNameMangler::addSubstitution(QualType T) {
   3410   if (!hasMangledSubstitutionQualifiers(T)) {
   3411     if (const RecordType *RT = T->getAs<RecordType>()) {
   3412       addSubstitution(RT->getDecl());
   3413       return;
   3414     }
   3415   }
   3416 
   3417   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
   3418   addSubstitution(TypePtr);
   3419 }
   3420 
   3421 void CXXNameMangler::addSubstitution(TemplateName Template) {
   3422   if (TemplateDecl *TD = Template.getAsTemplateDecl())
   3423     return addSubstitution(TD);
   3424 
   3425   Template = Context.getASTContext().getCanonicalTemplateName(Template);
   3426   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
   3427 }
   3428 
   3429 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
   3430   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
   3431   Substitutions[Ptr] = SeqID++;
   3432 }
   3433 
   3434 //
   3435 
   3436 /// \brief Mangles the name of the declaration D and emits that name to the
   3437 /// given output stream.
   3438 ///
   3439 /// If the declaration D requires a mangled name, this routine will emit that
   3440 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
   3441 /// and this routine will return false. In this case, the caller should just
   3442 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
   3443 /// name.
   3444 void ItaniumMangleContext::mangleName(const NamedDecl *D,
   3445                                       raw_ostream &Out) {
   3446   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
   3447           "Invalid mangleName() call, argument is not a variable or function!");
   3448   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
   3449          "Invalid mangleName() call on 'structor decl!");
   3450 
   3451   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
   3452                                  getASTContext().getSourceManager(),
   3453                                  "Mangling declaration");
   3454 
   3455   CXXNameMangler Mangler(*this, Out, D);
   3456   return Mangler.mangle(D);
   3457 }
   3458 
   3459 void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
   3460                                          CXXCtorType Type,
   3461                                          raw_ostream &Out) {
   3462   CXXNameMangler Mangler(*this, Out, D, Type);
   3463   Mangler.mangle(D);
   3464 }
   3465 
   3466 void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
   3467                                          CXXDtorType Type,
   3468                                          raw_ostream &Out) {
   3469   CXXNameMangler Mangler(*this, Out, D, Type);
   3470   Mangler.mangle(D);
   3471 }
   3472 
   3473 void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
   3474                                        const ThunkInfo &Thunk,
   3475                                        raw_ostream &Out) {
   3476   //  <special-name> ::= T <call-offset> <base encoding>
   3477   //                      # base is the nominal target function of thunk
   3478   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
   3479   //                      # base is the nominal target function of thunk
   3480   //                      # first call-offset is 'this' adjustment
   3481   //                      # second call-offset is result adjustment
   3482 
   3483   assert(!isa<CXXDestructorDecl>(MD) &&
   3484          "Use mangleCXXDtor for destructor decls!");
   3485   CXXNameMangler Mangler(*this, Out);
   3486   Mangler.getStream() << "_ZT";
   3487   if (!Thunk.Return.isEmpty())
   3488     Mangler.getStream() << 'c';
   3489 
   3490   // Mangle the 'this' pointer adjustment.
   3491   Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
   3492 
   3493   // Mangle the return pointer adjustment if there is one.
   3494   if (!Thunk.Return.isEmpty())
   3495     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
   3496                              Thunk.Return.VBaseOffsetOffset);
   3497 
   3498   Mangler.mangleFunctionEncoding(MD);
   3499 }
   3500 
   3501 void
   3502 ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
   3503                                          CXXDtorType Type,
   3504                                          const ThisAdjustment &ThisAdjustment,
   3505                                          raw_ostream &Out) {
   3506   //  <special-name> ::= T <call-offset> <base encoding>
   3507   //                      # base is the nominal target function of thunk
   3508   CXXNameMangler Mangler(*this, Out, DD, Type);
   3509   Mangler.getStream() << "_ZT";
   3510 
   3511   // Mangle the 'this' pointer adjustment.
   3512   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
   3513                            ThisAdjustment.VCallOffsetOffset);
   3514 
   3515   Mangler.mangleFunctionEncoding(DD);
   3516 }
   3517 
   3518 /// mangleGuardVariable - Returns the mangled name for a guard variable
   3519 /// for the passed in VarDecl.
   3520 void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
   3521                                                       raw_ostream &Out) {
   3522   //  <special-name> ::= GV <object name>       # Guard variable for one-time
   3523   //                                            # initialization
   3524   CXXNameMangler Mangler(*this, Out);
   3525   Mangler.getStream() << "_ZGV";
   3526   Mangler.mangleName(D);
   3527 }
   3528 
   3529 void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
   3530                                                     raw_ostream &Out) {
   3531   // We match the GCC mangling here.
   3532   //  <special-name> ::= GR <object name>
   3533   CXXNameMangler Mangler(*this, Out);
   3534   Mangler.getStream() << "_ZGR";
   3535   Mangler.mangleName(D);
   3536 }
   3537 
   3538 void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
   3539                                            raw_ostream &Out) {
   3540   // <special-name> ::= TV <type>  # virtual table
   3541   CXXNameMangler Mangler(*this, Out);
   3542   Mangler.getStream() << "_ZTV";
   3543   Mangler.mangleNameOrStandardSubstitution(RD);
   3544 }
   3545 
   3546 void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
   3547                                         raw_ostream &Out) {
   3548   // <special-name> ::= TT <type>  # VTT structure
   3549   CXXNameMangler Mangler(*this, Out);
   3550   Mangler.getStream() << "_ZTT";
   3551   Mangler.mangleNameOrStandardSubstitution(RD);
   3552 }
   3553 
   3554 void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
   3555                                                int64_t Offset,
   3556                                                const CXXRecordDecl *Type,
   3557                                                raw_ostream &Out) {
   3558   // <special-name> ::= TC <type> <offset number> _ <base type>
   3559   CXXNameMangler Mangler(*this, Out);
   3560   Mangler.getStream() << "_ZTC";
   3561   Mangler.mangleNameOrStandardSubstitution(RD);
   3562   Mangler.getStream() << Offset;
   3563   Mangler.getStream() << '_';
   3564   Mangler.mangleNameOrStandardSubstitution(Type);
   3565 }
   3566 
   3567 void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
   3568                                          raw_ostream &Out) {
   3569   // <special-name> ::= TI <type>  # typeinfo structure
   3570   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
   3571   CXXNameMangler Mangler(*this, Out);
   3572   Mangler.getStream() << "_ZTI";
   3573   Mangler.mangleType(Ty);
   3574 }
   3575 
   3576 void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
   3577                                              raw_ostream &Out) {
   3578   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
   3579   CXXNameMangler Mangler(*this, Out);
   3580   Mangler.getStream() << "_ZTS";
   3581   Mangler.mangleType(Ty);
   3582 }
   3583 
   3584 MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
   3585                                                  DiagnosticsEngine &Diags) {
   3586   return new ItaniumMangleContext(Context, Diags);
   3587 }
   3588