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