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