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