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