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->getRedeclContext();
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   if (Quals.hasUnaligned() ||
1451       (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1452     Out << 'F';
1453 }
1454 
1455 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1456   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1457   //                         ::= Q  # const
1458   //                         ::= R  # volatile
1459   //                         ::= S  # const volatile
1460   bool HasConst = Quals.hasConst(),
1461        HasVolatile = Quals.hasVolatile();
1462 
1463   if (HasConst && HasVolatile) {
1464     Out << 'S';
1465   } else if (HasVolatile) {
1466     Out << 'R';
1467   } else if (HasConst) {
1468     Out << 'Q';
1469   } else {
1470     Out << 'P';
1471   }
1472 }
1473 
1474 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1475                                                  SourceRange Range) {
1476   // MSVC will backreference two canonically equivalent types that have slightly
1477   // different manglings when mangled alone.
1478 
1479   // Decayed types do not match up with non-decayed versions of the same type.
1480   //
1481   // e.g.
1482   // void (*x)(void) will not form a backreference with void x(void)
1483   void *TypePtr;
1484   if (const auto *DT = T->getAs<DecayedType>()) {
1485     QualType OriginalType = DT->getOriginalType();
1486     // All decayed ArrayTypes should be treated identically; as-if they were
1487     // a decayed IncompleteArrayType.
1488     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1489       OriginalType = getASTContext().getIncompleteArrayType(
1490           AT->getElementType(), AT->getSizeModifier(),
1491           AT->getIndexTypeCVRQualifiers());
1492 
1493     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1494     // If the original parameter was textually written as an array,
1495     // instead treat the decayed parameter like it's const.
1496     //
1497     // e.g.
1498     // int [] -> int * const
1499     if (OriginalType->isArrayType())
1500       T = T.withConst();
1501   } else {
1502     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1503   }
1504 
1505   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1506 
1507   if (Found == TypeBackReferences.end()) {
1508     size_t OutSizeBefore = Out.tell();
1509 
1510     mangleType(T, Range, QMM_Drop);
1511 
1512     // See if it's worth creating a back reference.
1513     // Only types longer than 1 character are considered
1514     // and only 10 back references slots are available:
1515     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1516     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1517       size_t Size = TypeBackReferences.size();
1518       TypeBackReferences[TypePtr] = Size;
1519     }
1520   } else {
1521     Out << Found->second;
1522   }
1523 }
1524 
1525 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1526     const PassObjectSizeAttr *POSA) {
1527   int Type = POSA->getType();
1528 
1529   auto Iter = PassObjectSizeArgs.insert(Type).first;
1530   auto *TypePtr = (const void *)&*Iter;
1531   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1532 
1533   if (Found == TypeBackReferences.end()) {
1534     mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1535                            {"__clang"});
1536 
1537     if (TypeBackReferences.size() < 10) {
1538       size_t Size = TypeBackReferences.size();
1539       TypeBackReferences[TypePtr] = Size;
1540     }
1541   } else {
1542     Out << Found->second;
1543   }
1544 }
1545 
1546 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1547                                          QualifierMangleMode QMM) {
1548   // Don't use the canonical types.  MSVC includes things like 'const' on
1549   // pointer arguments to function pointers that canonicalization strips away.
1550   T = T.getDesugaredType(getASTContext());
1551   Qualifiers Quals = T.getLocalQualifiers();
1552   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1553     // If there were any Quals, getAsArrayType() pushed them onto the array
1554     // element type.
1555     if (QMM == QMM_Mangle)
1556       Out << 'A';
1557     else if (QMM == QMM_Escape || QMM == QMM_Result)
1558       Out << "$$B";
1559     mangleArrayType(AT);
1560     return;
1561   }
1562 
1563   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1564                    T->isReferenceType() || T->isBlockPointerType();
1565 
1566   switch (QMM) {
1567   case QMM_Drop:
1568     break;
1569   case QMM_Mangle:
1570     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1571       Out << '6';
1572       mangleFunctionType(FT);
1573       return;
1574     }
1575     mangleQualifiers(Quals, false);
1576     break;
1577   case QMM_Escape:
1578     if (!IsPointer && Quals) {
1579       Out << "$$C";
1580       mangleQualifiers(Quals, false);
1581     }
1582     break;
1583   case QMM_Result:
1584     // Presence of __unaligned qualifier shouldn't affect mangling here.
1585     Quals.removeUnaligned();
1586     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1587       Out << '?';
1588       mangleQualifiers(Quals, false);
1589     }
1590     break;
1591   }
1592 
1593   const Type *ty = T.getTypePtr();
1594 
1595   switch (ty->getTypeClass()) {
1596 #define ABSTRACT_TYPE(CLASS, PARENT)
1597 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1598   case Type::CLASS: \
1599     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1600     return;
1601 #define TYPE(CLASS, PARENT) \
1602   case Type::CLASS: \
1603     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1604     break;
1605 #include "clang/AST/TypeNodes.def"
1606 #undef ABSTRACT_TYPE
1607 #undef NON_CANONICAL_TYPE
1608 #undef TYPE
1609   }
1610 }
1611 
1612 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1613                                          SourceRange Range) {
1614   //  <type>         ::= <builtin-type>
1615   //  <builtin-type> ::= X  # void
1616   //                 ::= C  # signed char
1617   //                 ::= D  # char
1618   //                 ::= E  # unsigned char
1619   //                 ::= F  # short
1620   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1621   //                 ::= H  # int
1622   //                 ::= I  # unsigned int
1623   //                 ::= J  # long
1624   //                 ::= K  # unsigned long
1625   //                     L  # <none>
1626   //                 ::= M  # float
1627   //                 ::= N  # double
1628   //                 ::= O  # long double (__float80 is mangled differently)
1629   //                 ::= _J # long long, __int64
1630   //                 ::= _K # unsigned long long, __int64
1631   //                 ::= _L # __int128
1632   //                 ::= _M # unsigned __int128
1633   //                 ::= _N # bool
1634   //                     _O # <array in parameter>
1635   //                 ::= _T # __float80 (Intel)
1636   //                 ::= _W # wchar_t
1637   //                 ::= _Z # __float80 (Digital Mars)
1638   switch (T->getKind()) {
1639   case BuiltinType::Void:
1640     Out << 'X';
1641     break;
1642   case BuiltinType::SChar:
1643     Out << 'C';
1644     break;
1645   case BuiltinType::Char_U:
1646   case BuiltinType::Char_S:
1647     Out << 'D';
1648     break;
1649   case BuiltinType::UChar:
1650     Out << 'E';
1651     break;
1652   case BuiltinType::Short:
1653     Out << 'F';
1654     break;
1655   case BuiltinType::UShort:
1656     Out << 'G';
1657     break;
1658   case BuiltinType::Int:
1659     Out << 'H';
1660     break;
1661   case BuiltinType::UInt:
1662     Out << 'I';
1663     break;
1664   case BuiltinType::Long:
1665     Out << 'J';
1666     break;
1667   case BuiltinType::ULong:
1668     Out << 'K';
1669     break;
1670   case BuiltinType::Float:
1671     Out << 'M';
1672     break;
1673   case BuiltinType::Double:
1674     Out << 'N';
1675     break;
1676   // TODO: Determine size and mangle accordingly
1677   case BuiltinType::LongDouble:
1678     Out << 'O';
1679     break;
1680   case BuiltinType::LongLong:
1681     Out << "_J";
1682     break;
1683   case BuiltinType::ULongLong:
1684     Out << "_K";
1685     break;
1686   case BuiltinType::Int128:
1687     Out << "_L";
1688     break;
1689   case BuiltinType::UInt128:
1690     Out << "_M";
1691     break;
1692   case BuiltinType::Bool:
1693     Out << "_N";
1694     break;
1695   case BuiltinType::Char16:
1696     Out << "_S";
1697     break;
1698   case BuiltinType::Char32:
1699     Out << "_U";
1700     break;
1701   case BuiltinType::WChar_S:
1702   case BuiltinType::WChar_U:
1703     Out << "_W";
1704     break;
1705 
1706 #define BUILTIN_TYPE(Id, SingletonId)
1707 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1708   case BuiltinType::Id:
1709 #include "clang/AST/BuiltinTypes.def"
1710   case BuiltinType::Dependent:
1711     llvm_unreachable("placeholder types shouldn't get to name mangling");
1712 
1713   case BuiltinType::ObjCId:
1714     Out << "PA";
1715     mangleArtificalTagType(TTK_Struct, "objc_object");
1716     break;
1717   case BuiltinType::ObjCClass:
1718     Out << "PA";
1719     mangleArtificalTagType(TTK_Struct, "objc_class");
1720     break;
1721   case BuiltinType::ObjCSel:
1722     Out << "PA";
1723     mangleArtificalTagType(TTK_Struct, "objc_selector");
1724     break;
1725 
1726 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1727   case BuiltinType::Id: \
1728     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
1729     break;
1730 #include "clang/Basic/OpenCLImageTypes.def"
1731   case BuiltinType::OCLSampler:
1732     Out << "PA";
1733     mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1734     break;
1735   case BuiltinType::OCLEvent:
1736     Out << "PA";
1737     mangleArtificalTagType(TTK_Struct, "ocl_event");
1738     break;
1739   case BuiltinType::OCLClkEvent:
1740     Out << "PA";
1741     mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1742     break;
1743   case BuiltinType::OCLQueue:
1744     Out << "PA";
1745     mangleArtificalTagType(TTK_Struct, "ocl_queue");
1746     break;
1747   case BuiltinType::OCLNDRange:
1748     Out << "PA";
1749     mangleArtificalTagType(TTK_Struct, "ocl_ndrange");
1750     break;
1751   case BuiltinType::OCLReserveID:
1752     Out << "PA";
1753     mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1754     break;
1755 
1756   case BuiltinType::NullPtr:
1757     Out << "$$T";
1758     break;
1759 
1760   case BuiltinType::Float128:
1761   case BuiltinType::Half: {
1762     DiagnosticsEngine &Diags = Context.getDiags();
1763     unsigned DiagID = Diags.getCustomDiagID(
1764         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1765     Diags.Report(Range.getBegin(), DiagID)
1766         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1767     break;
1768   }
1769   }
1770 }
1771 
1772 // <type>          ::= <function-type>
1773 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1774                                          SourceRange) {
1775   // Structors only appear in decls, so at this point we know it's not a
1776   // structor type.
1777   // FIXME: This may not be lambda-friendly.
1778   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1779     Out << "$$A8@@";
1780     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1781   } else {
1782     Out << "$$A6";
1783     mangleFunctionType(T);
1784   }
1785 }
1786 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1787                                          Qualifiers, SourceRange) {
1788   Out << "$$A6";
1789   mangleFunctionType(T);
1790 }
1791 
1792 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1793                                                  const FunctionDecl *D,
1794                                                  bool ForceThisQuals) {
1795   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1796   //                     <return-type> <argument-list> <throw-spec>
1797   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1798 
1799   SourceRange Range;
1800   if (D) Range = D->getSourceRange();
1801 
1802   bool IsInLambda = false;
1803   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1804   CallingConv CC = T->getCallConv();
1805   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1806     if (MD->getParent()->isLambda())
1807       IsInLambda = true;
1808     if (MD->isInstance())
1809       HasThisQuals = true;
1810     if (isa<CXXDestructorDecl>(MD)) {
1811       IsStructor = true;
1812     } else if (isa<CXXConstructorDecl>(MD)) {
1813       IsStructor = true;
1814       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1815                        StructorType == Ctor_DefaultClosure) &&
1816                       getStructor(MD) == Structor;
1817       if (IsCtorClosure)
1818         CC = getASTContext().getDefaultCallingConvention(
1819             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1820     }
1821   }
1822 
1823   // If this is a C++ instance method, mangle the CVR qualifiers for the
1824   // this pointer.
1825   if (HasThisQuals) {
1826     Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals());
1827     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1828     mangleRefQualifier(Proto->getRefQualifier());
1829     mangleQualifiers(Quals, /*IsMember=*/false);
1830   }
1831 
1832   mangleCallingConvention(CC);
1833 
1834   // <return-type> ::= <type>
1835   //               ::= @ # structors (they have no declared return type)
1836   if (IsStructor) {
1837     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1838         StructorType == Dtor_Deleting) {
1839       // The scalar deleting destructor takes an extra int argument.
1840       // However, the FunctionType generated has 0 arguments.
1841       // FIXME: This is a temporary hack.
1842       // Maybe should fix the FunctionType creation instead?
1843       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1844       return;
1845     }
1846     if (IsCtorClosure) {
1847       // Default constructor closure and copy constructor closure both return
1848       // void.
1849       Out << 'X';
1850 
1851       if (StructorType == Ctor_DefaultClosure) {
1852         // Default constructor closure always has no arguments.
1853         Out << 'X';
1854       } else if (StructorType == Ctor_CopyingClosure) {
1855         // Copy constructor closure always takes an unqualified reference.
1856         mangleArgumentType(getASTContext().getLValueReferenceType(
1857                                Proto->getParamType(0)
1858                                    ->getAs<LValueReferenceType>()
1859                                    ->getPointeeType(),
1860                                /*SpelledAsLValue=*/true),
1861                            Range);
1862         Out << '@';
1863       } else {
1864         llvm_unreachable("unexpected constructor closure!");
1865       }
1866       Out << 'Z';
1867       return;
1868     }
1869     Out << '@';
1870   } else {
1871     QualType ResultType = T->getReturnType();
1872     if (const auto *AT =
1873             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1874       Out << '?';
1875       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1876       Out << '?';
1877       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
1878              "shouldn't need to mangle __auto_type!");
1879       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1880       Out << '@';
1881     } else if (IsInLambda) {
1882       Out << '@';
1883     } else {
1884       if (ResultType->isVoidType())
1885         ResultType = ResultType.getUnqualifiedType();
1886       mangleType(ResultType, Range, QMM_Result);
1887     }
1888   }
1889 
1890   // <argument-list> ::= X # void
1891   //                 ::= <type>+ @
1892   //                 ::= <type>* Z # varargs
1893   if (!Proto) {
1894     // Function types without prototypes can arise when mangling a function type
1895     // within an overloadable function in C. We mangle these as the absence of
1896     // any parameter types (not even an empty parameter list).
1897     Out << '@';
1898   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1899     Out << 'X';
1900   } else {
1901     // Happens for function pointer type arguments for example.
1902     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
1903       mangleArgumentType(Proto->getParamType(I), Range);
1904       // Mangle each pass_object_size parameter as if it's a paramater of enum
1905       // type passed directly after the parameter with the pass_object_size
1906       // attribute. The aforementioned enum's name is __pass_object_size, and we
1907       // pretend it resides in a top-level namespace called __clang.
1908       //
1909       // FIXME: Is there a defined extension notation for the MS ABI, or is it
1910       // necessary to just cross our fingers and hope this type+namespace
1911       // combination doesn't conflict with anything?
1912       if (D)
1913         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
1914           manglePassObjectSizeArg(P);
1915     }
1916     // <builtin-type>      ::= Z  # ellipsis
1917     if (Proto->isVariadic())
1918       Out << 'Z';
1919     else
1920       Out << '@';
1921   }
1922 
1923   mangleThrowSpecification(Proto);
1924 }
1925 
1926 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1927   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1928   //                                            # pointer. in 64-bit mode *all*
1929   //                                            # 'this' pointers are 64-bit.
1930   //                   ::= <global-function>
1931   // <member-function> ::= A # private: near
1932   //                   ::= B # private: far
1933   //                   ::= C # private: static near
1934   //                   ::= D # private: static far
1935   //                   ::= E # private: virtual near
1936   //                   ::= F # private: virtual far
1937   //                   ::= I # protected: near
1938   //                   ::= J # protected: far
1939   //                   ::= K # protected: static near
1940   //                   ::= L # protected: static far
1941   //                   ::= M # protected: virtual near
1942   //                   ::= N # protected: virtual far
1943   //                   ::= Q # public: near
1944   //                   ::= R # public: far
1945   //                   ::= S # public: static near
1946   //                   ::= T # public: static far
1947   //                   ::= U # public: virtual near
1948   //                   ::= V # public: virtual far
1949   // <global-function> ::= Y # global near
1950   //                   ::= Z # global far
1951   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1952     switch (MD->getAccess()) {
1953       case AS_none:
1954         llvm_unreachable("Unsupported access specifier");
1955       case AS_private:
1956         if (MD->isStatic())
1957           Out << 'C';
1958         else if (MD->isVirtual())
1959           Out << 'E';
1960         else
1961           Out << 'A';
1962         break;
1963       case AS_protected:
1964         if (MD->isStatic())
1965           Out << 'K';
1966         else if (MD->isVirtual())
1967           Out << 'M';
1968         else
1969           Out << 'I';
1970         break;
1971       case AS_public:
1972         if (MD->isStatic())
1973           Out << 'S';
1974         else if (MD->isVirtual())
1975           Out << 'U';
1976         else
1977           Out << 'Q';
1978     }
1979   } else {
1980     Out << 'Y';
1981   }
1982 }
1983 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1984   // <calling-convention> ::= A # __cdecl
1985   //                      ::= B # __export __cdecl
1986   //                      ::= C # __pascal
1987   //                      ::= D # __export __pascal
1988   //                      ::= E # __thiscall
1989   //                      ::= F # __export __thiscall
1990   //                      ::= G # __stdcall
1991   //                      ::= H # __export __stdcall
1992   //                      ::= I # __fastcall
1993   //                      ::= J # __export __fastcall
1994   //                      ::= Q # __vectorcall
1995   // The 'export' calling conventions are from a bygone era
1996   // (*cough*Win16*cough*) when functions were declared for export with
1997   // that keyword. (It didn't actually export them, it just made them so
1998   // that they could be in a DLL and somebody from another module could call
1999   // them.)
2000 
2001   switch (CC) {
2002     default:
2003       llvm_unreachable("Unsupported CC for mangling");
2004     case CC_X86_64Win64:
2005     case CC_X86_64SysV:
2006     case CC_C: Out << 'A'; break;
2007     case CC_X86Pascal: Out << 'C'; break;
2008     case CC_X86ThisCall: Out << 'E'; break;
2009     case CC_X86StdCall: Out << 'G'; break;
2010     case CC_X86FastCall: Out << 'I'; break;
2011     case CC_X86VectorCall: Out << 'Q'; break;
2012   }
2013 }
2014 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2015   mangleCallingConvention(T->getCallConv());
2016 }
2017 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2018                                                 const FunctionProtoType *FT) {
2019   // <throw-spec> ::= Z # throw(...) (default)
2020   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
2021   //              ::= <type>+
2022   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2023   // all actually mangled as 'Z'. (They're ignored because their associated
2024   // functionality isn't implemented, and probably never will be.)
2025   Out << 'Z';
2026 }
2027 
2028 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2029                                          Qualifiers, SourceRange Range) {
2030   // Probably should be mangled as a template instantiation; need to see what
2031   // VC does first.
2032   DiagnosticsEngine &Diags = Context.getDiags();
2033   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2034     "cannot mangle this unresolved dependent type yet");
2035   Diags.Report(Range.getBegin(), DiagID)
2036     << Range;
2037 }
2038 
2039 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2040 // <union-type>  ::= T <name>
2041 // <struct-type> ::= U <name>
2042 // <class-type>  ::= V <name>
2043 // <enum-type>   ::= W4 <name>
2044 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2045   switch (TTK) {
2046     case TTK_Union:
2047       Out << 'T';
2048       break;
2049     case TTK_Struct:
2050     case TTK_Interface:
2051       Out << 'U';
2052       break;
2053     case TTK_Class:
2054       Out << 'V';
2055       break;
2056     case TTK_Enum:
2057       Out << "W4";
2058       break;
2059   }
2060 }
2061 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2062                                          SourceRange) {
2063   mangleType(cast<TagType>(T)->getDecl());
2064 }
2065 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2066                                          SourceRange) {
2067   mangleType(cast<TagType>(T)->getDecl());
2068 }
2069 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2070   mangleTagTypeKind(TD->getTagKind());
2071   mangleName(TD);
2072 }
2073 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2074     TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) {
2075   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2076   mangleTagTypeKind(TK);
2077 
2078   // Always start with the unqualified name.
2079   mangleSourceName(UnqualifiedName);
2080 
2081   for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2082     mangleSourceName(*I);
2083 
2084   // Terminate the whole name with an '@'.
2085   Out << '@';
2086 }
2087 
2088 // <type>       ::= <array-type>
2089 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2090 //                  [Y <dimension-count> <dimension>+]
2091 //                  <element-type> # as global, E is never required
2092 // It's supposed to be the other way around, but for some strange reason, it
2093 // isn't. Today this behavior is retained for the sole purpose of backwards
2094 // compatibility.
2095 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2096   // This isn't a recursive mangling, so now we have to do it all in this
2097   // one call.
2098   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2099   mangleType(T->getElementType(), SourceRange());
2100 }
2101 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2102                                          SourceRange) {
2103   llvm_unreachable("Should have been special cased");
2104 }
2105 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2106                                          SourceRange) {
2107   llvm_unreachable("Should have been special cased");
2108 }
2109 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2110                                          Qualifiers, SourceRange) {
2111   llvm_unreachable("Should have been special cased");
2112 }
2113 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2114                                          Qualifiers, SourceRange) {
2115   llvm_unreachable("Should have been special cased");
2116 }
2117 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2118   QualType ElementTy(T, 0);
2119   SmallVector<llvm::APInt, 3> Dimensions;
2120   for (;;) {
2121     if (ElementTy->isConstantArrayType()) {
2122       const ConstantArrayType *CAT =
2123           getASTContext().getAsConstantArrayType(ElementTy);
2124       Dimensions.push_back(CAT->getSize());
2125       ElementTy = CAT->getElementType();
2126     } else if (ElementTy->isIncompleteArrayType()) {
2127       const IncompleteArrayType *IAT =
2128           getASTContext().getAsIncompleteArrayType(ElementTy);
2129       Dimensions.push_back(llvm::APInt(32, 0));
2130       ElementTy = IAT->getElementType();
2131     } else if (ElementTy->isVariableArrayType()) {
2132       const VariableArrayType *VAT =
2133         getASTContext().getAsVariableArrayType(ElementTy);
2134       Dimensions.push_back(llvm::APInt(32, 0));
2135       ElementTy = VAT->getElementType();
2136     } else if (ElementTy->isDependentSizedArrayType()) {
2137       // The dependent expression has to be folded into a constant (TODO).
2138       const DependentSizedArrayType *DSAT =
2139         getASTContext().getAsDependentSizedArrayType(ElementTy);
2140       DiagnosticsEngine &Diags = Context.getDiags();
2141       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2142         "cannot mangle this dependent-length array yet");
2143       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2144         << DSAT->getBracketsRange();
2145       return;
2146     } else {
2147       break;
2148     }
2149   }
2150   Out << 'Y';
2151   // <dimension-count> ::= <number> # number of extra dimensions
2152   mangleNumber(Dimensions.size());
2153   for (const llvm::APInt &Dimension : Dimensions)
2154     mangleNumber(Dimension.getLimitedValue());
2155   mangleType(ElementTy, SourceRange(), QMM_Escape);
2156 }
2157 
2158 // <type>                   ::= <pointer-to-member-type>
2159 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2160 //                                                          <class name> <type>
2161 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2162                                          SourceRange Range) {
2163   QualType PointeeType = T->getPointeeType();
2164   manglePointerCVQualifiers(Quals);
2165   manglePointerExtQualifiers(Quals, PointeeType);
2166   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2167     Out << '8';
2168     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2169     mangleFunctionType(FPT, nullptr, true);
2170   } else {
2171     mangleQualifiers(PointeeType.getQualifiers(), true);
2172     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2173     mangleType(PointeeType, Range, QMM_Drop);
2174   }
2175 }
2176 
2177 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2178                                          Qualifiers, SourceRange Range) {
2179   DiagnosticsEngine &Diags = Context.getDiags();
2180   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2181     "cannot mangle this template type parameter type yet");
2182   Diags.Report(Range.getBegin(), DiagID)
2183     << Range;
2184 }
2185 
2186 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2187                                          Qualifiers, SourceRange Range) {
2188   DiagnosticsEngine &Diags = Context.getDiags();
2189   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2190     "cannot mangle this substituted parameter pack yet");
2191   Diags.Report(Range.getBegin(), DiagID)
2192     << Range;
2193 }
2194 
2195 // <type> ::= <pointer-type>
2196 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2197 //                       # the E is required for 64-bit non-static pointers
2198 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2199                                          SourceRange Range) {
2200   QualType PointeeType = T->getPointeeType();
2201   manglePointerCVQualifiers(Quals);
2202   manglePointerExtQualifiers(Quals, PointeeType);
2203   mangleType(PointeeType, Range);
2204 }
2205 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2206                                          Qualifiers Quals, SourceRange Range) {
2207   QualType PointeeType = T->getPointeeType();
2208   manglePointerCVQualifiers(Quals);
2209   manglePointerExtQualifiers(Quals, PointeeType);
2210   // Object pointers never have qualifiers.
2211   Out << 'A';
2212   mangleType(PointeeType, Range);
2213 }
2214 
2215 // <type> ::= <reference-type>
2216 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2217 //                 # the E is required for 64-bit non-static lvalue references
2218 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2219                                          Qualifiers Quals, SourceRange Range) {
2220   QualType PointeeType = T->getPointeeType();
2221   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2222   Out << 'A';
2223   manglePointerExtQualifiers(Quals, PointeeType);
2224   mangleType(PointeeType, Range);
2225 }
2226 
2227 // <type> ::= <r-value-reference-type>
2228 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2229 //                 # the E is required for 64-bit non-static rvalue references
2230 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2231                                          Qualifiers Quals, SourceRange Range) {
2232   QualType PointeeType = T->getPointeeType();
2233   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2234   Out << "$$Q";
2235   manglePointerExtQualifiers(Quals, PointeeType);
2236   mangleType(PointeeType, Range);
2237 }
2238 
2239 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2240                                          SourceRange Range) {
2241   QualType ElementType = T->getElementType();
2242 
2243   llvm::SmallString<64> TemplateMangling;
2244   llvm::raw_svector_ostream Stream(TemplateMangling);
2245   MicrosoftCXXNameMangler Extra(Context, Stream);
2246   Stream << "?$";
2247   Extra.mangleSourceName("_Complex");
2248   Extra.mangleType(ElementType, Range, QMM_Escape);
2249 
2250   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2251 }
2252 
2253 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2254                                          SourceRange Range) {
2255   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2256   assert(ET && "vectors with non-builtin elements are unsupported");
2257   uint64_t Width = getASTContext().getTypeSize(T);
2258   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2259   // doesn't match the Intel types uses a custom mangling below.
2260   size_t OutSizeBefore = Out.tell();
2261   llvm::Triple::ArchType AT =
2262       getASTContext().getTargetInfo().getTriple().getArch();
2263   if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2264     if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2265       mangleArtificalTagType(TTK_Union, "__m64");
2266     } else if (Width >= 128) {
2267       if (ET->getKind() == BuiltinType::Float)
2268         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width));
2269       else if (ET->getKind() == BuiltinType::LongLong)
2270         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2271       else if (ET->getKind() == BuiltinType::Double)
2272         mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2273     }
2274   }
2275 
2276   bool IsBuiltin = Out.tell() != OutSizeBefore;
2277   if (!IsBuiltin) {
2278     // The MS ABI doesn't have a special mangling for vector types, so we define
2279     // our own mangling to handle uses of __vector_size__ on user-specified
2280     // types, and for extensions like __v4sf.
2281 
2282     llvm::SmallString<64> TemplateMangling;
2283     llvm::raw_svector_ostream Stream(TemplateMangling);
2284     MicrosoftCXXNameMangler Extra(Context, Stream);
2285     Stream << "?$";
2286     Extra.mangleSourceName("__vector");
2287     Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2288     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2289                                /*IsBoolean=*/false);
2290 
2291     mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"});
2292   }
2293 }
2294 
2295 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2296                                          Qualifiers Quals, SourceRange Range) {
2297   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2298 }
2299 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2300                                          Qualifiers, SourceRange Range) {
2301   DiagnosticsEngine &Diags = Context.getDiags();
2302   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2303     "cannot mangle this dependent-sized extended vector type yet");
2304   Diags.Report(Range.getBegin(), DiagID)
2305     << Range;
2306 }
2307 
2308 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2309                                          SourceRange) {
2310   // ObjC interfaces have structs underlying them.
2311   mangleTagTypeKind(TTK_Struct);
2312   mangleName(T->getDecl());
2313 }
2314 
2315 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2316                                          SourceRange Range) {
2317   // We don't allow overloading by different protocol qualification,
2318   // so mangling them isn't necessary.
2319   mangleType(T->getBaseType(), Range);
2320 }
2321 
2322 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2323                                          Qualifiers Quals, SourceRange Range) {
2324   QualType PointeeType = T->getPointeeType();
2325   manglePointerCVQualifiers(Quals);
2326   manglePointerExtQualifiers(Quals, PointeeType);
2327 
2328   Out << "_E";
2329 
2330   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2331 }
2332 
2333 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2334                                          Qualifiers, SourceRange) {
2335   llvm_unreachable("Cannot mangle injected class name type.");
2336 }
2337 
2338 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2339                                          Qualifiers, SourceRange Range) {
2340   DiagnosticsEngine &Diags = Context.getDiags();
2341   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2342     "cannot mangle this template specialization type yet");
2343   Diags.Report(Range.getBegin(), DiagID)
2344     << Range;
2345 }
2346 
2347 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2348                                          SourceRange Range) {
2349   DiagnosticsEngine &Diags = Context.getDiags();
2350   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2351     "cannot mangle this dependent name type yet");
2352   Diags.Report(Range.getBegin(), DiagID)
2353     << Range;
2354 }
2355 
2356 void MicrosoftCXXNameMangler::mangleType(
2357     const DependentTemplateSpecializationType *T, Qualifiers,
2358     SourceRange Range) {
2359   DiagnosticsEngine &Diags = Context.getDiags();
2360   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2361     "cannot mangle this dependent template specialization type yet");
2362   Diags.Report(Range.getBegin(), DiagID)
2363     << Range;
2364 }
2365 
2366 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2367                                          SourceRange Range) {
2368   DiagnosticsEngine &Diags = Context.getDiags();
2369   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2370     "cannot mangle this pack expansion yet");
2371   Diags.Report(Range.getBegin(), DiagID)
2372     << Range;
2373 }
2374 
2375 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2376                                          SourceRange Range) {
2377   DiagnosticsEngine &Diags = Context.getDiags();
2378   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2379     "cannot mangle this typeof(type) yet");
2380   Diags.Report(Range.getBegin(), DiagID)
2381     << Range;
2382 }
2383 
2384 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2385                                          SourceRange Range) {
2386   DiagnosticsEngine &Diags = Context.getDiags();
2387   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2388     "cannot mangle this typeof(expression) yet");
2389   Diags.Report(Range.getBegin(), DiagID)
2390     << Range;
2391 }
2392 
2393 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2394                                          SourceRange Range) {
2395   DiagnosticsEngine &Diags = Context.getDiags();
2396   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2397     "cannot mangle this decltype() yet");
2398   Diags.Report(Range.getBegin(), DiagID)
2399     << Range;
2400 }
2401 
2402 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2403                                          Qualifiers, SourceRange Range) {
2404   DiagnosticsEngine &Diags = Context.getDiags();
2405   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2406     "cannot mangle this unary transform type yet");
2407   Diags.Report(Range.getBegin(), DiagID)
2408     << Range;
2409 }
2410 
2411 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2412                                          SourceRange Range) {
2413   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2414 
2415   DiagnosticsEngine &Diags = Context.getDiags();
2416   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2417     "cannot mangle this 'auto' type yet");
2418   Diags.Report(Range.getBegin(), DiagID)
2419     << Range;
2420 }
2421 
2422 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2423                                          SourceRange Range) {
2424   QualType ValueType = T->getValueType();
2425 
2426   llvm::SmallString<64> TemplateMangling;
2427   llvm::raw_svector_ostream Stream(TemplateMangling);
2428   MicrosoftCXXNameMangler Extra(Context, Stream);
2429   Stream << "?$";
2430   Extra.mangleSourceName("_Atomic");
2431   Extra.mangleType(ValueType, Range, QMM_Escape);
2432 
2433   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2434 }
2435 
2436 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2437                                          SourceRange Range) {
2438   DiagnosticsEngine &Diags = Context.getDiags();
2439   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2440     "cannot mangle this OpenCL pipe type yet");
2441   Diags.Report(Range.getBegin(), DiagID)
2442     << Range;
2443 }
2444 
2445 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2446                                                raw_ostream &Out) {
2447   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2448          "Invalid mangleName() call, argument is not a variable or function!");
2449   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2450          "Invalid mangleName() call on 'structor decl!");
2451 
2452   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2453                                  getASTContext().getSourceManager(),
2454                                  "Mangling declaration");
2455 
2456   msvc_hashing_ostream MHO(Out);
2457   MicrosoftCXXNameMangler Mangler(*this, MHO);
2458   return Mangler.mangle(D);
2459 }
2460 
2461 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2462 //                       <virtual-adjustment>
2463 // <no-adjustment>      ::= A # private near
2464 //                      ::= B # private far
2465 //                      ::= I # protected near
2466 //                      ::= J # protected far
2467 //                      ::= Q # public near
2468 //                      ::= R # public far
2469 // <static-adjustment>  ::= G <static-offset> # private near
2470 //                      ::= H <static-offset> # private far
2471 //                      ::= O <static-offset> # protected near
2472 //                      ::= P <static-offset> # protected far
2473 //                      ::= W <static-offset> # public near
2474 //                      ::= X <static-offset> # public far
2475 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2476 //                      ::= $1 <virtual-shift> <static-offset> # private far
2477 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2478 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2479 //                      ::= $4 <virtual-shift> <static-offset> # public near
2480 //                      ::= $5 <virtual-shift> <static-offset> # public far
2481 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2482 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2483 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2484 //                          <offset-to-vtordisp>
2485 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2486                                       const ThisAdjustment &Adjustment,
2487                                       MicrosoftCXXNameMangler &Mangler,
2488                                       raw_ostream &Out) {
2489   if (!Adjustment.Virtual.isEmpty()) {
2490     Out << '$';
2491     char AccessSpec;
2492     switch (MD->getAccess()) {
2493     case AS_none:
2494       llvm_unreachable("Unsupported access specifier");
2495     case AS_private:
2496       AccessSpec = '0';
2497       break;
2498     case AS_protected:
2499       AccessSpec = '2';
2500       break;
2501     case AS_public:
2502       AccessSpec = '4';
2503     }
2504     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2505       Out << 'R' << AccessSpec;
2506       Mangler.mangleNumber(
2507           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2508       Mangler.mangleNumber(
2509           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2510       Mangler.mangleNumber(
2511           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2512       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2513     } else {
2514       Out << AccessSpec;
2515       Mangler.mangleNumber(
2516           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2517       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2518     }
2519   } else if (Adjustment.NonVirtual != 0) {
2520     switch (MD->getAccess()) {
2521     case AS_none:
2522       llvm_unreachable("Unsupported access specifier");
2523     case AS_private:
2524       Out << 'G';
2525       break;
2526     case AS_protected:
2527       Out << 'O';
2528       break;
2529     case AS_public:
2530       Out << 'W';
2531     }
2532     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2533   } else {
2534     switch (MD->getAccess()) {
2535     case AS_none:
2536       llvm_unreachable("Unsupported access specifier");
2537     case AS_private:
2538       Out << 'A';
2539       break;
2540     case AS_protected:
2541       Out << 'I';
2542       break;
2543     case AS_public:
2544       Out << 'Q';
2545     }
2546   }
2547 }
2548 
2549 void
2550 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2551                                                      raw_ostream &Out) {
2552   MicrosoftVTableContext *VTContext =
2553       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2554   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2555       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2556 
2557   msvc_hashing_ostream MHO(Out);
2558   MicrosoftCXXNameMangler Mangler(*this, MHO);
2559   Mangler.getStream() << "\01?";
2560   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2561 }
2562 
2563 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2564                                              const ThunkInfo &Thunk,
2565                                              raw_ostream &Out) {
2566   msvc_hashing_ostream MHO(Out);
2567   MicrosoftCXXNameMangler Mangler(*this, MHO);
2568   Mangler.getStream() << "\01?";
2569   Mangler.mangleName(MD);
2570   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, MHO);
2571   if (!Thunk.Return.isEmpty())
2572     assert(Thunk.Method != nullptr &&
2573            "Thunk info should hold the overridee decl");
2574 
2575   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2576   Mangler.mangleFunctionType(
2577       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2578 }
2579 
2580 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2581     const CXXDestructorDecl *DD, CXXDtorType Type,
2582     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2583   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2584   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2585   // mangling manually until we support both deleting dtor types.
2586   assert(Type == Dtor_Deleting);
2587   msvc_hashing_ostream MHO(Out);
2588   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
2589   Mangler.getStream() << "\01??_E";
2590   Mangler.mangleName(DD->getParent());
2591   mangleThunkThisAdjustment(DD, Adjustment, Mangler, MHO);
2592   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2593 }
2594 
2595 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2596     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2597     raw_ostream &Out) {
2598   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2599   //                    <cvr-qualifiers> [<name>] @
2600   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2601   // is always '6' for vftables.
2602   msvc_hashing_ostream MHO(Out);
2603   MicrosoftCXXNameMangler Mangler(*this, MHO);
2604   if (Derived->hasAttr<DLLImportAttr>())
2605     Mangler.getStream() << "\01??_S";
2606   else
2607     Mangler.getStream() << "\01??_7";
2608   Mangler.mangleName(Derived);
2609   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2610   for (const CXXRecordDecl *RD : BasePath)
2611     Mangler.mangleName(RD);
2612   Mangler.getStream() << '@';
2613 }
2614 
2615 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2616     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2617     raw_ostream &Out) {
2618   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2619   //                    <cvr-qualifiers> [<name>] @
2620   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2621   // is always '7' for vbtables.
2622   msvc_hashing_ostream MHO(Out);
2623   MicrosoftCXXNameMangler Mangler(*this, MHO);
2624   Mangler.getStream() << "\01??_8";
2625   Mangler.mangleName(Derived);
2626   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2627   for (const CXXRecordDecl *RD : BasePath)
2628     Mangler.mangleName(RD);
2629   Mangler.getStream() << '@';
2630 }
2631 
2632 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2633   msvc_hashing_ostream MHO(Out);
2634   MicrosoftCXXNameMangler Mangler(*this, MHO);
2635   Mangler.getStream() << "\01??_R0";
2636   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2637   Mangler.getStream() << "@8";
2638 }
2639 
2640 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2641                                                    raw_ostream &Out) {
2642   MicrosoftCXXNameMangler Mangler(*this, Out);
2643   Mangler.getStream() << '.';
2644   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2645 }
2646 
2647 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2648     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2649   msvc_hashing_ostream MHO(Out);
2650   MicrosoftCXXNameMangler Mangler(*this, MHO);
2651   Mangler.getStream() << "\01??_K";
2652   Mangler.mangleName(SrcRD);
2653   Mangler.getStream() << "$C";
2654   Mangler.mangleName(DstRD);
2655 }
2656 
2657 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2658                                                     bool IsConst,
2659                                                     bool IsVolatile,
2660                                                     uint32_t NumEntries,
2661                                                     raw_ostream &Out) {
2662   msvc_hashing_ostream MHO(Out);
2663   MicrosoftCXXNameMangler Mangler(*this, MHO);
2664   Mangler.getStream() << "_TI";
2665   if (IsConst)
2666     Mangler.getStream() << 'C';
2667   if (IsVolatile)
2668     Mangler.getStream() << 'V';
2669   Mangler.getStream() << NumEntries;
2670   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2671 }
2672 
2673 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2674     QualType T, uint32_t NumEntries, raw_ostream &Out) {
2675   msvc_hashing_ostream MHO(Out);
2676   MicrosoftCXXNameMangler Mangler(*this, MHO);
2677   Mangler.getStream() << "_CTA";
2678   Mangler.getStream() << NumEntries;
2679   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2680 }
2681 
2682 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2683     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2684     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2685     raw_ostream &Out) {
2686   MicrosoftCXXNameMangler Mangler(*this, Out);
2687   Mangler.getStream() << "_CT";
2688 
2689   llvm::SmallString<64> RTTIMangling;
2690   {
2691     llvm::raw_svector_ostream Stream(RTTIMangling);
2692     msvc_hashing_ostream MHO(Stream);
2693     mangleCXXRTTI(T, MHO);
2694   }
2695   Mangler.getStream() << RTTIMangling.substr(1);
2696 
2697   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
2698   // in fact, superfluous but I'm not sure the change was made consciously.
2699   llvm::SmallString<64> CopyCtorMangling;
2700   if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
2701           LangOptions::MSVC2015) &&
2702       CD) {
2703     llvm::raw_svector_ostream Stream(CopyCtorMangling);
2704     msvc_hashing_ostream MHO(Stream);
2705     mangleCXXCtor(CD, CT, MHO);
2706   }
2707   Mangler.getStream() << CopyCtorMangling.substr(1);
2708 
2709   Mangler.getStream() << Size;
2710   if (VBPtrOffset == -1) {
2711     if (NVOffset) {
2712       Mangler.getStream() << NVOffset;
2713     }
2714   } else {
2715     Mangler.getStream() << NVOffset;
2716     Mangler.getStream() << VBPtrOffset;
2717     Mangler.getStream() << VBIndex;
2718   }
2719 }
2720 
2721 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2722     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2723     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2724   msvc_hashing_ostream MHO(Out);
2725   MicrosoftCXXNameMangler Mangler(*this, MHO);
2726   Mangler.getStream() << "\01??_R1";
2727   Mangler.mangleNumber(NVOffset);
2728   Mangler.mangleNumber(VBPtrOffset);
2729   Mangler.mangleNumber(VBTableOffset);
2730   Mangler.mangleNumber(Flags);
2731   Mangler.mangleName(Derived);
2732   Mangler.getStream() << "8";
2733 }
2734 
2735 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2736     const CXXRecordDecl *Derived, raw_ostream &Out) {
2737   msvc_hashing_ostream MHO(Out);
2738   MicrosoftCXXNameMangler Mangler(*this, MHO);
2739   Mangler.getStream() << "\01??_R2";
2740   Mangler.mangleName(Derived);
2741   Mangler.getStream() << "8";
2742 }
2743 
2744 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2745     const CXXRecordDecl *Derived, raw_ostream &Out) {
2746   msvc_hashing_ostream MHO(Out);
2747   MicrosoftCXXNameMangler Mangler(*this, MHO);
2748   Mangler.getStream() << "\01??_R3";
2749   Mangler.mangleName(Derived);
2750   Mangler.getStream() << "8";
2751 }
2752 
2753 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2754     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2755     raw_ostream &Out) {
2756   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2757   //                    <cvr-qualifiers> [<name>] @
2758   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2759   // is always '6' for vftables.
2760   llvm::SmallString<64> VFTableMangling;
2761   llvm::raw_svector_ostream Stream(VFTableMangling);
2762   mangleCXXVFTable(Derived, BasePath, Stream);
2763 
2764   if (VFTableMangling.startswith("\01??@")) {
2765     assert(VFTableMangling.endswith("@"));
2766     Out << VFTableMangling << "??_R4@";
2767     return;
2768   }
2769 
2770   assert(VFTableMangling.startswith("\01??_7") ||
2771          VFTableMangling.startswith("\01??_S"));
2772 
2773   Out << "\01??_R4" << StringRef(VFTableMangling).drop_front(5);
2774 }
2775 
2776 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2777     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2778   msvc_hashing_ostream MHO(Out);
2779   MicrosoftCXXNameMangler Mangler(*this, MHO);
2780   // The function body is in the same comdat as the function with the handler,
2781   // so the numbering here doesn't have to be the same across TUs.
2782   //
2783   // <mangled-name> ::= ?filt$ <filter-number> @0
2784   Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2785   Mangler.mangleName(EnclosingDecl);
2786 }
2787 
2788 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2789     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2790   msvc_hashing_ostream MHO(Out);
2791   MicrosoftCXXNameMangler Mangler(*this, MHO);
2792   // The function body is in the same comdat as the function with the handler,
2793   // so the numbering here doesn't have to be the same across TUs.
2794   //
2795   // <mangled-name> ::= ?fin$ <filter-number> @0
2796   Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2797   Mangler.mangleName(EnclosingDecl);
2798 }
2799 
2800 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2801   // This is just a made up unique string for the purposes of tbaa.  undname
2802   // does *not* know how to demangle it.
2803   MicrosoftCXXNameMangler Mangler(*this, Out);
2804   Mangler.getStream() << '?';
2805   Mangler.mangleType(T, SourceRange());
2806 }
2807 
2808 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2809                                                CXXCtorType Type,
2810                                                raw_ostream &Out) {
2811   msvc_hashing_ostream MHO(Out);
2812   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
2813   mangler.mangle(D);
2814 }
2815 
2816 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2817                                                CXXDtorType Type,
2818                                                raw_ostream &Out) {
2819   msvc_hashing_ostream MHO(Out);
2820   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
2821   mangler.mangle(D);
2822 }
2823 
2824 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
2825     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
2826   msvc_hashing_ostream MHO(Out);
2827   MicrosoftCXXNameMangler Mangler(*this, MHO);
2828 
2829   Mangler.getStream() << "\01?$RT" << ManglingNumber << '@';
2830   Mangler.mangle(VD, "");
2831 }
2832 
2833 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2834     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2835   msvc_hashing_ostream MHO(Out);
2836   MicrosoftCXXNameMangler Mangler(*this, MHO);
2837 
2838   Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2839   Mangler.mangleNestedName(VD);
2840   Mangler.getStream() << "@4HA";
2841 }
2842 
2843 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2844                                                            raw_ostream &Out) {
2845   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2846   //              ::= ?__J <postfix> @5 <scope-depth>
2847   //              ::= ?$S <guard-num> @ <postfix> @4IA
2848 
2849   // The first mangling is what MSVC uses to guard static locals in inline
2850   // functions.  It uses a different mangling in external functions to support
2851   // guarding more than 32 variables.  MSVC rejects inline functions with more
2852   // than 32 static locals.  We don't fully implement the second mangling
2853   // because those guards are not externally visible, and instead use LLVM's
2854   // default renaming when creating a new guard variable.
2855   msvc_hashing_ostream MHO(Out);
2856   MicrosoftCXXNameMangler Mangler(*this, MHO);
2857 
2858   bool Visible = VD->isExternallyVisible();
2859   if (Visible) {
2860     Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2861   } else {
2862     Mangler.getStream() << "\01?$S1@";
2863   }
2864   unsigned ScopeDepth = 0;
2865   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2866     // If we do not have a discriminator and are emitting a guard variable for
2867     // use at global scope, then mangling the nested name will not be enough to
2868     // remove ambiguities.
2869     Mangler.mangle(VD, "");
2870   else
2871     Mangler.mangleNestedName(VD);
2872   Mangler.getStream() << (Visible ? "@5" : "@4IA");
2873   if (ScopeDepth)
2874     Mangler.mangleNumber(ScopeDepth);
2875 }
2876 
2877 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2878                                                     char CharCode,
2879                                                     raw_ostream &Out) {
2880   msvc_hashing_ostream MHO(Out);
2881   MicrosoftCXXNameMangler Mangler(*this, MHO);
2882   Mangler.getStream() << "\01??__" << CharCode;
2883   Mangler.mangleName(D);
2884   if (D->isStaticDataMember()) {
2885     Mangler.mangleVariableEncoding(D);
2886     Mangler.getStream() << '@';
2887   }
2888   // This is the function class mangling.  These stubs are global, non-variadic,
2889   // cdecl functions that return void and take no args.
2890   Mangler.getStream() << "YAXXZ";
2891 }
2892 
2893 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2894                                                           raw_ostream &Out) {
2895   // <initializer-name> ::= ?__E <name> YAXXZ
2896   mangleInitFiniStub(D, 'E', Out);
2897 }
2898 
2899 void
2900 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2901                                                           raw_ostream &Out) {
2902   // <destructor-name> ::= ?__F <name> YAXXZ
2903   mangleInitFiniStub(D, 'F', Out);
2904 }
2905 
2906 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2907                                                      raw_ostream &Out) {
2908   // <char-type> ::= 0   # char
2909   //             ::= 1   # wchar_t
2910   //             ::= ??? # char16_t/char32_t will need a mangling too...
2911   //
2912   // <literal-length> ::= <non-negative integer>  # the length of the literal
2913   //
2914   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2915   //                                              # null-terminator
2916   //
2917   // <encoded-string> ::= <simple character>           # uninteresting character
2918   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2919   //                                                   # encode the byte for the
2920   //                                                   # character
2921   //                  ::= '?' [a-z]                    # \xe1 - \xfa
2922   //                  ::= '?' [A-Z]                    # \xc1 - \xda
2923   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
2924   //
2925   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2926   //               <encoded-string> '@'
2927   MicrosoftCXXNameMangler Mangler(*this, Out);
2928   Mangler.getStream() << "\01??_C@_";
2929 
2930   // <char-type>: The "kind" of string literal is encoded into the mangled name.
2931   if (SL->isWide())
2932     Mangler.getStream() << '1';
2933   else
2934     Mangler.getStream() << '0';
2935 
2936   // <literal-length>: The next part of the mangled name consists of the length
2937   // of the string.
2938   // The StringLiteral does not consider the NUL terminator byte(s) but the
2939   // mangling does.
2940   // N.B. The length is in terms of bytes, not characters.
2941   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2942 
2943   auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2944     unsigned CharByteWidth = SL->getCharByteWidth();
2945     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2946     unsigned OffsetInCodeUnit = Index % CharByteWidth;
2947     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2948   };
2949 
2950   auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2951     unsigned CharByteWidth = SL->getCharByteWidth();
2952     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2953     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2954     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2955   };
2956 
2957   // CRC all the bytes of the StringLiteral.
2958   llvm::JamCRC JC;
2959   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2960     JC.update(GetLittleEndianByte(I));
2961 
2962   // The NUL terminator byte(s) were not present earlier,
2963   // we need to manually process those bytes into the CRC.
2964   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2965        ++NullTerminator)
2966     JC.update('\x00');
2967 
2968   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2969   // scheme.
2970   Mangler.mangleNumber(JC.getCRC());
2971 
2972   // <encoded-string>: The mangled name also contains the first 32 _characters_
2973   // (including null-terminator bytes) of the StringLiteral.
2974   // Each character is encoded by splitting them into bytes and then encoding
2975   // the constituent bytes.
2976   auto MangleByte = [&Mangler](char Byte) {
2977     // There are five different manglings for characters:
2978     // - [a-zA-Z0-9_$]: A one-to-one mapping.
2979     // - ?[a-z]: The range from \xe1 to \xfa.
2980     // - ?[A-Z]: The range from \xc1 to \xda.
2981     // - ?[0-9]: The set of [,/\:. \n\t'-].
2982     // - ?$XX: A fallback which maps nibbles.
2983     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2984       Mangler.getStream() << Byte;
2985     } else if (isLetter(Byte & 0x7f)) {
2986       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2987     } else {
2988       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
2989                                    ' ', '\n', '\t', '\'', '-'};
2990       const char *Pos =
2991           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2992       if (Pos != std::end(SpecialChars)) {
2993         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2994       } else {
2995         Mangler.getStream() << "?$";
2996         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2997         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2998       }
2999     }
3000   };
3001 
3002   // Enforce our 32 character max.
3003   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
3004   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
3005        ++I)
3006     if (SL->isWide())
3007       MangleByte(GetBigEndianByte(I));
3008     else
3009       MangleByte(GetLittleEndianByte(I));
3010 
3011   // Encode the NUL terminator if there is room.
3012   if (NumCharsToMangle < 32)
3013     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
3014          ++NullTerminator)
3015       MangleByte(0);
3016 
3017   Mangler.getStream() << '@';
3018 }
3019 
3020 MicrosoftMangleContext *
3021 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3022   return new MicrosoftMangleContextImpl(Context, Diags);
3023 }
3024