Home | History | Annotate | Download | only in AST
      1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/AST/Mangle.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/Attr.h"
     17 #include "clang/AST/CharUnits.h"
     18 #include "clang/AST/Decl.h"
     19 #include "clang/AST/DeclCXX.h"
     20 #include "clang/AST/DeclObjC.h"
     21 #include "clang/AST/DeclTemplate.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/Basic/ABI.h"
     24 #include "clang/Basic/DiagnosticOptions.h"
     25 #include <map>
     26 
     27 using namespace clang;
     28 
     29 namespace {
     30 
     31 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
     32   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
     33     return ftd->getTemplatedDecl();
     34 
     35   return fn;
     36 }
     37 
     38 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
     39 /// Microsoft Visual C++ ABI.
     40 class MicrosoftCXXNameMangler {
     41   MangleContext &Context;
     42   raw_ostream &Out;
     43 
     44   /// The "structor" is the top-level declaration being mangled, if
     45   /// that's not a template specialization; otherwise it's the pattern
     46   /// for that specialization.
     47   const NamedDecl *Structor;
     48   unsigned StructorType;
     49 
     50   // FIXME: audit the performance of BackRefMap as it might do way too many
     51   // copying of strings.
     52   typedef std::map<std::string, unsigned> BackRefMap;
     53   BackRefMap NameBackReferences;
     54   bool UseNameBackReferences;
     55 
     56   typedef llvm::DenseMap<void*, unsigned> ArgBackRefMap;
     57   ArgBackRefMap TypeBackReferences;
     58 
     59   ASTContext &getASTContext() const { return Context.getASTContext(); }
     60 
     61 public:
     62   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
     63     : Context(C), Out(Out_),
     64       Structor(0), StructorType(-1),
     65       UseNameBackReferences(true) { }
     66 
     67   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_,
     68                           const CXXDestructorDecl *D, CXXDtorType Type)
     69     : Context(C), Out(Out_),
     70       Structor(getStructor(D)), StructorType(Type),
     71       UseNameBackReferences(true) { }
     72 
     73   raw_ostream &getStream() const { return Out; }
     74 
     75   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
     76   void mangleName(const NamedDecl *ND);
     77   void mangleFunctionEncoding(const FunctionDecl *FD);
     78   void mangleVariableEncoding(const VarDecl *VD);
     79   void mangleNumber(int64_t Number);
     80   void mangleNumber(const llvm::APSInt &Value);
     81   void mangleType(QualType T, SourceRange Range, bool MangleQualifiers = true);
     82 
     83 private:
     84   void disableBackReferences() { UseNameBackReferences = false; }
     85   void mangleUnqualifiedName(const NamedDecl *ND) {
     86     mangleUnqualifiedName(ND, ND->getDeclName());
     87   }
     88   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
     89   void mangleSourceName(const IdentifierInfo *II);
     90   void manglePostfix(const DeclContext *DC, bool NoFunction=false);
     91   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
     92   void mangleCXXDtorType(CXXDtorType T);
     93   void mangleQualifiers(Qualifiers Quals, bool IsMember);
     94   void manglePointerQualifiers(Qualifiers Quals);
     95 
     96   void mangleUnscopedTemplateName(const TemplateDecl *ND);
     97   void mangleTemplateInstantiationName(const TemplateDecl *TD,
     98                       const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs);
     99   void mangleObjCMethodName(const ObjCMethodDecl *MD);
    100   void mangleLocalName(const FunctionDecl *FD);
    101 
    102   void mangleArgumentType(QualType T, SourceRange Range);
    103 
    104   // Declare manglers for every type class.
    105 #define ABSTRACT_TYPE(CLASS, PARENT)
    106 #define NON_CANONICAL_TYPE(CLASS, PARENT)
    107 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
    108                                             SourceRange Range);
    109 #include "clang/AST/TypeNodes.def"
    110 #undef ABSTRACT_TYPE
    111 #undef NON_CANONICAL_TYPE
    112 #undef TYPE
    113 
    114   void mangleType(const TagType*);
    115   void mangleType(const FunctionType *T, const FunctionDecl *D,
    116                   bool IsStructor, bool IsInstMethod);
    117   void mangleType(const ArrayType *T, bool IsGlobal);
    118   void mangleExtraDimensions(QualType T);
    119   void mangleFunctionClass(const FunctionDecl *FD);
    120   void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
    121   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
    122   void mangleExpression(const Expr *E);
    123   void mangleThrowSpecification(const FunctionProtoType *T);
    124 
    125   void mangleTemplateArgs(
    126                       const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs);
    127 
    128 };
    129 
    130 /// MicrosoftMangleContext - Overrides the default MangleContext for the
    131 /// Microsoft Visual C++ ABI.
    132 class MicrosoftMangleContext : public MangleContext {
    133 public:
    134   MicrosoftMangleContext(ASTContext &Context,
    135                    DiagnosticsEngine &Diags) : MangleContext(Context, Diags) { }
    136   virtual bool shouldMangleDeclName(const NamedDecl *D);
    137   virtual void mangleName(const NamedDecl *D, raw_ostream &Out);
    138   virtual void mangleThunk(const CXXMethodDecl *MD,
    139                            const ThunkInfo &Thunk,
    140                            raw_ostream &);
    141   virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
    142                                   const ThisAdjustment &ThisAdjustment,
    143                                   raw_ostream &);
    144   virtual void mangleCXXVTable(const CXXRecordDecl *RD,
    145                                raw_ostream &);
    146   virtual void mangleCXXVTT(const CXXRecordDecl *RD,
    147                             raw_ostream &);
    148   virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
    149                                    const CXXRecordDecl *Type,
    150                                    raw_ostream &);
    151   virtual void mangleCXXRTTI(QualType T, raw_ostream &);
    152   virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
    153   virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
    154                              raw_ostream &);
    155   virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
    156                              raw_ostream &);
    157   virtual void mangleReferenceTemporary(const clang::VarDecl *,
    158                                         raw_ostream &);
    159 };
    160 
    161 }
    162 
    163 static bool isInCLinkageSpecification(const Decl *D) {
    164   D = D->getCanonicalDecl();
    165   for (const DeclContext *DC = D->getDeclContext();
    166        !DC->isTranslationUnit(); DC = DC->getParent()) {
    167     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
    168       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
    169   }
    170 
    171   return false;
    172 }
    173 
    174 bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
    175   // In C, functions with no attributes never need to be mangled. Fastpath them.
    176   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
    177     return false;
    178 
    179   // Any decl can be declared with __asm("foo") on it, and this takes precedence
    180   // over all other naming in the .o file.
    181   if (D->hasAttr<AsmLabelAttr>())
    182     return true;
    183 
    184   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
    185   // (always) as does passing a C++ member function and a function
    186   // whose name is not a simple identifier.
    187   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
    188   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
    189              !FD->getDeclName().isIdentifier()))
    190     return true;
    191 
    192   // Otherwise, no mangling is done outside C++ mode.
    193   if (!getASTContext().getLangOpts().CPlusPlus)
    194     return false;
    195 
    196   // Variables at global scope with internal linkage are not mangled.
    197   if (!FD) {
    198     const DeclContext *DC = D->getDeclContext();
    199     if (DC->isTranslationUnit() && D->getLinkage() == InternalLinkage)
    200       return false;
    201   }
    202 
    203   // C functions and "main" are not mangled.
    204   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
    205     return false;
    206 
    207   return true;
    208 }
    209 
    210 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
    211                                      StringRef Prefix) {
    212   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
    213   // Therefore it's really important that we don't decorate the
    214   // name with leading underscores or leading/trailing at signs. So, by
    215   // default, we emit an asm marker at the start so we get the name right.
    216   // Callers can override this with a custom prefix.
    217 
    218   // Any decl can be declared with __asm("foo") on it, and this takes precedence
    219   // over all other naming in the .o file.
    220   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
    221     // If we have an asm name, then we use it as the mangling.
    222     Out << '\01' << ALA->getLabel();
    223     return;
    224   }
    225 
    226   // <mangled-name> ::= ? <name> <type-encoding>
    227   Out << Prefix;
    228   mangleName(D);
    229   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
    230     mangleFunctionEncoding(FD);
    231   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
    232     mangleVariableEncoding(VD);
    233   else {
    234     // TODO: Fields? Can MSVC even mangle them?
    235     // Issue a diagnostic for now.
    236     DiagnosticsEngine &Diags = Context.getDiags();
    237     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
    238       "cannot mangle this declaration yet");
    239     Diags.Report(D->getLocation(), DiagID)
    240       << D->getSourceRange();
    241   }
    242 }
    243 
    244 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
    245   // <type-encoding> ::= <function-class> <function-type>
    246 
    247   // Don't mangle in the type if this isn't a decl we should typically mangle.
    248   if (!Context.shouldMangleDeclName(FD))
    249     return;
    250 
    251   // We should never ever see a FunctionNoProtoType at this point.
    252   // We don't even know how to mangle their types anyway :).
    253   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
    254 
    255   bool InStructor = false, InInstMethod = false;
    256   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
    257   if (MD) {
    258     if (MD->isInstance())
    259       InInstMethod = true;
    260     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
    261       InStructor = true;
    262   }
    263 
    264   // First, the function class.
    265   mangleFunctionClass(FD);
    266 
    267   mangleType(FT, FD, InStructor, InInstMethod);
    268 }
    269 
    270 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
    271   // <type-encoding> ::= <storage-class> <variable-type>
    272   // <storage-class> ::= 0  # private static member
    273   //                 ::= 1  # protected static member
    274   //                 ::= 2  # public static member
    275   //                 ::= 3  # global
    276   //                 ::= 4  # static local
    277 
    278   // The first character in the encoding (after the name) is the storage class.
    279   if (VD->isStaticDataMember()) {
    280     // If it's a static member, it also encodes the access level.
    281     switch (VD->getAccess()) {
    282       default:
    283       case AS_private: Out << '0'; break;
    284       case AS_protected: Out << '1'; break;
    285       case AS_public: Out << '2'; break;
    286     }
    287   }
    288   else if (!VD->isStaticLocal())
    289     Out << '3';
    290   else
    291     Out << '4';
    292   // Now mangle the type.
    293   // <variable-type> ::= <type> <cvr-qualifiers>
    294   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
    295   // Pointers and references are odd. The type of 'int * const foo;' gets
    296   // mangled as 'QAHA' instead of 'PAHB', for example.
    297   TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
    298   QualType Ty = TL.getType();
    299   if (Ty->isPointerType() || Ty->isReferenceType()) {
    300     mangleType(Ty, TL.getSourceRange());
    301     mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
    302   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
    303     // Global arrays are funny, too.
    304     mangleType(AT, true);
    305     mangleQualifiers(Ty.getQualifiers(), false);
    306   } else {
    307     mangleType(Ty.getLocalUnqualifiedType(), TL.getSourceRange());
    308     mangleQualifiers(Ty.getLocalQualifiers(), false);
    309   }
    310 }
    311 
    312 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
    313   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
    314   const DeclContext *DC = ND->getDeclContext();
    315 
    316   // Always start with the unqualified name.
    317   mangleUnqualifiedName(ND);
    318 
    319   // If this is an extern variable declared locally, the relevant DeclContext
    320   // is that of the containing namespace, or the translation unit.
    321   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
    322     while (!DC->isNamespace() && !DC->isTranslationUnit())
    323       DC = DC->getParent();
    324 
    325   manglePostfix(DC);
    326 
    327   // Terminate the whole name with an '@'.
    328   Out << '@';
    329 }
    330 
    331 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
    332   llvm::APSInt APSNumber(/*BitWidth=*/64, /*isUnsigned=*/false);
    333   APSNumber = Number;
    334   mangleNumber(APSNumber);
    335 }
    336 
    337 void MicrosoftCXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
    338   // <number> ::= [?] <decimal digit> # 1 <= Number <= 10
    339   //          ::= [?] <hex digit>+ @ # 0 or > 9; A = 0, B = 1, etc...
    340   //          ::= [?] @ # 0 (alternate mangling, not emitted by VC)
    341   if (Value.isSigned() && Value.isNegative()) {
    342     Out << '?';
    343     mangleNumber(llvm::APSInt(Value.abs()));
    344     return;
    345   }
    346   llvm::APSInt Temp(Value);
    347   // There's a special shorter mangling for 0, but Microsoft
    348   // chose not to use it. Instead, 0 gets mangled as "A@". Oh well...
    349   if (Value.uge(1) && Value.ule(10)) {
    350     --Temp;
    351     Temp.print(Out, false);
    352   } else {
    353     // We have to build up the encoding in reverse order, so it will come
    354     // out right when we write it out.
    355     char Encoding[64];
    356     char *EndPtr = Encoding+sizeof(Encoding);
    357     char *CurPtr = EndPtr;
    358     llvm::APSInt NibbleMask(Value.getBitWidth(), Value.isUnsigned());
    359     NibbleMask = 0xf;
    360     do {
    361       *--CurPtr = 'A' + Temp.And(NibbleMask).getLimitedValue(0xf);
    362       Temp = Temp.lshr(4);
    363     } while (Temp != 0);
    364     Out.write(CurPtr, EndPtr-CurPtr);
    365     Out << '@';
    366   }
    367 }
    368 
    369 static const TemplateDecl *
    370 isTemplate(const NamedDecl *ND,
    371            SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
    372   // Check if we have a function template.
    373   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
    374     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
    375       if (FD->getTemplateSpecializationArgsAsWritten()) {
    376         const ASTTemplateArgumentListInfo *ArgList =
    377           FD->getTemplateSpecializationArgsAsWritten();
    378         TemplateArgs.append(ArgList->getTemplateArgs(),
    379                             ArgList->getTemplateArgs() +
    380                               ArgList->NumTemplateArgs);
    381       } else {
    382         const TemplateArgumentList *ArgList =
    383           FD->getTemplateSpecializationArgs();
    384         TemplateArgumentListInfo LI;
    385         for (unsigned i = 0, e = ArgList->size(); i != e; ++i)
    386           TemplateArgs.push_back(TemplateArgumentLoc(ArgList->get(i),
    387                                                      FD->getTypeSourceInfo()));
    388       }
    389       return TD;
    390     }
    391   }
    392 
    393   // Check if we have a class template.
    394   if (const ClassTemplateSpecializationDecl *Spec =
    395       dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
    396     TypeSourceInfo *TSI = Spec->getTypeAsWritten();
    397     if (TSI) {
    398       TemplateSpecializationTypeLoc TSTL =
    399           TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
    400       TemplateArgumentListInfo LI(TSTL.getLAngleLoc(), TSTL.getRAngleLoc());
    401       for (unsigned i = 0, e = TSTL.getNumArgs(); i != e; ++i)
    402         TemplateArgs.push_back(TSTL.getArgLoc(i));
    403     } else {
    404       TemplateArgumentListInfo LI;
    405       const TemplateArgumentList &ArgList =
    406         Spec->getTemplateArgs();
    407       for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
    408         TemplateArgs.push_back(TemplateArgumentLoc(ArgList[i],
    409                                                    TemplateArgumentLocInfo()));
    410     }
    411     return Spec->getSpecializedTemplate();
    412   }
    413 
    414   return 0;
    415 }
    416 
    417 void
    418 MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
    419                                                DeclarationName Name) {
    420   //  <unqualified-name> ::= <operator-name>
    421   //                     ::= <ctor-dtor-name>
    422   //                     ::= <source-name>
    423   //                     ::= <template-name>
    424   SmallVector<TemplateArgumentLoc, 2> TemplateArgs;
    425   // Check if we have a template.
    426   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
    427     // We have a template.
    428     // Here comes the tricky thing: if we need to mangle something like
    429     //   void foo(A::X<Y>, B::X<Y>),
    430     // the X<Y> part is aliased. However, if you need to mangle
    431     //   void foo(A::X<A::Y>, A::X<B::Y>),
    432     // the A::X<> part is not aliased.
    433     // That said, from the mangler's perspective we have a structure like this:
    434     //   namespace[s] -> type[ -> template-parameters]
    435     // but from the Clang perspective we have
    436     //   type [ -> template-parameters]
    437     //      \-> namespace[s]
    438     // What we do is we create a new mangler, mangle the same type (without
    439     // a namespace suffix) using the extra mangler with back references
    440     // disabled (to avoid infinite recursion) and then use the mangled type
    441     // name as a key to check the mangling of different types for aliasing.
    442 
    443     std::string BackReferenceKey;
    444     BackRefMap::iterator Found;
    445     if (UseNameBackReferences) {
    446       llvm::raw_string_ostream Stream(BackReferenceKey);
    447       MicrosoftCXXNameMangler Extra(Context, Stream);
    448       Extra.disableBackReferences();
    449       Extra.mangleUnqualifiedName(ND, Name);
    450       Stream.flush();
    451 
    452       Found = NameBackReferences.find(BackReferenceKey);
    453     }
    454     if (!UseNameBackReferences || Found == NameBackReferences.end()) {
    455       mangleTemplateInstantiationName(TD, TemplateArgs);
    456       if (UseNameBackReferences && NameBackReferences.size() < 10) {
    457         size_t Size = NameBackReferences.size();
    458         NameBackReferences[BackReferenceKey] = Size;
    459       }
    460     } else {
    461       Out << Found->second;
    462     }
    463     return;
    464   }
    465 
    466   switch (Name.getNameKind()) {
    467     case DeclarationName::Identifier: {
    468       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
    469         mangleSourceName(II);
    470         break;
    471       }
    472 
    473       // Otherwise, an anonymous entity.  We must have a declaration.
    474       assert(ND && "mangling empty name without declaration");
    475 
    476       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
    477         if (NS->isAnonymousNamespace()) {
    478           Out << "?A@";
    479           break;
    480         }
    481       }
    482 
    483       // We must have an anonymous struct.
    484       const TagDecl *TD = cast<TagDecl>(ND);
    485       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
    486         assert(TD->getDeclContext() == D->getDeclContext() &&
    487                "Typedef should not be in another decl context!");
    488         assert(D->getDeclName().getAsIdentifierInfo() &&
    489                "Typedef was not named!");
    490         mangleSourceName(D->getDeclName().getAsIdentifierInfo());
    491         break;
    492       }
    493 
    494       // When VC encounters an anonymous type with no tag and no typedef,
    495       // it literally emits '<unnamed-tag>'.
    496       Out << "<unnamed-tag>";
    497       break;
    498     }
    499 
    500     case DeclarationName::ObjCZeroArgSelector:
    501     case DeclarationName::ObjCOneArgSelector:
    502     case DeclarationName::ObjCMultiArgSelector:
    503       llvm_unreachable("Can't mangle Objective-C selector names here!");
    504 
    505     case DeclarationName::CXXConstructorName:
    506       if (ND == Structor) {
    507         assert(StructorType == Ctor_Complete &&
    508                "Should never be asked to mangle a ctor other than complete");
    509       }
    510       Out << "?0";
    511       break;
    512 
    513     case DeclarationName::CXXDestructorName:
    514       if (ND == Structor)
    515         // If the named decl is the C++ destructor we're mangling,
    516         // use the type we were given.
    517         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
    518       else
    519         // Otherwise, use the complete destructor name. This is relevant if a
    520         // class with a destructor is declared within a destructor.
    521         mangleCXXDtorType(Dtor_Complete);
    522       break;
    523 
    524     case DeclarationName::CXXConversionFunctionName:
    525       // <operator-name> ::= ?B # (cast)
    526       // The target type is encoded as the return type.
    527       Out << "?B";
    528       break;
    529 
    530     case DeclarationName::CXXOperatorName:
    531       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
    532       break;
    533 
    534     case DeclarationName::CXXLiteralOperatorName: {
    535       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
    536       DiagnosticsEngine Diags = Context.getDiags();
    537       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
    538         "cannot mangle this literal operator yet");
    539       Diags.Report(ND->getLocation(), DiagID);
    540       break;
    541     }
    542 
    543     case DeclarationName::CXXUsingDirective:
    544       llvm_unreachable("Can't mangle a using directive name!");
    545   }
    546 }
    547 
    548 void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
    549                                             bool NoFunction) {
    550   // <postfix> ::= <unqualified-name> [<postfix>]
    551   //           ::= <substitution> [<postfix>]
    552 
    553   if (!DC) return;
    554 
    555   while (isa<LinkageSpecDecl>(DC))
    556     DC = DC->getParent();
    557 
    558   if (DC->isTranslationUnit())
    559     return;
    560 
    561   if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
    562     Context.mangleBlock(BD, Out);
    563     Out << '@';
    564     return manglePostfix(DC->getParent(), NoFunction);
    565   }
    566 
    567   if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
    568     return;
    569   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
    570     mangleObjCMethodName(Method);
    571   else if (const FunctionDecl *Func = dyn_cast<FunctionDecl>(DC))
    572     mangleLocalName(Func);
    573   else {
    574     mangleUnqualifiedName(cast<NamedDecl>(DC));
    575     manglePostfix(DC->getParent(), NoFunction);
    576   }
    577 }
    578 
    579 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
    580   switch (T) {
    581   case Dtor_Deleting:
    582     Out << "?_G";
    583     return;
    584   case Dtor_Base:
    585     // FIXME: We should be asked to mangle base dtors.
    586     // However, fixing this would require larger changes to the CodeGenModule.
    587     // Please put llvm_unreachable here when CGM is changed.
    588     // For now, just mangle a base dtor the same way as a complete dtor...
    589   case Dtor_Complete:
    590     Out << "?1";
    591     return;
    592   }
    593   llvm_unreachable("Unsupported dtor type?");
    594 }
    595 
    596 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
    597                                                  SourceLocation Loc) {
    598   switch (OO) {
    599   //                     ?0 # constructor
    600   //                     ?1 # destructor
    601   // <operator-name> ::= ?2 # new
    602   case OO_New: Out << "?2"; break;
    603   // <operator-name> ::= ?3 # delete
    604   case OO_Delete: Out << "?3"; break;
    605   // <operator-name> ::= ?4 # =
    606   case OO_Equal: Out << "?4"; break;
    607   // <operator-name> ::= ?5 # >>
    608   case OO_GreaterGreater: Out << "?5"; break;
    609   // <operator-name> ::= ?6 # <<
    610   case OO_LessLess: Out << "?6"; break;
    611   // <operator-name> ::= ?7 # !
    612   case OO_Exclaim: Out << "?7"; break;
    613   // <operator-name> ::= ?8 # ==
    614   case OO_EqualEqual: Out << "?8"; break;
    615   // <operator-name> ::= ?9 # !=
    616   case OO_ExclaimEqual: Out << "?9"; break;
    617   // <operator-name> ::= ?A # []
    618   case OO_Subscript: Out << "?A"; break;
    619   //                     ?B # conversion
    620   // <operator-name> ::= ?C # ->
    621   case OO_Arrow: Out << "?C"; break;
    622   // <operator-name> ::= ?D # *
    623   case OO_Star: Out << "?D"; break;
    624   // <operator-name> ::= ?E # ++
    625   case OO_PlusPlus: Out << "?E"; break;
    626   // <operator-name> ::= ?F # --
    627   case OO_MinusMinus: Out << "?F"; break;
    628   // <operator-name> ::= ?G # -
    629   case OO_Minus: Out << "?G"; break;
    630   // <operator-name> ::= ?H # +
    631   case OO_Plus: Out << "?H"; break;
    632   // <operator-name> ::= ?I # &
    633   case OO_Amp: Out << "?I"; break;
    634   // <operator-name> ::= ?J # ->*
    635   case OO_ArrowStar: Out << "?J"; break;
    636   // <operator-name> ::= ?K # /
    637   case OO_Slash: Out << "?K"; break;
    638   // <operator-name> ::= ?L # %
    639   case OO_Percent: Out << "?L"; break;
    640   // <operator-name> ::= ?M # <
    641   case OO_Less: Out << "?M"; break;
    642   // <operator-name> ::= ?N # <=
    643   case OO_LessEqual: Out << "?N"; break;
    644   // <operator-name> ::= ?O # >
    645   case OO_Greater: Out << "?O"; break;
    646   // <operator-name> ::= ?P # >=
    647   case OO_GreaterEqual: Out << "?P"; break;
    648   // <operator-name> ::= ?Q # ,
    649   case OO_Comma: Out << "?Q"; break;
    650   // <operator-name> ::= ?R # ()
    651   case OO_Call: Out << "?R"; break;
    652   // <operator-name> ::= ?S # ~
    653   case OO_Tilde: Out << "?S"; break;
    654   // <operator-name> ::= ?T # ^
    655   case OO_Caret: Out << "?T"; break;
    656   // <operator-name> ::= ?U # |
    657   case OO_Pipe: Out << "?U"; break;
    658   // <operator-name> ::= ?V # &&
    659   case OO_AmpAmp: Out << "?V"; break;
    660   // <operator-name> ::= ?W # ||
    661   case OO_PipePipe: Out << "?W"; break;
    662   // <operator-name> ::= ?X # *=
    663   case OO_StarEqual: Out << "?X"; break;
    664   // <operator-name> ::= ?Y # +=
    665   case OO_PlusEqual: Out << "?Y"; break;
    666   // <operator-name> ::= ?Z # -=
    667   case OO_MinusEqual: Out << "?Z"; break;
    668   // <operator-name> ::= ?_0 # /=
    669   case OO_SlashEqual: Out << "?_0"; break;
    670   // <operator-name> ::= ?_1 # %=
    671   case OO_PercentEqual: Out << "?_1"; break;
    672   // <operator-name> ::= ?_2 # >>=
    673   case OO_GreaterGreaterEqual: Out << "?_2"; break;
    674   // <operator-name> ::= ?_3 # <<=
    675   case OO_LessLessEqual: Out << "?_3"; break;
    676   // <operator-name> ::= ?_4 # &=
    677   case OO_AmpEqual: Out << "?_4"; break;
    678   // <operator-name> ::= ?_5 # |=
    679   case OO_PipeEqual: Out << "?_5"; break;
    680   // <operator-name> ::= ?_6 # ^=
    681   case OO_CaretEqual: Out << "?_6"; break;
    682   //                     ?_7 # vftable
    683   //                     ?_8 # vbtable
    684   //                     ?_9 # vcall
    685   //                     ?_A # typeof
    686   //                     ?_B # local static guard
    687   //                     ?_C # string
    688   //                     ?_D # vbase destructor
    689   //                     ?_E # vector deleting destructor
    690   //                     ?_F # default constructor closure
    691   //                     ?_G # scalar deleting destructor
    692   //                     ?_H # vector constructor iterator
    693   //                     ?_I # vector destructor iterator
    694   //                     ?_J # vector vbase constructor iterator
    695   //                     ?_K # virtual displacement map
    696   //                     ?_L # eh vector constructor iterator
    697   //                     ?_M # eh vector destructor iterator
    698   //                     ?_N # eh vector vbase constructor iterator
    699   //                     ?_O # copy constructor closure
    700   //                     ?_P<name> # udt returning <name>
    701   //                     ?_Q # <unknown>
    702   //                     ?_R0 # RTTI Type Descriptor
    703   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
    704   //                     ?_R2 # RTTI Base Class Array
    705   //                     ?_R3 # RTTI Class Hierarchy Descriptor
    706   //                     ?_R4 # RTTI Complete Object Locator
    707   //                     ?_S # local vftable
    708   //                     ?_T # local vftable constructor closure
    709   // <operator-name> ::= ?_U # new[]
    710   case OO_Array_New: Out << "?_U"; break;
    711   // <operator-name> ::= ?_V # delete[]
    712   case OO_Array_Delete: Out << "?_V"; break;
    713 
    714   case OO_Conditional: {
    715     DiagnosticsEngine &Diags = Context.getDiags();
    716     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
    717       "cannot mangle this conditional operator yet");
    718     Diags.Report(Loc, DiagID);
    719     break;
    720   }
    721 
    722   case OO_None:
    723   case NUM_OVERLOADED_OPERATORS:
    724     llvm_unreachable("Not an overloaded operator");
    725   }
    726 }
    727 
    728 void MicrosoftCXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
    729   // <source name> ::= <identifier> @
    730   std::string key = II->getNameStart();
    731   BackRefMap::iterator Found;
    732   if (UseNameBackReferences)
    733     Found = NameBackReferences.find(key);
    734   if (!UseNameBackReferences || Found == NameBackReferences.end()) {
    735     Out << II->getName() << '@';
    736     if (UseNameBackReferences && NameBackReferences.size() < 10) {
    737       size_t Size = NameBackReferences.size();
    738       NameBackReferences[key] = Size;
    739     }
    740   } else {
    741     Out << Found->second;
    742   }
    743 }
    744 
    745 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
    746   Context.mangleObjCMethodName(MD, Out);
    747 }
    748 
    749 // Find out how many function decls live above this one and return an integer
    750 // suitable for use as the number in a numbered anonymous scope.
    751 // TODO: Memoize.
    752 static unsigned getLocalNestingLevel(const FunctionDecl *FD) {
    753   const DeclContext *DC = FD->getParent();
    754   int level = 1;
    755 
    756   while (DC && !DC->isTranslationUnit()) {
    757     if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) level++;
    758     DC = DC->getParent();
    759   }
    760 
    761   return 2*level;
    762 }
    763 
    764 void MicrosoftCXXNameMangler::mangleLocalName(const FunctionDecl *FD) {
    765   // <nested-name> ::= <numbered-anonymous-scope> ? <mangled-name>
    766   // <numbered-anonymous-scope> ::= ? <number>
    767   // Even though the name is rendered in reverse order (e.g.
    768   // A::B::C is rendered as C@B@A), VC numbers the scopes from outermost to
    769   // innermost. So a method bar in class C local to function foo gets mangled
    770   // as something like:
    771   // ?bar@C@?1??foo@@YAXXZ@QAEXXZ
    772   // This is more apparent when you have a type nested inside a method of a
    773   // type nested inside a function. A method baz in class D local to method
    774   // bar of class C local to function foo gets mangled as:
    775   // ?baz@D@?3??bar@C@?1??foo@@YAXXZ@QAEXXZ@QAEXXZ
    776   // This scheme is general enough to support GCC-style nested
    777   // functions. You could have a method baz of class C inside a function bar
    778   // inside a function foo, like so:
    779   // ?baz@C@?3??bar@?1??foo@@YAXXZ@YAXXZ@QAEXXZ
    780   int NestLevel = getLocalNestingLevel(FD);
    781   Out << '?';
    782   mangleNumber(NestLevel);
    783   Out << '?';
    784   mangle(FD, "?");
    785 }
    786 
    787 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
    788                                                          const TemplateDecl *TD,
    789                      const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
    790   // <template-name> ::= <unscoped-template-name> <template-args>
    791   //                 ::= <substitution>
    792   // Always start with the unqualified name.
    793 
    794   // Templates have their own context for back references.
    795   ArgBackRefMap OuterArgsContext;
    796   BackRefMap OuterTemplateContext;
    797   NameBackReferences.swap(OuterTemplateContext);
    798   TypeBackReferences.swap(OuterArgsContext);
    799 
    800   mangleUnscopedTemplateName(TD);
    801   mangleTemplateArgs(TemplateArgs);
    802 
    803   // Restore the previous back reference contexts.
    804   NameBackReferences.swap(OuterTemplateContext);
    805   TypeBackReferences.swap(OuterArgsContext);
    806 }
    807 
    808 void
    809 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
    810   // <unscoped-template-name> ::= ?$ <unqualified-name>
    811   Out << "?$";
    812   mangleUnqualifiedName(TD);
    813 }
    814 
    815 void
    816 MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
    817                                               bool IsBoolean) {
    818   // <integer-literal> ::= $0 <number>
    819   Out << "$0";
    820   // Make sure booleans are encoded as 0/1.
    821   if (IsBoolean && Value.getBoolValue())
    822     mangleNumber(1);
    823   else
    824     mangleNumber(Value);
    825 }
    826 
    827 void
    828 MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
    829   // See if this is a constant expression.
    830   llvm::APSInt Value;
    831   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
    832     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
    833     return;
    834   }
    835 
    836   // As bad as this diagnostic is, it's better than crashing.
    837   DiagnosticsEngine &Diags = Context.getDiags();
    838   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
    839                                    "cannot yet mangle expression type %0");
    840   Diags.Report(E->getExprLoc(), DiagID)
    841     << E->getStmtClassName() << E->getSourceRange();
    842 }
    843 
    844 void
    845 MicrosoftCXXNameMangler::mangleTemplateArgs(
    846                      const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
    847   // <template-args> ::= {<type> | <integer-literal>}+ @
    848   unsigned NumTemplateArgs = TemplateArgs.size();
    849   for (unsigned i = 0; i < NumTemplateArgs; ++i) {
    850     const TemplateArgumentLoc &TAL = TemplateArgs[i];
    851     const TemplateArgument &TA = TAL.getArgument();
    852     switch (TA.getKind()) {
    853     case TemplateArgument::Null:
    854       llvm_unreachable("Can't mangle null template arguments!");
    855     case TemplateArgument::Type:
    856       mangleType(TA.getAsType(), TAL.getSourceRange());
    857       break;
    858     case TemplateArgument::Integral:
    859       mangleIntegerLiteral(TA.getAsIntegral(),
    860                            TA.getIntegralType()->isBooleanType());
    861       break;
    862     case TemplateArgument::Expression:
    863       mangleExpression(TA.getAsExpr());
    864       break;
    865     case TemplateArgument::Template:
    866     case TemplateArgument::TemplateExpansion:
    867     case TemplateArgument::Declaration:
    868     case TemplateArgument::NullPtr:
    869     case TemplateArgument::Pack: {
    870       // Issue a diagnostic.
    871       DiagnosticsEngine &Diags = Context.getDiags();
    872       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
    873         "cannot mangle this %select{ERROR|ERROR|pointer/reference|nullptr|"
    874         "integral|template|template pack expansion|ERROR|parameter pack}0 "
    875         "template argument yet");
    876       Diags.Report(TAL.getLocation(), DiagID)
    877         << TA.getKind()
    878         << TAL.getSourceRange();
    879     }
    880     }
    881   }
    882   Out << '@';
    883 }
    884 
    885 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
    886                                                bool IsMember) {
    887   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
    888   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
    889   // 'I' means __restrict (32/64-bit).
    890   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
    891   // keyword!
    892   // <base-cvr-qualifiers> ::= A  # near
    893   //                       ::= B  # near const
    894   //                       ::= C  # near volatile
    895   //                       ::= D  # near const volatile
    896   //                       ::= E  # far (16-bit)
    897   //                       ::= F  # far const (16-bit)
    898   //                       ::= G  # far volatile (16-bit)
    899   //                       ::= H  # far const volatile (16-bit)
    900   //                       ::= I  # huge (16-bit)
    901   //                       ::= J  # huge const (16-bit)
    902   //                       ::= K  # huge volatile (16-bit)
    903   //                       ::= L  # huge const volatile (16-bit)
    904   //                       ::= M <basis> # based
    905   //                       ::= N <basis> # based const
    906   //                       ::= O <basis> # based volatile
    907   //                       ::= P <basis> # based const volatile
    908   //                       ::= Q  # near member
    909   //                       ::= R  # near const member
    910   //                       ::= S  # near volatile member
    911   //                       ::= T  # near const volatile member
    912   //                       ::= U  # far member (16-bit)
    913   //                       ::= V  # far const member (16-bit)
    914   //                       ::= W  # far volatile member (16-bit)
    915   //                       ::= X  # far const volatile member (16-bit)
    916   //                       ::= Y  # huge member (16-bit)
    917   //                       ::= Z  # huge const member (16-bit)
    918   //                       ::= 0  # huge volatile member (16-bit)
    919   //                       ::= 1  # huge const volatile member (16-bit)
    920   //                       ::= 2 <basis> # based member
    921   //                       ::= 3 <basis> # based const member
    922   //                       ::= 4 <basis> # based volatile member
    923   //                       ::= 5 <basis> # based const volatile member
    924   //                       ::= 6  # near function (pointers only)
    925   //                       ::= 7  # far function (pointers only)
    926   //                       ::= 8  # near method (pointers only)
    927   //                       ::= 9  # far method (pointers only)
    928   //                       ::= _A <basis> # based function (pointers only)
    929   //                       ::= _B <basis> # based function (far?) (pointers only)
    930   //                       ::= _C <basis> # based method (pointers only)
    931   //                       ::= _D <basis> # based method (far?) (pointers only)
    932   //                       ::= _E # block (Clang)
    933   // <basis> ::= 0 # __based(void)
    934   //         ::= 1 # __based(segment)?
    935   //         ::= 2 <name> # __based(name)
    936   //         ::= 3 # ?
    937   //         ::= 4 # ?
    938   //         ::= 5 # not really based
    939   bool HasConst = Quals.hasConst(),
    940        HasVolatile = Quals.hasVolatile();
    941   if (!IsMember) {
    942     if (HasConst && HasVolatile) {
    943       Out << 'D';
    944     } else if (HasVolatile) {
    945       Out << 'C';
    946     } else if (HasConst) {
    947       Out << 'B';
    948     } else {
    949       Out << 'A';
    950     }
    951   } else {
    952     if (HasConst && HasVolatile) {
    953       Out << 'T';
    954     } else if (HasVolatile) {
    955       Out << 'S';
    956     } else if (HasConst) {
    957       Out << 'R';
    958     } else {
    959       Out << 'Q';
    960     }
    961   }
    962 
    963   // FIXME: For now, just drop all extension qualifiers on the floor.
    964 }
    965 
    966 void MicrosoftCXXNameMangler::manglePointerQualifiers(Qualifiers Quals) {
    967   // <pointer-cvr-qualifiers> ::= P  # no qualifiers
    968   //                          ::= Q  # const
    969   //                          ::= R  # volatile
    970   //                          ::= S  # const volatile
    971   bool HasConst = Quals.hasConst(),
    972        HasVolatile = Quals.hasVolatile();
    973   if (HasConst && HasVolatile) {
    974     Out << 'S';
    975   } else if (HasVolatile) {
    976     Out << 'R';
    977   } else if (HasConst) {
    978     Out << 'Q';
    979   } else {
    980     Out << 'P';
    981   }
    982 }
    983 
    984 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
    985                                                  SourceRange Range) {
    986   void *TypePtr = getASTContext().getCanonicalType(T).getAsOpaquePtr();
    987   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
    988 
    989   if (Found == TypeBackReferences.end()) {
    990     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
    991 
    992     mangleType(T, Range, false);
    993 
    994     // See if it's worth creating a back reference.
    995     // Only types longer than 1 character are considered
    996     // and only 10 back references slots are available:
    997     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
    998     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
    999       size_t Size = TypeBackReferences.size();
   1000       TypeBackReferences[TypePtr] = Size;
   1001     }
   1002   } else {
   1003     Out << Found->second;
   1004   }
   1005 }
   1006 
   1007 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
   1008                                          bool MangleQualifiers) {
   1009   // Only operate on the canonical type!
   1010   T = getASTContext().getCanonicalType(T);
   1011 
   1012   Qualifiers Quals = T.getLocalQualifiers();
   1013   // We have to mangle these now, while we still have enough information.
   1014   if (T->isAnyPointerType() || T->isMemberPointerType() ||
   1015       T->isBlockPointerType()) {
   1016     manglePointerQualifiers(Quals);
   1017   } else if (Quals && MangleQualifiers) {
   1018     mangleQualifiers(Quals, false);
   1019   }
   1020 
   1021   SplitQualType split = T.split();
   1022   const Type *ty = split.Ty;
   1023 
   1024   // If we're mangling a qualified array type, push the qualifiers to
   1025   // the element type.
   1026   if (split.Quals && isa<ArrayType>(T)) {
   1027     ty = Context.getASTContext().getAsArrayType(T);
   1028   }
   1029 
   1030   switch (ty->getTypeClass()) {
   1031 #define ABSTRACT_TYPE(CLASS, PARENT)
   1032 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
   1033   case Type::CLASS: \
   1034     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
   1035     return;
   1036 #define TYPE(CLASS, PARENT) \
   1037   case Type::CLASS: \
   1038     mangleType(cast<CLASS##Type>(ty), Range); \
   1039     break;
   1040 #include "clang/AST/TypeNodes.def"
   1041 #undef ABSTRACT_TYPE
   1042 #undef NON_CANONICAL_TYPE
   1043 #undef TYPE
   1044   }
   1045 }
   1046 
   1047 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
   1048                                          SourceRange Range) {
   1049   //  <type>         ::= <builtin-type>
   1050   //  <builtin-type> ::= X  # void
   1051   //                 ::= C  # signed char
   1052   //                 ::= D  # char
   1053   //                 ::= E  # unsigned char
   1054   //                 ::= F  # short
   1055   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
   1056   //                 ::= H  # int
   1057   //                 ::= I  # unsigned int
   1058   //                 ::= J  # long
   1059   //                 ::= K  # unsigned long
   1060   //                     L  # <none>
   1061   //                 ::= M  # float
   1062   //                 ::= N  # double
   1063   //                 ::= O  # long double (__float80 is mangled differently)
   1064   //                 ::= _J # long long, __int64
   1065   //                 ::= _K # unsigned long long, __int64
   1066   //                 ::= _L # __int128
   1067   //                 ::= _M # unsigned __int128
   1068   //                 ::= _N # bool
   1069   //                     _O # <array in parameter>
   1070   //                 ::= _T # __float80 (Intel)
   1071   //                 ::= _W # wchar_t
   1072   //                 ::= _Z # __float80 (Digital Mars)
   1073   switch (T->getKind()) {
   1074   case BuiltinType::Void: Out << 'X'; break;
   1075   case BuiltinType::SChar: Out << 'C'; break;
   1076   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
   1077   case BuiltinType::UChar: Out << 'E'; break;
   1078   case BuiltinType::Short: Out << 'F'; break;
   1079   case BuiltinType::UShort: Out << 'G'; break;
   1080   case BuiltinType::Int: Out << 'H'; break;
   1081   case BuiltinType::UInt: Out << 'I'; break;
   1082   case BuiltinType::Long: Out << 'J'; break;
   1083   case BuiltinType::ULong: Out << 'K'; break;
   1084   case BuiltinType::Float: Out << 'M'; break;
   1085   case BuiltinType::Double: Out << 'N'; break;
   1086   // TODO: Determine size and mangle accordingly
   1087   case BuiltinType::LongDouble: Out << 'O'; break;
   1088   case BuiltinType::LongLong: Out << "_J"; break;
   1089   case BuiltinType::ULongLong: Out << "_K"; break;
   1090   case BuiltinType::Int128: Out << "_L"; break;
   1091   case BuiltinType::UInt128: Out << "_M"; break;
   1092   case BuiltinType::Bool: Out << "_N"; break;
   1093   case BuiltinType::WChar_S:
   1094   case BuiltinType::WChar_U: Out << "_W"; break;
   1095 
   1096 #define BUILTIN_TYPE(Id, SingletonId)
   1097 #define PLACEHOLDER_TYPE(Id, SingletonId) \
   1098   case BuiltinType::Id:
   1099 #include "clang/AST/BuiltinTypes.def"
   1100   case BuiltinType::Dependent:
   1101     llvm_unreachable("placeholder types shouldn't get to name mangling");
   1102 
   1103   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
   1104   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
   1105   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
   1106 
   1107   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
   1108   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
   1109   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
   1110   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
   1111   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
   1112   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
   1113   case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
   1114   case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
   1115 
   1116   case BuiltinType::NullPtr: Out << "$$T"; break;
   1117 
   1118   case BuiltinType::Char16:
   1119   case BuiltinType::Char32:
   1120   case BuiltinType::Half: {
   1121     DiagnosticsEngine &Diags = Context.getDiags();
   1122     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1123       "cannot mangle this built-in %0 type yet");
   1124     Diags.Report(Range.getBegin(), DiagID)
   1125       << T->getName(Context.getASTContext().getPrintingPolicy())
   1126       << Range;
   1127     break;
   1128   }
   1129   }
   1130 }
   1131 
   1132 // <type>          ::= <function-type>
   1133 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
   1134                                          SourceRange) {
   1135   // Structors only appear in decls, so at this point we know it's not a
   1136   // structor type.
   1137   // FIXME: This may not be lambda-friendly.
   1138   Out << "$$A6";
   1139   mangleType(T, NULL, false, false);
   1140 }
   1141 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
   1142                                          SourceRange) {
   1143   llvm_unreachable("Can't mangle K&R function prototypes");
   1144 }
   1145 
   1146 void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
   1147                                          const FunctionDecl *D,
   1148                                          bool IsStructor,
   1149                                          bool IsInstMethod) {
   1150   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
   1151   //                     <return-type> <argument-list> <throw-spec>
   1152   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
   1153 
   1154   // If this is a C++ instance method, mangle the CVR qualifiers for the
   1155   // this pointer.
   1156   if (IsInstMethod)
   1157     mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
   1158 
   1159   mangleCallingConvention(T, IsInstMethod);
   1160 
   1161   // <return-type> ::= <type>
   1162   //               ::= @ # structors (they have no declared return type)
   1163   if (IsStructor) {
   1164     if (isa<CXXDestructorDecl>(D) && D == Structor &&
   1165         StructorType == Dtor_Deleting) {
   1166       // The scalar deleting destructor takes an extra int argument.
   1167       // However, the FunctionType generated has 0 arguments.
   1168       // FIXME: This is a temporary hack.
   1169       // Maybe should fix the FunctionType creation instead?
   1170       Out << "PAXI@Z";
   1171       return;
   1172     }
   1173     Out << '@';
   1174   } else {
   1175     QualType Result = Proto->getResultType();
   1176     const Type* RT = Result.getTypePtr();
   1177     if (!RT->isAnyPointerType() && !RT->isReferenceType()) {
   1178       if (Result.hasQualifiers() || !RT->isBuiltinType())
   1179         Out << '?';
   1180       if (!RT->isBuiltinType() && !Result.hasQualifiers()) {
   1181         // Lack of qualifiers for user types is mangled as 'A'.
   1182         Out << 'A';
   1183       }
   1184     }
   1185 
   1186     // FIXME: Get the source range for the result type. Or, better yet,
   1187     // implement the unimplemented stuff so we don't need accurate source
   1188     // location info anymore :).
   1189     mangleType(Result, SourceRange());
   1190   }
   1191 
   1192   // <argument-list> ::= X # void
   1193   //                 ::= <type>+ @
   1194   //                 ::= <type>* Z # varargs
   1195   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
   1196     Out << 'X';
   1197   } else {
   1198     if (D) {
   1199       // If we got a decl, use the type-as-written to make sure arrays
   1200       // get mangled right.  Note that we can't rely on the TSI
   1201       // existing if (for example) the parameter was synthesized.
   1202       for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
   1203              ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
   1204         TypeSourceInfo *TSI = (*Parm)->getTypeSourceInfo();
   1205         QualType Type = TSI ? TSI->getType() : (*Parm)->getType();
   1206         mangleArgumentType(Type, (*Parm)->getSourceRange());
   1207       }
   1208     } else {
   1209       // Happens for function pointer type arguments for example.
   1210       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
   1211            ArgEnd = Proto->arg_type_end();
   1212            Arg != ArgEnd; ++Arg)
   1213         mangleArgumentType(*Arg, SourceRange());
   1214     }
   1215     // <builtin-type>      ::= Z  # ellipsis
   1216     if (Proto->isVariadic())
   1217       Out << 'Z';
   1218     else
   1219       Out << '@';
   1220   }
   1221 
   1222   mangleThrowSpecification(Proto);
   1223 }
   1224 
   1225 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
   1226   // <function-class> ::= A # private: near
   1227   //                  ::= B # private: far
   1228   //                  ::= C # private: static near
   1229   //                  ::= D # private: static far
   1230   //                  ::= E # private: virtual near
   1231   //                  ::= F # private: virtual far
   1232   //                  ::= G # private: thunk near
   1233   //                  ::= H # private: thunk far
   1234   //                  ::= I # protected: near
   1235   //                  ::= J # protected: far
   1236   //                  ::= K # protected: static near
   1237   //                  ::= L # protected: static far
   1238   //                  ::= M # protected: virtual near
   1239   //                  ::= N # protected: virtual far
   1240   //                  ::= O # protected: thunk near
   1241   //                  ::= P # protected: thunk far
   1242   //                  ::= Q # public: near
   1243   //                  ::= R # public: far
   1244   //                  ::= S # public: static near
   1245   //                  ::= T # public: static far
   1246   //                  ::= U # public: virtual near
   1247   //                  ::= V # public: virtual far
   1248   //                  ::= W # public: thunk near
   1249   //                  ::= X # public: thunk far
   1250   //                  ::= Y # global near
   1251   //                  ::= Z # global far
   1252   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
   1253     switch (MD->getAccess()) {
   1254       default:
   1255       case AS_private:
   1256         if (MD->isStatic())
   1257           Out << 'C';
   1258         else if (MD->isVirtual())
   1259           Out << 'E';
   1260         else
   1261           Out << 'A';
   1262         break;
   1263       case AS_protected:
   1264         if (MD->isStatic())
   1265           Out << 'K';
   1266         else if (MD->isVirtual())
   1267           Out << 'M';
   1268         else
   1269           Out << 'I';
   1270         break;
   1271       case AS_public:
   1272         if (MD->isStatic())
   1273           Out << 'S';
   1274         else if (MD->isVirtual())
   1275           Out << 'U';
   1276         else
   1277           Out << 'Q';
   1278     }
   1279   } else
   1280     Out << 'Y';
   1281 }
   1282 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
   1283                                                       bool IsInstMethod) {
   1284   // <calling-convention> ::= A # __cdecl
   1285   //                      ::= B # __export __cdecl
   1286   //                      ::= C # __pascal
   1287   //                      ::= D # __export __pascal
   1288   //                      ::= E # __thiscall
   1289   //                      ::= F # __export __thiscall
   1290   //                      ::= G # __stdcall
   1291   //                      ::= H # __export __stdcall
   1292   //                      ::= I # __fastcall
   1293   //                      ::= J # __export __fastcall
   1294   // The 'export' calling conventions are from a bygone era
   1295   // (*cough*Win16*cough*) when functions were declared for export with
   1296   // that keyword. (It didn't actually export them, it just made them so
   1297   // that they could be in a DLL and somebody from another module could call
   1298   // them.)
   1299   CallingConv CC = T->getCallConv();
   1300   if (CC == CC_Default) {
   1301     if (IsInstMethod) {
   1302       const FunctionProtoType *FPT =
   1303         T->getCanonicalTypeUnqualified().castAs<FunctionProtoType>();
   1304       bool isVariadic = FPT->isVariadic();
   1305       CC = getASTContext().getDefaultCXXMethodCallConv(isVariadic);
   1306     } else {
   1307       CC = CC_C;
   1308     }
   1309   }
   1310   switch (CC) {
   1311     default:
   1312       llvm_unreachable("Unsupported CC for mangling");
   1313     case CC_Default:
   1314     case CC_C: Out << 'A'; break;
   1315     case CC_X86Pascal: Out << 'C'; break;
   1316     case CC_X86ThisCall: Out << 'E'; break;
   1317     case CC_X86StdCall: Out << 'G'; break;
   1318     case CC_X86FastCall: Out << 'I'; break;
   1319   }
   1320 }
   1321 void MicrosoftCXXNameMangler::mangleThrowSpecification(
   1322                                                 const FunctionProtoType *FT) {
   1323   // <throw-spec> ::= Z # throw(...) (default)
   1324   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
   1325   //              ::= <type>+
   1326   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
   1327   // all actually mangled as 'Z'. (They're ignored because their associated
   1328   // functionality isn't implemented, and probably never will be.)
   1329   Out << 'Z';
   1330 }
   1331 
   1332 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
   1333                                          SourceRange Range) {
   1334   // Probably should be mangled as a template instantiation; need to see what
   1335   // VC does first.
   1336   DiagnosticsEngine &Diags = Context.getDiags();
   1337   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1338     "cannot mangle this unresolved dependent type yet");
   1339   Diags.Report(Range.getBegin(), DiagID)
   1340     << Range;
   1341 }
   1342 
   1343 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
   1344 // <union-type>  ::= T <name>
   1345 // <struct-type> ::= U <name>
   1346 // <class-type>  ::= V <name>
   1347 // <enum-type>   ::= W <size> <name>
   1348 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
   1349   mangleType(cast<TagType>(T));
   1350 }
   1351 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
   1352   mangleType(cast<TagType>(T));
   1353 }
   1354 void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
   1355   switch (T->getDecl()->getTagKind()) {
   1356     case TTK_Union:
   1357       Out << 'T';
   1358       break;
   1359     case TTK_Struct:
   1360     case TTK_Interface:
   1361       Out << 'U';
   1362       break;
   1363     case TTK_Class:
   1364       Out << 'V';
   1365       break;
   1366     case TTK_Enum:
   1367       Out << 'W';
   1368       Out << getASTContext().getTypeSizeInChars(
   1369                 cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
   1370       break;
   1371   }
   1372   mangleName(T->getDecl());
   1373 }
   1374 
   1375 // <type>       ::= <array-type>
   1376 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
   1377 //                  [Y <dimension-count> <dimension>+]
   1378 //                  <element-type> # as global
   1379 //              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
   1380 //                  <element-type> # as param
   1381 // It's supposed to be the other way around, but for some strange reason, it
   1382 // isn't. Today this behavior is retained for the sole purpose of backwards
   1383 // compatibility.
   1384 void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
   1385   // This isn't a recursive mangling, so now we have to do it all in this
   1386   // one call.
   1387   if (IsGlobal) {
   1388     manglePointerQualifiers(T->getElementType().getQualifiers());
   1389   } else {
   1390     Out << 'Q';
   1391   }
   1392   mangleExtraDimensions(T->getElementType());
   1393 }
   1394 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
   1395                                          SourceRange) {
   1396   mangleType(cast<ArrayType>(T), false);
   1397 }
   1398 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
   1399                                          SourceRange) {
   1400   mangleType(cast<ArrayType>(T), false);
   1401 }
   1402 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
   1403                                          SourceRange) {
   1404   mangleType(cast<ArrayType>(T), false);
   1405 }
   1406 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
   1407                                          SourceRange) {
   1408   mangleType(cast<ArrayType>(T), false);
   1409 }
   1410 void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
   1411   SmallVector<llvm::APInt, 3> Dimensions;
   1412   for (;;) {
   1413     if (const ConstantArrayType *CAT =
   1414           getASTContext().getAsConstantArrayType(ElementTy)) {
   1415       Dimensions.push_back(CAT->getSize());
   1416       ElementTy = CAT->getElementType();
   1417     } else if (ElementTy->isVariableArrayType()) {
   1418       const VariableArrayType *VAT =
   1419         getASTContext().getAsVariableArrayType(ElementTy);
   1420       DiagnosticsEngine &Diags = Context.getDiags();
   1421       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1422         "cannot mangle this variable-length array yet");
   1423       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
   1424         << VAT->getBracketsRange();
   1425       return;
   1426     } else if (ElementTy->isDependentSizedArrayType()) {
   1427       // The dependent expression has to be folded into a constant (TODO).
   1428       const DependentSizedArrayType *DSAT =
   1429         getASTContext().getAsDependentSizedArrayType(ElementTy);
   1430       DiagnosticsEngine &Diags = Context.getDiags();
   1431       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1432         "cannot mangle this dependent-length array yet");
   1433       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
   1434         << DSAT->getBracketsRange();
   1435       return;
   1436     } else if (ElementTy->isIncompleteArrayType()) continue;
   1437     else break;
   1438   }
   1439   mangleQualifiers(ElementTy.getQualifiers(), false);
   1440   // If there are any additional dimensions, mangle them now.
   1441   if (Dimensions.size() > 0) {
   1442     Out << 'Y';
   1443     // <dimension-count> ::= <number> # number of extra dimensions
   1444     mangleNumber(Dimensions.size());
   1445     for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
   1446       mangleNumber(Dimensions[Dim].getLimitedValue());
   1447     }
   1448   }
   1449   mangleType(ElementTy.getLocalUnqualifiedType(), SourceRange());
   1450 }
   1451 
   1452 // <type>                   ::= <pointer-to-member-type>
   1453 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
   1454 //                                                          <class name> <type>
   1455 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
   1456                                          SourceRange Range) {
   1457   QualType PointeeType = T->getPointeeType();
   1458   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
   1459     Out << '8';
   1460     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
   1461     mangleType(FPT, NULL, false, true);
   1462   } else {
   1463     mangleQualifiers(PointeeType.getQualifiers(), true);
   1464     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
   1465     mangleType(PointeeType.getLocalUnqualifiedType(), Range);
   1466   }
   1467 }
   1468 
   1469 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
   1470                                          SourceRange Range) {
   1471   DiagnosticsEngine &Diags = Context.getDiags();
   1472   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1473     "cannot mangle this template type parameter type yet");
   1474   Diags.Report(Range.getBegin(), DiagID)
   1475     << Range;
   1476 }
   1477 
   1478 void MicrosoftCXXNameMangler::mangleType(
   1479                                        const SubstTemplateTypeParmPackType *T,
   1480                                        SourceRange Range) {
   1481   DiagnosticsEngine &Diags = Context.getDiags();
   1482   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1483     "cannot mangle this substituted parameter pack yet");
   1484   Diags.Report(Range.getBegin(), DiagID)
   1485     << Range;
   1486 }
   1487 
   1488 // <type> ::= <pointer-type>
   1489 // <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
   1490 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
   1491                                          SourceRange Range) {
   1492   QualType PointeeTy = T->getPointeeType();
   1493   if (PointeeTy->isArrayType()) {
   1494     // Pointers to arrays are mangled like arrays.
   1495     mangleExtraDimensions(PointeeTy);
   1496   } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
   1497     // Function pointers are special.
   1498     Out << '6';
   1499     mangleType(FT, NULL, false, false);
   1500   } else {
   1501     mangleQualifiers(PointeeTy.getQualifiers(), false);
   1502     mangleType(PointeeTy, Range, false);
   1503   }
   1504 }
   1505 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
   1506                                          SourceRange Range) {
   1507   // Object pointers never have qualifiers.
   1508   Out << 'A';
   1509   mangleType(T->getPointeeType(), Range);
   1510 }
   1511 
   1512 // <type> ::= <reference-type>
   1513 // <reference-type> ::= A <cvr-qualifiers> <type>
   1514 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
   1515                                          SourceRange Range) {
   1516   Out << 'A';
   1517   QualType PointeeTy = T->getPointeeType();
   1518   if (!PointeeTy.hasQualifiers())
   1519     // Lack of qualifiers is mangled as 'A'.
   1520     Out << 'A';
   1521   mangleType(PointeeTy, Range);
   1522 }
   1523 
   1524 // <type> ::= <r-value-reference-type>
   1525 // <r-value-reference-type> ::= $$Q <cvr-qualifiers> <type>
   1526 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
   1527                                          SourceRange Range) {
   1528   Out << "$$Q";
   1529   QualType PointeeTy = T->getPointeeType();
   1530   if (!PointeeTy.hasQualifiers())
   1531     // Lack of qualifiers is mangled as 'A'.
   1532     Out << 'A';
   1533   mangleType(PointeeTy, Range);
   1534 }
   1535 
   1536 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
   1537                                          SourceRange Range) {
   1538   DiagnosticsEngine &Diags = Context.getDiags();
   1539   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1540     "cannot mangle this complex number type yet");
   1541   Diags.Report(Range.getBegin(), DiagID)
   1542     << Range;
   1543 }
   1544 
   1545 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
   1546                                          SourceRange Range) {
   1547   DiagnosticsEngine &Diags = Context.getDiags();
   1548   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1549     "cannot mangle this vector type yet");
   1550   Diags.Report(Range.getBegin(), DiagID)
   1551     << Range;
   1552 }
   1553 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
   1554                                          SourceRange Range) {
   1555   DiagnosticsEngine &Diags = Context.getDiags();
   1556   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1557     "cannot mangle this extended vector type yet");
   1558   Diags.Report(Range.getBegin(), DiagID)
   1559     << Range;
   1560 }
   1561 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
   1562                                          SourceRange Range) {
   1563   DiagnosticsEngine &Diags = Context.getDiags();
   1564   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1565     "cannot mangle this dependent-sized extended vector type yet");
   1566   Diags.Report(Range.getBegin(), DiagID)
   1567     << Range;
   1568 }
   1569 
   1570 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
   1571                                          SourceRange) {
   1572   // ObjC interfaces have structs underlying them.
   1573   Out << 'U';
   1574   mangleName(T->getDecl());
   1575 }
   1576 
   1577 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
   1578                                          SourceRange Range) {
   1579   // We don't allow overloading by different protocol qualification,
   1580   // so mangling them isn't necessary.
   1581   mangleType(T->getBaseType(), Range);
   1582 }
   1583 
   1584 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
   1585                                          SourceRange Range) {
   1586   Out << "_E";
   1587 
   1588   QualType pointee = T->getPointeeType();
   1589   mangleType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
   1590 }
   1591 
   1592 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T,
   1593                                          SourceRange Range) {
   1594   DiagnosticsEngine &Diags = Context.getDiags();
   1595   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1596     "cannot mangle this injected class name type yet");
   1597   Diags.Report(Range.getBegin(), DiagID)
   1598     << Range;
   1599 }
   1600 
   1601 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
   1602                                          SourceRange Range) {
   1603   DiagnosticsEngine &Diags = Context.getDiags();
   1604   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1605     "cannot mangle this template specialization type yet");
   1606   Diags.Report(Range.getBegin(), DiagID)
   1607     << Range;
   1608 }
   1609 
   1610 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
   1611                                          SourceRange Range) {
   1612   DiagnosticsEngine &Diags = Context.getDiags();
   1613   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1614     "cannot mangle this dependent name type yet");
   1615   Diags.Report(Range.getBegin(), DiagID)
   1616     << Range;
   1617 }
   1618 
   1619 void MicrosoftCXXNameMangler::mangleType(
   1620                                  const DependentTemplateSpecializationType *T,
   1621                                  SourceRange Range) {
   1622   DiagnosticsEngine &Diags = Context.getDiags();
   1623   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1624     "cannot mangle this dependent template specialization type yet");
   1625   Diags.Report(Range.getBegin(), DiagID)
   1626     << Range;
   1627 }
   1628 
   1629 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
   1630                                          SourceRange Range) {
   1631   DiagnosticsEngine &Diags = Context.getDiags();
   1632   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1633     "cannot mangle this pack expansion yet");
   1634   Diags.Report(Range.getBegin(), DiagID)
   1635     << Range;
   1636 }
   1637 
   1638 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
   1639                                          SourceRange Range) {
   1640   DiagnosticsEngine &Diags = Context.getDiags();
   1641   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1642     "cannot mangle this typeof(type) yet");
   1643   Diags.Report(Range.getBegin(), DiagID)
   1644     << Range;
   1645 }
   1646 
   1647 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
   1648                                          SourceRange Range) {
   1649   DiagnosticsEngine &Diags = Context.getDiags();
   1650   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1651     "cannot mangle this typeof(expression) yet");
   1652   Diags.Report(Range.getBegin(), DiagID)
   1653     << Range;
   1654 }
   1655 
   1656 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
   1657                                          SourceRange Range) {
   1658   DiagnosticsEngine &Diags = Context.getDiags();
   1659   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1660     "cannot mangle this decltype() yet");
   1661   Diags.Report(Range.getBegin(), DiagID)
   1662     << Range;
   1663 }
   1664 
   1665 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
   1666                                          SourceRange Range) {
   1667   DiagnosticsEngine &Diags = Context.getDiags();
   1668   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1669     "cannot mangle this unary transform type yet");
   1670   Diags.Report(Range.getBegin(), DiagID)
   1671     << Range;
   1672 }
   1673 
   1674 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
   1675   DiagnosticsEngine &Diags = Context.getDiags();
   1676   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1677     "cannot mangle this 'auto' type yet");
   1678   Diags.Report(Range.getBegin(), DiagID)
   1679     << Range;
   1680 }
   1681 
   1682 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
   1683                                          SourceRange Range) {
   1684   DiagnosticsEngine &Diags = Context.getDiags();
   1685   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1686     "cannot mangle this C11 atomic type yet");
   1687   Diags.Report(Range.getBegin(), DiagID)
   1688     << Range;
   1689 }
   1690 
   1691 void MicrosoftMangleContext::mangleName(const NamedDecl *D,
   1692                                         raw_ostream &Out) {
   1693   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
   1694          "Invalid mangleName() call, argument is not a variable or function!");
   1695   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
   1696          "Invalid mangleName() call on 'structor decl!");
   1697 
   1698   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
   1699                                  getASTContext().getSourceManager(),
   1700                                  "Mangling declaration");
   1701 
   1702   MicrosoftCXXNameMangler Mangler(*this, Out);
   1703   return Mangler.mangle(D);
   1704 }
   1705 void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
   1706                                          const ThunkInfo &Thunk,
   1707                                          raw_ostream &) {
   1708   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   1709     "cannot mangle thunk for this method yet");
   1710   getDiags().Report(MD->getLocation(), DiagID);
   1711 }
   1712 void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
   1713                                                 CXXDtorType Type,
   1714                                                 const ThisAdjustment &,
   1715                                                 raw_ostream &) {
   1716   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   1717     "cannot mangle thunk for this destructor yet");
   1718   getDiags().Report(DD->getLocation(), DiagID);
   1719 }
   1720 void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
   1721                                              raw_ostream &Out) {
   1722   // <mangled-name> ::= ? <operator-name> <class-name> <storage-class>
   1723   //                      <cvr-qualifiers> [<name>] @
   1724   // <operator-name> ::= _7 # vftable
   1725   //                 ::= _8 # vbtable
   1726   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
   1727   // is always '6' for vftables and '7' for vbtables. (The difference is
   1728   // beyond me.)
   1729   // TODO: vbtables.
   1730   MicrosoftCXXNameMangler Mangler(*this, Out);
   1731   Mangler.getStream() << "\01??_7";
   1732   Mangler.mangleName(RD);
   1733   Mangler.getStream() << "6B";
   1734   // TODO: If the class has more than one vtable, mangle in the class it came
   1735   // from.
   1736   Mangler.getStream() << '@';
   1737 }
   1738 void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
   1739                                           raw_ostream &) {
   1740   llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
   1741 }
   1742 void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
   1743                                                  int64_t Offset,
   1744                                                  const CXXRecordDecl *Type,
   1745                                                  raw_ostream &) {
   1746   llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
   1747 }
   1748 void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
   1749                                            raw_ostream &) {
   1750   // FIXME: Give a location...
   1751   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   1752     "cannot mangle RTTI descriptors for type %0 yet");
   1753   getDiags().Report(DiagID)
   1754     << T.getBaseTypeIdentifier();
   1755 }
   1756 void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
   1757                                                raw_ostream &) {
   1758   // FIXME: Give a location...
   1759   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   1760     "cannot mangle the name of type %0 into RTTI descriptors yet");
   1761   getDiags().Report(DiagID)
   1762     << T.getBaseTypeIdentifier();
   1763 }
   1764 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
   1765                                            CXXCtorType Type,
   1766                                            raw_ostream & Out) {
   1767   MicrosoftCXXNameMangler mangler(*this, Out);
   1768   mangler.mangle(D);
   1769 }
   1770 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
   1771                                            CXXDtorType Type,
   1772                                            raw_ostream & Out) {
   1773   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
   1774   mangler.mangle(D);
   1775 }
   1776 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *VD,
   1777                                                       raw_ostream &) {
   1778   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   1779     "cannot mangle this reference temporary yet");
   1780   getDiags().Report(VD->getLocation(), DiagID);
   1781 }
   1782 
   1783 MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
   1784                                                    DiagnosticsEngine &Diags) {
   1785   return new MicrosoftMangleContext(Context, Diags);
   1786 }
   1787