clang API Documentation

ItaniumMangle.cpp
Go to the documentation of this file.
00001 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implements C++ name mangling according to the Itanium C++ ABI,
00011 // which is used in GCC 3.2 and newer (and many compilers that are
00012 // ABI-compatible with GCC):
00013 //
00014 //   http://mentorembedded.github.io/cxx-abi/abi.html#mangling
00015 //
00016 //===----------------------------------------------------------------------===//
00017 #include "clang/AST/Mangle.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/Attr.h"
00020 #include "clang/AST/Decl.h"
00021 #include "clang/AST/DeclCXX.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/DeclTemplate.h"
00024 #include "clang/AST/Expr.h"
00025 #include "clang/AST/ExprCXX.h"
00026 #include "clang/AST/ExprObjC.h"
00027 #include "clang/AST/TypeLoc.h"
00028 #include "clang/Basic/ABI.h"
00029 #include "clang/Basic/SourceManager.h"
00030 #include "clang/Basic/TargetInfo.h"
00031 #include "llvm/ADT/StringExtras.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 
00035 #define MANGLE_CHECKER 0
00036 
00037 #if MANGLE_CHECKER
00038 #include <cxxabi.h>
00039 #endif
00040 
00041 using namespace clang;
00042 
00043 namespace {
00044 
00045 /// \brief Retrieve the declaration context that should be used when mangling 
00046 /// the given declaration.
00047 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
00048   // The ABI assumes that lambda closure types that occur within 
00049   // default arguments live in the context of the function. However, due to
00050   // the way in which Clang parses and creates function declarations, this is
00051   // not the case: the lambda closure type ends up living in the context 
00052   // where the function itself resides, because the function declaration itself
00053   // had not yet been created. Fix the context here.
00054   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
00055     if (RD->isLambda())
00056       if (ParmVarDecl *ContextParam
00057             = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
00058         return ContextParam->getDeclContext();
00059   }
00060 
00061   // Perform the same check for block literals.
00062   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
00063     if (ParmVarDecl *ContextParam
00064           = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
00065       return ContextParam->getDeclContext();
00066   }
00067   
00068   const DeclContext *DC = D->getDeclContext();
00069   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
00070     return getEffectiveDeclContext(CD);
00071 
00072   return DC;
00073 }
00074 
00075 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
00076   return getEffectiveDeclContext(cast<Decl>(DC));
00077 }
00078 
00079 static bool isLocalContainerContext(const DeclContext *DC) {
00080   return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
00081 }
00082 
00083 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
00084   const DeclContext *DC = getEffectiveDeclContext(D);
00085   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
00086     if (isLocalContainerContext(DC))
00087       return dyn_cast<RecordDecl>(D);
00088     D = cast<Decl>(DC);
00089     DC = getEffectiveDeclContext(D);
00090   }
00091   return nullptr;
00092 }
00093 
00094 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
00095   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
00096     return ftd->getTemplatedDecl();
00097 
00098   return fn;
00099 }
00100 
00101 static const NamedDecl *getStructor(const NamedDecl *decl) {
00102   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
00103   return (fn ? getStructor(fn) : decl);
00104 }
00105 
00106 static bool isLambda(const NamedDecl *ND) {
00107   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
00108   if (!Record)
00109     return false;
00110 
00111   return Record->isLambda();
00112 }
00113 
00114 static const unsigned UnknownArity = ~0U;
00115 
00116 class ItaniumMangleContextImpl : public ItaniumMangleContext {
00117   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
00118   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
00119   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
00120   
00121 public:
00122   explicit ItaniumMangleContextImpl(ASTContext &Context,
00123                                     DiagnosticsEngine &Diags)
00124       : ItaniumMangleContext(Context, Diags) {}
00125 
00126   /// @name Mangler Entry Points
00127   /// @{
00128 
00129   bool shouldMangleCXXName(const NamedDecl *D) override;
00130   bool shouldMangleStringLiteral(const StringLiteral *) override {
00131     return false;
00132   }
00133   void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
00134   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
00135                    raw_ostream &) override;
00136   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
00137                           const ThisAdjustment &ThisAdjustment,
00138                           raw_ostream &) override;
00139   void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
00140                                 raw_ostream &) override;
00141   void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
00142   void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
00143   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
00144                            const CXXRecordDecl *Type, raw_ostream &) override;
00145   void mangleCXXRTTI(QualType T, raw_ostream &) override;
00146   void mangleCXXRTTIName(QualType T, raw_ostream &) override;
00147   void mangleTypeName(QualType T, raw_ostream &) override;
00148   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
00149                      raw_ostream &) override;
00150   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
00151                      raw_ostream &) override;
00152 
00153   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
00154   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
00155   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
00156   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
00157   void mangleDynamicAtExitDestructor(const VarDecl *D,
00158                                      raw_ostream &Out) override;
00159   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
00160   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
00161                                        raw_ostream &) override;
00162 
00163   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
00164 
00165   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
00166     // Lambda closure types are already numbered.
00167     if (isLambda(ND))
00168       return false;
00169 
00170     // Anonymous tags are already numbered.
00171     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
00172       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
00173         return false;
00174     }
00175 
00176     // Use the canonical number for externally visible decls.
00177     if (ND->isExternallyVisible()) {
00178       unsigned discriminator = getASTContext().getManglingNumber(ND);
00179       if (discriminator == 1)
00180         return false;
00181       disc = discriminator - 2;
00182       return true;
00183     }
00184 
00185     // Make up a reasonable number for internal decls.
00186     unsigned &discriminator = Uniquifier[ND];
00187     if (!discriminator) {
00188       const DeclContext *DC = getEffectiveDeclContext(ND);
00189       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
00190     }
00191     if (discriminator == 1)
00192       return false;
00193     disc = discriminator-2;
00194     return true;
00195   }
00196   /// @}
00197 };
00198 
00199 /// CXXNameMangler - Manage the mangling of a single name.
00200 class CXXNameMangler {
00201   ItaniumMangleContextImpl &Context;
00202   raw_ostream &Out;
00203 
00204   /// The "structor" is the top-level declaration being mangled, if
00205   /// that's not a template specialization; otherwise it's the pattern
00206   /// for that specialization.
00207   const NamedDecl *Structor;
00208   unsigned StructorType;
00209 
00210   /// SeqID - The next subsitution sequence number.
00211   unsigned SeqID;
00212 
00213   class FunctionTypeDepthState {
00214     unsigned Bits;
00215 
00216     enum { InResultTypeMask = 1 };
00217 
00218   public:
00219     FunctionTypeDepthState() : Bits(0) {}
00220 
00221     /// The number of function types we're inside.
00222     unsigned getDepth() const {
00223       return Bits >> 1;
00224     }
00225 
00226     /// True if we're in the return type of the innermost function type.
00227     bool isInResultType() const {
00228       return Bits & InResultTypeMask;
00229     }
00230 
00231     FunctionTypeDepthState push() {
00232       FunctionTypeDepthState tmp = *this;
00233       Bits = (Bits & ~InResultTypeMask) + 2;
00234       return tmp;
00235     }
00236 
00237     void enterResultType() {
00238       Bits |= InResultTypeMask;
00239     }
00240 
00241     void leaveResultType() {
00242       Bits &= ~InResultTypeMask;
00243     }
00244 
00245     void pop(FunctionTypeDepthState saved) {
00246       assert(getDepth() == saved.getDepth() + 1);
00247       Bits = saved.Bits;
00248     }
00249 
00250   } FunctionTypeDepth;
00251 
00252   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
00253 
00254   ASTContext &getASTContext() const { return Context.getASTContext(); }
00255 
00256 public:
00257   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
00258                  const NamedDecl *D = nullptr)
00259     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
00260       SeqID(0) {
00261     // These can't be mangled without a ctor type or dtor type.
00262     assert(!D || (!isa<CXXDestructorDecl>(D) &&
00263                   !isa<CXXConstructorDecl>(D)));
00264   }
00265   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
00266                  const CXXConstructorDecl *D, CXXCtorType Type)
00267     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
00268       SeqID(0) { }
00269   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
00270                  const CXXDestructorDecl *D, CXXDtorType Type)
00271     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
00272       SeqID(0) { }
00273 
00274 #if MANGLE_CHECKER
00275   ~CXXNameMangler() {
00276     if (Out.str()[0] == '\01')
00277       return;
00278 
00279     int status = 0;
00280     char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
00281     assert(status == 0 && "Could not demangle mangled name!");
00282     free(result);
00283   }
00284 #endif
00285   raw_ostream &getStream() { return Out; }
00286 
00287   void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
00288   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
00289   void mangleNumber(const llvm::APSInt &I);
00290   void mangleNumber(int64_t Number);
00291   void mangleFloat(const llvm::APFloat &F);
00292   void mangleFunctionEncoding(const FunctionDecl *FD);
00293   void mangleSeqID(unsigned SeqID);
00294   void mangleName(const NamedDecl *ND);
00295   void mangleType(QualType T);
00296   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
00297   
00298 private:
00299 
00300   bool mangleSubstitution(const NamedDecl *ND);
00301   bool mangleSubstitution(QualType T);
00302   bool mangleSubstitution(TemplateName Template);
00303   bool mangleSubstitution(uintptr_t Ptr);
00304 
00305   void mangleExistingSubstitution(QualType type);
00306   void mangleExistingSubstitution(TemplateName name);
00307 
00308   bool mangleStandardSubstitution(const NamedDecl *ND);
00309 
00310   void addSubstitution(const NamedDecl *ND) {
00311     ND = cast<NamedDecl>(ND->getCanonicalDecl());
00312 
00313     addSubstitution(reinterpret_cast<uintptr_t>(ND));
00314   }
00315   void addSubstitution(QualType T);
00316   void addSubstitution(TemplateName Template);
00317   void addSubstitution(uintptr_t Ptr);
00318 
00319   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
00320                               NamedDecl *firstQualifierLookup,
00321                               bool recursive = false);
00322   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
00323                             NamedDecl *firstQualifierLookup,
00324                             DeclarationName name,
00325                             unsigned KnownArity = UnknownArity);
00326 
00327   void mangleName(const TemplateDecl *TD,
00328                   const TemplateArgument *TemplateArgs,
00329                   unsigned NumTemplateArgs);
00330   void mangleUnqualifiedName(const NamedDecl *ND) {
00331     mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
00332   }
00333   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
00334                              unsigned KnownArity);
00335   void mangleUnscopedName(const NamedDecl *ND);
00336   void mangleUnscopedTemplateName(const TemplateDecl *ND);
00337   void mangleUnscopedTemplateName(TemplateName);
00338   void mangleSourceName(const IdentifierInfo *II);
00339   void mangleLocalName(const Decl *D);
00340   void mangleBlockForPrefix(const BlockDecl *Block);
00341   void mangleUnqualifiedBlock(const BlockDecl *Block);
00342   void mangleLambda(const CXXRecordDecl *Lambda);
00343   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
00344                         bool NoFunction=false);
00345   void mangleNestedName(const TemplateDecl *TD,
00346                         const TemplateArgument *TemplateArgs,
00347                         unsigned NumTemplateArgs);
00348   void manglePrefix(NestedNameSpecifier *qualifier);
00349   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
00350   void manglePrefix(QualType type);
00351   void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
00352   void mangleTemplatePrefix(TemplateName Template);
00353   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
00354   void mangleQualifiers(Qualifiers Quals);
00355   void mangleRefQualifier(RefQualifierKind RefQualifier);
00356 
00357   void mangleObjCMethodName(const ObjCMethodDecl *MD);
00358 
00359   // Declare manglers for every type class.
00360 #define ABSTRACT_TYPE(CLASS, PARENT)
00361 #define NON_CANONICAL_TYPE(CLASS, PARENT)
00362 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
00363 #include "clang/AST/TypeNodes.def"
00364 
00365   void mangleType(const TagType*);
00366   void mangleType(TemplateName);
00367   void mangleBareFunctionType(const FunctionType *T,
00368                               bool MangleReturnType);
00369   void mangleNeonVectorType(const VectorType *T);
00370   void mangleAArch64NeonVectorType(const VectorType *T);
00371 
00372   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
00373   void mangleMemberExpr(const Expr *base, bool isArrow,
00374                         NestedNameSpecifier *qualifier,
00375                         NamedDecl *firstQualifierLookup,
00376                         DeclarationName name,
00377                         unsigned knownArity);
00378   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
00379   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
00380   void mangleCXXCtorType(CXXCtorType T);
00381   void mangleCXXDtorType(CXXDtorType T);
00382 
00383   void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
00384   void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
00385                           unsigned NumTemplateArgs);
00386   void mangleTemplateArgs(const TemplateArgumentList &AL);
00387   void mangleTemplateArg(TemplateArgument A);
00388 
00389   void mangleTemplateParameter(unsigned Index);
00390 
00391   void mangleFunctionParam(const ParmVarDecl *parm);
00392 };
00393 
00394 }
00395 
00396 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
00397   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
00398   if (FD) {
00399     LanguageLinkage L = FD->getLanguageLinkage();
00400     // Overloadable functions need mangling.
00401     if (FD->hasAttr<OverloadableAttr>())
00402       return true;
00403 
00404     // "main" is not mangled.
00405     if (FD->isMain())
00406       return false;
00407 
00408     // C++ functions and those whose names are not a simple identifier need
00409     // mangling.
00410     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
00411       return true;
00412 
00413     // C functions are not mangled.
00414     if (L == CLanguageLinkage)
00415       return false;
00416   }
00417 
00418   // Otherwise, no mangling is done outside C++ mode.
00419   if (!getASTContext().getLangOpts().CPlusPlus)
00420     return false;
00421 
00422   const VarDecl *VD = dyn_cast<VarDecl>(D);
00423   if (VD) {
00424     // C variables are not mangled.
00425     if (VD->isExternC())
00426       return false;
00427 
00428     // Variables at global scope with non-internal linkage are not mangled
00429     const DeclContext *DC = getEffectiveDeclContext(D);
00430     // Check for extern variable declared locally.
00431     if (DC->isFunctionOrMethod() && D->hasLinkage())
00432       while (!DC->isNamespace() && !DC->isTranslationUnit())
00433         DC = getEffectiveParentContext(DC);
00434     if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
00435         !isa<VarTemplateSpecializationDecl>(D))
00436       return false;
00437   }
00438 
00439   return true;
00440 }
00441 
00442 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
00443   // <mangled-name> ::= _Z <encoding>
00444   //            ::= <data name>
00445   //            ::= <special-name>
00446   Out << Prefix;
00447   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
00448     mangleFunctionEncoding(FD);
00449   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
00450     mangleName(VD);
00451   else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
00452     mangleName(IFD->getAnonField());
00453   else
00454     mangleName(cast<FieldDecl>(D));
00455 }
00456 
00457 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
00458   // <encoding> ::= <function name> <bare-function-type>
00459   mangleName(FD);
00460 
00461   // Don't mangle in the type if this isn't a decl we should typically mangle.
00462   if (!Context.shouldMangleDeclName(FD))
00463     return;
00464 
00465   if (FD->hasAttr<EnableIfAttr>()) {
00466     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
00467     Out << "Ua9enable_ifI";
00468     // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
00469     // it here.
00470     for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
00471                                          E = FD->getAttrs().rend();
00472          I != E; ++I) {
00473       EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
00474       if (!EIA)
00475         continue;
00476       Out << 'X';
00477       mangleExpression(EIA->getCond());
00478       Out << 'E';
00479     }
00480     Out << 'E';
00481     FunctionTypeDepth.pop(Saved);
00482   }
00483 
00484   // Whether the mangling of a function type includes the return type depends on
00485   // the context and the nature of the function. The rules for deciding whether
00486   // the return type is included are:
00487   //
00488   //   1. Template functions (names or types) have return types encoded, with
00489   //   the exceptions listed below.
00490   //   2. Function types not appearing as part of a function name mangling,
00491   //   e.g. parameters, pointer types, etc., have return type encoded, with the
00492   //   exceptions listed below.
00493   //   3. Non-template function names do not have return types encoded.
00494   //
00495   // The exceptions mentioned in (1) and (2) above, for which the return type is
00496   // never included, are
00497   //   1. Constructors.
00498   //   2. Destructors.
00499   //   3. Conversion operator functions, e.g. operator int.
00500   bool MangleReturnType = false;
00501   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
00502     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
00503           isa<CXXConversionDecl>(FD)))
00504       MangleReturnType = true;
00505 
00506     // Mangle the type of the primary template.
00507     FD = PrimaryTemplate->getTemplatedDecl();
00508   }
00509 
00510   mangleBareFunctionType(FD->getType()->getAs<FunctionType>(), 
00511                          MangleReturnType);
00512 }
00513 
00514 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
00515   while (isa<LinkageSpecDecl>(DC)) {
00516     DC = getEffectiveParentContext(DC);
00517   }
00518 
00519   return DC;
00520 }
00521 
00522 /// isStd - Return whether a given namespace is the 'std' namespace.
00523 static bool isStd(const NamespaceDecl *NS) {
00524   if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
00525                                 ->isTranslationUnit())
00526     return false;
00527   
00528   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
00529   return II && II->isStr("std");
00530 }
00531 
00532 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
00533 // namespace.
00534 static bool isStdNamespace(const DeclContext *DC) {
00535   if (!DC->isNamespace())
00536     return false;
00537 
00538   return isStd(cast<NamespaceDecl>(DC));
00539 }
00540 
00541 static const TemplateDecl *
00542 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
00543   // Check if we have a function template.
00544   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
00545     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
00546       TemplateArgs = FD->getTemplateSpecializationArgs();
00547       return TD;
00548     }
00549   }
00550 
00551   // Check if we have a class template.
00552   if (const ClassTemplateSpecializationDecl *Spec =
00553         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
00554     TemplateArgs = &Spec->getTemplateArgs();
00555     return Spec->getSpecializedTemplate();
00556   }
00557 
00558   // Check if we have a variable template.
00559   if (const VarTemplateSpecializationDecl *Spec =
00560           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
00561     TemplateArgs = &Spec->getTemplateArgs();
00562     return Spec->getSpecializedTemplate();
00563   }
00564 
00565   return nullptr;
00566 }
00567 
00568 void CXXNameMangler::mangleName(const NamedDecl *ND) {
00569   //  <name> ::= <nested-name>
00570   //         ::= <unscoped-name>
00571   //         ::= <unscoped-template-name> <template-args>
00572   //         ::= <local-name>
00573   //
00574   const DeclContext *DC = getEffectiveDeclContext(ND);
00575 
00576   // If this is an extern variable declared locally, the relevant DeclContext
00577   // is that of the containing namespace, or the translation unit.
00578   // FIXME: This is a hack; extern variables declared locally should have
00579   // a proper semantic declaration context!
00580   if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
00581     while (!DC->isNamespace() && !DC->isTranslationUnit())
00582       DC = getEffectiveParentContext(DC);
00583   else if (GetLocalClassDecl(ND)) {
00584     mangleLocalName(ND);
00585     return;
00586   }
00587 
00588   DC = IgnoreLinkageSpecDecls(DC);
00589 
00590   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
00591     // Check if we have a template.
00592     const TemplateArgumentList *TemplateArgs = nullptr;
00593     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
00594       mangleUnscopedTemplateName(TD);
00595       mangleTemplateArgs(*TemplateArgs);
00596       return;
00597     }
00598 
00599     mangleUnscopedName(ND);
00600     return;
00601   }
00602 
00603   if (isLocalContainerContext(DC)) {
00604     mangleLocalName(ND);
00605     return;
00606   }
00607 
00608   mangleNestedName(ND, DC);
00609 }
00610 void CXXNameMangler::mangleName(const TemplateDecl *TD,
00611                                 const TemplateArgument *TemplateArgs,
00612                                 unsigned NumTemplateArgs) {
00613   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
00614 
00615   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
00616     mangleUnscopedTemplateName(TD);
00617     mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
00618   } else {
00619     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
00620   }
00621 }
00622 
00623 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
00624   //  <unscoped-name> ::= <unqualified-name>
00625   //                  ::= St <unqualified-name>   # ::std::
00626 
00627   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
00628     Out << "St";
00629 
00630   mangleUnqualifiedName(ND);
00631 }
00632 
00633 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
00634   //     <unscoped-template-name> ::= <unscoped-name>
00635   //                              ::= <substitution>
00636   if (mangleSubstitution(ND))
00637     return;
00638 
00639   // <template-template-param> ::= <template-param>
00640   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
00641     mangleTemplateParameter(TTP->getIndex());
00642   else
00643     mangleUnscopedName(ND->getTemplatedDecl());
00644 
00645   addSubstitution(ND);
00646 }
00647 
00648 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
00649   //     <unscoped-template-name> ::= <unscoped-name>
00650   //                              ::= <substitution>
00651   if (TemplateDecl *TD = Template.getAsTemplateDecl())
00652     return mangleUnscopedTemplateName(TD);
00653   
00654   if (mangleSubstitution(Template))
00655     return;
00656 
00657   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
00658   assert(Dependent && "Not a dependent template name?");
00659   if (const IdentifierInfo *Id = Dependent->getIdentifier())
00660     mangleSourceName(Id);
00661   else
00662     mangleOperatorName(Dependent->getOperator(), UnknownArity);
00663   
00664   addSubstitution(Template);
00665 }
00666 
00667 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
00668   // ABI:
00669   //   Floating-point literals are encoded using a fixed-length
00670   //   lowercase hexadecimal string corresponding to the internal
00671   //   representation (IEEE on Itanium), high-order bytes first,
00672   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
00673   //   on Itanium.
00674   // The 'without leading zeroes' thing seems to be an editorial
00675   // mistake; see the discussion on cxx-abi-dev beginning on
00676   // 2012-01-16.
00677 
00678   // Our requirements here are just barely weird enough to justify
00679   // using a custom algorithm instead of post-processing APInt::toString().
00680 
00681   llvm::APInt valueBits = f.bitcastToAPInt();
00682   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
00683   assert(numCharacters != 0);
00684 
00685   // Allocate a buffer of the right number of characters.
00686   SmallVector<char, 20> buffer;
00687   buffer.set_size(numCharacters);
00688 
00689   // Fill the buffer left-to-right.
00690   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
00691     // The bit-index of the next hex digit.
00692     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
00693 
00694     // Project out 4 bits starting at 'digitIndex'.
00695     llvm::integerPart hexDigit
00696       = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
00697     hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
00698     hexDigit &= 0xF;
00699 
00700     // Map that over to a lowercase hex digit.
00701     static const char charForHex[16] = {
00702       '0', '1', '2', '3', '4', '5', '6', '7',
00703       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
00704     };
00705     buffer[stringIndex] = charForHex[hexDigit];
00706   }
00707 
00708   Out.write(buffer.data(), numCharacters);
00709 }
00710 
00711 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
00712   if (Value.isSigned() && Value.isNegative()) {
00713     Out << 'n';
00714     Value.abs().print(Out, /*signed*/ false);
00715   } else {
00716     Value.print(Out, /*signed*/ false);
00717   }
00718 }
00719 
00720 void CXXNameMangler::mangleNumber(int64_t Number) {
00721   //  <number> ::= [n] <non-negative decimal integer>
00722   if (Number < 0) {
00723     Out << 'n';
00724     Number = -Number;
00725   }
00726 
00727   Out << Number;
00728 }
00729 
00730 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
00731   //  <call-offset>  ::= h <nv-offset> _
00732   //                 ::= v <v-offset> _
00733   //  <nv-offset>    ::= <offset number>        # non-virtual base override
00734   //  <v-offset>     ::= <offset number> _ <virtual offset number>
00735   //                      # virtual base override, with vcall offset
00736   if (!Virtual) {
00737     Out << 'h';
00738     mangleNumber(NonVirtual);
00739     Out << '_';
00740     return;
00741   }
00742 
00743   Out << 'v';
00744   mangleNumber(NonVirtual);
00745   Out << '_';
00746   mangleNumber(Virtual);
00747   Out << '_';
00748 }
00749 
00750 void CXXNameMangler::manglePrefix(QualType type) {
00751   if (const TemplateSpecializationType *TST =
00752         type->getAs<TemplateSpecializationType>()) {
00753     if (!mangleSubstitution(QualType(TST, 0))) {
00754       mangleTemplatePrefix(TST->getTemplateName());
00755         
00756       // FIXME: GCC does not appear to mangle the template arguments when
00757       // the template in question is a dependent template name. Should we
00758       // emulate that badness?
00759       mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
00760       addSubstitution(QualType(TST, 0));
00761     }
00762   } else if (const DependentTemplateSpecializationType *DTST
00763                = type->getAs<DependentTemplateSpecializationType>()) {
00764     TemplateName Template
00765       = getASTContext().getDependentTemplateName(DTST->getQualifier(), 
00766                                                  DTST->getIdentifier());
00767     mangleTemplatePrefix(Template);
00768 
00769     // FIXME: GCC does not appear to mangle the template arguments when
00770     // the template in question is a dependent template name. Should we
00771     // emulate that badness?
00772     mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
00773   } else {
00774     // We use the QualType mangle type variant here because it handles
00775     // substitutions.
00776     mangleType(type);
00777   }
00778 }
00779 
00780 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
00781 ///
00782 /// \param firstQualifierLookup - the entity found by unqualified lookup
00783 ///   for the first name in the qualifier, if this is for a member expression
00784 /// \param recursive - true if this is being called recursively,
00785 ///   i.e. if there is more prefix "to the right".
00786 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
00787                                             NamedDecl *firstQualifierLookup,
00788                                             bool recursive) {
00789 
00790   // x, ::x
00791   // <unresolved-name> ::= [gs] <base-unresolved-name>
00792 
00793   // T::x / decltype(p)::x
00794   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
00795 
00796   // T::N::x /decltype(p)::N::x
00797   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
00798   //                       <base-unresolved-name>
00799 
00800   // A::x, N::y, A<T>::z; "gs" means leading "::"
00801   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
00802   //                       <base-unresolved-name>
00803 
00804   switch (qualifier->getKind()) {
00805   case NestedNameSpecifier::Global:
00806     Out << "gs";
00807 
00808     // We want an 'sr' unless this is the entire NNS.
00809     if (recursive)
00810       Out << "sr";
00811 
00812     // We never want an 'E' here.
00813     return;
00814 
00815   case NestedNameSpecifier::Super:
00816     llvm_unreachable("Can't mangle __super specifier");
00817 
00818   case NestedNameSpecifier::Namespace:
00819     if (qualifier->getPrefix())
00820       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
00821                              /*recursive*/ true);
00822     else
00823       Out << "sr";
00824     mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
00825     break;
00826   case NestedNameSpecifier::NamespaceAlias:
00827     if (qualifier->getPrefix())
00828       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
00829                              /*recursive*/ true);
00830     else
00831       Out << "sr";
00832     mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
00833     break;
00834 
00835   case NestedNameSpecifier::TypeSpec:
00836   case NestedNameSpecifier::TypeSpecWithTemplate: {
00837     const Type *type = qualifier->getAsType();
00838 
00839     // We only want to use an unresolved-type encoding if this is one of:
00840     //   - a decltype
00841     //   - a template type parameter
00842     //   - a template template parameter with arguments
00843     // In all of these cases, we should have no prefix.
00844     if (qualifier->getPrefix()) {
00845       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
00846                              /*recursive*/ true);
00847     } else {
00848       // Otherwise, all the cases want this.
00849       Out << "sr";
00850     }
00851 
00852     // Only certain other types are valid as prefixes;  enumerate them.
00853     switch (type->getTypeClass()) {
00854     case Type::Builtin:
00855     case Type::Complex:
00856     case Type::Adjusted:
00857     case Type::Decayed:
00858     case Type::Pointer:
00859     case Type::BlockPointer:
00860     case Type::LValueReference:
00861     case Type::RValueReference:
00862     case Type::MemberPointer:
00863     case Type::ConstantArray:
00864     case Type::IncompleteArray:
00865     case Type::VariableArray:
00866     case Type::DependentSizedArray:
00867     case Type::DependentSizedExtVector:
00868     case Type::Vector:
00869     case Type::ExtVector:
00870     case Type::FunctionProto:
00871     case Type::FunctionNoProto:
00872     case Type::Enum:
00873     case Type::Paren:
00874     case Type::Elaborated:
00875     case Type::Attributed:
00876     case Type::Auto:
00877     case Type::PackExpansion:
00878     case Type::ObjCObject:
00879     case Type::ObjCInterface:
00880     case Type::ObjCObjectPointer:
00881     case Type::Atomic:
00882       llvm_unreachable("type is illegal as a nested name specifier");
00883 
00884     case Type::SubstTemplateTypeParmPack:
00885       // FIXME: not clear how to mangle this!
00886       // template <class T...> class A {
00887       //   template <class U...> void foo(decltype(T::foo(U())) x...);
00888       // };
00889       Out << "_SUBSTPACK_";
00890       break;
00891 
00892     // <unresolved-type> ::= <template-param>
00893     //                   ::= <decltype>
00894     //                   ::= <template-template-param> <template-args>
00895     // (this last is not official yet)
00896     case Type::TypeOfExpr:
00897     case Type::TypeOf:
00898     case Type::Decltype:
00899     case Type::TemplateTypeParm:
00900     case Type::UnaryTransform:
00901     case Type::SubstTemplateTypeParm:
00902     unresolvedType:
00903       assert(!qualifier->getPrefix());
00904 
00905       // We only get here recursively if we're followed by identifiers.
00906       if (recursive) Out << 'N';
00907 
00908       // This seems to do everything we want.  It's not really
00909       // sanctioned for a substituted template parameter, though.
00910       mangleType(QualType(type, 0));
00911 
00912       // We never want to print 'E' directly after an unresolved-type,
00913       // so we return directly.
00914       return;
00915 
00916     case Type::Typedef:
00917       mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
00918       break;
00919 
00920     case Type::UnresolvedUsing:
00921       mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
00922                          ->getIdentifier());
00923       break;
00924 
00925     case Type::Record:
00926       mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
00927       break;
00928 
00929     case Type::TemplateSpecialization: {
00930       const TemplateSpecializationType *tst
00931         = cast<TemplateSpecializationType>(type);
00932       TemplateName name = tst->getTemplateName();
00933       switch (name.getKind()) {
00934       case TemplateName::Template:
00935       case TemplateName::QualifiedTemplate: {
00936         TemplateDecl *temp = name.getAsTemplateDecl();
00937 
00938         // If the base is a template template parameter, this is an
00939         // unresolved type.
00940         assert(temp && "no template for template specialization type");
00941         if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
00942 
00943         mangleSourceName(temp->getIdentifier());
00944         break;
00945       }
00946 
00947       case TemplateName::OverloadedTemplate:
00948       case TemplateName::DependentTemplate:
00949         llvm_unreachable("invalid base for a template specialization type");
00950 
00951       case TemplateName::SubstTemplateTemplateParm: {
00952         SubstTemplateTemplateParmStorage *subst
00953           = name.getAsSubstTemplateTemplateParm();
00954         mangleExistingSubstitution(subst->getReplacement());
00955         break;
00956       }
00957 
00958       case TemplateName::SubstTemplateTemplateParmPack: {
00959         // FIXME: not clear how to mangle this!
00960         // template <template <class U> class T...> class A {
00961         //   template <class U...> void foo(decltype(T<U>::foo) x...);
00962         // };
00963         Out << "_SUBSTPACK_";
00964         break;
00965       }
00966       }
00967 
00968       mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
00969       break;
00970     }
00971 
00972     case Type::InjectedClassName:
00973       mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
00974                          ->getIdentifier());
00975       break;
00976 
00977     case Type::DependentName:
00978       mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
00979       break;
00980 
00981     case Type::DependentTemplateSpecialization: {
00982       const DependentTemplateSpecializationType *tst
00983         = cast<DependentTemplateSpecializationType>(type);
00984       mangleSourceName(tst->getIdentifier());
00985       mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
00986       break;
00987     }
00988     }
00989     break;
00990   }
00991 
00992   case NestedNameSpecifier::Identifier:
00993     // Member expressions can have these without prefixes.
00994     if (qualifier->getPrefix()) {
00995       mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
00996                              /*recursive*/ true);
00997     } else if (firstQualifierLookup) {
00998 
00999       // Try to make a proper qualifier out of the lookup result, and
01000       // then just recurse on that.
01001       NestedNameSpecifier *newQualifier;
01002       if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
01003         QualType type = getASTContext().getTypeDeclType(typeDecl);
01004 
01005         // Pretend we had a different nested name specifier.
01006         newQualifier = NestedNameSpecifier::Create(getASTContext(),
01007                                                    /*prefix*/ nullptr,
01008                                                    /*template*/ false,
01009                                                    type.getTypePtr());
01010       } else if (NamespaceDecl *nspace =
01011                    dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
01012         newQualifier = NestedNameSpecifier::Create(getASTContext(),
01013                                                    /*prefix*/ nullptr,
01014                                                    nspace);
01015       } else if (NamespaceAliasDecl *alias =
01016                    dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
01017         newQualifier = NestedNameSpecifier::Create(getASTContext(),
01018                                                    /*prefix*/ nullptr,
01019                                                    alias);
01020       } else {
01021         // No sensible mangling to do here.
01022         newQualifier = nullptr;
01023       }
01024 
01025       if (newQualifier)
01026         return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
01027                                       recursive);
01028 
01029     } else {
01030       Out << "sr";
01031     }
01032 
01033     mangleSourceName(qualifier->getAsIdentifier());
01034     break;
01035   }
01036 
01037   // If this was the innermost part of the NNS, and we fell out to
01038   // here, append an 'E'.
01039   if (!recursive)
01040     Out << 'E';
01041 }
01042 
01043 /// Mangle an unresolved-name, which is generally used for names which
01044 /// weren't resolved to specific entities.
01045 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
01046                                           NamedDecl *firstQualifierLookup,
01047                                           DeclarationName name,
01048                                           unsigned knownArity) {
01049   if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
01050   mangleUnqualifiedName(nullptr, name, knownArity);
01051 }
01052 
01053 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
01054   assert(RD->isAnonymousStructOrUnion() &&
01055          "Expected anonymous struct or union!");
01056   
01057   for (const auto *I : RD->fields()) {
01058     if (I->getIdentifier())
01059       return I;
01060     
01061     if (const RecordType *RT = I->getType()->getAs<RecordType>())
01062       if (const FieldDecl *NamedDataMember = 
01063           FindFirstNamedDataMember(RT->getDecl()))
01064         return NamedDataMember;
01065   }
01066 
01067   // We didn't find a named data member.
01068   return nullptr;
01069 }
01070 
01071 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
01072                                            DeclarationName Name,
01073                                            unsigned KnownArity) {
01074   //  <unqualified-name> ::= <operator-name>
01075   //                     ::= <ctor-dtor-name>
01076   //                     ::= <source-name>
01077   switch (Name.getNameKind()) {
01078   case DeclarationName::Identifier: {
01079     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
01080       // We must avoid conflicts between internally- and externally-
01081       // linked variable and function declaration names in the same TU:
01082       //   void test() { extern void foo(); }
01083       //   static void foo();
01084       // This naming convention is the same as that followed by GCC,
01085       // though it shouldn't actually matter.
01086       if (ND && ND->getFormalLinkage() == InternalLinkage &&
01087           getEffectiveDeclContext(ND)->isFileContext())
01088         Out << 'L';
01089 
01090       mangleSourceName(II);
01091       break;
01092     }
01093 
01094     // Otherwise, an anonymous entity.  We must have a declaration.
01095     assert(ND && "mangling empty name without declaration");
01096 
01097     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
01098       if (NS->isAnonymousNamespace()) {
01099         // This is how gcc mangles these names.
01100         Out << "12_GLOBAL__N_1";
01101         break;
01102       }
01103     }
01104 
01105     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
01106       // We must have an anonymous union or struct declaration.
01107       const RecordDecl *RD = 
01108         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
01109       
01110       // Itanium C++ ABI 5.1.2:
01111       //
01112       //   For the purposes of mangling, the name of an anonymous union is
01113       //   considered to be the name of the first named data member found by a
01114       //   pre-order, depth-first, declaration-order walk of the data members of
01115       //   the anonymous union. If there is no such data member (i.e., if all of
01116       //   the data members in the union are unnamed), then there is no way for
01117       //   a program to refer to the anonymous union, and there is therefore no
01118       //   need to mangle its name.
01119       const FieldDecl *FD = FindFirstNamedDataMember(RD);
01120 
01121       // It's actually possible for various reasons for us to get here
01122       // with an empty anonymous struct / union.  Fortunately, it
01123       // doesn't really matter what name we generate.
01124       if (!FD) break;
01125       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
01126       
01127       mangleSourceName(FD->getIdentifier());
01128       break;
01129     }
01130 
01131     // Class extensions have no name as a category, and it's possible
01132     // for them to be the semantic parent of certain declarations
01133     // (primarily, tag decls defined within declarations).  Such
01134     // declarations will always have internal linkage, so the name
01135     // doesn't really matter, but we shouldn't crash on them.  For
01136     // safety, just handle all ObjC containers here.
01137     if (isa<ObjCContainerDecl>(ND))
01138       break;
01139     
01140     // We must have an anonymous struct.
01141     const TagDecl *TD = cast<TagDecl>(ND);
01142     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
01143       assert(TD->getDeclContext() == D->getDeclContext() &&
01144              "Typedef should not be in another decl context!");
01145       assert(D->getDeclName().getAsIdentifierInfo() &&
01146              "Typedef was not named!");
01147       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
01148       break;
01149     }
01150 
01151     // <unnamed-type-name> ::= <closure-type-name>
01152     // 
01153     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
01154     // <lambda-sig> ::= <parameter-type>+   # Parameter types or 'v' for 'void'.
01155     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
01156       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
01157         mangleLambda(Record);
01158         break;
01159       }
01160     }
01161 
01162     if (TD->isExternallyVisible()) {
01163       unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
01164       Out << "Ut";
01165       if (UnnamedMangle > 1)
01166         Out << llvm::utostr(UnnamedMangle - 2);
01167       Out << '_';
01168       break;
01169     }
01170 
01171     // Get a unique id for the anonymous struct.
01172     unsigned AnonStructId = Context.getAnonymousStructId(TD);
01173 
01174     // Mangle it as a source name in the form
01175     // [n] $_<id>
01176     // where n is the length of the string.
01177     SmallString<8> Str;
01178     Str += "$_";
01179     Str += llvm::utostr(AnonStructId);
01180 
01181     Out << Str.size();
01182     Out << Str.str();
01183     break;
01184   }
01185 
01186   case DeclarationName::ObjCZeroArgSelector:
01187   case DeclarationName::ObjCOneArgSelector:
01188   case DeclarationName::ObjCMultiArgSelector:
01189     llvm_unreachable("Can't mangle Objective-C selector names here!");
01190 
01191   case DeclarationName::CXXConstructorName:
01192     if (ND == Structor)
01193       // If the named decl is the C++ constructor we're mangling, use the type
01194       // we were given.
01195       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
01196     else
01197       // Otherwise, use the complete constructor name. This is relevant if a
01198       // class with a constructor is declared within a constructor.
01199       mangleCXXCtorType(Ctor_Complete);
01200     break;
01201 
01202   case DeclarationName::CXXDestructorName:
01203     if (ND == Structor)
01204       // If the named decl is the C++ destructor we're mangling, use the type we
01205       // were given.
01206       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
01207     else
01208       // Otherwise, use the complete destructor name. This is relevant if a
01209       // class with a destructor is declared within a destructor.
01210       mangleCXXDtorType(Dtor_Complete);
01211     break;
01212 
01213   case DeclarationName::CXXConversionFunctionName:
01214     // <operator-name> ::= cv <type>    # (cast)
01215     Out << "cv";
01216     mangleType(Name.getCXXNameType());
01217     break;
01218 
01219   case DeclarationName::CXXOperatorName: {
01220     unsigned Arity;
01221     if (ND) {
01222       Arity = cast<FunctionDecl>(ND)->getNumParams();
01223 
01224       // If we have a C++ member function, we need to include the 'this' pointer.
01225       // FIXME: This does not make sense for operators that are static, but their
01226       // names stay the same regardless of the arity (operator new for instance).
01227       if (isa<CXXMethodDecl>(ND))
01228         Arity++;
01229     } else
01230       Arity = KnownArity;
01231 
01232     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
01233     break;
01234   }
01235 
01236   case DeclarationName::CXXLiteralOperatorName:
01237     // FIXME: This mangling is not yet official.
01238     Out << "li";
01239     mangleSourceName(Name.getCXXLiteralIdentifier());
01240     break;
01241 
01242   case DeclarationName::CXXUsingDirective:
01243     llvm_unreachable("Can't mangle a using directive name!");
01244   }
01245 }
01246 
01247 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
01248   // <source-name> ::= <positive length number> <identifier>
01249   // <number> ::= [n] <non-negative decimal integer>
01250   // <identifier> ::= <unqualified source code identifier>
01251   Out << II->getLength() << II->getName();
01252 }
01253 
01254 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
01255                                       const DeclContext *DC,
01256                                       bool NoFunction) {
01257   // <nested-name> 
01258   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
01259   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 
01260   //       <template-args> E
01261 
01262   Out << 'N';
01263   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
01264     Qualifiers MethodQuals =
01265         Qualifiers::fromCVRMask(Method->getTypeQualifiers());
01266     // We do not consider restrict a distinguishing attribute for overloading
01267     // purposes so we must not mangle it.
01268     MethodQuals.removeRestrict();
01269     mangleQualifiers(MethodQuals);
01270     mangleRefQualifier(Method->getRefQualifier());
01271   }
01272   
01273   // Check if we have a template.
01274   const TemplateArgumentList *TemplateArgs = nullptr;
01275   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
01276     mangleTemplatePrefix(TD, NoFunction);
01277     mangleTemplateArgs(*TemplateArgs);
01278   }
01279   else {
01280     manglePrefix(DC, NoFunction);
01281     mangleUnqualifiedName(ND);
01282   }
01283 
01284   Out << 'E';
01285 }
01286 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
01287                                       const TemplateArgument *TemplateArgs,
01288                                       unsigned NumTemplateArgs) {
01289   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
01290 
01291   Out << 'N';
01292 
01293   mangleTemplatePrefix(TD);
01294   mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
01295 
01296   Out << 'E';
01297 }
01298 
01299 void CXXNameMangler::mangleLocalName(const Decl *D) {
01300   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
01301   //              := Z <function encoding> E s [<discriminator>]
01302   // <local-name> := Z <function encoding> E d [ <parameter number> ] 
01303   //                 _ <entity name>
01304   // <discriminator> := _ <non-negative number>
01305   assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
01306   const RecordDecl *RD = GetLocalClassDecl(D);
01307   const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
01308 
01309   Out << 'Z';
01310 
01311   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
01312     mangleObjCMethodName(MD);
01313   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
01314     mangleBlockForPrefix(BD);
01315   else
01316     mangleFunctionEncoding(cast<FunctionDecl>(DC));
01317 
01318   Out << 'E';
01319 
01320   if (RD) {
01321     // The parameter number is omitted for the last parameter, 0 for the 
01322     // second-to-last parameter, 1 for the third-to-last parameter, etc. The 
01323     // <entity name> will of course contain a <closure-type-name>: Its 
01324     // numbering will be local to the particular argument in which it appears
01325     // -- other default arguments do not affect its encoding.
01326     const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
01327     if (CXXRD->isLambda()) {
01328       if (const ParmVarDecl *Parm
01329               = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
01330         if (const FunctionDecl *Func
01331               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
01332           Out << 'd';
01333           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
01334           if (Num > 1)
01335             mangleNumber(Num - 2);
01336           Out << '_';
01337         }
01338       }
01339     }
01340     
01341     // Mangle the name relative to the closest enclosing function.
01342     // equality ok because RD derived from ND above
01343     if (D == RD)  {
01344       mangleUnqualifiedName(RD);
01345     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
01346       manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
01347       mangleUnqualifiedBlock(BD);
01348     } else {
01349       const NamedDecl *ND = cast<NamedDecl>(D);
01350       mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
01351     }
01352   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
01353     // Mangle a block in a default parameter; see above explanation for
01354     // lambdas.
01355     if (const ParmVarDecl *Parm
01356             = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
01357       if (const FunctionDecl *Func
01358             = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
01359         Out << 'd';
01360         unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
01361         if (Num > 1)
01362           mangleNumber(Num - 2);
01363         Out << '_';
01364       }
01365     }
01366 
01367     mangleUnqualifiedBlock(BD);
01368   } else {
01369     mangleUnqualifiedName(cast<NamedDecl>(D));
01370   }
01371 
01372   if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
01373     unsigned disc;
01374     if (Context.getNextDiscriminator(ND, disc)) {
01375       if (disc < 10)
01376         Out << '_' << disc;
01377       else
01378         Out << "__" << disc << '_';
01379     }
01380   }
01381 }
01382 
01383 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
01384   if (GetLocalClassDecl(Block)) {
01385     mangleLocalName(Block);
01386     return;
01387   }
01388   const DeclContext *DC = getEffectiveDeclContext(Block);
01389   if (isLocalContainerContext(DC)) {
01390     mangleLocalName(Block);
01391     return;
01392   }
01393   manglePrefix(getEffectiveDeclContext(Block));
01394   mangleUnqualifiedBlock(Block);
01395 }
01396 
01397 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
01398   if (Decl *Context = Block->getBlockManglingContextDecl()) {
01399     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
01400         Context->getDeclContext()->isRecord()) {
01401       if (const IdentifierInfo *Name
01402             = cast<NamedDecl>(Context)->getIdentifier()) {
01403         mangleSourceName(Name);
01404         Out << 'M';            
01405       }
01406     }
01407   }
01408 
01409   // If we have a block mangling number, use it.
01410   unsigned Number = Block->getBlockManglingNumber();
01411   // Otherwise, just make up a number. It doesn't matter what it is because
01412   // the symbol in question isn't externally visible.
01413   if (!Number)
01414     Number = Context.getBlockId(Block, false);
01415   Out << "Ub";
01416   if (Number > 0)
01417     Out << Number - 1;
01418   Out << '_';
01419 }
01420 
01421 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
01422   // If the context of a closure type is an initializer for a class member 
01423   // (static or nonstatic), it is encoded in a qualified name with a final 
01424   // <prefix> of the form:
01425   //
01426   //   <data-member-prefix> := <member source-name> M
01427   //
01428   // Technically, the data-member-prefix is part of the <prefix>. However,
01429   // since a closure type will always be mangled with a prefix, it's easier
01430   // to emit that last part of the prefix here.
01431   if (Decl *Context = Lambda->getLambdaContextDecl()) {
01432     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
01433         Context->getDeclContext()->isRecord()) {
01434       if (const IdentifierInfo *Name
01435             = cast<NamedDecl>(Context)->getIdentifier()) {
01436         mangleSourceName(Name);
01437         Out << 'M';            
01438       }
01439     }
01440   }
01441 
01442   Out << "Ul";
01443   const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
01444                                    getAs<FunctionProtoType>();
01445   mangleBareFunctionType(Proto, /*MangleReturnType=*/false);        
01446   Out << "E";
01447   
01448   // The number is omitted for the first closure type with a given 
01449   // <lambda-sig> in a given context; it is n-2 for the nth closure type 
01450   // (in lexical order) with that same <lambda-sig> and context.
01451   //
01452   // The AST keeps track of the number for us.
01453   unsigned Number = Lambda->getLambdaManglingNumber();
01454   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
01455   if (Number > 1)
01456     mangleNumber(Number - 2);
01457   Out << '_';  
01458 }
01459 
01460 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
01461   switch (qualifier->getKind()) {
01462   case NestedNameSpecifier::Global:
01463     // nothing
01464     return;
01465 
01466   case NestedNameSpecifier::Super:
01467     llvm_unreachable("Can't mangle __super specifier");
01468 
01469   case NestedNameSpecifier::Namespace:
01470     mangleName(qualifier->getAsNamespace());
01471     return;
01472 
01473   case NestedNameSpecifier::NamespaceAlias:
01474     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
01475     return;
01476 
01477   case NestedNameSpecifier::TypeSpec:
01478   case NestedNameSpecifier::TypeSpecWithTemplate:
01479     manglePrefix(QualType(qualifier->getAsType(), 0));
01480     return;
01481 
01482   case NestedNameSpecifier::Identifier:
01483     // Member expressions can have these without prefixes, but that
01484     // should end up in mangleUnresolvedPrefix instead.
01485     assert(qualifier->getPrefix());
01486     manglePrefix(qualifier->getPrefix());
01487 
01488     mangleSourceName(qualifier->getAsIdentifier());
01489     return;
01490   }
01491 
01492   llvm_unreachable("unexpected nested name specifier");
01493 }
01494 
01495 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
01496   //  <prefix> ::= <prefix> <unqualified-name>
01497   //           ::= <template-prefix> <template-args>
01498   //           ::= <template-param>
01499   //           ::= # empty
01500   //           ::= <substitution>
01501 
01502   DC = IgnoreLinkageSpecDecls(DC);
01503 
01504   if (DC->isTranslationUnit())
01505     return;
01506 
01507   if (NoFunction && isLocalContainerContext(DC))
01508     return;
01509 
01510   assert(!isLocalContainerContext(DC));
01511 
01512   const NamedDecl *ND = cast<NamedDecl>(DC);  
01513   if (mangleSubstitution(ND))
01514     return;
01515   
01516   // Check if we have a template.
01517   const TemplateArgumentList *TemplateArgs = nullptr;
01518   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
01519     mangleTemplatePrefix(TD);
01520     mangleTemplateArgs(*TemplateArgs);
01521   } else {
01522     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
01523     mangleUnqualifiedName(ND);
01524   }
01525 
01526   addSubstitution(ND);
01527 }
01528 
01529 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
01530   // <template-prefix> ::= <prefix> <template unqualified-name>
01531   //                   ::= <template-param>
01532   //                   ::= <substitution>
01533   if (TemplateDecl *TD = Template.getAsTemplateDecl())
01534     return mangleTemplatePrefix(TD);
01535 
01536   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
01537     manglePrefix(Qualified->getQualifier());
01538   
01539   if (OverloadedTemplateStorage *Overloaded
01540                                       = Template.getAsOverloadedTemplate()) {
01541     mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
01542                           UnknownArity);
01543     return;
01544   }
01545    
01546   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
01547   assert(Dependent && "Unknown template name kind?");
01548   manglePrefix(Dependent->getQualifier());
01549   mangleUnscopedTemplateName(Template);
01550 }
01551 
01552 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
01553                                           bool NoFunction) {
01554   // <template-prefix> ::= <prefix> <template unqualified-name>
01555   //                   ::= <template-param>
01556   //                   ::= <substitution>
01557   // <template-template-param> ::= <template-param>
01558   //                               <substitution>
01559 
01560   if (mangleSubstitution(ND))
01561     return;
01562 
01563   // <template-template-param> ::= <template-param>
01564   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
01565     mangleTemplateParameter(TTP->getIndex());
01566   } else {
01567     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
01568     mangleUnqualifiedName(ND->getTemplatedDecl());
01569   }
01570 
01571   addSubstitution(ND);
01572 }
01573 
01574 /// Mangles a template name under the production <type>.  Required for
01575 /// template template arguments.
01576 ///   <type> ::= <class-enum-type>
01577 ///          ::= <template-param>
01578 ///          ::= <substitution>
01579 void CXXNameMangler::mangleType(TemplateName TN) {
01580   if (mangleSubstitution(TN))
01581     return;
01582 
01583   TemplateDecl *TD = nullptr;
01584 
01585   switch (TN.getKind()) {
01586   case TemplateName::QualifiedTemplate:
01587     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
01588     goto HaveDecl;
01589 
01590   case TemplateName::Template:
01591     TD = TN.getAsTemplateDecl();
01592     goto HaveDecl;
01593 
01594   HaveDecl:
01595     if (isa<TemplateTemplateParmDecl>(TD))
01596       mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
01597     else
01598       mangleName(TD);
01599     break;
01600 
01601   case TemplateName::OverloadedTemplate:
01602     llvm_unreachable("can't mangle an overloaded template name as a <type>");
01603 
01604   case TemplateName::DependentTemplate: {
01605     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
01606     assert(Dependent->isIdentifier());
01607 
01608     // <class-enum-type> ::= <name>
01609     // <name> ::= <nested-name>
01610     mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
01611     mangleSourceName(Dependent->getIdentifier());
01612     break;
01613   }
01614 
01615   case TemplateName::SubstTemplateTemplateParm: {
01616     // Substituted template parameters are mangled as the substituted
01617     // template.  This will check for the substitution twice, which is
01618     // fine, but we have to return early so that we don't try to *add*
01619     // the substitution twice.
01620     SubstTemplateTemplateParmStorage *subst
01621       = TN.getAsSubstTemplateTemplateParm();
01622     mangleType(subst->getReplacement());
01623     return;
01624   }
01625 
01626   case TemplateName::SubstTemplateTemplateParmPack: {
01627     // FIXME: not clear how to mangle this!
01628     // template <template <class> class T...> class A {
01629     //   template <template <class> class U...> void foo(B<T,U> x...);
01630     // };
01631     Out << "_SUBSTPACK_";
01632     break;
01633   }
01634   }
01635 
01636   addSubstitution(TN);
01637 }
01638 
01639 void
01640 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
01641   switch (OO) {
01642   // <operator-name> ::= nw     # new
01643   case OO_New: Out << "nw"; break;
01644   //              ::= na        # new[]
01645   case OO_Array_New: Out << "na"; break;
01646   //              ::= dl        # delete
01647   case OO_Delete: Out << "dl"; break;
01648   //              ::= da        # delete[]
01649   case OO_Array_Delete: Out << "da"; break;
01650   //              ::= ps        # + (unary)
01651   //              ::= pl        # + (binary or unknown)
01652   case OO_Plus:
01653     Out << (Arity == 1? "ps" : "pl"); break;
01654   //              ::= ng        # - (unary)
01655   //              ::= mi        # - (binary or unknown)
01656   case OO_Minus:
01657     Out << (Arity == 1? "ng" : "mi"); break;
01658   //              ::= ad        # & (unary)
01659   //              ::= an        # & (binary or unknown)
01660   case OO_Amp:
01661     Out << (Arity == 1? "ad" : "an"); break;
01662   //              ::= de        # * (unary)
01663   //              ::= ml        # * (binary or unknown)
01664   case OO_Star:
01665     // Use binary when unknown.
01666     Out << (Arity == 1? "de" : "ml"); break;
01667   //              ::= co        # ~
01668   case OO_Tilde: Out << "co"; break;
01669   //              ::= dv        # /
01670   case OO_Slash: Out << "dv"; break;
01671   //              ::= rm        # %
01672   case OO_Percent: Out << "rm"; break;
01673   //              ::= or        # |
01674   case OO_Pipe: Out << "or"; break;
01675   //              ::= eo        # ^
01676   case OO_Caret: Out << "eo"; break;
01677   //              ::= aS        # =
01678   case OO_Equal: Out << "aS"; break;
01679   //              ::= pL        # +=
01680   case OO_PlusEqual: Out << "pL"; break;
01681   //              ::= mI        # -=
01682   case OO_MinusEqual: Out << "mI"; break;
01683   //              ::= mL        # *=
01684   case OO_StarEqual: Out << "mL"; break;
01685   //              ::= dV        # /=
01686   case OO_SlashEqual: Out << "dV"; break;
01687   //              ::= rM        # %=
01688   case OO_PercentEqual: Out << "rM"; break;
01689   //              ::= aN        # &=
01690   case OO_AmpEqual: Out << "aN"; break;
01691   //              ::= oR        # |=
01692   case OO_PipeEqual: Out << "oR"; break;
01693   //              ::= eO        # ^=
01694   case OO_CaretEqual: Out << "eO"; break;
01695   //              ::= ls        # <<
01696   case OO_LessLess: Out << "ls"; break;
01697   //              ::= rs        # >>
01698   case OO_GreaterGreater: Out << "rs"; break;
01699   //              ::= lS        # <<=
01700   case OO_LessLessEqual: Out << "lS"; break;
01701   //              ::= rS        # >>=
01702   case OO_GreaterGreaterEqual: Out << "rS"; break;
01703   //              ::= eq        # ==
01704   case OO_EqualEqual: Out << "eq"; break;
01705   //              ::= ne        # !=
01706   case OO_ExclaimEqual: Out << "ne"; break;
01707   //              ::= lt        # <
01708   case OO_Less: Out << "lt"; break;
01709   //              ::= gt        # >
01710   case OO_Greater: Out << "gt"; break;
01711   //              ::= le        # <=
01712   case OO_LessEqual: Out << "le"; break;
01713   //              ::= ge        # >=
01714   case OO_GreaterEqual: Out << "ge"; break;
01715   //              ::= nt        # !
01716   case OO_Exclaim: Out << "nt"; break;
01717   //              ::= aa        # &&
01718   case OO_AmpAmp: Out << "aa"; break;
01719   //              ::= oo        # ||
01720   case OO_PipePipe: Out << "oo"; break;
01721   //              ::= pp        # ++
01722   case OO_PlusPlus: Out << "pp"; break;
01723   //              ::= mm        # --
01724   case OO_MinusMinus: Out << "mm"; break;
01725   //              ::= cm        # ,
01726   case OO_Comma: Out << "cm"; break;
01727   //              ::= pm        # ->*
01728   case OO_ArrowStar: Out << "pm"; break;
01729   //              ::= pt        # ->
01730   case OO_Arrow: Out << "pt"; break;
01731   //              ::= cl        # ()
01732   case OO_Call: Out << "cl"; break;
01733   //              ::= ix        # []
01734   case OO_Subscript: Out << "ix"; break;
01735 
01736   //              ::= qu        # ?
01737   // The conditional operator can't be overloaded, but we still handle it when
01738   // mangling expressions.
01739   case OO_Conditional: Out << "qu"; break;
01740 
01741   case OO_None:
01742   case NUM_OVERLOADED_OPERATORS:
01743     llvm_unreachable("Not an overloaded operator");
01744   }
01745 }
01746 
01747 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
01748   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
01749   if (Quals.hasRestrict())
01750     Out << 'r';
01751   if (Quals.hasVolatile())
01752     Out << 'V';
01753   if (Quals.hasConst())
01754     Out << 'K';
01755 
01756   if (Quals.hasAddressSpace()) {
01757     // Address space extension:
01758     //
01759     //   <type> ::= U <target-addrspace>
01760     //   <type> ::= U <OpenCL-addrspace>
01761     //   <type> ::= U <CUDA-addrspace>
01762 
01763     SmallString<64> ASString;
01764     unsigned AS = Quals.getAddressSpace();
01765 
01766     if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
01767       //  <target-addrspace> ::= "AS" <address-space-number>
01768       unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
01769       ASString = "AS" + llvm::utostr_32(TargetAS);
01770     } else {
01771       switch (AS) {
01772       default: llvm_unreachable("Not a language specific address space");
01773       //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
01774       case LangAS::opencl_global:   ASString = "CLglobal";   break;
01775       case LangAS::opencl_local:    ASString = "CLlocal";    break;
01776       case LangAS::opencl_constant: ASString = "CLconstant"; break;
01777       //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
01778       case LangAS::cuda_device:     ASString = "CUdevice";   break;
01779       case LangAS::cuda_constant:   ASString = "CUconstant"; break;
01780       case LangAS::cuda_shared:     ASString = "CUshared";   break;
01781       }
01782     }
01783     Out << 'U' << ASString.size() << ASString;
01784   }
01785   
01786   StringRef LifetimeName;
01787   switch (Quals.getObjCLifetime()) {
01788   // Objective-C ARC Extension:
01789   //
01790   //   <type> ::= U "__strong"
01791   //   <type> ::= U "__weak"
01792   //   <type> ::= U "__autoreleasing"
01793   case Qualifiers::OCL_None:
01794     break;
01795     
01796   case Qualifiers::OCL_Weak:
01797     LifetimeName = "__weak";
01798     break;
01799     
01800   case Qualifiers::OCL_Strong:
01801     LifetimeName = "__strong";
01802     break;
01803     
01804   case Qualifiers::OCL_Autoreleasing:
01805     LifetimeName = "__autoreleasing";
01806     break;
01807     
01808   case Qualifiers::OCL_ExplicitNone:
01809     // The __unsafe_unretained qualifier is *not* mangled, so that
01810     // __unsafe_unretained types in ARC produce the same manglings as the
01811     // equivalent (but, naturally, unqualified) types in non-ARC, providing
01812     // better ABI compatibility.
01813     //
01814     // It's safe to do this because unqualified 'id' won't show up
01815     // in any type signatures that need to be mangled.
01816     break;
01817   }
01818   if (!LifetimeName.empty())
01819     Out << 'U' << LifetimeName.size() << LifetimeName;
01820 }
01821 
01822 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
01823   // <ref-qualifier> ::= R                # lvalue reference
01824   //                 ::= O                # rvalue-reference
01825   switch (RefQualifier) {
01826   case RQ_None:
01827     break;
01828       
01829   case RQ_LValue:
01830     Out << 'R';
01831     break;
01832       
01833   case RQ_RValue:
01834     Out << 'O';
01835     break;
01836   }
01837 }
01838 
01839 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
01840   Context.mangleObjCMethodName(MD, Out);
01841 }
01842 
01843 void CXXNameMangler::mangleType(QualType T) {
01844   // If our type is instantiation-dependent but not dependent, we mangle
01845   // it as it was written in the source, removing any top-level sugar. 
01846   // Otherwise, use the canonical type.
01847   //
01848   // FIXME: This is an approximation of the instantiation-dependent name 
01849   // mangling rules, since we should really be using the type as written and
01850   // augmented via semantic analysis (i.e., with implicit conversions and
01851   // default template arguments) for any instantiation-dependent type. 
01852   // Unfortunately, that requires several changes to our AST:
01853   //   - Instantiation-dependent TemplateSpecializationTypes will need to be 
01854   //     uniqued, so that we can handle substitutions properly
01855   //   - Default template arguments will need to be represented in the
01856   //     TemplateSpecializationType, since they need to be mangled even though
01857   //     they aren't written.
01858   //   - Conversions on non-type template arguments need to be expressed, since
01859   //     they can affect the mangling of sizeof/alignof.
01860   if (!T->isInstantiationDependentType() || T->isDependentType())
01861     T = T.getCanonicalType();
01862   else {
01863     // Desugar any types that are purely sugar.
01864     do {
01865       // Don't desugar through template specialization types that aren't
01866       // type aliases. We need to mangle the template arguments as written.
01867       if (const TemplateSpecializationType *TST 
01868                                       = dyn_cast<TemplateSpecializationType>(T))
01869         if (!TST->isTypeAlias())
01870           break;
01871 
01872       QualType Desugared 
01873         = T.getSingleStepDesugaredType(Context.getASTContext());
01874       if (Desugared == T)
01875         break;
01876       
01877       T = Desugared;
01878     } while (true);
01879   }
01880   SplitQualType split = T.split();
01881   Qualifiers quals = split.Quals;
01882   const Type *ty = split.Ty;
01883 
01884   bool isSubstitutable = quals || !isa<BuiltinType>(T);
01885   if (isSubstitutable && mangleSubstitution(T))
01886     return;
01887 
01888   // If we're mangling a qualified array type, push the qualifiers to
01889   // the element type.
01890   if (quals && isa<ArrayType>(T)) {
01891     ty = Context.getASTContext().getAsArrayType(T);
01892     quals = Qualifiers();
01893 
01894     // Note that we don't update T: we want to add the
01895     // substitution at the original type.
01896   }
01897 
01898   if (quals) {
01899     mangleQualifiers(quals);
01900     // Recurse:  even if the qualified type isn't yet substitutable,
01901     // the unqualified type might be.
01902     mangleType(QualType(ty, 0));
01903   } else {
01904     switch (ty->getTypeClass()) {
01905 #define ABSTRACT_TYPE(CLASS, PARENT)
01906 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
01907     case Type::CLASS: \
01908       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
01909       return;
01910 #define TYPE(CLASS, PARENT) \
01911     case Type::CLASS: \
01912       mangleType(static_cast<const CLASS##Type*>(ty)); \
01913       break;
01914 #include "clang/AST/TypeNodes.def"
01915     }
01916   }
01917 
01918   // Add the substitution.
01919   if (isSubstitutable)
01920     addSubstitution(T);
01921 }
01922 
01923 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
01924   if (!mangleStandardSubstitution(ND))
01925     mangleName(ND);
01926 }
01927 
01928 void CXXNameMangler::mangleType(const BuiltinType *T) {
01929   //  <type>         ::= <builtin-type>
01930   //  <builtin-type> ::= v  # void
01931   //                 ::= w  # wchar_t
01932   //                 ::= b  # bool
01933   //                 ::= c  # char
01934   //                 ::= a  # signed char
01935   //                 ::= h  # unsigned char
01936   //                 ::= s  # short
01937   //                 ::= t  # unsigned short
01938   //                 ::= i  # int
01939   //                 ::= j  # unsigned int
01940   //                 ::= l  # long
01941   //                 ::= m  # unsigned long
01942   //                 ::= x  # long long, __int64
01943   //                 ::= y  # unsigned long long, __int64
01944   //                 ::= n  # __int128
01945   //                 ::= o  # unsigned __int128
01946   //                 ::= f  # float
01947   //                 ::= d  # double
01948   //                 ::= e  # long double, __float80
01949   // UNSUPPORTED:    ::= g  # __float128
01950   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
01951   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
01952   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
01953   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
01954   //                 ::= Di # char32_t
01955   //                 ::= Ds # char16_t
01956   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
01957   //                 ::= u <source-name>    # vendor extended type
01958   switch (T->getKind()) {
01959   case BuiltinType::Void: Out << 'v'; break;
01960   case BuiltinType::Bool: Out << 'b'; break;
01961   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
01962   case BuiltinType::UChar: Out << 'h'; break;
01963   case BuiltinType::UShort: Out << 't'; break;
01964   case BuiltinType::UInt: Out << 'j'; break;
01965   case BuiltinType::ULong: Out << 'm'; break;
01966   case BuiltinType::ULongLong: Out << 'y'; break;
01967   case BuiltinType::UInt128: Out << 'o'; break;
01968   case BuiltinType::SChar: Out << 'a'; break;
01969   case BuiltinType::WChar_S:
01970   case BuiltinType::WChar_U: Out << 'w'; break;
01971   case BuiltinType::Char16: Out << "Ds"; break;
01972   case BuiltinType::Char32: Out << "Di"; break;
01973   case BuiltinType::Short: Out << 's'; break;
01974   case BuiltinType::Int: Out << 'i'; break;
01975   case BuiltinType::Long: Out << 'l'; break;
01976   case BuiltinType::LongLong: Out << 'x'; break;
01977   case BuiltinType::Int128: Out << 'n'; break;
01978   case BuiltinType::Half: Out << "Dh"; break;
01979   case BuiltinType::Float: Out << 'f'; break;
01980   case BuiltinType::Double: Out << 'd'; break;
01981   case BuiltinType::LongDouble: Out << 'e'; break;
01982   case BuiltinType::NullPtr: Out << "Dn"; break;
01983 
01984 #define BUILTIN_TYPE(Id, SingletonId)
01985 #define PLACEHOLDER_TYPE(Id, SingletonId) \
01986   case BuiltinType::Id:
01987 #include "clang/AST/BuiltinTypes.def"
01988   case BuiltinType::Dependent:
01989     llvm_unreachable("mangling a placeholder type");
01990   case BuiltinType::ObjCId: Out << "11objc_object"; break;
01991   case BuiltinType::ObjCClass: Out << "10objc_class"; break;
01992   case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
01993   case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
01994   case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
01995   case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
01996   case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
01997   case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
01998   case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
01999   case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
02000   case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
02001   }
02002 }
02003 
02004 // <type>          ::= <function-type>
02005 // <function-type> ::= [<CV-qualifiers>] F [Y]
02006 //                      <bare-function-type> [<ref-qualifier>] E
02007 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
02008   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
02009   // e.g. "const" in "int (A::*)() const".
02010   mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
02011 
02012   Out << 'F';
02013 
02014   // FIXME: We don't have enough information in the AST to produce the 'Y'
02015   // encoding for extern "C" function types.
02016   mangleBareFunctionType(T, /*MangleReturnType=*/true);
02017 
02018   // Mangle the ref-qualifier, if present.
02019   mangleRefQualifier(T->getRefQualifier());
02020 
02021   Out << 'E';
02022 }
02023 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
02024   llvm_unreachable("Can't mangle K&R function prototypes");
02025 }
02026 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
02027                                             bool MangleReturnType) {
02028   // We should never be mangling something without a prototype.
02029   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
02030 
02031   // Record that we're in a function type.  See mangleFunctionParam
02032   // for details on what we're trying to achieve here.
02033   FunctionTypeDepthState saved = FunctionTypeDepth.push();
02034 
02035   // <bare-function-type> ::= <signature type>+
02036   if (MangleReturnType) {
02037     FunctionTypeDepth.enterResultType();
02038     mangleType(Proto->getReturnType());
02039     FunctionTypeDepth.leaveResultType();
02040   }
02041 
02042   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
02043     //   <builtin-type> ::= v   # void
02044     Out << 'v';
02045 
02046     FunctionTypeDepth.pop(saved);
02047     return;
02048   }
02049 
02050   for (const auto &Arg : Proto->param_types())
02051     mangleType(Context.getASTContext().getSignatureParameterType(Arg));
02052 
02053   FunctionTypeDepth.pop(saved);
02054 
02055   // <builtin-type>      ::= z  # ellipsis
02056   if (Proto->isVariadic())
02057     Out << 'z';
02058 }
02059 
02060 // <type>            ::= <class-enum-type>
02061 // <class-enum-type> ::= <name>
02062 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
02063   mangleName(T->getDecl());
02064 }
02065 
02066 // <type>            ::= <class-enum-type>
02067 // <class-enum-type> ::= <name>
02068 void CXXNameMangler::mangleType(const EnumType *T) {
02069   mangleType(static_cast<const TagType*>(T));
02070 }
02071 void CXXNameMangler::mangleType(const RecordType *T) {
02072   mangleType(static_cast<const TagType*>(T));
02073 }
02074 void CXXNameMangler::mangleType(const TagType *T) {
02075   mangleName(T->getDecl());
02076 }
02077 
02078 // <type>       ::= <array-type>
02079 // <array-type> ::= A <positive dimension number> _ <element type>
02080 //              ::= A [<dimension expression>] _ <element type>
02081 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
02082   Out << 'A' << T->getSize() << '_';
02083   mangleType(T->getElementType());
02084 }
02085 void CXXNameMangler::mangleType(const VariableArrayType *T) {
02086   Out << 'A';
02087   // decayed vla types (size 0) will just be skipped.
02088   if (T->getSizeExpr())
02089     mangleExpression(T->getSizeExpr());
02090   Out << '_';
02091   mangleType(T->getElementType());
02092 }
02093 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
02094   Out << 'A';
02095   mangleExpression(T->getSizeExpr());
02096   Out << '_';
02097   mangleType(T->getElementType());
02098 }
02099 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
02100   Out << "A_";
02101   mangleType(T->getElementType());
02102 }
02103 
02104 // <type>                   ::= <pointer-to-member-type>
02105 // <pointer-to-member-type> ::= M <class type> <member type>
02106 void CXXNameMangler::mangleType(const MemberPointerType *T) {
02107   Out << 'M';
02108   mangleType(QualType(T->getClass(), 0));
02109   QualType PointeeType = T->getPointeeType();
02110   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
02111     mangleType(FPT);
02112     
02113     // Itanium C++ ABI 5.1.8:
02114     //
02115     //   The type of a non-static member function is considered to be different,
02116     //   for the purposes of substitution, from the type of a namespace-scope or
02117     //   static member function whose type appears similar. The types of two
02118     //   non-static member functions are considered to be different, for the
02119     //   purposes of substitution, if the functions are members of different
02120     //   classes. In other words, for the purposes of substitution, the class of 
02121     //   which the function is a member is considered part of the type of 
02122     //   function.
02123 
02124     // Given that we already substitute member function pointers as a
02125     // whole, the net effect of this rule is just to unconditionally
02126     // suppress substitution on the function type in a member pointer.
02127     // We increment the SeqID here to emulate adding an entry to the
02128     // substitution table.
02129     ++SeqID;
02130   } else
02131     mangleType(PointeeType);
02132 }
02133 
02134 // <type>           ::= <template-param>
02135 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
02136   mangleTemplateParameter(T->getIndex());
02137 }
02138 
02139 // <type>           ::= <template-param>
02140 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
02141   // FIXME: not clear how to mangle this!
02142   // template <class T...> class A {
02143   //   template <class U...> void foo(T(*)(U) x...);
02144   // };
02145   Out << "_SUBSTPACK_";
02146 }
02147 
02148 // <type> ::= P <type>   # pointer-to
02149 void CXXNameMangler::mangleType(const PointerType *T) {
02150   Out << 'P';
02151   mangleType(T->getPointeeType());
02152 }
02153 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
02154   Out << 'P';
02155   mangleType(T->getPointeeType());
02156 }
02157 
02158 // <type> ::= R <type>   # reference-to
02159 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
02160   Out << 'R';
02161   mangleType(T->getPointeeType());
02162 }
02163 
02164 // <type> ::= O <type>   # rvalue reference-to (C++0x)
02165 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
02166   Out << 'O';
02167   mangleType(T->getPointeeType());
02168 }
02169 
02170 // <type> ::= C <type>   # complex pair (C 2000)
02171 void CXXNameMangler::mangleType(const ComplexType *T) {
02172   Out << 'C';
02173   mangleType(T->getElementType());
02174 }
02175 
02176 // ARM's ABI for Neon vector types specifies that they should be mangled as
02177 // if they are structs (to match ARM's initial implementation).  The
02178 // vector type must be one of the special types predefined by ARM.
02179 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
02180   QualType EltType = T->getElementType();
02181   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
02182   const char *EltName = nullptr;
02183   if (T->getVectorKind() == VectorType::NeonPolyVector) {
02184     switch (cast<BuiltinType>(EltType)->getKind()) {
02185     case BuiltinType::SChar:
02186     case BuiltinType::UChar:
02187       EltName = "poly8_t";
02188       break;
02189     case BuiltinType::Short:
02190     case BuiltinType::UShort:
02191       EltName = "poly16_t";
02192       break;
02193     case BuiltinType::ULongLong:
02194       EltName = "poly64_t";
02195       break;
02196     default: llvm_unreachable("unexpected Neon polynomial vector element type");
02197     }
02198   } else {
02199     switch (cast<BuiltinType>(EltType)->getKind()) {
02200     case BuiltinType::SChar:     EltName = "int8_t"; break;
02201     case BuiltinType::UChar:     EltName = "uint8_t"; break;
02202     case BuiltinType::Short:     EltName = "int16_t"; break;
02203     case BuiltinType::UShort:    EltName = "uint16_t"; break;
02204     case BuiltinType::Int:       EltName = "int32_t"; break;
02205     case BuiltinType::UInt:      EltName = "uint32_t"; break;
02206     case BuiltinType::LongLong:  EltName = "int64_t"; break;
02207     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
02208     case BuiltinType::Double:    EltName = "float64_t"; break;
02209     case BuiltinType::Float:     EltName = "float32_t"; break;
02210     case BuiltinType::Half:      EltName = "float16_t";break;
02211     default:
02212       llvm_unreachable("unexpected Neon vector element type");
02213     }
02214   }
02215   const char *BaseName = nullptr;
02216   unsigned BitSize = (T->getNumElements() *
02217                       getASTContext().getTypeSize(EltType));
02218   if (BitSize == 64)
02219     BaseName = "__simd64_";
02220   else {
02221     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
02222     BaseName = "__simd128_";
02223   }
02224   Out << strlen(BaseName) + strlen(EltName);
02225   Out << BaseName << EltName;
02226 }
02227 
02228 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
02229   switch (EltType->getKind()) {
02230   case BuiltinType::SChar:
02231     return "Int8";
02232   case BuiltinType::Short:
02233     return "Int16";
02234   case BuiltinType::Int:
02235     return "Int32";
02236   case BuiltinType::Long:
02237   case BuiltinType::LongLong:
02238     return "Int64";
02239   case BuiltinType::UChar:
02240     return "Uint8";
02241   case BuiltinType::UShort:
02242     return "Uint16";
02243   case BuiltinType::UInt:
02244     return "Uint32";
02245   case BuiltinType::ULong:
02246   case BuiltinType::ULongLong:
02247     return "Uint64";
02248   case BuiltinType::Half:
02249     return "Float16";
02250   case BuiltinType::Float:
02251     return "Float32";
02252   case BuiltinType::Double:
02253     return "Float64";
02254   default:
02255     llvm_unreachable("Unexpected vector element base type");
02256   }
02257 }
02258 
02259 // AArch64's ABI for Neon vector types specifies that they should be mangled as
02260 // the equivalent internal name. The vector type must be one of the special
02261 // types predefined by ARM.
02262 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
02263   QualType EltType = T->getElementType();
02264   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
02265   unsigned BitSize =
02266       (T->getNumElements() * getASTContext().getTypeSize(EltType));
02267   (void)BitSize; // Silence warning.
02268 
02269   assert((BitSize == 64 || BitSize == 128) &&
02270          "Neon vector type not 64 or 128 bits");
02271 
02272   StringRef EltName;
02273   if (T->getVectorKind() == VectorType::NeonPolyVector) {
02274     switch (cast<BuiltinType>(EltType)->getKind()) {
02275     case BuiltinType::UChar:
02276       EltName = "Poly8";
02277       break;
02278     case BuiltinType::UShort:
02279       EltName = "Poly16";
02280       break;
02281     case BuiltinType::ULong:
02282       EltName = "Poly64";
02283       break;
02284     default:
02285       llvm_unreachable("unexpected Neon polynomial vector element type");
02286     }
02287   } else
02288     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
02289 
02290   std::string TypeName =
02291       ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
02292   Out << TypeName.length() << TypeName;
02293 }
02294 
02295 // GNU extension: vector types
02296 // <type>                  ::= <vector-type>
02297 // <vector-type>           ::= Dv <positive dimension number> _
02298 //                                    <extended element type>
02299 //                         ::= Dv [<dimension expression>] _ <element type>
02300 // <extended element type> ::= <element type>
02301 //                         ::= p # AltiVec vector pixel
02302 //                         ::= b # Altivec vector bool
02303 void CXXNameMangler::mangleType(const VectorType *T) {
02304   if ((T->getVectorKind() == VectorType::NeonVector ||
02305        T->getVectorKind() == VectorType::NeonPolyVector)) {
02306     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
02307     llvm::Triple::ArchType Arch =
02308         getASTContext().getTargetInfo().getTriple().getArch();
02309     if ((Arch == llvm::Triple::aarch64 ||
02310          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
02311       mangleAArch64NeonVectorType(T);
02312     else
02313       mangleNeonVectorType(T);
02314     return;
02315   }
02316   Out << "Dv" << T->getNumElements() << '_';
02317   if (T->getVectorKind() == VectorType::AltiVecPixel)
02318     Out << 'p';
02319   else if (T->getVectorKind() == VectorType::AltiVecBool)
02320     Out << 'b';
02321   else
02322     mangleType(T->getElementType());
02323 }
02324 void CXXNameMangler::mangleType(const ExtVectorType *T) {
02325   mangleType(static_cast<const VectorType*>(T));
02326 }
02327 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
02328   Out << "Dv";
02329   mangleExpression(T->getSizeExpr());
02330   Out << '_';
02331   mangleType(T->getElementType());
02332 }
02333 
02334 void CXXNameMangler::mangleType(const PackExpansionType *T) {
02335   // <type>  ::= Dp <type>          # pack expansion (C++0x)
02336   Out << "Dp";
02337   mangleType(T->getPattern());
02338 }
02339 
02340 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
02341   mangleSourceName(T->getDecl()->getIdentifier());
02342 }
02343 
02344 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
02345   if (!T->qual_empty()) {
02346     // Mangle protocol qualifiers.
02347     SmallString<64> QualStr;
02348     llvm::raw_svector_ostream QualOS(QualStr);
02349     QualOS << "objcproto";
02350     for (const auto *I : T->quals()) {
02351       StringRef name = I->getName();
02352       QualOS << name.size() << name;
02353     }
02354     QualOS.flush();
02355     Out << 'U' << QualStr.size() << QualStr;
02356   }
02357   mangleType(T->getBaseType());
02358 }
02359 
02360 void CXXNameMangler::mangleType(const BlockPointerType *T) {
02361   Out << "U13block_pointer";
02362   mangleType(T->getPointeeType());
02363 }
02364 
02365 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
02366   // Mangle injected class name types as if the user had written the
02367   // specialization out fully.  It may not actually be possible to see
02368   // this mangling, though.
02369   mangleType(T->getInjectedSpecializationType());
02370 }
02371 
02372 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
02373   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
02374     mangleName(TD, T->getArgs(), T->getNumArgs());
02375   } else {
02376     if (mangleSubstitution(QualType(T, 0)))
02377       return;
02378     
02379     mangleTemplatePrefix(T->getTemplateName());
02380     
02381     // FIXME: GCC does not appear to mangle the template arguments when
02382     // the template in question is a dependent template name. Should we
02383     // emulate that badness?
02384     mangleTemplateArgs(T->getArgs(), T->getNumArgs());
02385     addSubstitution(QualType(T, 0));
02386   }
02387 }
02388 
02389 void CXXNameMangler::mangleType(const DependentNameType *T) {
02390   // Proposal by cxx-abi-dev, 2014-03-26
02391   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
02392   //                                 # dependent elaborated type specifier using
02393   //                                 # 'typename'
02394   //                   ::= Ts <name> # dependent elaborated type specifier using
02395   //                                 # 'struct' or 'class'
02396   //                   ::= Tu <name> # dependent elaborated type specifier using
02397   //                                 # 'union'
02398   //                   ::= Te <name> # dependent elaborated type specifier using
02399   //                                 # 'enum'
02400   switch (T->getKeyword()) {
02401     case ETK_Typename:
02402       break;
02403     case ETK_Struct:
02404     case ETK_Class:
02405     case ETK_Interface:
02406       Out << "Ts";
02407       break;
02408     case ETK_Union:
02409       Out << "Tu";
02410       break;
02411     case ETK_Enum:
02412       Out << "Te";
02413       break;
02414     default:
02415       llvm_unreachable("unexpected keyword for dependent type name");
02416   }
02417   // Typename types are always nested
02418   Out << 'N';
02419   manglePrefix(T->getQualifier());
02420   mangleSourceName(T->getIdentifier());
02421   Out << 'E';
02422 }
02423 
02424 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
02425   // Dependently-scoped template types are nested if they have a prefix.
02426   Out << 'N';
02427 
02428   // TODO: avoid making this TemplateName.
02429   TemplateName Prefix =
02430     getASTContext().getDependentTemplateName(T->getQualifier(),
02431                                              T->getIdentifier());
02432   mangleTemplatePrefix(Prefix);
02433 
02434   // FIXME: GCC does not appear to mangle the template arguments when
02435   // the template in question is a dependent template name. Should we
02436   // emulate that badness?
02437   mangleTemplateArgs(T->getArgs(), T->getNumArgs());    
02438   Out << 'E';
02439 }
02440 
02441 void CXXNameMangler::mangleType(const TypeOfType *T) {
02442   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
02443   // "extension with parameters" mangling.
02444   Out << "u6typeof";
02445 }
02446 
02447 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
02448   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
02449   // "extension with parameters" mangling.
02450   Out << "u6typeof";
02451 }
02452 
02453 void CXXNameMangler::mangleType(const DecltypeType *T) {
02454   Expr *E = T->getUnderlyingExpr();
02455 
02456   // type ::= Dt <expression> E  # decltype of an id-expression
02457   //                             #   or class member access
02458   //      ::= DT <expression> E  # decltype of an expression
02459 
02460   // This purports to be an exhaustive list of id-expressions and
02461   // class member accesses.  Note that we do not ignore parentheses;
02462   // parentheses change the semantics of decltype for these
02463   // expressions (and cause the mangler to use the other form).
02464   if (isa<DeclRefExpr>(E) ||
02465       isa<MemberExpr>(E) ||
02466       isa<UnresolvedLookupExpr>(E) ||
02467       isa<DependentScopeDeclRefExpr>(E) ||
02468       isa<CXXDependentScopeMemberExpr>(E) ||
02469       isa<UnresolvedMemberExpr>(E))
02470     Out << "Dt";
02471   else
02472     Out << "DT";
02473   mangleExpression(E);
02474   Out << 'E';
02475 }
02476 
02477 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
02478   // If this is dependent, we need to record that. If not, we simply
02479   // mangle it as the underlying type since they are equivalent.
02480   if (T->isDependentType()) {
02481     Out << 'U';
02482     
02483     switch (T->getUTTKind()) {
02484       case UnaryTransformType::EnumUnderlyingType:
02485         Out << "3eut";
02486         break;
02487     }
02488   }
02489 
02490   mangleType(T->getUnderlyingType());
02491 }
02492 
02493 void CXXNameMangler::mangleType(const AutoType *T) {
02494   QualType D = T->getDeducedType();
02495   // <builtin-type> ::= Da  # dependent auto
02496   if (D.isNull())
02497     Out << (T->isDecltypeAuto() ? "Dc" : "Da");
02498   else
02499     mangleType(D);
02500 }
02501 
02502 void CXXNameMangler::mangleType(const AtomicType *T) {
02503   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
02504   // (Until there's a standardized mangling...)
02505   Out << "U7_Atomic";
02506   mangleType(T->getValueType());
02507 }
02508 
02509 void CXXNameMangler::mangleIntegerLiteral(QualType T,
02510                                           const llvm::APSInt &Value) {
02511   //  <expr-primary> ::= L <type> <value number> E # integer literal
02512   Out << 'L';
02513 
02514   mangleType(T);
02515   if (T->isBooleanType()) {
02516     // Boolean values are encoded as 0/1.
02517     Out << (Value.getBoolValue() ? '1' : '0');
02518   } else {
02519     mangleNumber(Value);
02520   }
02521   Out << 'E';
02522 
02523 }
02524 
02525 /// Mangles a member expression.
02526 void CXXNameMangler::mangleMemberExpr(const Expr *base,
02527                                       bool isArrow,
02528                                       NestedNameSpecifier *qualifier,
02529                                       NamedDecl *firstQualifierLookup,
02530                                       DeclarationName member,
02531                                       unsigned arity) {
02532   // <expression> ::= dt <expression> <unresolved-name>
02533   //              ::= pt <expression> <unresolved-name>
02534   if (base) {
02535     if (base->isImplicitCXXThis()) {
02536       // Note: GCC mangles member expressions to the implicit 'this' as
02537       // *this., whereas we represent them as this->. The Itanium C++ ABI
02538       // does not specify anything here, so we follow GCC.
02539       Out << "dtdefpT";
02540     } else {
02541       Out << (isArrow ? "pt" : "dt");
02542       mangleExpression(base);
02543     }
02544   }
02545   mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
02546 }
02547 
02548 /// Look at the callee of the given call expression and determine if
02549 /// it's a parenthesized id-expression which would have triggered ADL
02550 /// otherwise.
02551 static bool isParenthesizedADLCallee(const CallExpr *call) {
02552   const Expr *callee = call->getCallee();
02553   const Expr *fn = callee->IgnoreParens();
02554 
02555   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
02556   // too, but for those to appear in the callee, it would have to be
02557   // parenthesized.
02558   if (callee == fn) return false;
02559 
02560   // Must be an unresolved lookup.
02561   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
02562   if (!lookup) return false;
02563 
02564   assert(!lookup->requiresADL());
02565 
02566   // Must be an unqualified lookup.
02567   if (lookup->getQualifier()) return false;
02568 
02569   // Must not have found a class member.  Note that if one is a class
02570   // member, they're all class members.
02571   if (lookup->getNumDecls() > 0 &&
02572       (*lookup->decls_begin())->isCXXClassMember())
02573     return false;
02574 
02575   // Otherwise, ADL would have been triggered.
02576   return true;
02577 }
02578 
02579 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
02580   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
02581   Out << CastEncoding;
02582   mangleType(ECE->getType());
02583   mangleExpression(ECE->getSubExpr());
02584 }
02585 
02586 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
02587   // <expression> ::= <unary operator-name> <expression>
02588   //              ::= <binary operator-name> <expression> <expression>
02589   //              ::= <trinary operator-name> <expression> <expression> <expression>
02590   //              ::= cv <type> expression           # conversion with one argument
02591   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
02592   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
02593   //              ::= sc <type> <expression>         # static_cast<type> (expression)
02594   //              ::= cc <type> <expression>         # const_cast<type> (expression)
02595   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
02596   //              ::= st <type>                      # sizeof (a type)
02597   //              ::= at <type>                      # alignof (a type)
02598   //              ::= <template-param>
02599   //              ::= <function-param>
02600   //              ::= sr <type> <unqualified-name>                   # dependent name
02601   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
02602   //              ::= ds <expression> <expression>                   # expr.*expr
02603   //              ::= sZ <template-param>                            # size of a parameter pack
02604   //              ::= sZ <function-param>    # size of a function parameter pack
02605   //              ::= <expr-primary>
02606   // <expr-primary> ::= L <type> <value number> E    # integer literal
02607   //                ::= L <type <value float> E      # floating literal
02608   //                ::= L <mangled-name> E           # external name
02609   //                ::= fpT                          # 'this' expression
02610   QualType ImplicitlyConvertedToType;
02611   
02612 recurse:
02613   switch (E->getStmtClass()) {
02614   case Expr::NoStmtClass:
02615 #define ABSTRACT_STMT(Type)
02616 #define EXPR(Type, Base)
02617 #define STMT(Type, Base) \
02618   case Expr::Type##Class:
02619 #include "clang/AST/StmtNodes.inc"
02620     // fallthrough
02621 
02622   // These all can only appear in local or variable-initialization
02623   // contexts and so should never appear in a mangling.
02624   case Expr::AddrLabelExprClass:
02625   case Expr::DesignatedInitExprClass:
02626   case Expr::ImplicitValueInitExprClass:
02627   case Expr::ParenListExprClass:
02628   case Expr::LambdaExprClass:
02629   case Expr::MSPropertyRefExprClass:
02630   case Expr::TypoExprClass:  // This should no longer exist in the AST by now.
02631     llvm_unreachable("unexpected statement kind");
02632 
02633   // FIXME: invent manglings for all these.
02634   case Expr::BlockExprClass:
02635   case Expr::CXXPseudoDestructorExprClass:
02636   case Expr::ChooseExprClass:
02637   case Expr::CompoundLiteralExprClass:
02638   case Expr::ExtVectorElementExprClass:
02639   case Expr::GenericSelectionExprClass:
02640   case Expr::ObjCEncodeExprClass:
02641   case Expr::ObjCIsaExprClass:
02642   case Expr::ObjCIvarRefExprClass:
02643   case Expr::ObjCMessageExprClass:
02644   case Expr::ObjCPropertyRefExprClass:
02645   case Expr::ObjCProtocolExprClass:
02646   case Expr::ObjCSelectorExprClass:
02647   case Expr::ObjCStringLiteralClass:
02648   case Expr::ObjCBoxedExprClass:
02649   case Expr::ObjCArrayLiteralClass:
02650   case Expr::ObjCDictionaryLiteralClass:
02651   case Expr::ObjCSubscriptRefExprClass:
02652   case Expr::ObjCIndirectCopyRestoreExprClass:
02653   case Expr::OffsetOfExprClass:
02654   case Expr::PredefinedExprClass:
02655   case Expr::ShuffleVectorExprClass:
02656   case Expr::ConvertVectorExprClass:
02657   case Expr::StmtExprClass:
02658   case Expr::TypeTraitExprClass:
02659   case Expr::ArrayTypeTraitExprClass:
02660   case Expr::ExpressionTraitExprClass:
02661   case Expr::VAArgExprClass:
02662   case Expr::CUDAKernelCallExprClass:
02663   case Expr::AsTypeExprClass:
02664   case Expr::PseudoObjectExprClass:
02665   case Expr::AtomicExprClass:
02666   {
02667     // As bad as this diagnostic is, it's better than crashing.
02668     DiagnosticsEngine &Diags = Context.getDiags();
02669     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
02670                                      "cannot yet mangle expression type %0");
02671     Diags.Report(E->getExprLoc(), DiagID)
02672       << E->getStmtClassName() << E->getSourceRange();
02673     break;
02674   }
02675 
02676   case Expr::CXXUuidofExprClass: {
02677     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
02678     if (UE->isTypeOperand()) {
02679       QualType UuidT = UE->getTypeOperand(Context.getASTContext());
02680       Out << "u8__uuidoft";
02681       mangleType(UuidT);
02682     } else {
02683       Expr *UuidExp = UE->getExprOperand();
02684       Out << "u8__uuidofz";
02685       mangleExpression(UuidExp, Arity);
02686     }
02687     break;
02688   }
02689 
02690   // Even gcc-4.5 doesn't mangle this.
02691   case Expr::BinaryConditionalOperatorClass: {
02692     DiagnosticsEngine &Diags = Context.getDiags();
02693     unsigned DiagID =
02694       Diags.getCustomDiagID(DiagnosticsEngine::Error,
02695                 "?: operator with omitted middle operand cannot be mangled");
02696     Diags.Report(E->getExprLoc(), DiagID)
02697       << E->getStmtClassName() << E->getSourceRange();
02698     break;
02699   }
02700 
02701   // These are used for internal purposes and cannot be meaningfully mangled.
02702   case Expr::OpaqueValueExprClass:
02703     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
02704 
02705   case Expr::InitListExprClass: {
02706     Out << "il";
02707     const InitListExpr *InitList = cast<InitListExpr>(E);
02708     for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
02709       mangleExpression(InitList->getInit(i));
02710     Out << "E";
02711     break;
02712   }
02713 
02714   case Expr::CXXDefaultArgExprClass:
02715     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
02716     break;
02717 
02718   case Expr::CXXDefaultInitExprClass:
02719     mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
02720     break;
02721 
02722   case Expr::CXXStdInitializerListExprClass:
02723     mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
02724     break;
02725 
02726   case Expr::SubstNonTypeTemplateParmExprClass:
02727     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
02728                      Arity);
02729     break;
02730 
02731   case Expr::UserDefinedLiteralClass:
02732     // We follow g++'s approach of mangling a UDL as a call to the literal
02733     // operator.
02734   case Expr::CXXMemberCallExprClass: // fallthrough
02735   case Expr::CallExprClass: {
02736     const CallExpr *CE = cast<CallExpr>(E);
02737 
02738     // <expression> ::= cp <simple-id> <expression>* E
02739     // We use this mangling only when the call would use ADL except
02740     // for being parenthesized.  Per discussion with David
02741     // Vandervoorde, 2011.04.25.
02742     if (isParenthesizedADLCallee(CE)) {
02743       Out << "cp";
02744       // The callee here is a parenthesized UnresolvedLookupExpr with
02745       // no qualifier and should always get mangled as a <simple-id>
02746       // anyway.
02747 
02748     // <expression> ::= cl <expression>* E
02749     } else {
02750       Out << "cl";
02751     }
02752 
02753     mangleExpression(CE->getCallee(), CE->getNumArgs());
02754     for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
02755       mangleExpression(CE->getArg(I));
02756     Out << 'E';
02757     break;
02758   }
02759 
02760   case Expr::CXXNewExprClass: {
02761     const CXXNewExpr *New = cast<CXXNewExpr>(E);
02762     if (New->isGlobalNew()) Out << "gs";
02763     Out << (New->isArray() ? "na" : "nw");
02764     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
02765            E = New->placement_arg_end(); I != E; ++I)
02766       mangleExpression(*I);
02767     Out << '_';
02768     mangleType(New->getAllocatedType());
02769     if (New->hasInitializer()) {
02770       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
02771         Out << "il";
02772       else
02773         Out << "pi";
02774       const Expr *Init = New->getInitializer();
02775       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
02776         // Directly inline the initializers.
02777         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
02778                                                   E = CCE->arg_end();
02779              I != E; ++I)
02780           mangleExpression(*I);
02781       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
02782         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
02783           mangleExpression(PLE->getExpr(i));
02784       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
02785                  isa<InitListExpr>(Init)) {
02786         // Only take InitListExprs apart for list-initialization.
02787         const InitListExpr *InitList = cast<InitListExpr>(Init);
02788         for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
02789           mangleExpression(InitList->getInit(i));
02790       } else
02791         mangleExpression(Init);
02792     }
02793     Out << 'E';
02794     break;
02795   }
02796 
02797   case Expr::MemberExprClass: {
02798     const MemberExpr *ME = cast<MemberExpr>(E);
02799     mangleMemberExpr(ME->getBase(), ME->isArrow(),
02800                      ME->getQualifier(), nullptr,
02801                      ME->getMemberDecl()->getDeclName(), Arity);
02802     break;
02803   }
02804 
02805   case Expr::UnresolvedMemberExprClass: {
02806     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
02807     mangleMemberExpr(ME->getBase(), ME->isArrow(),
02808                      ME->getQualifier(), nullptr, ME->getMemberName(),
02809                      Arity);
02810     if (ME->hasExplicitTemplateArgs())
02811       mangleTemplateArgs(ME->getExplicitTemplateArgs());
02812     break;
02813   }
02814 
02815   case Expr::CXXDependentScopeMemberExprClass: {
02816     const CXXDependentScopeMemberExpr *ME
02817       = cast<CXXDependentScopeMemberExpr>(E);
02818     mangleMemberExpr(ME->getBase(), ME->isArrow(),
02819                      ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
02820                      ME->getMember(), Arity);
02821     if (ME->hasExplicitTemplateArgs())
02822       mangleTemplateArgs(ME->getExplicitTemplateArgs());
02823     break;
02824   }
02825 
02826   case Expr::UnresolvedLookupExprClass: {
02827     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
02828     mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
02829 
02830     // All the <unresolved-name> productions end in a
02831     // base-unresolved-name, where <template-args> are just tacked
02832     // onto the end.
02833     if (ULE->hasExplicitTemplateArgs())
02834       mangleTemplateArgs(ULE->getExplicitTemplateArgs());
02835     break;
02836   }
02837 
02838   case Expr::CXXUnresolvedConstructExprClass: {
02839     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
02840     unsigned N = CE->arg_size();
02841 
02842     Out << "cv";
02843     mangleType(CE->getType());
02844     if (N != 1) Out << '_';
02845     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
02846     if (N != 1) Out << 'E';
02847     break;
02848   }
02849 
02850   case Expr::CXXTemporaryObjectExprClass:
02851   case Expr::CXXConstructExprClass: {
02852     const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
02853     unsigned N = CE->getNumArgs();
02854 
02855     if (CE->isListInitialization())
02856       Out << "tl";
02857     else
02858       Out << "cv";
02859     mangleType(CE->getType());
02860     if (N != 1) Out << '_';
02861     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
02862     if (N != 1) Out << 'E';
02863     break;
02864   }
02865 
02866   case Expr::CXXScalarValueInitExprClass:
02867     Out <<"cv";
02868     mangleType(E->getType());
02869     Out <<"_E";
02870     break;
02871 
02872   case Expr::CXXNoexceptExprClass:
02873     Out << "nx";
02874     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
02875     break;
02876 
02877   case Expr::UnaryExprOrTypeTraitExprClass: {
02878     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
02879     
02880     if (!SAE->isInstantiationDependent()) {
02881       // Itanium C++ ABI:
02882       //   If the operand of a sizeof or alignof operator is not 
02883       //   instantiation-dependent it is encoded as an integer literal 
02884       //   reflecting the result of the operator.
02885       //
02886       //   If the result of the operator is implicitly converted to a known 
02887       //   integer type, that type is used for the literal; otherwise, the type 
02888       //   of std::size_t or std::ptrdiff_t is used.
02889       QualType T = (ImplicitlyConvertedToType.isNull() || 
02890                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
02891                                                     : ImplicitlyConvertedToType;
02892       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
02893       mangleIntegerLiteral(T, V);
02894       break;
02895     }
02896     
02897     switch(SAE->getKind()) {
02898     case UETT_SizeOf:
02899       Out << 's';
02900       break;
02901     case UETT_AlignOf:
02902       Out << 'a';
02903       break;
02904     case UETT_VecStep:
02905       DiagnosticsEngine &Diags = Context.getDiags();
02906       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
02907                                      "cannot yet mangle vec_step expression");
02908       Diags.Report(DiagID);
02909       return;
02910     }
02911     if (SAE->isArgumentType()) {
02912       Out << 't';
02913       mangleType(SAE->getArgumentType());
02914     } else {
02915       Out << 'z';
02916       mangleExpression(SAE->getArgumentExpr());
02917     }
02918     break;
02919   }
02920 
02921   case Expr::CXXThrowExprClass: {
02922     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
02923     //  <expression> ::= tw <expression>  # throw expression
02924     //               ::= tr               # rethrow
02925     if (TE->getSubExpr()) {
02926       Out << "tw";
02927       mangleExpression(TE->getSubExpr());
02928     } else {
02929       Out << "tr";
02930     }
02931     break;
02932   }
02933 
02934   case Expr::CXXTypeidExprClass: {
02935     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
02936     //  <expression> ::= ti <type>        # typeid (type)
02937     //               ::= te <expression>  # typeid (expression)
02938     if (TIE->isTypeOperand()) {
02939       Out << "ti";
02940       mangleType(TIE->getTypeOperand(Context.getASTContext()));
02941     } else {
02942       Out << "te";
02943       mangleExpression(TIE->getExprOperand());
02944     }
02945     break;
02946   }
02947 
02948   case Expr::CXXDeleteExprClass: {
02949     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
02950     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
02951     //               ::= [gs] da <expression>  # [::] delete [] expr
02952     if (DE->isGlobalDelete()) Out << "gs";
02953     Out << (DE->isArrayForm() ? "da" : "dl");
02954     mangleExpression(DE->getArgument());
02955     break;
02956   }
02957 
02958   case Expr::UnaryOperatorClass: {
02959     const UnaryOperator *UO = cast<UnaryOperator>(E);
02960     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
02961                        /*Arity=*/1);
02962     mangleExpression(UO->getSubExpr());
02963     break;
02964   }
02965 
02966   case Expr::ArraySubscriptExprClass: {
02967     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
02968 
02969     // Array subscript is treated as a syntactically weird form of
02970     // binary operator.
02971     Out << "ix";
02972     mangleExpression(AE->getLHS());
02973     mangleExpression(AE->getRHS());
02974     break;
02975   }
02976 
02977   case Expr::CompoundAssignOperatorClass: // fallthrough
02978   case Expr::BinaryOperatorClass: {
02979     const BinaryOperator *BO = cast<BinaryOperator>(E);
02980     if (BO->getOpcode() == BO_PtrMemD)
02981       Out << "ds";
02982     else
02983       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
02984                          /*Arity=*/2);
02985     mangleExpression(BO->getLHS());
02986     mangleExpression(BO->getRHS());
02987     break;
02988   }
02989 
02990   case Expr::ConditionalOperatorClass: {
02991     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
02992     mangleOperatorName(OO_Conditional, /*Arity=*/3);
02993     mangleExpression(CO->getCond());
02994     mangleExpression(CO->getLHS(), Arity);
02995     mangleExpression(CO->getRHS(), Arity);
02996     break;
02997   }
02998 
02999   case Expr::ImplicitCastExprClass: {
03000     ImplicitlyConvertedToType = E->getType();
03001     E = cast<ImplicitCastExpr>(E)->getSubExpr();
03002     goto recurse;
03003   }
03004       
03005   case Expr::ObjCBridgedCastExprClass: {
03006     // Mangle ownership casts as a vendor extended operator __bridge, 
03007     // __bridge_transfer, or __bridge_retain.
03008     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
03009     Out << "v1U" << Kind.size() << Kind;
03010   }
03011   // Fall through to mangle the cast itself.
03012       
03013   case Expr::CStyleCastExprClass:
03014   case Expr::CXXFunctionalCastExprClass:
03015     mangleCastExpression(E, "cv");
03016     break;
03017 
03018   case Expr::CXXStaticCastExprClass:
03019     mangleCastExpression(E, "sc");
03020     break;
03021   case Expr::CXXDynamicCastExprClass:
03022     mangleCastExpression(E, "dc");
03023     break;
03024   case Expr::CXXReinterpretCastExprClass:
03025     mangleCastExpression(E, "rc");
03026     break;
03027   case Expr::CXXConstCastExprClass:
03028     mangleCastExpression(E, "cc");
03029     break;
03030 
03031   case Expr::CXXOperatorCallExprClass: {
03032     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
03033     unsigned NumArgs = CE->getNumArgs();
03034     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
03035     // Mangle the arguments.
03036     for (unsigned i = 0; i != NumArgs; ++i)
03037       mangleExpression(CE->getArg(i));
03038     break;
03039   }
03040 
03041   case Expr::ParenExprClass:
03042     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
03043     break;
03044 
03045   case Expr::DeclRefExprClass: {
03046     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
03047 
03048     switch (D->getKind()) {
03049     default:
03050       //  <expr-primary> ::= L <mangled-name> E # external name
03051       Out << 'L';
03052       mangle(D, "_Z");
03053       Out << 'E';
03054       break;
03055 
03056     case Decl::ParmVar:
03057       mangleFunctionParam(cast<ParmVarDecl>(D));
03058       break;
03059 
03060     case Decl::EnumConstant: {
03061       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
03062       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
03063       break;
03064     }
03065 
03066     case Decl::NonTypeTemplateParm: {
03067       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
03068       mangleTemplateParameter(PD->getIndex());
03069       break;
03070     }
03071 
03072     }
03073 
03074     break;
03075   }
03076 
03077   case Expr::SubstNonTypeTemplateParmPackExprClass:
03078     // FIXME: not clear how to mangle this!
03079     // template <unsigned N...> class A {
03080     //   template <class U...> void foo(U (&x)[N]...);
03081     // };
03082     Out << "_SUBSTPACK_";
03083     break;
03084 
03085   case Expr::FunctionParmPackExprClass: {
03086     // FIXME: not clear how to mangle this!
03087     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
03088     Out << "v110_SUBSTPACK";
03089     mangleFunctionParam(FPPE->getParameterPack());
03090     break;
03091   }
03092 
03093   case Expr::DependentScopeDeclRefExprClass: {
03094     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
03095     mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
03096                          Arity);
03097 
03098     // All the <unresolved-name> productions end in a
03099     // base-unresolved-name, where <template-args> are just tacked
03100     // onto the end.
03101     if (DRE->hasExplicitTemplateArgs())
03102       mangleTemplateArgs(DRE->getExplicitTemplateArgs());
03103     break;
03104   }
03105 
03106   case Expr::CXXBindTemporaryExprClass:
03107     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
03108     break;
03109 
03110   case Expr::ExprWithCleanupsClass:
03111     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
03112     break;
03113 
03114   case Expr::FloatingLiteralClass: {
03115     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
03116     Out << 'L';
03117     mangleType(FL->getType());
03118     mangleFloat(FL->getValue());
03119     Out << 'E';
03120     break;
03121   }
03122 
03123   case Expr::CharacterLiteralClass:
03124     Out << 'L';
03125     mangleType(E->getType());
03126     Out << cast<CharacterLiteral>(E)->getValue();
03127     Out << 'E';
03128     break;
03129 
03130   // FIXME. __objc_yes/__objc_no are mangled same as true/false
03131   case Expr::ObjCBoolLiteralExprClass:
03132     Out << "Lb";
03133     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
03134     Out << 'E';
03135     break;
03136   
03137   case Expr::CXXBoolLiteralExprClass:
03138     Out << "Lb";
03139     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
03140     Out << 'E';
03141     break;
03142 
03143   case Expr::IntegerLiteralClass: {
03144     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
03145     if (E->getType()->isSignedIntegerType())
03146       Value.setIsSigned(true);
03147     mangleIntegerLiteral(E->getType(), Value);
03148     break;
03149   }
03150 
03151   case Expr::ImaginaryLiteralClass: {
03152     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
03153     // Mangle as if a complex literal.
03154     // Proposal from David Vandevoorde, 2010.06.30.
03155     Out << 'L';
03156     mangleType(E->getType());
03157     if (const FloatingLiteral *Imag =
03158           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
03159       // Mangle a floating-point zero of the appropriate type.
03160       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
03161       Out << '_';
03162       mangleFloat(Imag->getValue());
03163     } else {
03164       Out << "0_";
03165       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
03166       if (IE->getSubExpr()->getType()->isSignedIntegerType())
03167         Value.setIsSigned(true);
03168       mangleNumber(Value);
03169     }
03170     Out << 'E';
03171     break;
03172   }
03173 
03174   case Expr::StringLiteralClass: {
03175     // Revised proposal from David Vandervoorde, 2010.07.15.
03176     Out << 'L';
03177     assert(isa<ConstantArrayType>(E->getType()));
03178     mangleType(E->getType());
03179     Out << 'E';
03180     break;
03181   }
03182 
03183   case Expr::GNUNullExprClass:
03184     // FIXME: should this really be mangled the same as nullptr?
03185     // fallthrough
03186 
03187   case Expr::CXXNullPtrLiteralExprClass: {
03188     Out << "LDnE";
03189     break;
03190   }
03191       
03192   case Expr::PackExpansionExprClass:
03193     Out << "sp";
03194     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
03195     break;
03196       
03197   case Expr::SizeOfPackExprClass: {
03198     Out << "sZ";
03199     const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
03200     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
03201       mangleTemplateParameter(TTP->getIndex());
03202     else if (const NonTypeTemplateParmDecl *NTTP
03203                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
03204       mangleTemplateParameter(NTTP->getIndex());
03205     else if (const TemplateTemplateParmDecl *TempTP
03206                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
03207       mangleTemplateParameter(TempTP->getIndex());
03208     else
03209       mangleFunctionParam(cast<ParmVarDecl>(Pack));
03210     break;
03211   }
03212 
03213   case Expr::MaterializeTemporaryExprClass: {
03214     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
03215     break;
03216   }
03217 
03218   case Expr::CXXFoldExprClass: {
03219     auto *FE = cast<CXXFoldExpr>(E);
03220     if (FE->isLeftFold())
03221       Out << (FE->getInit() ? "fL" : "fl");
03222     else
03223       Out << (FE->getInit() ? "fR" : "fr");
03224 
03225     if (FE->getOperator() == BO_PtrMemD)
03226       Out << "ds";
03227     else
03228       mangleOperatorName(
03229           BinaryOperator::getOverloadedOperator(FE->getOperator()),
03230           /*Arity=*/2);
03231 
03232     if (FE->getLHS())
03233       mangleExpression(FE->getLHS());
03234     if (FE->getRHS())
03235       mangleExpression(FE->getRHS());
03236     break;
03237   }
03238 
03239   case Expr::CXXThisExprClass:
03240     Out << "fpT";
03241     break;
03242   }
03243 }
03244 
03245 /// Mangle an expression which refers to a parameter variable.
03246 ///
03247 /// <expression>     ::= <function-param>
03248 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
03249 /// <function-param> ::= fp <top-level CV-qualifiers>
03250 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
03251 /// <function-param> ::= fL <L-1 non-negative number>
03252 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
03253 /// <function-param> ::= fL <L-1 non-negative number>
03254 ///                      p <top-level CV-qualifiers>
03255 ///                      <I-1 non-negative number> _         # L > 0, I > 0
03256 ///
03257 /// L is the nesting depth of the parameter, defined as 1 if the
03258 /// parameter comes from the innermost function prototype scope
03259 /// enclosing the current context, 2 if from the next enclosing
03260 /// function prototype scope, and so on, with one special case: if
03261 /// we've processed the full parameter clause for the innermost
03262 /// function type, then L is one less.  This definition conveniently
03263 /// makes it irrelevant whether a function's result type was written
03264 /// trailing or leading, but is otherwise overly complicated; the
03265 /// numbering was first designed without considering references to
03266 /// parameter in locations other than return types, and then the
03267 /// mangling had to be generalized without changing the existing
03268 /// manglings.
03269 ///
03270 /// I is the zero-based index of the parameter within its parameter
03271 /// declaration clause.  Note that the original ABI document describes
03272 /// this using 1-based ordinals.
03273 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
03274   unsigned parmDepth = parm->getFunctionScopeDepth();
03275   unsigned parmIndex = parm->getFunctionScopeIndex();
03276 
03277   // Compute 'L'.
03278   // parmDepth does not include the declaring function prototype.
03279   // FunctionTypeDepth does account for that.
03280   assert(parmDepth < FunctionTypeDepth.getDepth());
03281   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
03282   if (FunctionTypeDepth.isInResultType())
03283     nestingDepth--;
03284 
03285   if (nestingDepth == 0) {
03286     Out << "fp";
03287   } else {
03288     Out << "fL" << (nestingDepth - 1) << 'p';
03289   }
03290 
03291   // Top-level qualifiers.  We don't have to worry about arrays here,
03292   // because parameters declared as arrays should already have been
03293   // transformed to have pointer type. FIXME: apparently these don't
03294   // get mangled if used as an rvalue of a known non-class type?
03295   assert(!parm->getType()->isArrayType()
03296          && "parameter's type is still an array type?");
03297   mangleQualifiers(parm->getType().getQualifiers());
03298 
03299   // Parameter index.
03300   if (parmIndex != 0) {
03301     Out << (parmIndex - 1);
03302   }
03303   Out << '_';
03304 }
03305 
03306 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
03307   // <ctor-dtor-name> ::= C1  # complete object constructor
03308   //                  ::= C2  # base object constructor
03309   //
03310   // In addition, C5 is a comdat name with C1 and C2 in it.
03311   switch (T) {
03312   case Ctor_Complete:
03313     Out << "C1";
03314     break;
03315   case Ctor_Base:
03316     Out << "C2";
03317     break;
03318   case Ctor_Comdat:
03319     Out << "C5";
03320     break;
03321   }
03322 }
03323 
03324 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
03325   // <ctor-dtor-name> ::= D0  # deleting destructor
03326   //                  ::= D1  # complete object destructor
03327   //                  ::= D2  # base object destructor
03328   //
03329   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
03330   switch (T) {
03331   case Dtor_Deleting:
03332     Out << "D0";
03333     break;
03334   case Dtor_Complete:
03335     Out << "D1";
03336     break;
03337   case Dtor_Base:
03338     Out << "D2";
03339     break;
03340   case Dtor_Comdat:
03341     Out << "D5";
03342     break;
03343   }
03344 }
03345 
03346 void CXXNameMangler::mangleTemplateArgs(
03347                           const ASTTemplateArgumentListInfo &TemplateArgs) {
03348   // <template-args> ::= I <template-arg>+ E
03349   Out << 'I';
03350   for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
03351     mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
03352   Out << 'E';
03353 }
03354 
03355 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
03356   // <template-args> ::= I <template-arg>+ E
03357   Out << 'I';
03358   for (unsigned i = 0, e = AL.size(); i != e; ++i)
03359     mangleTemplateArg(AL[i]);
03360   Out << 'E';
03361 }
03362 
03363 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
03364                                         unsigned NumTemplateArgs) {
03365   // <template-args> ::= I <template-arg>+ E
03366   Out << 'I';
03367   for (unsigned i = 0; i != NumTemplateArgs; ++i)
03368     mangleTemplateArg(TemplateArgs[i]);
03369   Out << 'E';
03370 }
03371 
03372 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
03373   // <template-arg> ::= <type>              # type or template
03374   //                ::= X <expression> E    # expression
03375   //                ::= <expr-primary>      # simple expressions
03376   //                ::= J <template-arg>* E # argument pack
03377   if (!A.isInstantiationDependent() || A.isDependent())
03378     A = Context.getASTContext().getCanonicalTemplateArgument(A);
03379   
03380   switch (A.getKind()) {
03381   case TemplateArgument::Null:
03382     llvm_unreachable("Cannot mangle NULL template argument");
03383       
03384   case TemplateArgument::Type:
03385     mangleType(A.getAsType());
03386     break;
03387   case TemplateArgument::Template:
03388     // This is mangled as <type>.
03389     mangleType(A.getAsTemplate());
03390     break;
03391   case TemplateArgument::TemplateExpansion:
03392     // <type>  ::= Dp <type>          # pack expansion (C++0x)
03393     Out << "Dp";
03394     mangleType(A.getAsTemplateOrTemplatePattern());
03395     break;
03396   case TemplateArgument::Expression: {
03397     // It's possible to end up with a DeclRefExpr here in certain
03398     // dependent cases, in which case we should mangle as a
03399     // declaration.
03400     const Expr *E = A.getAsExpr()->IgnoreParens();
03401     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
03402       const ValueDecl *D = DRE->getDecl();
03403       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
03404         Out << "L";
03405         mangle(D, "_Z");
03406         Out << 'E';
03407         break;
03408       }
03409     }
03410     
03411     Out << 'X';
03412     mangleExpression(E);
03413     Out << 'E';
03414     break;
03415   }
03416   case TemplateArgument::Integral:
03417     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
03418     break;
03419   case TemplateArgument::Declaration: {
03420     //  <expr-primary> ::= L <mangled-name> E # external name
03421     // Clang produces AST's where pointer-to-member-function expressions
03422     // and pointer-to-function expressions are represented as a declaration not
03423     // an expression. We compensate for it here to produce the correct mangling.
03424     ValueDecl *D = A.getAsDecl();
03425     bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
03426     if (compensateMangling) {
03427       Out << 'X';
03428       mangleOperatorName(OO_Amp, 1);
03429     }
03430 
03431     Out << 'L';
03432     // References to external entities use the mangled name; if the name would
03433     // not normally be manged then mangle it as unqualified.
03434     //
03435     // FIXME: The ABI specifies that external names here should have _Z, but
03436     // gcc leaves this off.
03437     if (compensateMangling)
03438       mangle(D, "_Z");
03439     else
03440       mangle(D, "Z");
03441     Out << 'E';
03442 
03443     if (compensateMangling)
03444       Out << 'E';
03445 
03446     break;
03447   }
03448   case TemplateArgument::NullPtr: {
03449     //  <expr-primary> ::= L <type> 0 E
03450     Out << 'L';
03451     mangleType(A.getNullPtrType());
03452     Out << "0E";
03453     break;
03454   }
03455   case TemplateArgument::Pack: {
03456     //  <template-arg> ::= J <template-arg>* E
03457     Out << 'J';
03458     for (const auto &P : A.pack_elements())
03459       mangleTemplateArg(P);
03460     Out << 'E';
03461   }
03462   }
03463 }
03464 
03465 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
03466   // <template-param> ::= T_    # first template parameter
03467   //                  ::= T <parameter-2 non-negative number> _
03468   if (Index == 0)
03469     Out << "T_";
03470   else
03471     Out << 'T' << (Index - 1) << '_';
03472 }
03473 
03474 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
03475   if (SeqID == 1)
03476     Out << '0';
03477   else if (SeqID > 1) {
03478     SeqID--;
03479 
03480     // <seq-id> is encoded in base-36, using digits and upper case letters.
03481     char Buffer[7]; // log(2**32) / log(36) ~= 7
03482     MutableArrayRef<char> BufferRef(Buffer);
03483     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
03484 
03485     for (; SeqID != 0; SeqID /= 36) {
03486       unsigned C = SeqID % 36;
03487       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
03488     }
03489 
03490     Out.write(I.base(), I - BufferRef.rbegin());
03491   }
03492   Out << '_';
03493 }
03494 
03495 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
03496   bool result = mangleSubstitution(type);
03497   assert(result && "no existing substitution for type");
03498   (void) result;
03499 }
03500 
03501 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
03502   bool result = mangleSubstitution(tname);
03503   assert(result && "no existing substitution for template name");
03504   (void) result;
03505 }
03506 
03507 // <substitution> ::= S <seq-id> _
03508 //                ::= S_
03509 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
03510   // Try one of the standard substitutions first.
03511   if (mangleStandardSubstitution(ND))
03512     return true;
03513 
03514   ND = cast<NamedDecl>(ND->getCanonicalDecl());
03515   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
03516 }
03517 
03518 /// \brief Determine whether the given type has any qualifiers that are
03519 /// relevant for substitutions.
03520 static bool hasMangledSubstitutionQualifiers(QualType T) {
03521   Qualifiers Qs = T.getQualifiers();
03522   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
03523 }
03524 
03525 bool CXXNameMangler::mangleSubstitution(QualType T) {
03526   if (!hasMangledSubstitutionQualifiers(T)) {
03527     if (const RecordType *RT = T->getAs<RecordType>())
03528       return mangleSubstitution(RT->getDecl());
03529   }
03530 
03531   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
03532 
03533   return mangleSubstitution(TypePtr);
03534 }
03535 
03536 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
03537   if (TemplateDecl *TD = Template.getAsTemplateDecl())
03538     return mangleSubstitution(TD);
03539   
03540   Template = Context.getASTContext().getCanonicalTemplateName(Template);
03541   return mangleSubstitution(
03542                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
03543 }
03544 
03545 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
03546   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
03547   if (I == Substitutions.end())
03548     return false;
03549 
03550   unsigned SeqID = I->second;
03551   Out << 'S';
03552   mangleSeqID(SeqID);
03553 
03554   return true;
03555 }
03556 
03557 static bool isCharType(QualType T) {
03558   if (T.isNull())
03559     return false;
03560 
03561   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
03562     T->isSpecificBuiltinType(BuiltinType::Char_U);
03563 }
03564 
03565 /// isCharSpecialization - Returns whether a given type is a template
03566 /// specialization of a given name with a single argument of type char.
03567 static bool isCharSpecialization(QualType T, const char *Name) {
03568   if (T.isNull())
03569     return false;
03570 
03571   const RecordType *RT = T->getAs<RecordType>();
03572   if (!RT)
03573     return false;
03574 
03575   const ClassTemplateSpecializationDecl *SD =
03576     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
03577   if (!SD)
03578     return false;
03579 
03580   if (!isStdNamespace(getEffectiveDeclContext(SD)))
03581     return false;
03582 
03583   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
03584   if (TemplateArgs.size() != 1)
03585     return false;
03586 
03587   if (!isCharType(TemplateArgs[0].getAsType()))
03588     return false;
03589 
03590   return SD->getIdentifier()->getName() == Name;
03591 }
03592 
03593 template <std::size_t StrLen>
03594 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
03595                                        const char (&Str)[StrLen]) {
03596   if (!SD->getIdentifier()->isStr(Str))
03597     return false;
03598 
03599   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
03600   if (TemplateArgs.size() != 2)
03601     return false;
03602 
03603   if (!isCharType(TemplateArgs[0].getAsType()))
03604     return false;
03605 
03606   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
03607     return false;
03608 
03609   return true;
03610 }
03611 
03612 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
03613   // <substitution> ::= St # ::std::
03614   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
03615     if (isStd(NS)) {
03616       Out << "St";
03617       return true;
03618     }
03619   }
03620 
03621   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
03622     if (!isStdNamespace(getEffectiveDeclContext(TD)))
03623       return false;
03624 
03625     // <substitution> ::= Sa # ::std::allocator
03626     if (TD->getIdentifier()->isStr("allocator")) {
03627       Out << "Sa";
03628       return true;
03629     }
03630 
03631     // <<substitution> ::= Sb # ::std::basic_string
03632     if (TD->getIdentifier()->isStr("basic_string")) {
03633       Out << "Sb";
03634       return true;
03635     }
03636   }
03637 
03638   if (const ClassTemplateSpecializationDecl *SD =
03639         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
03640     if (!isStdNamespace(getEffectiveDeclContext(SD)))
03641       return false;
03642 
03643     //    <substitution> ::= Ss # ::std::basic_string<char,
03644     //                            ::std::char_traits<char>,
03645     //                            ::std::allocator<char> >
03646     if (SD->getIdentifier()->isStr("basic_string")) {
03647       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
03648 
03649       if (TemplateArgs.size() != 3)
03650         return false;
03651 
03652       if (!isCharType(TemplateArgs[0].getAsType()))
03653         return false;
03654 
03655       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
03656         return false;
03657 
03658       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
03659         return false;
03660 
03661       Out << "Ss";
03662       return true;
03663     }
03664 
03665     //    <substitution> ::= Si # ::std::basic_istream<char,
03666     //                            ::std::char_traits<char> >
03667     if (isStreamCharSpecialization(SD, "basic_istream")) {
03668       Out << "Si";
03669       return true;
03670     }
03671 
03672     //    <substitution> ::= So # ::std::basic_ostream<char,
03673     //                            ::std::char_traits<char> >
03674     if (isStreamCharSpecialization(SD, "basic_ostream")) {
03675       Out << "So";
03676       return true;
03677     }
03678 
03679     //    <substitution> ::= Sd # ::std::basic_iostream<char,
03680     //                            ::std::char_traits<char> >
03681     if (isStreamCharSpecialization(SD, "basic_iostream")) {
03682       Out << "Sd";
03683       return true;
03684     }
03685   }
03686   return false;
03687 }
03688 
03689 void CXXNameMangler::addSubstitution(QualType T) {
03690   if (!hasMangledSubstitutionQualifiers(T)) {
03691     if (const RecordType *RT = T->getAs<RecordType>()) {
03692       addSubstitution(RT->getDecl());
03693       return;
03694     }
03695   }
03696 
03697   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
03698   addSubstitution(TypePtr);
03699 }
03700 
03701 void CXXNameMangler::addSubstitution(TemplateName Template) {
03702   if (TemplateDecl *TD = Template.getAsTemplateDecl())
03703     return addSubstitution(TD);
03704   
03705   Template = Context.getASTContext().getCanonicalTemplateName(Template);
03706   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
03707 }
03708 
03709 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
03710   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
03711   Substitutions[Ptr] = SeqID++;
03712 }
03713 
03714 //
03715 
03716 /// \brief Mangles the name of the declaration D and emits that name to the
03717 /// given output stream.
03718 ///
03719 /// If the declaration D requires a mangled name, this routine will emit that
03720 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
03721 /// and this routine will return false. In this case, the caller should just
03722 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
03723 /// name.
03724 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
03725                                              raw_ostream &Out) {
03726   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
03727           "Invalid mangleName() call, argument is not a variable or function!");
03728   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
03729          "Invalid mangleName() call on 'structor decl!");
03730 
03731   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
03732                                  getASTContext().getSourceManager(),
03733                                  "Mangling declaration");
03734 
03735   CXXNameMangler Mangler(*this, Out, D);
03736   return Mangler.mangle(D);
03737 }
03738 
03739 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
03740                                              CXXCtorType Type,
03741                                              raw_ostream &Out) {
03742   CXXNameMangler Mangler(*this, Out, D, Type);
03743   Mangler.mangle(D);
03744 }
03745 
03746 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
03747                                              CXXDtorType Type,
03748                                              raw_ostream &Out) {
03749   CXXNameMangler Mangler(*this, Out, D, Type);
03750   Mangler.mangle(D);
03751 }
03752 
03753 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
03754                                                    raw_ostream &Out) {
03755   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
03756   Mangler.mangle(D);
03757 }
03758 
03759 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
03760                                                    raw_ostream &Out) {
03761   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
03762   Mangler.mangle(D);
03763 }
03764 
03765 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
03766                                            const ThunkInfo &Thunk,
03767                                            raw_ostream &Out) {
03768   //  <special-name> ::= T <call-offset> <base encoding>
03769   //                      # base is the nominal target function of thunk
03770   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
03771   //                      # base is the nominal target function of thunk
03772   //                      # first call-offset is 'this' adjustment
03773   //                      # second call-offset is result adjustment
03774   
03775   assert(!isa<CXXDestructorDecl>(MD) &&
03776          "Use mangleCXXDtor for destructor decls!");
03777   CXXNameMangler Mangler(*this, Out);
03778   Mangler.getStream() << "_ZT";
03779   if (!Thunk.Return.isEmpty())
03780     Mangler.getStream() << 'c';
03781   
03782   // Mangle the 'this' pointer adjustment.
03783   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
03784                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
03785 
03786   // Mangle the return pointer adjustment if there is one.
03787   if (!Thunk.Return.isEmpty())
03788     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
03789                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
03790 
03791   Mangler.mangleFunctionEncoding(MD);
03792 }
03793 
03794 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
03795     const CXXDestructorDecl *DD, CXXDtorType Type,
03796     const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
03797   //  <special-name> ::= T <call-offset> <base encoding>
03798   //                      # base is the nominal target function of thunk
03799   CXXNameMangler Mangler(*this, Out, DD, Type);
03800   Mangler.getStream() << "_ZT";
03801 
03802   // Mangle the 'this' pointer adjustment.
03803   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 
03804                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
03805 
03806   Mangler.mangleFunctionEncoding(DD);
03807 }
03808 
03809 /// mangleGuardVariable - Returns the mangled name for a guard variable
03810 /// for the passed in VarDecl.
03811 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
03812                                                          raw_ostream &Out) {
03813   //  <special-name> ::= GV <object name>       # Guard variable for one-time
03814   //                                            # initialization
03815   CXXNameMangler Mangler(*this, Out);
03816   Mangler.getStream() << "_ZGV";
03817   Mangler.mangleName(D);
03818 }
03819 
03820 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
03821                                                         raw_ostream &Out) {
03822   // These symbols are internal in the Itanium ABI, so the names don't matter.
03823   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
03824   // avoid duplicate symbols.
03825   Out << "__cxx_global_var_init";
03826 }
03827 
03828 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
03829                                                              raw_ostream &Out) {
03830   // Prefix the mangling of D with __dtor_.
03831   CXXNameMangler Mangler(*this, Out);
03832   Mangler.getStream() << "__dtor_";
03833   if (shouldMangleDeclName(D))
03834     Mangler.mangle(D);
03835   else
03836     Mangler.getStream() << D->getName();
03837 }
03838 
03839 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
03840                                                             raw_ostream &Out) {
03841   //  <special-name> ::= TH <object name>
03842   CXXNameMangler Mangler(*this, Out);
03843   Mangler.getStream() << "_ZTH";
03844   Mangler.mangleName(D);
03845 }
03846 
03847 void
03848 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
03849                                                           raw_ostream &Out) {
03850   //  <special-name> ::= TW <object name>
03851   CXXNameMangler Mangler(*this, Out);
03852   Mangler.getStream() << "_ZTW";
03853   Mangler.mangleName(D);
03854 }
03855 
03856 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
03857                                                         unsigned ManglingNumber,
03858                                                         raw_ostream &Out) {
03859   // We match the GCC mangling here.
03860   //  <special-name> ::= GR <object name>
03861   CXXNameMangler Mangler(*this, Out);
03862   Mangler.getStream() << "_ZGR";
03863   Mangler.mangleName(D);
03864   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
03865   Mangler.mangleSeqID(ManglingNumber - 1);
03866 }
03867 
03868 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
03869                                                raw_ostream &Out) {
03870   // <special-name> ::= TV <type>  # virtual table
03871   CXXNameMangler Mangler(*this, Out);
03872   Mangler.getStream() << "_ZTV";
03873   Mangler.mangleNameOrStandardSubstitution(RD);
03874 }
03875 
03876 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
03877                                             raw_ostream &Out) {
03878   // <special-name> ::= TT <type>  # VTT structure
03879   CXXNameMangler Mangler(*this, Out);
03880   Mangler.getStream() << "_ZTT";
03881   Mangler.mangleNameOrStandardSubstitution(RD);
03882 }
03883 
03884 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
03885                                                    int64_t Offset,
03886                                                    const CXXRecordDecl *Type,
03887                                                    raw_ostream &Out) {
03888   // <special-name> ::= TC <type> <offset number> _ <base type>
03889   CXXNameMangler Mangler(*this, Out);
03890   Mangler.getStream() << "_ZTC";
03891   Mangler.mangleNameOrStandardSubstitution(RD);
03892   Mangler.getStream() << Offset;
03893   Mangler.getStream() << '_';
03894   Mangler.mangleNameOrStandardSubstitution(Type);
03895 }
03896 
03897 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
03898   // <special-name> ::= TI <type>  # typeinfo structure
03899   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
03900   CXXNameMangler Mangler(*this, Out);
03901   Mangler.getStream() << "_ZTI";
03902   Mangler.mangleType(Ty);
03903 }
03904 
03905 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
03906                                                  raw_ostream &Out) {
03907   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
03908   CXXNameMangler Mangler(*this, Out);
03909   Mangler.getStream() << "_ZTS";
03910   Mangler.mangleType(Ty);
03911 }
03912 
03913 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
03914   mangleCXXRTTIName(Ty, Out);
03915 }
03916 
03917 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
03918   llvm_unreachable("Can't mangle string literals");
03919 }
03920 
03921 ItaniumMangleContext *
03922 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
03923   return new ItaniumMangleContextImpl(Context, Diags);
03924 }