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