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