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/CXXInheritance.h"
     18 #include "clang/AST/CharUnits.h"
     19 #include "clang/AST/Decl.h"
     20 #include "clang/AST/DeclCXX.h"
     21 #include "clang/AST/DeclObjC.h"
     22 #include "clang/AST/DeclTemplate.h"
     23 #include "clang/AST/Expr.h"
     24 #include "clang/AST/ExprCXX.h"
     25 #include "clang/AST/VTableBuilder.h"
     26 #include "clang/Basic/ABI.h"
     27 #include "clang/Basic/DiagnosticOptions.h"
     28 #include "clang/Basic/TargetInfo.h"
     29 #include "llvm/ADT/StringExtras.h"
     30 #include "llvm/Support/MathExtras.h"
     31 
     32 using namespace clang;
     33 
     34 namespace {
     35 
     36 /// \brief Retrieve the declaration context that should be used when mangling
     37 /// the given declaration.
     38 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
     39   // The ABI assumes that lambda closure types that occur within
     40   // default arguments live in the context of the function. However, due to
     41   // the way in which Clang parses and creates function declarations, this is
     42   // not the case: the lambda closure type ends up living in the context
     43   // where the function itself resides, because the function declaration itself
     44   // had not yet been created. Fix the context here.
     45   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
     46     if (RD->isLambda())
     47       if (ParmVarDecl *ContextParam =
     48               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
     49         return ContextParam->getDeclContext();
     50   }
     51 
     52   // Perform the same check for block literals.
     53   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
     54     if (ParmVarDecl *ContextParam =
     55             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
     56       return ContextParam->getDeclContext();
     57   }
     58 
     59   const DeclContext *DC = D->getDeclContext();
     60   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
     61     return getEffectiveDeclContext(CD);
     62 
     63   return DC;
     64 }
     65 
     66 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
     67   return getEffectiveDeclContext(cast<Decl>(DC));
     68 }
     69 
     70 static const FunctionDecl *getStructor(const NamedDecl *ND) {
     71   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
     72     return FTD->getTemplatedDecl();
     73 
     74   const auto *FD = cast<FunctionDecl>(ND);
     75   if (const auto *FTD = FD->getPrimaryTemplate())
     76     return FTD->getTemplatedDecl();
     77 
     78   return FD;
     79 }
     80 
     81 static bool isLambda(const NamedDecl *ND) {
     82   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
     83   if (!Record)
     84     return false;
     85 
     86   return Record->isLambda();
     87 }
     88 
     89 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
     90 /// Microsoft Visual C++ ABI.
     91 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
     92   typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
     93   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
     94   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
     95   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
     96   llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
     97   llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
     98 
     99 public:
    100   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
    101       : MicrosoftMangleContext(Context, Diags) {}
    102   bool shouldMangleCXXName(const NamedDecl *D) override;
    103   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
    104   void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
    105   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
    106                                 raw_ostream &) override;
    107   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
    108                    raw_ostream &) override;
    109   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
    110                           const ThisAdjustment &ThisAdjustment,
    111                           raw_ostream &) override;
    112   void mangleCXXVFTable(const CXXRecordDecl *Derived,
    113                         ArrayRef<const CXXRecordDecl *> BasePath,
    114                         raw_ostream &Out) override;
    115   void mangleCXXVBTable(const CXXRecordDecl *Derived,
    116                         ArrayRef<const CXXRecordDecl *> BasePath,
    117                         raw_ostream &Out) override;
    118   void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
    119                           uint32_t NumEntries, raw_ostream &Out) override;
    120   void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
    121                                    raw_ostream &Out) override;
    122   void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
    123                               CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
    124                               int32_t VBPtrOffset, uint32_t VBIndex,
    125                               raw_ostream &Out) override;
    126   void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
    127                                  raw_ostream &Out) override;
    128   void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
    129   void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
    130   void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
    131                                         uint32_t NVOffset, int32_t VBPtrOffset,
    132                                         uint32_t VBTableOffset, uint32_t Flags,
    133                                         raw_ostream &Out) override;
    134   void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
    135                                    raw_ostream &Out) override;
    136   void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
    137                                              raw_ostream &Out) override;
    138   void
    139   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
    140                                      ArrayRef<const CXXRecordDecl *> BasePath,
    141                                      raw_ostream &Out) override;
    142   void mangleTypeName(QualType T, raw_ostream &) override;
    143   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
    144                      raw_ostream &) override;
    145   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
    146                      raw_ostream &) override;
    147   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
    148                                 raw_ostream &) override;
    149   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
    150   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
    151   void mangleDynamicAtExitDestructor(const VarDecl *D,
    152                                      raw_ostream &Out) override;
    153   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
    154                                  raw_ostream &Out) override;
    155   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
    156                              raw_ostream &Out) override;
    157   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
    158   void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
    159                              raw_ostream &Out) override;
    160   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
    161     // Lambda closure types are already numbered.
    162     if (isLambda(ND))
    163       return false;
    164 
    165     const DeclContext *DC = getEffectiveDeclContext(ND);
    166     if (!DC->isFunctionOrMethod())
    167       return false;
    168 
    169     // Use the canonical number for externally visible decls.
    170     if (ND->isExternallyVisible()) {
    171       disc = getASTContext().getManglingNumber(ND);
    172       return true;
    173     }
    174 
    175     // Anonymous tags are already numbered.
    176     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
    177       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
    178         return false;
    179     }
    180 
    181     // Make up a reasonable number for internal decls.
    182     unsigned &discriminator = Uniquifier[ND];
    183     if (!discriminator)
    184       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
    185     disc = discriminator + 1;
    186     return true;
    187   }
    188 
    189   unsigned getLambdaId(const CXXRecordDecl *RD) {
    190     assert(RD->isLambda() && "RD must be a lambda!");
    191     assert(!RD->isExternallyVisible() && "RD must not be visible!");
    192     assert(RD->getLambdaManglingNumber() == 0 &&
    193            "RD must not have a mangling number!");
    194     std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
    195         Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
    196     return Result.first->second;
    197   }
    198 
    199 private:
    200   void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
    201 };
    202 
    203 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
    204 /// Microsoft Visual C++ ABI.
    205 class MicrosoftCXXNameMangler {
    206   MicrosoftMangleContextImpl &Context;
    207   raw_ostream &Out;
    208 
    209   /// The "structor" is the top-level declaration being mangled, if
    210   /// that's not a template specialization; otherwise it's the pattern
    211   /// for that specialization.
    212   const NamedDecl *Structor;
    213   unsigned StructorType;
    214 
    215   typedef llvm::SmallVector<std::string, 10> BackRefVec;
    216   BackRefVec NameBackReferences;
    217 
    218   typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
    219   ArgBackRefMap TypeBackReferences;
    220 
    221   ASTContext &getASTContext() const { return Context.getASTContext(); }
    222 
    223   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
    224   // this check into mangleQualifiers().
    225   const bool PointersAre64Bit;
    226 
    227 public:
    228   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
    229 
    230   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
    231       : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
    232         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
    233                          64) {}
    234 
    235   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
    236                           const CXXConstructorDecl *D, CXXCtorType Type)
    237       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    238         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
    239                          64) {}
    240 
    241   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
    242                           const CXXDestructorDecl *D, CXXDtorType Type)
    243       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
    244         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
    245                          64) {}
    246 
    247   raw_ostream &getStream() const { return Out; }
    248 
    249   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
    250   void mangleName(const NamedDecl *ND);
    251   void mangleFunctionEncoding(const FunctionDecl *FD);
    252   void mangleVariableEncoding(const VarDecl *VD);
    253   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
    254   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
    255                                    const CXXMethodDecl *MD);
    256   void mangleVirtualMemPtrThunk(
    257       const CXXMethodDecl *MD,
    258       const MicrosoftVTableContext::MethodVFTableLocation &ML);
    259   void mangleNumber(int64_t Number);
    260   void mangleType(QualType T, SourceRange Range,
    261                   QualifierMangleMode QMM = QMM_Mangle);
    262   void mangleFunctionType(const FunctionType *T,
    263                           const FunctionDecl *D = nullptr,
    264                           bool ForceThisQuals = false);
    265   void mangleNestedName(const NamedDecl *ND);
    266 
    267 private:
    268   void mangleUnqualifiedName(const NamedDecl *ND) {
    269     mangleUnqualifiedName(ND, ND->getDeclName());
    270   }
    271   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
    272   void mangleSourceName(StringRef Name);
    273   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
    274   void mangleCXXDtorType(CXXDtorType T);
    275   void mangleQualifiers(Qualifiers Quals, bool IsMember);
    276   void mangleRefQualifier(RefQualifierKind RefQualifier);
    277   void manglePointerCVQualifiers(Qualifiers Quals);
    278   void manglePointerExtQualifiers(Qualifiers Quals, const Type *PointeeType);
    279 
    280   void mangleUnscopedTemplateName(const TemplateDecl *ND);
    281   void
    282   mangleTemplateInstantiationName(const TemplateDecl *TD,
    283                                   const TemplateArgumentList &TemplateArgs);
    284   void mangleObjCMethodName(const ObjCMethodDecl *MD);
    285 
    286   void mangleArgumentType(QualType T, SourceRange Range);
    287 
    288   // Declare manglers for every type class.
    289 #define ABSTRACT_TYPE(CLASS, PARENT)
    290 #define NON_CANONICAL_TYPE(CLASS, PARENT)
    291 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
    292                                             SourceRange Range);
    293 #include "clang/AST/TypeNodes.def"
    294 #undef ABSTRACT_TYPE
    295 #undef NON_CANONICAL_TYPE
    296 #undef TYPE
    297 
    298   void mangleType(const TagDecl *TD);
    299   void mangleDecayedArrayType(const ArrayType *T);
    300   void mangleArrayType(const ArrayType *T);
    301   void mangleFunctionClass(const FunctionDecl *FD);
    302   void mangleCallingConvention(CallingConv CC);
    303   void mangleCallingConvention(const FunctionType *T);
    304   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
    305   void mangleExpression(const Expr *E);
    306   void mangleThrowSpecification(const FunctionProtoType *T);
    307 
    308   void mangleTemplateArgs(const TemplateDecl *TD,
    309                           const TemplateArgumentList &TemplateArgs);
    310   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
    311                          const NamedDecl *Parm);
    312 };
    313 }
    314 
    315 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
    316   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    317     LanguageLinkage L = FD->getLanguageLinkage();
    318     // Overloadable functions need mangling.
    319     if (FD->hasAttr<OverloadableAttr>())
    320       return true;
    321 
    322     // The ABI expects that we would never mangle "typical" user-defined entry
    323     // points regardless of visibility or freestanding-ness.
    324     //
    325     // N.B. This is distinct from asking about "main".  "main" has a lot of
    326     // special rules associated with it in the standard while these
    327     // user-defined entry points are outside of the purview of the standard.
    328     // For example, there can be only one definition for "main" in a standards
    329     // compliant program; however nothing forbids the existence of wmain and
    330     // WinMain in the same translation unit.
    331     if (FD->isMSVCRTEntryPoint())
    332       return false;
    333 
    334     // C++ functions and those whose names are not a simple identifier need
    335     // mangling.
    336     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
    337       return true;
    338 
    339     // C functions are not mangled.
    340     if (L == CLanguageLinkage)
    341       return false;
    342   }
    343 
    344   // Otherwise, no mangling is done outside C++ mode.
    345   if (!getASTContext().getLangOpts().CPlusPlus)
    346     return false;
    347 
    348   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
    349     // C variables are not mangled.
    350     if (VD->isExternC())
    351       return false;
    352 
    353     // Variables at global scope with non-internal linkage are not mangled.
    354     const DeclContext *DC = getEffectiveDeclContext(D);
    355     // Check for extern variable declared locally.
    356     if (DC->isFunctionOrMethod() && D->hasLinkage())
    357       while (!DC->isNamespace() && !DC->isTranslationUnit())
    358         DC = getEffectiveParentContext(DC);
    359 
    360     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
    361         !isa<VarTemplateSpecializationDecl>(D))
    362       return false;
    363   }
    364 
    365   return true;
    366 }
    367 
    368 bool
    369 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
    370   return true;
    371 }
    372 
    373 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
    374   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
    375   // Therefore it's really important that we don't decorate the
    376   // name with leading underscores or leading/trailing at signs. So, by
    377   // default, we emit an asm marker at the start so we get the name right.
    378   // Callers can override this with a custom prefix.
    379 
    380   // <mangled-name> ::= ? <name> <type-encoding>
    381   Out << Prefix;
    382   mangleName(D);
    383   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
    384     mangleFunctionEncoding(FD);
    385   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
    386     mangleVariableEncoding(VD);
    387   else {
    388     // TODO: Fields? Can MSVC even mangle them?
    389     // Issue a diagnostic for now.
    390     DiagnosticsEngine &Diags = Context.getDiags();
    391     unsigned DiagID = Diags.getCustomDiagID(
    392         DiagnosticsEngine::Error, "cannot mangle this declaration yet");
    393     Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
    394   }
    395 }
    396 
    397 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
    398   // <type-encoding> ::= <function-class> <function-type>
    399 
    400   // Since MSVC operates on the type as written and not the canonical type, it
    401   // actually matters which decl we have here.  MSVC appears to choose the
    402   // first, since it is most likely to be the declaration in a header file.
    403   FD = FD->getFirstDecl();
    404 
    405   // We should never ever see a FunctionNoProtoType at this point.
    406   // We don't even know how to mangle their types anyway :).
    407   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
    408 
    409   // extern "C" functions can hold entities that must be mangled.
    410   // As it stands, these functions still need to get expressed in the full
    411   // external name.  They have their class and type omitted, replaced with '9'.
    412   if (Context.shouldMangleDeclName(FD)) {
    413     // First, the function class.
    414     mangleFunctionClass(FD);
    415 
    416     mangleFunctionType(FT, FD);
    417   } else
    418     Out << '9';
    419 }
    420 
    421 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
    422   // <type-encoding> ::= <storage-class> <variable-type>
    423   // <storage-class> ::= 0  # private static member
    424   //                 ::= 1  # protected static member
    425   //                 ::= 2  # public static member
    426   //                 ::= 3  # global
    427   //                 ::= 4  # static local
    428 
    429   // The first character in the encoding (after the name) is the storage class.
    430   if (VD->isStaticDataMember()) {
    431     // If it's a static member, it also encodes the access level.
    432     switch (VD->getAccess()) {
    433       default:
    434       case AS_private: Out << '0'; break;
    435       case AS_protected: Out << '1'; break;
    436       case AS_public: Out << '2'; break;
    437     }
    438   }
    439   else if (!VD->isStaticLocal())
    440     Out << '3';
    441   else
    442     Out << '4';
    443   // Now mangle the type.
    444   // <variable-type> ::= <type> <cvr-qualifiers>
    445   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
    446   // Pointers and references are odd. The type of 'int * const foo;' gets
    447   // mangled as 'QAHA' instead of 'PAHB', for example.
    448   SourceRange SR = VD->getSourceRange();
    449   QualType Ty = VD->getType();
    450   if (Ty->isPointerType() || Ty->isReferenceType() ||
    451       Ty->isMemberPointerType()) {
    452     mangleType(Ty, SR, QMM_Drop);
    453     manglePointerExtQualifiers(
    454         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), nullptr);
    455     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
    456       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
    457       // Member pointers are suffixed with a back reference to the member
    458       // pointer's class name.
    459       mangleName(MPT->getClass()->getAsCXXRecordDecl());
    460     } else
    461       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
    462   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
    463     // Global arrays are funny, too.
    464     mangleDecayedArrayType(AT);
    465     if (AT->getElementType()->isArrayType())
    466       Out << 'A';
    467     else
    468       mangleQualifiers(Ty.getQualifiers(), false);
    469   } else {
    470     mangleType(Ty, SR, QMM_Drop);
    471     mangleQualifiers(Ty.getQualifiers(), false);
    472   }
    473 }
    474 
    475 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
    476                                                       const ValueDecl *VD) {
    477   // <member-data-pointer> ::= <integer-literal>
    478   //                       ::= $F <number> <number>
    479   //                       ::= $G <number> <number> <number>
    480 
    481   int64_t FieldOffset;
    482   int64_t VBTableOffset;
    483   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
    484   if (VD) {
    485     FieldOffset = getASTContext().getFieldOffset(VD);
    486     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
    487            "cannot take address of bitfield");
    488     FieldOffset /= getASTContext().getCharWidth();
    489 
    490     VBTableOffset = 0;
    491   } else {
    492     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
    493 
    494     VBTableOffset = -1;
    495   }
    496 
    497   char Code = '\0';
    498   switch (IM) {
    499   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
    500   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
    501   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
    502   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
    503   }
    504 
    505   Out << '$' << Code;
    506 
    507   mangleNumber(FieldOffset);
    508 
    509   // The C++ standard doesn't allow base-to-derived member pointer conversions
    510   // in template parameter contexts, so the vbptr offset of data member pointers
    511   // is always zero.
    512   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
    513     mangleNumber(0);
    514   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
    515     mangleNumber(VBTableOffset);
    516 }
    517 
    518 void
    519 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
    520                                                      const CXXMethodDecl *MD) {
    521   // <member-function-pointer> ::= $1? <name>
    522   //                           ::= $H? <name> <number>
    523   //                           ::= $I? <name> <number> <number>
    524   //                           ::= $J? <name> <number> <number> <number>
    525 
    526   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
    527 
    528   char Code = '\0';
    529   switch (IM) {
    530   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
    531   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
    532   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
    533   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
    534   }
    535 
    536   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
    537   // thunk.
    538   uint64_t NVOffset = 0;
    539   uint64_t VBTableOffset = 0;
    540   uint64_t VBPtrOffset = 0;
    541   if (MD) {
    542     Out << '$' << Code << '?';
    543     if (MD->isVirtual()) {
    544       MicrosoftVTableContext *VTContext =
    545           cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
    546       const MicrosoftVTableContext::MethodVFTableLocation &ML =
    547           VTContext->getMethodVFTableLocation(GlobalDecl(MD));
    548       mangleVirtualMemPtrThunk(MD, ML);
    549       NVOffset = ML.VFPtrOffset.getQuantity();
    550       VBTableOffset = ML.VBTableIndex * 4;
    551       if (ML.VBase) {
    552         const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
    553         VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
    554       }
    555     } else {
    556       mangleName(MD);
    557       mangleFunctionEncoding(MD);
    558     }
    559   } else {
    560     // Null single inheritance member functions are encoded as a simple nullptr.
    561     if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
    562       Out << "$0A@";
    563       return;
    564     }
    565     if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
    566       VBTableOffset = -1;
    567     Out << '$' << Code;
    568   }
    569 
    570   if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
    571     mangleNumber(NVOffset);
    572   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
    573     mangleNumber(VBPtrOffset);
    574   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
    575     mangleNumber(VBTableOffset);
    576 }
    577 
    578 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
    579     const CXXMethodDecl *MD,
    580     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
    581   // Get the vftable offset.
    582   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
    583       getASTContext().getTargetInfo().getPointerWidth(0));
    584   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
    585 
    586   Out << "?_9";
    587   mangleName(MD->getParent());
    588   Out << "$B";
    589   mangleNumber(OffsetInVFTable);
    590   Out << 'A';
    591   mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
    592 }
    593 
    594 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
    595   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
    596 
    597   // Always start with the unqualified name.
    598   mangleUnqualifiedName(ND);
    599 
    600   mangleNestedName(ND);
    601 
    602   // Terminate the whole name with an '@'.
    603   Out << '@';
    604 }
    605 
    606 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
    607   // <non-negative integer> ::= A@              # when Number == 0
    608   //                        ::= <decimal digit> # when 1 <= Number <= 10
    609   //                        ::= <hex digit>+ @  # when Number >= 10
    610   //
    611   // <number>               ::= [?] <non-negative integer>
    612 
    613   uint64_t Value = static_cast<uint64_t>(Number);
    614   if (Number < 0) {
    615     Value = -Value;
    616     Out << '?';
    617   }
    618 
    619   if (Value == 0)
    620     Out << "A@";
    621   else if (Value >= 1 && Value <= 10)
    622     Out << (Value - 1);
    623   else {
    624     // Numbers that are not encoded as decimal digits are represented as nibbles
    625     // in the range of ASCII characters 'A' to 'P'.
    626     // The number 0x123450 would be encoded as 'BCDEFA'
    627     char EncodedNumberBuffer[sizeof(uint64_t) * 2];
    628     MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
    629     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
    630     for (; Value != 0; Value >>= 4)
    631       *I++ = 'A' + (Value & 0xf);
    632     Out.write(I.base(), I - BufferRef.rbegin());
    633     Out << '@';
    634   }
    635 }
    636 
    637 static const TemplateDecl *
    638 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
    639   // Check if we have a function template.
    640   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
    641     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
    642       TemplateArgs = FD->getTemplateSpecializationArgs();
    643       return TD;
    644     }
    645   }
    646 
    647   // Check if we have a class template.
    648   if (const ClassTemplateSpecializationDecl *Spec =
    649           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
    650     TemplateArgs = &Spec->getTemplateArgs();
    651     return Spec->getSpecializedTemplate();
    652   }
    653 
    654   // Check if we have a variable template.
    655   if (const VarTemplateSpecializationDecl *Spec =
    656           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
    657     TemplateArgs = &Spec->getTemplateArgs();
    658     return Spec->getSpecializedTemplate();
    659   }
    660 
    661   return nullptr;
    662 }
    663 
    664 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
    665                                                     DeclarationName Name) {
    666   //  <unqualified-name> ::= <operator-name>
    667   //                     ::= <ctor-dtor-name>
    668   //                     ::= <source-name>
    669   //                     ::= <template-name>
    670 
    671   // Check if we have a template.
    672   const TemplateArgumentList *TemplateArgs = nullptr;
    673   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
    674     // Function templates aren't considered for name back referencing.  This
    675     // makes sense since function templates aren't likely to occur multiple
    676     // times in a symbol.
    677     // FIXME: Test alias template mangling with MSVC 2013.
    678     if (!isa<ClassTemplateDecl>(TD)) {
    679       mangleTemplateInstantiationName(TD, *TemplateArgs);
    680       Out << '@';
    681       return;
    682     }
    683 
    684     // Here comes the tricky thing: if we need to mangle something like
    685     //   void foo(A::X<Y>, B::X<Y>),
    686     // the X<Y> part is aliased. However, if you need to mangle
    687     //   void foo(A::X<A::Y>, A::X<B::Y>),
    688     // the A::X<> part is not aliased.
    689     // That said, from the mangler's perspective we have a structure like this:
    690     //   namespace[s] -> type[ -> template-parameters]
    691     // but from the Clang perspective we have
    692     //   type [ -> template-parameters]
    693     //      \-> namespace[s]
    694     // What we do is we create a new mangler, mangle the same type (without
    695     // a namespace suffix) to a string using the extra mangler and then use
    696     // the mangled type name as a key to check the mangling of different types
    697     // for aliasing.
    698 
    699     llvm::SmallString<64> TemplateMangling;
    700     llvm::raw_svector_ostream Stream(TemplateMangling);
    701     MicrosoftCXXNameMangler Extra(Context, Stream);
    702     Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
    703     Stream.flush();
    704 
    705     mangleSourceName(TemplateMangling);
    706     return;
    707   }
    708 
    709   switch (Name.getNameKind()) {
    710     case DeclarationName::Identifier: {
    711       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
    712         mangleSourceName(II->getName());
    713         break;
    714       }
    715 
    716       // Otherwise, an anonymous entity.  We must have a declaration.
    717       assert(ND && "mangling empty name without declaration");
    718 
    719       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
    720         if (NS->isAnonymousNamespace()) {
    721           Out << "?A@";
    722           break;
    723         }
    724       }
    725 
    726       if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
    727         // We must have an anonymous union or struct declaration.
    728         const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
    729         assert(RD && "expected variable decl to have a record type");
    730         // Anonymous types with no tag or typedef get the name of their
    731         // declarator mangled in.  If they have no declarator, number them with
    732         // a $S prefix.
    733         llvm::SmallString<64> Name("$S");
    734         // Get a unique id for the anonymous struct.
    735         Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
    736         mangleSourceName(Name.str());
    737         break;
    738       }
    739 
    740       // We must have an anonymous struct.
    741       const TagDecl *TD = cast<TagDecl>(ND);
    742       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
    743         assert(TD->getDeclContext() == D->getDeclContext() &&
    744                "Typedef should not be in another decl context!");
    745         assert(D->getDeclName().getAsIdentifierInfo() &&
    746                "Typedef was not named!");
    747         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
    748         break;
    749       }
    750 
    751       if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
    752         if (Record->isLambda()) {
    753           llvm::SmallString<10> Name("<lambda_");
    754           unsigned LambdaId;
    755           if (Record->getLambdaManglingNumber())
    756             LambdaId = Record->getLambdaManglingNumber();
    757           else
    758             LambdaId = Context.getLambdaId(Record);
    759 
    760           Name += llvm::utostr(LambdaId);
    761           Name += ">";
    762 
    763           mangleSourceName(Name);
    764           break;
    765         }
    766       }
    767 
    768       llvm::SmallString<64> Name("<unnamed-type-");
    769       if (TD->hasDeclaratorForAnonDecl()) {
    770         // Anonymous types with no tag or typedef get the name of their
    771         // declarator mangled in if they have one.
    772         Name += TD->getDeclaratorForAnonDecl()->getName();
    773       } else {
    774         // Otherwise, number the types using a $S prefix.
    775         Name += "$S";
    776         Name += llvm::utostr(Context.getAnonymousStructId(TD));
    777       }
    778       Name += ">";
    779       mangleSourceName(Name.str());
    780       break;
    781     }
    782 
    783     case DeclarationName::ObjCZeroArgSelector:
    784     case DeclarationName::ObjCOneArgSelector:
    785     case DeclarationName::ObjCMultiArgSelector:
    786       llvm_unreachable("Can't mangle Objective-C selector names here!");
    787 
    788     case DeclarationName::CXXConstructorName:
    789       if (Structor == getStructor(ND)) {
    790         if (StructorType == Ctor_CopyingClosure) {
    791           Out << "?_O";
    792           return;
    793         }
    794         if (StructorType == Ctor_DefaultClosure) {
    795           Out << "?_F";
    796           return;
    797         }
    798       }
    799       Out << "?0";
    800       return;
    801 
    802     case DeclarationName::CXXDestructorName:
    803       if (ND == Structor)
    804         // If the named decl is the C++ destructor we're mangling,
    805         // use the type we were given.
    806         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
    807       else
    808         // Otherwise, use the base destructor name. This is relevant if a
    809         // class with a destructor is declared within a destructor.
    810         mangleCXXDtorType(Dtor_Base);
    811       break;
    812 
    813     case DeclarationName::CXXConversionFunctionName:
    814       // <operator-name> ::= ?B # (cast)
    815       // The target type is encoded as the return type.
    816       Out << "?B";
    817       break;
    818 
    819     case DeclarationName::CXXOperatorName:
    820       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
    821       break;
    822 
    823     case DeclarationName::CXXLiteralOperatorName: {
    824       Out << "?__K";
    825       mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
    826       break;
    827     }
    828 
    829     case DeclarationName::CXXUsingDirective:
    830       llvm_unreachable("Can't mangle a using directive name!");
    831   }
    832 }
    833 
    834 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
    835   // <postfix> ::= <unqualified-name> [<postfix>]
    836   //           ::= <substitution> [<postfix>]
    837   const DeclContext *DC = getEffectiveDeclContext(ND);
    838 
    839   while (!DC->isTranslationUnit()) {
    840     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
    841       unsigned Disc;
    842       if (Context.getNextDiscriminator(ND, Disc)) {
    843         Out << '?';
    844         mangleNumber(Disc);
    845         Out << '?';
    846       }
    847     }
    848 
    849     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
    850       DiagnosticsEngine &Diags = Context.getDiags();
    851       unsigned DiagID =
    852           Diags.getCustomDiagID(DiagnosticsEngine::Error,
    853                                 "cannot mangle a local inside this block yet");
    854       Diags.Report(BD->getLocation(), DiagID);
    855 
    856       // FIXME: This is completely, utterly, wrong; see ItaniumMangle
    857       // for how this should be done.
    858       Out << "__block_invoke" << Context.getBlockId(BD, false);
    859       Out << '@';
    860       continue;
    861     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
    862       mangleObjCMethodName(Method);
    863     } else if (isa<NamedDecl>(DC)) {
    864       ND = cast<NamedDecl>(DC);
    865       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
    866         mangle(FD, "?");
    867         break;
    868       } else
    869         mangleUnqualifiedName(ND);
    870     }
    871     DC = DC->getParent();
    872   }
    873 }
    874 
    875 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
    876   // Microsoft uses the names on the case labels for these dtor variants.  Clang
    877   // uses the Itanium terminology internally.  Everything in this ABI delegates
    878   // towards the base dtor.
    879   switch (T) {
    880   // <operator-name> ::= ?1  # destructor
    881   case Dtor_Base: Out << "?1"; return;
    882   // <operator-name> ::= ?_D # vbase destructor
    883   case Dtor_Complete: Out << "?_D"; return;
    884   // <operator-name> ::= ?_G # scalar deleting destructor
    885   case Dtor_Deleting: Out << "?_G"; return;
    886   // <operator-name> ::= ?_E # vector deleting destructor
    887   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
    888   // it.
    889   case Dtor_Comdat:
    890     llvm_unreachable("not expecting a COMDAT");
    891   }
    892   llvm_unreachable("Unsupported dtor type?");
    893 }
    894 
    895 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
    896                                                  SourceLocation Loc) {
    897   switch (OO) {
    898   //                     ?0 # constructor
    899   //                     ?1 # destructor
    900   // <operator-name> ::= ?2 # new
    901   case OO_New: Out << "?2"; break;
    902   // <operator-name> ::= ?3 # delete
    903   case OO_Delete: Out << "?3"; break;
    904   // <operator-name> ::= ?4 # =
    905   case OO_Equal: Out << "?4"; break;
    906   // <operator-name> ::= ?5 # >>
    907   case OO_GreaterGreater: Out << "?5"; break;
    908   // <operator-name> ::= ?6 # <<
    909   case OO_LessLess: Out << "?6"; break;
    910   // <operator-name> ::= ?7 # !
    911   case OO_Exclaim: Out << "?7"; break;
    912   // <operator-name> ::= ?8 # ==
    913   case OO_EqualEqual: Out << "?8"; break;
    914   // <operator-name> ::= ?9 # !=
    915   case OO_ExclaimEqual: Out << "?9"; break;
    916   // <operator-name> ::= ?A # []
    917   case OO_Subscript: Out << "?A"; break;
    918   //                     ?B # conversion
    919   // <operator-name> ::= ?C # ->
    920   case OO_Arrow: Out << "?C"; break;
    921   // <operator-name> ::= ?D # *
    922   case OO_Star: Out << "?D"; break;
    923   // <operator-name> ::= ?E # ++
    924   case OO_PlusPlus: Out << "?E"; break;
    925   // <operator-name> ::= ?F # --
    926   case OO_MinusMinus: Out << "?F"; break;
    927   // <operator-name> ::= ?G # -
    928   case OO_Minus: Out << "?G"; break;
    929   // <operator-name> ::= ?H # +
    930   case OO_Plus: Out << "?H"; break;
    931   // <operator-name> ::= ?I # &
    932   case OO_Amp: Out << "?I"; break;
    933   // <operator-name> ::= ?J # ->*
    934   case OO_ArrowStar: Out << "?J"; break;
    935   // <operator-name> ::= ?K # /
    936   case OO_Slash: Out << "?K"; break;
    937   // <operator-name> ::= ?L # %
    938   case OO_Percent: Out << "?L"; break;
    939   // <operator-name> ::= ?M # <
    940   case OO_Less: Out << "?M"; break;
    941   // <operator-name> ::= ?N # <=
    942   case OO_LessEqual: Out << "?N"; break;
    943   // <operator-name> ::= ?O # >
    944   case OO_Greater: Out << "?O"; break;
    945   // <operator-name> ::= ?P # >=
    946   case OO_GreaterEqual: Out << "?P"; break;
    947   // <operator-name> ::= ?Q # ,
    948   case OO_Comma: Out << "?Q"; break;
    949   // <operator-name> ::= ?R # ()
    950   case OO_Call: Out << "?R"; break;
    951   // <operator-name> ::= ?S # ~
    952   case OO_Tilde: Out << "?S"; break;
    953   // <operator-name> ::= ?T # ^
    954   case OO_Caret: Out << "?T"; break;
    955   // <operator-name> ::= ?U # |
    956   case OO_Pipe: Out << "?U"; break;
    957   // <operator-name> ::= ?V # &&
    958   case OO_AmpAmp: Out << "?V"; break;
    959   // <operator-name> ::= ?W # ||
    960   case OO_PipePipe: Out << "?W"; break;
    961   // <operator-name> ::= ?X # *=
    962   case OO_StarEqual: Out << "?X"; break;
    963   // <operator-name> ::= ?Y # +=
    964   case OO_PlusEqual: Out << "?Y"; break;
    965   // <operator-name> ::= ?Z # -=
    966   case OO_MinusEqual: Out << "?Z"; break;
    967   // <operator-name> ::= ?_0 # /=
    968   case OO_SlashEqual: Out << "?_0"; break;
    969   // <operator-name> ::= ?_1 # %=
    970   case OO_PercentEqual: Out << "?_1"; break;
    971   // <operator-name> ::= ?_2 # >>=
    972   case OO_GreaterGreaterEqual: Out << "?_2"; break;
    973   // <operator-name> ::= ?_3 # <<=
    974   case OO_LessLessEqual: Out << "?_3"; break;
    975   // <operator-name> ::= ?_4 # &=
    976   case OO_AmpEqual: Out << "?_4"; break;
    977   // <operator-name> ::= ?_5 # |=
    978   case OO_PipeEqual: Out << "?_5"; break;
    979   // <operator-name> ::= ?_6 # ^=
    980   case OO_CaretEqual: Out << "?_6"; break;
    981   //                     ?_7 # vftable
    982   //                     ?_8 # vbtable
    983   //                     ?_9 # vcall
    984   //                     ?_A # typeof
    985   //                     ?_B # local static guard
    986   //                     ?_C # string
    987   //                     ?_D # vbase destructor
    988   //                     ?_E # vector deleting destructor
    989   //                     ?_F # default constructor closure
    990   //                     ?_G # scalar deleting destructor
    991   //                     ?_H # vector constructor iterator
    992   //                     ?_I # vector destructor iterator
    993   //                     ?_J # vector vbase constructor iterator
    994   //                     ?_K # virtual displacement map
    995   //                     ?_L # eh vector constructor iterator
    996   //                     ?_M # eh vector destructor iterator
    997   //                     ?_N # eh vector vbase constructor iterator
    998   //                     ?_O # copy constructor closure
    999   //                     ?_P<name> # udt returning <name>
   1000   //                     ?_Q # <unknown>
   1001   //                     ?_R0 # RTTI Type Descriptor
   1002   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
   1003   //                     ?_R2 # RTTI Base Class Array
   1004   //                     ?_R3 # RTTI Class Hierarchy Descriptor
   1005   //                     ?_R4 # RTTI Complete Object Locator
   1006   //                     ?_S # local vftable
   1007   //                     ?_T # local vftable constructor closure
   1008   // <operator-name> ::= ?_U # new[]
   1009   case OO_Array_New: Out << "?_U"; break;
   1010   // <operator-name> ::= ?_V # delete[]
   1011   case OO_Array_Delete: Out << "?_V"; break;
   1012 
   1013   case OO_Conditional: {
   1014     DiagnosticsEngine &Diags = Context.getDiags();
   1015     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1016       "cannot mangle this conditional operator yet");
   1017     Diags.Report(Loc, DiagID);
   1018     break;
   1019   }
   1020 
   1021   case OO_None:
   1022   case NUM_OVERLOADED_OPERATORS:
   1023     llvm_unreachable("Not an overloaded operator");
   1024   }
   1025 }
   1026 
   1027 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
   1028   // <source name> ::= <identifier> @
   1029   BackRefVec::iterator Found =
   1030       std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
   1031   if (Found == NameBackReferences.end()) {
   1032     if (NameBackReferences.size() < 10)
   1033       NameBackReferences.push_back(Name);
   1034     Out << Name << '@';
   1035   } else {
   1036     Out << (Found - NameBackReferences.begin());
   1037   }
   1038 }
   1039 
   1040 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
   1041   Context.mangleObjCMethodName(MD, Out);
   1042 }
   1043 
   1044 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
   1045     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
   1046   // <template-name> ::= <unscoped-template-name> <template-args>
   1047   //                 ::= <substitution>
   1048   // Always start with the unqualified name.
   1049 
   1050   // Templates have their own context for back references.
   1051   ArgBackRefMap OuterArgsContext;
   1052   BackRefVec OuterTemplateContext;
   1053   NameBackReferences.swap(OuterTemplateContext);
   1054   TypeBackReferences.swap(OuterArgsContext);
   1055 
   1056   mangleUnscopedTemplateName(TD);
   1057   mangleTemplateArgs(TD, TemplateArgs);
   1058 
   1059   // Restore the previous back reference contexts.
   1060   NameBackReferences.swap(OuterTemplateContext);
   1061   TypeBackReferences.swap(OuterArgsContext);
   1062 }
   1063 
   1064 void
   1065 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
   1066   // <unscoped-template-name> ::= ?$ <unqualified-name>
   1067   Out << "?$";
   1068   mangleUnqualifiedName(TD);
   1069 }
   1070 
   1071 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
   1072                                                    bool IsBoolean) {
   1073   // <integer-literal> ::= $0 <number>
   1074   Out << "$0";
   1075   // Make sure booleans are encoded as 0/1.
   1076   if (IsBoolean && Value.getBoolValue())
   1077     mangleNumber(1);
   1078   else if (Value.isSigned())
   1079     mangleNumber(Value.getSExtValue());
   1080   else
   1081     mangleNumber(Value.getZExtValue());
   1082 }
   1083 
   1084 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
   1085   // See if this is a constant expression.
   1086   llvm::APSInt Value;
   1087   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
   1088     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
   1089     return;
   1090   }
   1091 
   1092   // Look through no-op casts like template parameter substitutions.
   1093   E = E->IgnoreParenNoopCasts(Context.getASTContext());
   1094 
   1095   const CXXUuidofExpr *UE = nullptr;
   1096   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
   1097     if (UO->getOpcode() == UO_AddrOf)
   1098       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
   1099   } else
   1100     UE = dyn_cast<CXXUuidofExpr>(E);
   1101 
   1102   if (UE) {
   1103     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
   1104     // const __s_GUID _GUID_{lower case UUID with underscores}
   1105     StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
   1106     std::string Name = "_GUID_" + Uuid.lower();
   1107     std::replace(Name.begin(), Name.end(), '-', '_');
   1108 
   1109     // If we had to peek through an address-of operator, treat this like we are
   1110     // dealing with a pointer type.  Otherwise, treat it like a const reference.
   1111     //
   1112     // N.B. This matches up with the handling of TemplateArgument::Declaration
   1113     // in mangleTemplateArg
   1114     if (UE == E)
   1115       Out << "$E?";
   1116     else
   1117       Out << "$1?";
   1118     Out << Name << "@@3U__s_GUID@@B";
   1119     return;
   1120   }
   1121 
   1122   // As bad as this diagnostic is, it's better than crashing.
   1123   DiagnosticsEngine &Diags = Context.getDiags();
   1124   unsigned DiagID = Diags.getCustomDiagID(
   1125       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
   1126   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
   1127                                         << E->getSourceRange();
   1128 }
   1129 
   1130 void MicrosoftCXXNameMangler::mangleTemplateArgs(
   1131     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
   1132   // <template-args> ::= <template-arg>+
   1133   const TemplateParameterList *TPL = TD->getTemplateParameters();
   1134   assert(TPL->size() == TemplateArgs.size() &&
   1135          "size mismatch between args and parms!");
   1136 
   1137   unsigned Idx = 0;
   1138   for (const TemplateArgument &TA : TemplateArgs.asArray())
   1139     mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
   1140 }
   1141 
   1142 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
   1143                                                 const TemplateArgument &TA,
   1144                                                 const NamedDecl *Parm) {
   1145   // <template-arg> ::= <type>
   1146   //                ::= <integer-literal>
   1147   //                ::= <member-data-pointer>
   1148   //                ::= <member-function-pointer>
   1149   //                ::= $E? <name> <type-encoding>
   1150   //                ::= $1? <name> <type-encoding>
   1151   //                ::= $0A@
   1152   //                ::= <template-args>
   1153 
   1154   switch (TA.getKind()) {
   1155   case TemplateArgument::Null:
   1156     llvm_unreachable("Can't mangle null template arguments!");
   1157   case TemplateArgument::TemplateExpansion:
   1158     llvm_unreachable("Can't mangle template expansion arguments!");
   1159   case TemplateArgument::Type: {
   1160     QualType T = TA.getAsType();
   1161     mangleType(T, SourceRange(), QMM_Escape);
   1162     break;
   1163   }
   1164   case TemplateArgument::Declaration: {
   1165     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
   1166     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
   1167       mangleMemberDataPointer(
   1168           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
   1169           cast<ValueDecl>(ND));
   1170     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
   1171       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   1172       if (MD && MD->isInstance())
   1173         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
   1174       else
   1175         mangle(FD, "$1?");
   1176     } else {
   1177       mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
   1178     }
   1179     break;
   1180   }
   1181   case TemplateArgument::Integral:
   1182     mangleIntegerLiteral(TA.getAsIntegral(),
   1183                          TA.getIntegralType()->isBooleanType());
   1184     break;
   1185   case TemplateArgument::NullPtr: {
   1186     QualType T = TA.getNullPtrType();
   1187     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
   1188       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
   1189       if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
   1190         mangleMemberFunctionPointer(RD, nullptr);
   1191         return;
   1192       }
   1193       if (MPT->isMemberDataPointer()) {
   1194         mangleMemberDataPointer(RD, nullptr);
   1195         return;
   1196       }
   1197     }
   1198     Out << "$0A@";
   1199     break;
   1200   }
   1201   case TemplateArgument::Expression:
   1202     mangleExpression(TA.getAsExpr());
   1203     break;
   1204   case TemplateArgument::Pack: {
   1205     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
   1206     if (TemplateArgs.empty()) {
   1207       if (isa<TemplateTypeParmDecl>(Parm) ||
   1208           isa<TemplateTemplateParmDecl>(Parm))
   1209         // MSVC 2015 changed the mangling for empty expanded template packs,
   1210         // use the old mangling for link compatibility for old versions.
   1211         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(19)
   1212                     ? "$$V"
   1213                     : "$$$V");
   1214       else if (isa<NonTypeTemplateParmDecl>(Parm))
   1215         Out << "$S";
   1216       else
   1217         llvm_unreachable("unexpected template parameter decl!");
   1218     } else {
   1219       for (const TemplateArgument &PA : TemplateArgs)
   1220         mangleTemplateArg(TD, PA, Parm);
   1221     }
   1222     break;
   1223   }
   1224   case TemplateArgument::Template: {
   1225     const NamedDecl *ND =
   1226         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
   1227     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
   1228       mangleType(TD);
   1229     } else if (isa<TypeAliasDecl>(ND)) {
   1230       Out << "$$Y";
   1231       mangleName(ND);
   1232     } else {
   1233       llvm_unreachable("unexpected template template NamedDecl!");
   1234     }
   1235     break;
   1236   }
   1237   }
   1238 }
   1239 
   1240 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
   1241                                                bool IsMember) {
   1242   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
   1243   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
   1244   // 'I' means __restrict (32/64-bit).
   1245   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
   1246   // keyword!
   1247   // <base-cvr-qualifiers> ::= A  # near
   1248   //                       ::= B  # near const
   1249   //                       ::= C  # near volatile
   1250   //                       ::= D  # near const volatile
   1251   //                       ::= E  # far (16-bit)
   1252   //                       ::= F  # far const (16-bit)
   1253   //                       ::= G  # far volatile (16-bit)
   1254   //                       ::= H  # far const volatile (16-bit)
   1255   //                       ::= I  # huge (16-bit)
   1256   //                       ::= J  # huge const (16-bit)
   1257   //                       ::= K  # huge volatile (16-bit)
   1258   //                       ::= L  # huge const volatile (16-bit)
   1259   //                       ::= M <basis> # based
   1260   //                       ::= N <basis> # based const
   1261   //                       ::= O <basis> # based volatile
   1262   //                       ::= P <basis> # based const volatile
   1263   //                       ::= Q  # near member
   1264   //                       ::= R  # near const member
   1265   //                       ::= S  # near volatile member
   1266   //                       ::= T  # near const volatile member
   1267   //                       ::= U  # far member (16-bit)
   1268   //                       ::= V  # far const member (16-bit)
   1269   //                       ::= W  # far volatile member (16-bit)
   1270   //                       ::= X  # far const volatile member (16-bit)
   1271   //                       ::= Y  # huge member (16-bit)
   1272   //                       ::= Z  # huge const member (16-bit)
   1273   //                       ::= 0  # huge volatile member (16-bit)
   1274   //                       ::= 1  # huge const volatile member (16-bit)
   1275   //                       ::= 2 <basis> # based member
   1276   //                       ::= 3 <basis> # based const member
   1277   //                       ::= 4 <basis> # based volatile member
   1278   //                       ::= 5 <basis> # based const volatile member
   1279   //                       ::= 6  # near function (pointers only)
   1280   //                       ::= 7  # far function (pointers only)
   1281   //                       ::= 8  # near method (pointers only)
   1282   //                       ::= 9  # far method (pointers only)
   1283   //                       ::= _A <basis> # based function (pointers only)
   1284   //                       ::= _B <basis> # based function (far?) (pointers only)
   1285   //                       ::= _C <basis> # based method (pointers only)
   1286   //                       ::= _D <basis> # based method (far?) (pointers only)
   1287   //                       ::= _E # block (Clang)
   1288   // <basis> ::= 0 # __based(void)
   1289   //         ::= 1 # __based(segment)?
   1290   //         ::= 2 <name> # __based(name)
   1291   //         ::= 3 # ?
   1292   //         ::= 4 # ?
   1293   //         ::= 5 # not really based
   1294   bool HasConst = Quals.hasConst(),
   1295        HasVolatile = Quals.hasVolatile();
   1296 
   1297   if (!IsMember) {
   1298     if (HasConst && HasVolatile) {
   1299       Out << 'D';
   1300     } else if (HasVolatile) {
   1301       Out << 'C';
   1302     } else if (HasConst) {
   1303       Out << 'B';
   1304     } else {
   1305       Out << 'A';
   1306     }
   1307   } else {
   1308     if (HasConst && HasVolatile) {
   1309       Out << 'T';
   1310     } else if (HasVolatile) {
   1311       Out << 'S';
   1312     } else if (HasConst) {
   1313       Out << 'R';
   1314     } else {
   1315       Out << 'Q';
   1316     }
   1317   }
   1318 
   1319   // FIXME: For now, just drop all extension qualifiers on the floor.
   1320 }
   1321 
   1322 void
   1323 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
   1324   // <ref-qualifier> ::= G                # lvalue reference
   1325   //                 ::= H                # rvalue-reference
   1326   switch (RefQualifier) {
   1327   case RQ_None:
   1328     break;
   1329 
   1330   case RQ_LValue:
   1331     Out << 'G';
   1332     break;
   1333 
   1334   case RQ_RValue:
   1335     Out << 'H';
   1336     break;
   1337   }
   1338 }
   1339 
   1340 void
   1341 MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
   1342                                                     const Type *PointeeType) {
   1343   bool HasRestrict = Quals.hasRestrict();
   1344   if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
   1345     Out << 'E';
   1346 
   1347   if (HasRestrict)
   1348     Out << 'I';
   1349 }
   1350 
   1351 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
   1352   // <pointer-cv-qualifiers> ::= P  # no qualifiers
   1353   //                         ::= Q  # const
   1354   //                         ::= R  # volatile
   1355   //                         ::= S  # const volatile
   1356   bool HasConst = Quals.hasConst(),
   1357        HasVolatile = Quals.hasVolatile();
   1358 
   1359   if (HasConst && HasVolatile) {
   1360     Out << 'S';
   1361   } else if (HasVolatile) {
   1362     Out << 'R';
   1363   } else if (HasConst) {
   1364     Out << 'Q';
   1365   } else {
   1366     Out << 'P';
   1367   }
   1368 }
   1369 
   1370 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
   1371                                                  SourceRange Range) {
   1372   // MSVC will backreference two canonically equivalent types that have slightly
   1373   // different manglings when mangled alone.
   1374 
   1375   // Decayed types do not match up with non-decayed versions of the same type.
   1376   //
   1377   // e.g.
   1378   // void (*x)(void) will not form a backreference with void x(void)
   1379   void *TypePtr;
   1380   if (const DecayedType *DT = T->getAs<DecayedType>()) {
   1381     TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
   1382     // If the original parameter was textually written as an array,
   1383     // instead treat the decayed parameter like it's const.
   1384     //
   1385     // e.g.
   1386     // int [] -> int * const
   1387     if (DT->getOriginalType()->isArrayType())
   1388       T = T.withConst();
   1389   } else
   1390     TypePtr = T.getCanonicalType().getAsOpaquePtr();
   1391 
   1392   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
   1393 
   1394   if (Found == TypeBackReferences.end()) {
   1395     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
   1396 
   1397     mangleType(T, Range, QMM_Drop);
   1398 
   1399     // See if it's worth creating a back reference.
   1400     // Only types longer than 1 character are considered
   1401     // and only 10 back references slots are available:
   1402     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
   1403     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
   1404       size_t Size = TypeBackReferences.size();
   1405       TypeBackReferences[TypePtr] = Size;
   1406     }
   1407   } else {
   1408     Out << Found->second;
   1409   }
   1410 }
   1411 
   1412 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
   1413                                          QualifierMangleMode QMM) {
   1414   // Don't use the canonical types.  MSVC includes things like 'const' on
   1415   // pointer arguments to function pointers that canonicalization strips away.
   1416   T = T.getDesugaredType(getASTContext());
   1417   Qualifiers Quals = T.getLocalQualifiers();
   1418   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
   1419     // If there were any Quals, getAsArrayType() pushed them onto the array
   1420     // element type.
   1421     if (QMM == QMM_Mangle)
   1422       Out << 'A';
   1423     else if (QMM == QMM_Escape || QMM == QMM_Result)
   1424       Out << "$$B";
   1425     mangleArrayType(AT);
   1426     return;
   1427   }
   1428 
   1429   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
   1430                    T->isBlockPointerType();
   1431 
   1432   switch (QMM) {
   1433   case QMM_Drop:
   1434     break;
   1435   case QMM_Mangle:
   1436     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
   1437       Out << '6';
   1438       mangleFunctionType(FT);
   1439       return;
   1440     }
   1441     mangleQualifiers(Quals, false);
   1442     break;
   1443   case QMM_Escape:
   1444     if (!IsPointer && Quals) {
   1445       Out << "$$C";
   1446       mangleQualifiers(Quals, false);
   1447     }
   1448     break;
   1449   case QMM_Result:
   1450     if ((!IsPointer && Quals) || isa<TagType>(T)) {
   1451       Out << '?';
   1452       mangleQualifiers(Quals, false);
   1453     }
   1454     break;
   1455   }
   1456 
   1457   // We have to mangle these now, while we still have enough information.
   1458   if (IsPointer) {
   1459     manglePointerCVQualifiers(Quals);
   1460     manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
   1461   }
   1462   const Type *ty = T.getTypePtr();
   1463 
   1464   switch (ty->getTypeClass()) {
   1465 #define ABSTRACT_TYPE(CLASS, PARENT)
   1466 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
   1467   case Type::CLASS: \
   1468     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
   1469     return;
   1470 #define TYPE(CLASS, PARENT) \
   1471   case Type::CLASS: \
   1472     mangleType(cast<CLASS##Type>(ty), Range); \
   1473     break;
   1474 #include "clang/AST/TypeNodes.def"
   1475 #undef ABSTRACT_TYPE
   1476 #undef NON_CANONICAL_TYPE
   1477 #undef TYPE
   1478   }
   1479 }
   1480 
   1481 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
   1482                                          SourceRange Range) {
   1483   //  <type>         ::= <builtin-type>
   1484   //  <builtin-type> ::= X  # void
   1485   //                 ::= C  # signed char
   1486   //                 ::= D  # char
   1487   //                 ::= E  # unsigned char
   1488   //                 ::= F  # short
   1489   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
   1490   //                 ::= H  # int
   1491   //                 ::= I  # unsigned int
   1492   //                 ::= J  # long
   1493   //                 ::= K  # unsigned long
   1494   //                     L  # <none>
   1495   //                 ::= M  # float
   1496   //                 ::= N  # double
   1497   //                 ::= O  # long double (__float80 is mangled differently)
   1498   //                 ::= _J # long long, __int64
   1499   //                 ::= _K # unsigned long long, __int64
   1500   //                 ::= _L # __int128
   1501   //                 ::= _M # unsigned __int128
   1502   //                 ::= _N # bool
   1503   //                     _O # <array in parameter>
   1504   //                 ::= _T # __float80 (Intel)
   1505   //                 ::= _W # wchar_t
   1506   //                 ::= _Z # __float80 (Digital Mars)
   1507   switch (T->getKind()) {
   1508   case BuiltinType::Void: Out << 'X'; break;
   1509   case BuiltinType::SChar: Out << 'C'; break;
   1510   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
   1511   case BuiltinType::UChar: Out << 'E'; break;
   1512   case BuiltinType::Short: Out << 'F'; break;
   1513   case BuiltinType::UShort: Out << 'G'; break;
   1514   case BuiltinType::Int: Out << 'H'; break;
   1515   case BuiltinType::UInt: Out << 'I'; break;
   1516   case BuiltinType::Long: Out << 'J'; break;
   1517   case BuiltinType::ULong: Out << 'K'; break;
   1518   case BuiltinType::Float: Out << 'M'; break;
   1519   case BuiltinType::Double: Out << 'N'; break;
   1520   // TODO: Determine size and mangle accordingly
   1521   case BuiltinType::LongDouble: Out << 'O'; break;
   1522   case BuiltinType::LongLong: Out << "_J"; break;
   1523   case BuiltinType::ULongLong: Out << "_K"; break;
   1524   case BuiltinType::Int128: Out << "_L"; break;
   1525   case BuiltinType::UInt128: Out << "_M"; break;
   1526   case BuiltinType::Bool: Out << "_N"; break;
   1527   case BuiltinType::Char16: Out << "_S"; break;
   1528   case BuiltinType::Char32: Out << "_U"; break;
   1529   case BuiltinType::WChar_S:
   1530   case BuiltinType::WChar_U: Out << "_W"; break;
   1531 
   1532 #define BUILTIN_TYPE(Id, SingletonId)
   1533 #define PLACEHOLDER_TYPE(Id, SingletonId) \
   1534   case BuiltinType::Id:
   1535 #include "clang/AST/BuiltinTypes.def"
   1536   case BuiltinType::Dependent:
   1537     llvm_unreachable("placeholder types shouldn't get to name mangling");
   1538 
   1539   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
   1540   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
   1541   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
   1542 
   1543   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
   1544   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
   1545   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
   1546   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
   1547   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
   1548   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
   1549   case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
   1550   case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
   1551 
   1552   case BuiltinType::NullPtr: Out << "$$T"; break;
   1553 
   1554   case BuiltinType::Half: {
   1555     DiagnosticsEngine &Diags = Context.getDiags();
   1556     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1557       "cannot mangle this built-in %0 type yet");
   1558     Diags.Report(Range.getBegin(), DiagID)
   1559       << T->getName(Context.getASTContext().getPrintingPolicy())
   1560       << Range;
   1561     break;
   1562   }
   1563   }
   1564 }
   1565 
   1566 // <type>          ::= <function-type>
   1567 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
   1568                                          SourceRange) {
   1569   // Structors only appear in decls, so at this point we know it's not a
   1570   // structor type.
   1571   // FIXME: This may not be lambda-friendly.
   1572   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
   1573     Out << "$$A8@@";
   1574     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
   1575   } else {
   1576     Out << "$$A6";
   1577     mangleFunctionType(T);
   1578   }
   1579 }
   1580 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
   1581                                          SourceRange) {
   1582   llvm_unreachable("Can't mangle K&R function prototypes");
   1583 }
   1584 
   1585 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
   1586                                                  const FunctionDecl *D,
   1587                                                  bool ForceThisQuals) {
   1588   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
   1589   //                     <return-type> <argument-list> <throw-spec>
   1590   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
   1591 
   1592   SourceRange Range;
   1593   if (D) Range = D->getSourceRange();
   1594 
   1595   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
   1596   CallingConv CC = T->getCallConv();
   1597   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
   1598     if (MD->isInstance())
   1599       HasThisQuals = true;
   1600     if (isa<CXXDestructorDecl>(MD)) {
   1601       IsStructor = true;
   1602     } else if (isa<CXXConstructorDecl>(MD)) {
   1603       IsStructor = true;
   1604       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
   1605                        StructorType == Ctor_DefaultClosure) &&
   1606                       getStructor(MD) == Structor;
   1607       if (IsCtorClosure)
   1608         CC = getASTContext().getDefaultCallingConvention(
   1609             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
   1610     }
   1611   }
   1612 
   1613   // If this is a C++ instance method, mangle the CVR qualifiers for the
   1614   // this pointer.
   1615   if (HasThisQuals) {
   1616     Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
   1617     manglePointerExtQualifiers(Quals, /*PointeeType=*/nullptr);
   1618     mangleRefQualifier(Proto->getRefQualifier());
   1619     mangleQualifiers(Quals, /*IsMember=*/false);
   1620   }
   1621 
   1622   mangleCallingConvention(CC);
   1623 
   1624   // <return-type> ::= <type>
   1625   //               ::= @ # structors (they have no declared return type)
   1626   if (IsStructor) {
   1627     if (isa<CXXDestructorDecl>(D) && D == Structor &&
   1628         StructorType == Dtor_Deleting) {
   1629       // The scalar deleting destructor takes an extra int argument.
   1630       // However, the FunctionType generated has 0 arguments.
   1631       // FIXME: This is a temporary hack.
   1632       // Maybe should fix the FunctionType creation instead?
   1633       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
   1634       return;
   1635     }
   1636     if (IsCtorClosure) {
   1637       // Default constructor closure and copy constructor closure both return
   1638       // void.
   1639       Out << 'X';
   1640 
   1641       if (StructorType == Ctor_DefaultClosure) {
   1642         // Default constructor closure always has no arguments.
   1643         Out << 'X';
   1644       } else if (StructorType == Ctor_CopyingClosure) {
   1645         // Copy constructor closure always takes an unqualified reference.
   1646         mangleArgumentType(getASTContext().getLValueReferenceType(
   1647                                Proto->getParamType(0)
   1648                                    ->getAs<LValueReferenceType>()
   1649                                    ->getPointeeType(),
   1650                                /*SpelledAsLValue=*/true),
   1651                            Range);
   1652         Out << '@';
   1653       } else {
   1654         llvm_unreachable("unexpected constructor closure!");
   1655       }
   1656       Out << 'Z';
   1657       return;
   1658     }
   1659     Out << '@';
   1660   } else {
   1661     QualType ResultType = Proto->getReturnType();
   1662     if (const auto *AT =
   1663             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
   1664       Out << '?';
   1665       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
   1666       Out << '?';
   1667       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
   1668       Out << '@';
   1669     } else {
   1670       if (ResultType->isVoidType())
   1671         ResultType = ResultType.getUnqualifiedType();
   1672       mangleType(ResultType, Range, QMM_Result);
   1673     }
   1674   }
   1675 
   1676   // <argument-list> ::= X # void
   1677   //                 ::= <type>+ @
   1678   //                 ::= <type>* Z # varargs
   1679   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
   1680     Out << 'X';
   1681   } else {
   1682     // Happens for function pointer type arguments for example.
   1683     for (const QualType &Arg : Proto->param_types())
   1684       mangleArgumentType(Arg, Range);
   1685     // <builtin-type>      ::= Z  # ellipsis
   1686     if (Proto->isVariadic())
   1687       Out << 'Z';
   1688     else
   1689       Out << '@';
   1690   }
   1691 
   1692   mangleThrowSpecification(Proto);
   1693 }
   1694 
   1695 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
   1696   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
   1697   //                                            # pointer. in 64-bit mode *all*
   1698   //                                            # 'this' pointers are 64-bit.
   1699   //                   ::= <global-function>
   1700   // <member-function> ::= A # private: near
   1701   //                   ::= B # private: far
   1702   //                   ::= C # private: static near
   1703   //                   ::= D # private: static far
   1704   //                   ::= E # private: virtual near
   1705   //                   ::= F # private: virtual far
   1706   //                   ::= I # protected: near
   1707   //                   ::= J # protected: far
   1708   //                   ::= K # protected: static near
   1709   //                   ::= L # protected: static far
   1710   //                   ::= M # protected: virtual near
   1711   //                   ::= N # protected: virtual far
   1712   //                   ::= Q # public: near
   1713   //                   ::= R # public: far
   1714   //                   ::= S # public: static near
   1715   //                   ::= T # public: static far
   1716   //                   ::= U # public: virtual near
   1717   //                   ::= V # public: virtual far
   1718   // <global-function> ::= Y # global near
   1719   //                   ::= Z # global far
   1720   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
   1721     switch (MD->getAccess()) {
   1722       case AS_none:
   1723         llvm_unreachable("Unsupported access specifier");
   1724       case AS_private:
   1725         if (MD->isStatic())
   1726           Out << 'C';
   1727         else if (MD->isVirtual())
   1728           Out << 'E';
   1729         else
   1730           Out << 'A';
   1731         break;
   1732       case AS_protected:
   1733         if (MD->isStatic())
   1734           Out << 'K';
   1735         else if (MD->isVirtual())
   1736           Out << 'M';
   1737         else
   1738           Out << 'I';
   1739         break;
   1740       case AS_public:
   1741         if (MD->isStatic())
   1742           Out << 'S';
   1743         else if (MD->isVirtual())
   1744           Out << 'U';
   1745         else
   1746           Out << 'Q';
   1747     }
   1748   } else
   1749     Out << 'Y';
   1750 }
   1751 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
   1752   // <calling-convention> ::= A # __cdecl
   1753   //                      ::= B # __export __cdecl
   1754   //                      ::= C # __pascal
   1755   //                      ::= D # __export __pascal
   1756   //                      ::= E # __thiscall
   1757   //                      ::= F # __export __thiscall
   1758   //                      ::= G # __stdcall
   1759   //                      ::= H # __export __stdcall
   1760   //                      ::= I # __fastcall
   1761   //                      ::= J # __export __fastcall
   1762   //                      ::= Q # __vectorcall
   1763   // The 'export' calling conventions are from a bygone era
   1764   // (*cough*Win16*cough*) when functions were declared for export with
   1765   // that keyword. (It didn't actually export them, it just made them so
   1766   // that they could be in a DLL and somebody from another module could call
   1767   // them.)
   1768 
   1769   switch (CC) {
   1770     default:
   1771       llvm_unreachable("Unsupported CC for mangling");
   1772     case CC_X86_64Win64:
   1773     case CC_X86_64SysV:
   1774     case CC_C: Out << 'A'; break;
   1775     case CC_X86Pascal: Out << 'C'; break;
   1776     case CC_X86ThisCall: Out << 'E'; break;
   1777     case CC_X86StdCall: Out << 'G'; break;
   1778     case CC_X86FastCall: Out << 'I'; break;
   1779     case CC_X86VectorCall: Out << 'Q'; break;
   1780   }
   1781 }
   1782 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
   1783   mangleCallingConvention(T->getCallConv());
   1784 }
   1785 void MicrosoftCXXNameMangler::mangleThrowSpecification(
   1786                                                 const FunctionProtoType *FT) {
   1787   // <throw-spec> ::= Z # throw(...) (default)
   1788   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
   1789   //              ::= <type>+
   1790   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
   1791   // all actually mangled as 'Z'. (They're ignored because their associated
   1792   // functionality isn't implemented, and probably never will be.)
   1793   Out << 'Z';
   1794 }
   1795 
   1796 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
   1797                                          SourceRange Range) {
   1798   // Probably should be mangled as a template instantiation; need to see what
   1799   // VC does first.
   1800   DiagnosticsEngine &Diags = Context.getDiags();
   1801   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1802     "cannot mangle this unresolved dependent type yet");
   1803   Diags.Report(Range.getBegin(), DiagID)
   1804     << Range;
   1805 }
   1806 
   1807 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
   1808 // <union-type>  ::= T <name>
   1809 // <struct-type> ::= U <name>
   1810 // <class-type>  ::= V <name>
   1811 // <enum-type>   ::= W4 <name>
   1812 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
   1813   mangleType(cast<TagType>(T)->getDecl());
   1814 }
   1815 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
   1816   mangleType(cast<TagType>(T)->getDecl());
   1817 }
   1818 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
   1819   switch (TD->getTagKind()) {
   1820     case TTK_Union:
   1821       Out << 'T';
   1822       break;
   1823     case TTK_Struct:
   1824     case TTK_Interface:
   1825       Out << 'U';
   1826       break;
   1827     case TTK_Class:
   1828       Out << 'V';
   1829       break;
   1830     case TTK_Enum:
   1831       Out << "W4";
   1832       break;
   1833   }
   1834   mangleName(TD);
   1835 }
   1836 
   1837 // <type>       ::= <array-type>
   1838 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
   1839 //                  [Y <dimension-count> <dimension>+]
   1840 //                  <element-type> # as global, E is never required
   1841 // It's supposed to be the other way around, but for some strange reason, it
   1842 // isn't. Today this behavior is retained for the sole purpose of backwards
   1843 // compatibility.
   1844 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
   1845   // This isn't a recursive mangling, so now we have to do it all in this
   1846   // one call.
   1847   manglePointerCVQualifiers(T->getElementType().getQualifiers());
   1848   mangleType(T->getElementType(), SourceRange());
   1849 }
   1850 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
   1851                                          SourceRange) {
   1852   llvm_unreachable("Should have been special cased");
   1853 }
   1854 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
   1855                                          SourceRange) {
   1856   llvm_unreachable("Should have been special cased");
   1857 }
   1858 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
   1859                                          SourceRange) {
   1860   llvm_unreachable("Should have been special cased");
   1861 }
   1862 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
   1863                                          SourceRange) {
   1864   llvm_unreachable("Should have been special cased");
   1865 }
   1866 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
   1867   QualType ElementTy(T, 0);
   1868   SmallVector<llvm::APInt, 3> Dimensions;
   1869   for (;;) {
   1870     if (const ConstantArrayType *CAT =
   1871             getASTContext().getAsConstantArrayType(ElementTy)) {
   1872       Dimensions.push_back(CAT->getSize());
   1873       ElementTy = CAT->getElementType();
   1874     } else if (ElementTy->isVariableArrayType()) {
   1875       const VariableArrayType *VAT =
   1876         getASTContext().getAsVariableArrayType(ElementTy);
   1877       DiagnosticsEngine &Diags = Context.getDiags();
   1878       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1879         "cannot mangle this variable-length array yet");
   1880       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
   1881         << VAT->getBracketsRange();
   1882       return;
   1883     } else if (ElementTy->isDependentSizedArrayType()) {
   1884       // The dependent expression has to be folded into a constant (TODO).
   1885       const DependentSizedArrayType *DSAT =
   1886         getASTContext().getAsDependentSizedArrayType(ElementTy);
   1887       DiagnosticsEngine &Diags = Context.getDiags();
   1888       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1889         "cannot mangle this dependent-length array yet");
   1890       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
   1891         << DSAT->getBracketsRange();
   1892       return;
   1893     } else if (const IncompleteArrayType *IAT =
   1894                    getASTContext().getAsIncompleteArrayType(ElementTy)) {
   1895       Dimensions.push_back(llvm::APInt(32, 0));
   1896       ElementTy = IAT->getElementType();
   1897     }
   1898     else break;
   1899   }
   1900   Out << 'Y';
   1901   // <dimension-count> ::= <number> # number of extra dimensions
   1902   mangleNumber(Dimensions.size());
   1903   for (const llvm::APInt &Dimension : Dimensions)
   1904     mangleNumber(Dimension.getLimitedValue());
   1905   mangleType(ElementTy, SourceRange(), QMM_Escape);
   1906 }
   1907 
   1908 // <type>                   ::= <pointer-to-member-type>
   1909 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
   1910 //                                                          <class name> <type>
   1911 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
   1912                                          SourceRange Range) {
   1913   QualType PointeeType = T->getPointeeType();
   1914   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
   1915     Out << '8';
   1916     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
   1917     mangleFunctionType(FPT, nullptr, true);
   1918   } else {
   1919     mangleQualifiers(PointeeType.getQualifiers(), true);
   1920     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
   1921     mangleType(PointeeType, Range, QMM_Drop);
   1922   }
   1923 }
   1924 
   1925 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
   1926                                          SourceRange Range) {
   1927   DiagnosticsEngine &Diags = Context.getDiags();
   1928   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1929     "cannot mangle this template type parameter type yet");
   1930   Diags.Report(Range.getBegin(), DiagID)
   1931     << Range;
   1932 }
   1933 
   1934 void MicrosoftCXXNameMangler::mangleType(
   1935                                        const SubstTemplateTypeParmPackType *T,
   1936                                        SourceRange Range) {
   1937   DiagnosticsEngine &Diags = Context.getDiags();
   1938   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1939     "cannot mangle this substituted parameter pack yet");
   1940   Diags.Report(Range.getBegin(), DiagID)
   1941     << Range;
   1942 }
   1943 
   1944 // <type> ::= <pointer-type>
   1945 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
   1946 //                       # the E is required for 64-bit non-static pointers
   1947 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
   1948                                          SourceRange Range) {
   1949   QualType PointeeTy = T->getPointeeType();
   1950   mangleType(PointeeTy, Range);
   1951 }
   1952 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
   1953                                          SourceRange Range) {
   1954   // Object pointers never have qualifiers.
   1955   Out << 'A';
   1956   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
   1957   mangleType(T->getPointeeType(), Range);
   1958 }
   1959 
   1960 // <type> ::= <reference-type>
   1961 // <reference-type> ::= A E? <cvr-qualifiers> <type>
   1962 //                 # the E is required for 64-bit non-static lvalue references
   1963 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
   1964                                          SourceRange Range) {
   1965   Out << 'A';
   1966   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
   1967   mangleType(T->getPointeeType(), Range);
   1968 }
   1969 
   1970 // <type> ::= <r-value-reference-type>
   1971 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
   1972 //                 # the E is required for 64-bit non-static rvalue references
   1973 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
   1974                                          SourceRange Range) {
   1975   Out << "$$Q";
   1976   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
   1977   mangleType(T->getPointeeType(), Range);
   1978 }
   1979 
   1980 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
   1981                                          SourceRange Range) {
   1982   DiagnosticsEngine &Diags = Context.getDiags();
   1983   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1984     "cannot mangle this complex number type yet");
   1985   Diags.Report(Range.getBegin(), DiagID)
   1986     << Range;
   1987 }
   1988 
   1989 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
   1990                                          SourceRange Range) {
   1991   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
   1992   assert(ET && "vectors with non-builtin elements are unsupported");
   1993   uint64_t Width = getASTContext().getTypeSize(T);
   1994   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
   1995   // doesn't match the Intel types uses a custom mangling below.
   1996   bool IntelVector = true;
   1997   if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
   1998     Out << "T__m64";
   1999   } else if (Width == 128 || Width == 256) {
   2000     if (ET->getKind() == BuiltinType::Float)
   2001       Out << "T__m" << Width;
   2002     else if (ET->getKind() == BuiltinType::LongLong)
   2003       Out << "T__m" << Width << 'i';
   2004     else if (ET->getKind() == BuiltinType::Double)
   2005       Out << "U__m" << Width << 'd';
   2006     else
   2007       IntelVector = false;
   2008   } else {
   2009     IntelVector = false;
   2010   }
   2011 
   2012   if (!IntelVector) {
   2013     // The MS ABI doesn't have a special mangling for vector types, so we define
   2014     // our own mangling to handle uses of __vector_size__ on user-specified
   2015     // types, and for extensions like __v4sf.
   2016     Out << "T__clang_vec" << T->getNumElements() << '_';
   2017     mangleType(ET, Range);
   2018   }
   2019 
   2020   Out << "@@";
   2021 }
   2022 
   2023 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
   2024                                          SourceRange Range) {
   2025   DiagnosticsEngine &Diags = Context.getDiags();
   2026   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2027     "cannot mangle this extended vector type yet");
   2028   Diags.Report(Range.getBegin(), DiagID)
   2029     << Range;
   2030 }
   2031 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
   2032                                          SourceRange Range) {
   2033   DiagnosticsEngine &Diags = Context.getDiags();
   2034   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2035     "cannot mangle this dependent-sized extended vector type yet");
   2036   Diags.Report(Range.getBegin(), DiagID)
   2037     << Range;
   2038 }
   2039 
   2040 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
   2041                                          SourceRange) {
   2042   // ObjC interfaces have structs underlying them.
   2043   Out << 'U';
   2044   mangleName(T->getDecl());
   2045 }
   2046 
   2047 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
   2048                                          SourceRange Range) {
   2049   // We don't allow overloading by different protocol qualification,
   2050   // so mangling them isn't necessary.
   2051   mangleType(T->getBaseType(), Range);
   2052 }
   2053 
   2054 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
   2055                                          SourceRange Range) {
   2056   Out << "_E";
   2057 
   2058   QualType pointee = T->getPointeeType();
   2059   mangleFunctionType(pointee->castAs<FunctionProtoType>());
   2060 }
   2061 
   2062 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
   2063                                          SourceRange) {
   2064   llvm_unreachable("Cannot mangle injected class name type.");
   2065 }
   2066 
   2067 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
   2068                                          SourceRange Range) {
   2069   DiagnosticsEngine &Diags = Context.getDiags();
   2070   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2071     "cannot mangle this template specialization type yet");
   2072   Diags.Report(Range.getBegin(), DiagID)
   2073     << Range;
   2074 }
   2075 
   2076 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
   2077                                          SourceRange Range) {
   2078   DiagnosticsEngine &Diags = Context.getDiags();
   2079   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2080     "cannot mangle this dependent name type yet");
   2081   Diags.Report(Range.getBegin(), DiagID)
   2082     << Range;
   2083 }
   2084 
   2085 void MicrosoftCXXNameMangler::mangleType(
   2086                                  const DependentTemplateSpecializationType *T,
   2087                                  SourceRange Range) {
   2088   DiagnosticsEngine &Diags = Context.getDiags();
   2089   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2090     "cannot mangle this dependent template specialization type yet");
   2091   Diags.Report(Range.getBegin(), DiagID)
   2092     << Range;
   2093 }
   2094 
   2095 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
   2096                                          SourceRange Range) {
   2097   DiagnosticsEngine &Diags = Context.getDiags();
   2098   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2099     "cannot mangle this pack expansion yet");
   2100   Diags.Report(Range.getBegin(), DiagID)
   2101     << Range;
   2102 }
   2103 
   2104 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
   2105                                          SourceRange Range) {
   2106   DiagnosticsEngine &Diags = Context.getDiags();
   2107   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2108     "cannot mangle this typeof(type) yet");
   2109   Diags.Report(Range.getBegin(), DiagID)
   2110     << Range;
   2111 }
   2112 
   2113 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
   2114                                          SourceRange Range) {
   2115   DiagnosticsEngine &Diags = Context.getDiags();
   2116   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2117     "cannot mangle this typeof(expression) yet");
   2118   Diags.Report(Range.getBegin(), DiagID)
   2119     << Range;
   2120 }
   2121 
   2122 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
   2123                                          SourceRange Range) {
   2124   DiagnosticsEngine &Diags = Context.getDiags();
   2125   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2126     "cannot mangle this decltype() yet");
   2127   Diags.Report(Range.getBegin(), DiagID)
   2128     << Range;
   2129 }
   2130 
   2131 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
   2132                                          SourceRange Range) {
   2133   DiagnosticsEngine &Diags = Context.getDiags();
   2134   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2135     "cannot mangle this unary transform type yet");
   2136   Diags.Report(Range.getBegin(), DiagID)
   2137     << Range;
   2138 }
   2139 
   2140 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
   2141   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
   2142 
   2143   DiagnosticsEngine &Diags = Context.getDiags();
   2144   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2145     "cannot mangle this 'auto' type yet");
   2146   Diags.Report(Range.getBegin(), DiagID)
   2147     << Range;
   2148 }
   2149 
   2150 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
   2151                                          SourceRange Range) {
   2152   DiagnosticsEngine &Diags = Context.getDiags();
   2153   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
   2154     "cannot mangle this C11 atomic type yet");
   2155   Diags.Report(Range.getBegin(), DiagID)
   2156     << Range;
   2157 }
   2158 
   2159 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
   2160                                                raw_ostream &Out) {
   2161   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
   2162          "Invalid mangleName() call, argument is not a variable or function!");
   2163   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
   2164          "Invalid mangleName() call on 'structor decl!");
   2165 
   2166   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
   2167                                  getASTContext().getSourceManager(),
   2168                                  "Mangling declaration");
   2169 
   2170   MicrosoftCXXNameMangler Mangler(*this, Out);
   2171   return Mangler.mangle(D);
   2172 }
   2173 
   2174 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
   2175 //                       <virtual-adjustment>
   2176 // <no-adjustment>      ::= A # private near
   2177 //                      ::= B # private far
   2178 //                      ::= I # protected near
   2179 //                      ::= J # protected far
   2180 //                      ::= Q # public near
   2181 //                      ::= R # public far
   2182 // <static-adjustment>  ::= G <static-offset> # private near
   2183 //                      ::= H <static-offset> # private far
   2184 //                      ::= O <static-offset> # protected near
   2185 //                      ::= P <static-offset> # protected far
   2186 //                      ::= W <static-offset> # public near
   2187 //                      ::= X <static-offset> # public far
   2188 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
   2189 //                      ::= $1 <virtual-shift> <static-offset> # private far
   2190 //                      ::= $2 <virtual-shift> <static-offset> # protected near
   2191 //                      ::= $3 <virtual-shift> <static-offset> # protected far
   2192 //                      ::= $4 <virtual-shift> <static-offset> # public near
   2193 //                      ::= $5 <virtual-shift> <static-offset> # public far
   2194 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
   2195 // <vtordisp-shift>     ::= <offset-to-vtordisp>
   2196 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
   2197 //                          <offset-to-vtordisp>
   2198 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
   2199                                       const ThisAdjustment &Adjustment,
   2200                                       MicrosoftCXXNameMangler &Mangler,
   2201                                       raw_ostream &Out) {
   2202   if (!Adjustment.Virtual.isEmpty()) {
   2203     Out << '$';
   2204     char AccessSpec;
   2205     switch (MD->getAccess()) {
   2206     case AS_none:
   2207       llvm_unreachable("Unsupported access specifier");
   2208     case AS_private:
   2209       AccessSpec = '0';
   2210       break;
   2211     case AS_protected:
   2212       AccessSpec = '2';
   2213       break;
   2214     case AS_public:
   2215       AccessSpec = '4';
   2216     }
   2217     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
   2218       Out << 'R' << AccessSpec;
   2219       Mangler.mangleNumber(
   2220           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
   2221       Mangler.mangleNumber(
   2222           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
   2223       Mangler.mangleNumber(
   2224           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
   2225       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
   2226     } else {
   2227       Out << AccessSpec;
   2228       Mangler.mangleNumber(
   2229           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
   2230       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
   2231     }
   2232   } else if (Adjustment.NonVirtual != 0) {
   2233     switch (MD->getAccess()) {
   2234     case AS_none:
   2235       llvm_unreachable("Unsupported access specifier");
   2236     case AS_private:
   2237       Out << 'G';
   2238       break;
   2239     case AS_protected:
   2240       Out << 'O';
   2241       break;
   2242     case AS_public:
   2243       Out << 'W';
   2244     }
   2245     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
   2246   } else {
   2247     switch (MD->getAccess()) {
   2248     case AS_none:
   2249       llvm_unreachable("Unsupported access specifier");
   2250     case AS_private:
   2251       Out << 'A';
   2252       break;
   2253     case AS_protected:
   2254       Out << 'I';
   2255       break;
   2256     case AS_public:
   2257       Out << 'Q';
   2258     }
   2259   }
   2260 }
   2261 
   2262 void
   2263 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
   2264                                                      raw_ostream &Out) {
   2265   MicrosoftVTableContext *VTContext =
   2266       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
   2267   const MicrosoftVTableContext::MethodVFTableLocation &ML =
   2268       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
   2269 
   2270   MicrosoftCXXNameMangler Mangler(*this, Out);
   2271   Mangler.getStream() << "\01?";
   2272   Mangler.mangleVirtualMemPtrThunk(MD, ML);
   2273 }
   2274 
   2275 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
   2276                                              const ThunkInfo &Thunk,
   2277                                              raw_ostream &Out) {
   2278   MicrosoftCXXNameMangler Mangler(*this, Out);
   2279   Out << "\01?";
   2280   Mangler.mangleName(MD);
   2281   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
   2282   if (!Thunk.Return.isEmpty())
   2283     assert(Thunk.Method != nullptr &&
   2284            "Thunk info should hold the overridee decl");
   2285 
   2286   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
   2287   Mangler.mangleFunctionType(
   2288       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
   2289 }
   2290 
   2291 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
   2292     const CXXDestructorDecl *DD, CXXDtorType Type,
   2293     const ThisAdjustment &Adjustment, raw_ostream &Out) {
   2294   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
   2295   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
   2296   // mangling manually until we support both deleting dtor types.
   2297   assert(Type == Dtor_Deleting);
   2298   MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
   2299   Out << "\01??_E";
   2300   Mangler.mangleName(DD->getParent());
   2301   mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
   2302   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
   2303 }
   2304 
   2305 void MicrosoftMangleContextImpl::mangleCXXVFTable(
   2306     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
   2307     raw_ostream &Out) {
   2308   // <mangled-name> ::= ?_7 <class-name> <storage-class>
   2309   //                    <cvr-qualifiers> [<name>] @
   2310   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
   2311   // is always '6' for vftables.
   2312   MicrosoftCXXNameMangler Mangler(*this, Out);
   2313   Mangler.getStream() << "\01??_7";
   2314   Mangler.mangleName(Derived);
   2315   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
   2316   for (const CXXRecordDecl *RD : BasePath)
   2317     Mangler.mangleName(RD);
   2318   Mangler.getStream() << '@';
   2319 }
   2320 
   2321 void MicrosoftMangleContextImpl::mangleCXXVBTable(
   2322     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
   2323     raw_ostream &Out) {
   2324   // <mangled-name> ::= ?_8 <class-name> <storage-class>
   2325   //                    <cvr-qualifiers> [<name>] @
   2326   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
   2327   // is always '7' for vbtables.
   2328   MicrosoftCXXNameMangler Mangler(*this, Out);
   2329   Mangler.getStream() << "\01??_8";
   2330   Mangler.mangleName(Derived);
   2331   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
   2332   for (const CXXRecordDecl *RD : BasePath)
   2333     Mangler.mangleName(RD);
   2334   Mangler.getStream() << '@';
   2335 }
   2336 
   2337 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
   2338   MicrosoftCXXNameMangler Mangler(*this, Out);
   2339   Mangler.getStream() << "\01??_R0";
   2340   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
   2341   Mangler.getStream() << "@8";
   2342 }
   2343 
   2344 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
   2345                                                    raw_ostream &Out) {
   2346   MicrosoftCXXNameMangler Mangler(*this, Out);
   2347   Mangler.getStream() << '.';
   2348   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
   2349 }
   2350 
   2351 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
   2352                                                            uint32_t Flags,
   2353                                                            raw_ostream &Out) {
   2354   MicrosoftCXXNameMangler Mangler(*this, Out);
   2355   Mangler.getStream() << "llvm.eh.handlertype.";
   2356   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
   2357   Mangler.getStream() << '.' << Flags;
   2358 }
   2359 
   2360 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
   2361                                                     bool IsConst,
   2362                                                     bool IsVolatile,
   2363                                                     uint32_t NumEntries,
   2364                                                     raw_ostream &Out) {
   2365   MicrosoftCXXNameMangler Mangler(*this, Out);
   2366   Mangler.getStream() << "_TI";
   2367   if (IsConst)
   2368     Mangler.getStream() << 'C';
   2369   if (IsVolatile)
   2370     Mangler.getStream() << 'V';
   2371   Mangler.getStream() << NumEntries;
   2372   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
   2373 }
   2374 
   2375 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
   2376     QualType T, uint32_t NumEntries, raw_ostream &Out) {
   2377   MicrosoftCXXNameMangler Mangler(*this, Out);
   2378   Mangler.getStream() << "_CTA";
   2379   Mangler.getStream() << NumEntries;
   2380   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
   2381 }
   2382 
   2383 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
   2384     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
   2385     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
   2386     raw_ostream &Out) {
   2387   MicrosoftCXXNameMangler Mangler(*this, Out);
   2388   Mangler.getStream() << "_CT";
   2389 
   2390   llvm::SmallString<64> RTTIMangling;
   2391   {
   2392     llvm::raw_svector_ostream Stream(RTTIMangling);
   2393     mangleCXXRTTI(T, Stream);
   2394   }
   2395   Mangler.getStream() << RTTIMangling.substr(1);
   2396 
   2397   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
   2398   // in fact, superfluous but I'm not sure the change was made consciously.
   2399   // TODO: Revisit this when VS2015 gets released.
   2400   llvm::SmallString<64> CopyCtorMangling;
   2401   if (CD) {
   2402     llvm::raw_svector_ostream Stream(CopyCtorMangling);
   2403     mangleCXXCtor(CD, CT, Stream);
   2404   }
   2405   Mangler.getStream() << CopyCtorMangling.substr(1);
   2406 
   2407   Mangler.getStream() << Size;
   2408   if (VBPtrOffset == -1) {
   2409     if (NVOffset) {
   2410       Mangler.getStream() << NVOffset;
   2411     }
   2412   } else {
   2413     Mangler.getStream() << NVOffset;
   2414     Mangler.getStream() << VBPtrOffset;
   2415     Mangler.getStream() << VBIndex;
   2416   }
   2417 }
   2418 
   2419 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
   2420     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
   2421     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
   2422   MicrosoftCXXNameMangler Mangler(*this, Out);
   2423   Mangler.getStream() << "\01??_R1";
   2424   Mangler.mangleNumber(NVOffset);
   2425   Mangler.mangleNumber(VBPtrOffset);
   2426   Mangler.mangleNumber(VBTableOffset);
   2427   Mangler.mangleNumber(Flags);
   2428   Mangler.mangleName(Derived);
   2429   Mangler.getStream() << "8";
   2430 }
   2431 
   2432 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
   2433     const CXXRecordDecl *Derived, raw_ostream &Out) {
   2434   MicrosoftCXXNameMangler Mangler(*this, Out);
   2435   Mangler.getStream() << "\01??_R2";
   2436   Mangler.mangleName(Derived);
   2437   Mangler.getStream() << "8";
   2438 }
   2439 
   2440 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
   2441     const CXXRecordDecl *Derived, raw_ostream &Out) {
   2442   MicrosoftCXXNameMangler Mangler(*this, Out);
   2443   Mangler.getStream() << "\01??_R3";
   2444   Mangler.mangleName(Derived);
   2445   Mangler.getStream() << "8";
   2446 }
   2447 
   2448 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
   2449     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
   2450     raw_ostream &Out) {
   2451   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
   2452   //                    <cvr-qualifiers> [<name>] @
   2453   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
   2454   // is always '6' for vftables.
   2455   MicrosoftCXXNameMangler Mangler(*this, Out);
   2456   Mangler.getStream() << "\01??_R4";
   2457   Mangler.mangleName(Derived);
   2458   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
   2459   for (const CXXRecordDecl *RD : BasePath)
   2460     Mangler.mangleName(RD);
   2461   Mangler.getStream() << '@';
   2462 }
   2463 
   2464 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
   2465     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
   2466   MicrosoftCXXNameMangler Mangler(*this, Out);
   2467   // The function body is in the same comdat as the function with the handler,
   2468   // so the numbering here doesn't have to be the same across TUs.
   2469   //
   2470   // <mangled-name> ::= ?filt$ <filter-number> @0
   2471   Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
   2472   Mangler.mangleName(EnclosingDecl);
   2473 }
   2474 
   2475 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
   2476     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
   2477   MicrosoftCXXNameMangler Mangler(*this, Out);
   2478   // The function body is in the same comdat as the function with the handler,
   2479   // so the numbering here doesn't have to be the same across TUs.
   2480   //
   2481   // <mangled-name> ::= ?fin$ <filter-number> @0
   2482   Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
   2483   Mangler.mangleName(EnclosingDecl);
   2484 }
   2485 
   2486 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
   2487   // This is just a made up unique string for the purposes of tbaa.  undname
   2488   // does *not* know how to demangle it.
   2489   MicrosoftCXXNameMangler Mangler(*this, Out);
   2490   Mangler.getStream() << '?';
   2491   Mangler.mangleType(T, SourceRange());
   2492 }
   2493 
   2494 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
   2495                                                CXXCtorType Type,
   2496                                                raw_ostream &Out) {
   2497   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
   2498   mangler.mangle(D);
   2499 }
   2500 
   2501 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
   2502                                                CXXDtorType Type,
   2503                                                raw_ostream &Out) {
   2504   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
   2505   mangler.mangle(D);
   2506 }
   2507 
   2508 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
   2509                                                           unsigned,
   2510                                                           raw_ostream &) {
   2511   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
   2512     "cannot mangle this reference temporary yet");
   2513   getDiags().Report(VD->getLocation(), DiagID);
   2514 }
   2515 
   2516 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
   2517                                                            raw_ostream &Out) {
   2518   // TODO: This is not correct, especially with respect to VS "14".  VS "14"
   2519   // utilizes thread local variables to implement thread safe, re-entrant
   2520   // initialization for statics.  They no longer differentiate between an
   2521   // externally visible and non-externally visible static with respect to
   2522   // mangling, they all get $TSS <number>.
   2523   //
   2524   // N.B. This means that they can get more than 32 static variable guards in a
   2525   // scope.  It also means that they broke compatibility with their own ABI.
   2526 
   2527   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
   2528   //              ::= ?$S <guard-num> @ <postfix> @4IA
   2529 
   2530   // The first mangling is what MSVC uses to guard static locals in inline
   2531   // functions.  It uses a different mangling in external functions to support
   2532   // guarding more than 32 variables.  MSVC rejects inline functions with more
   2533   // than 32 static locals.  We don't fully implement the second mangling
   2534   // because those guards are not externally visible, and instead use LLVM's
   2535   // default renaming when creating a new guard variable.
   2536   MicrosoftCXXNameMangler Mangler(*this, Out);
   2537 
   2538   bool Visible = VD->isExternallyVisible();
   2539   // <operator-name> ::= ?_B # local static guard
   2540   Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
   2541   unsigned ScopeDepth = 0;
   2542   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
   2543     // If we do not have a discriminator and are emitting a guard variable for
   2544     // use at global scope, then mangling the nested name will not be enough to
   2545     // remove ambiguities.
   2546     Mangler.mangle(VD, "");
   2547   else
   2548     Mangler.mangleNestedName(VD);
   2549   Mangler.getStream() << (Visible ? "@5" : "@4IA");
   2550   if (ScopeDepth)
   2551     Mangler.mangleNumber(ScopeDepth);
   2552 }
   2553 
   2554 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
   2555                                                     raw_ostream &Out,
   2556                                                     char CharCode) {
   2557   MicrosoftCXXNameMangler Mangler(*this, Out);
   2558   Mangler.getStream() << "\01??__" << CharCode;
   2559   Mangler.mangleName(D);
   2560   if (D->isStaticDataMember()) {
   2561     Mangler.mangleVariableEncoding(D);
   2562     Mangler.getStream() << '@';
   2563   }
   2564   // This is the function class mangling.  These stubs are global, non-variadic,
   2565   // cdecl functions that return void and take no args.
   2566   Mangler.getStream() << "YAXXZ";
   2567 }
   2568 
   2569 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
   2570                                                           raw_ostream &Out) {
   2571   // <initializer-name> ::= ?__E <name> YAXXZ
   2572   mangleInitFiniStub(D, Out, 'E');
   2573 }
   2574 
   2575 void
   2576 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
   2577                                                           raw_ostream &Out) {
   2578   // <destructor-name> ::= ?__F <name> YAXXZ
   2579   mangleInitFiniStub(D, Out, 'F');
   2580 }
   2581 
   2582 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
   2583                                                      raw_ostream &Out) {
   2584   // <char-type> ::= 0   # char
   2585   //             ::= 1   # wchar_t
   2586   //             ::= ??? # char16_t/char32_t will need a mangling too...
   2587   //
   2588   // <literal-length> ::= <non-negative integer>  # the length of the literal
   2589   //
   2590   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
   2591   //                                              # null-terminator
   2592   //
   2593   // <encoded-string> ::= <simple character>           # uninteresting character
   2594   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
   2595   //                                                   # encode the byte for the
   2596   //                                                   # character
   2597   //                  ::= '?' [a-z]                    # \xe1 - \xfa
   2598   //                  ::= '?' [A-Z]                    # \xc1 - \xda
   2599   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
   2600   //
   2601   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
   2602   //               <encoded-string> '@'
   2603   MicrosoftCXXNameMangler Mangler(*this, Out);
   2604   Mangler.getStream() << "\01??_C@_";
   2605 
   2606   // <char-type>: The "kind" of string literal is encoded into the mangled name.
   2607   if (SL->isWide())
   2608     Mangler.getStream() << '1';
   2609   else
   2610     Mangler.getStream() << '0';
   2611 
   2612   // <literal-length>: The next part of the mangled name consists of the length
   2613   // of the string.
   2614   // The StringLiteral does not consider the NUL terminator byte(s) but the
   2615   // mangling does.
   2616   // N.B. The length is in terms of bytes, not characters.
   2617   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
   2618 
   2619   // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
   2620   // properties of our CRC:
   2621   //   Width  : 32
   2622   //   Poly   : 04C11DB7
   2623   //   Init   : FFFFFFFF
   2624   //   RefIn  : True
   2625   //   RefOut : True
   2626   //   XorOut : 00000000
   2627   //   Check  : 340BC6D9
   2628   uint32_t CRC = 0xFFFFFFFFU;
   2629 
   2630   auto UpdateCRC = [&CRC](char Byte) {
   2631     for (unsigned i = 0; i < 8; ++i) {
   2632       bool Bit = CRC & 0x80000000U;
   2633       if (Byte & (1U << i))
   2634         Bit = !Bit;
   2635       CRC <<= 1;
   2636       if (Bit)
   2637         CRC ^= 0x04C11DB7U;
   2638     }
   2639   };
   2640 
   2641   auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
   2642     unsigned CharByteWidth = SL->getCharByteWidth();
   2643     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
   2644     unsigned OffsetInCodeUnit = Index % CharByteWidth;
   2645     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
   2646   };
   2647 
   2648   auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
   2649     unsigned CharByteWidth = SL->getCharByteWidth();
   2650     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
   2651     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
   2652     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
   2653   };
   2654 
   2655   // CRC all the bytes of the StringLiteral.
   2656   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
   2657     UpdateCRC(GetLittleEndianByte(I));
   2658 
   2659   // The NUL terminator byte(s) were not present earlier,
   2660   // we need to manually process those bytes into the CRC.
   2661   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
   2662        ++NullTerminator)
   2663     UpdateCRC('\x00');
   2664 
   2665   // The literature refers to the process of reversing the bits in the final CRC
   2666   // output as "reflection".
   2667   CRC = llvm::reverseBits(CRC);
   2668 
   2669   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
   2670   // scheme.
   2671   Mangler.mangleNumber(CRC);
   2672 
   2673   // <encoded-string>: The mangled name also contains the first 32 _characters_
   2674   // (including null-terminator bytes) of the StringLiteral.
   2675   // Each character is encoded by splitting them into bytes and then encoding
   2676   // the constituent bytes.
   2677   auto MangleByte = [&Mangler](char Byte) {
   2678     // There are five different manglings for characters:
   2679     // - [a-zA-Z0-9_$]: A one-to-one mapping.
   2680     // - ?[a-z]: The range from \xe1 to \xfa.
   2681     // - ?[A-Z]: The range from \xc1 to \xda.
   2682     // - ?[0-9]: The set of [,/\:. \n\t'-].
   2683     // - ?$XX: A fallback which maps nibbles.
   2684     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
   2685       Mangler.getStream() << Byte;
   2686     } else if (isLetter(Byte & 0x7f)) {
   2687       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
   2688     } else {
   2689       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
   2690                                    ' ', '\n', '\t', '\'', '-'};
   2691       const char *Pos =
   2692           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
   2693       if (Pos != std::end(SpecialChars)) {
   2694         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
   2695       } else {
   2696         Mangler.getStream() << "?$";
   2697         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
   2698         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
   2699       }
   2700     }
   2701   };
   2702 
   2703   // Enforce our 32 character max.
   2704   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
   2705   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
   2706        ++I)
   2707     if (SL->isWide())
   2708       MangleByte(GetBigEndianByte(I));
   2709     else
   2710       MangleByte(GetLittleEndianByte(I));
   2711 
   2712   // Encode the NUL terminator if there is room.
   2713   if (NumCharsToMangle < 32)
   2714     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
   2715          ++NullTerminator)
   2716       MangleByte(0);
   2717 
   2718   Mangler.getStream() << '@';
   2719 }
   2720 
   2721 void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
   2722                                                        raw_ostream &Out) {
   2723   llvm::report_fatal_error("Cannot mangle bitsets yet");
   2724 }
   2725 
   2726 MicrosoftMangleContext *
   2727 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
   2728   return new MicrosoftMangleContextImpl(Context, Diags);
   2729 }
   2730