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