1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/GlobalDecl.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/VTableBuilder.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CRC.h"
35 #include "llvm/Support/MD5.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/StringSaver.h"
38 #include "llvm/Support/xxhash.h"
39 #include <functional>
40 #include <optional>
41 
42 using namespace clang;
43 
44 namespace {
45 
46 // Get GlobalDecl of DeclContext of local entities.
47 static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
48   GlobalDecl GD;
49   if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
50     GD = GlobalDecl(CD, Ctor_Complete);
51   else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
52     GD = GlobalDecl(DD, Dtor_Complete);
53   else
54     GD = GlobalDecl(cast<FunctionDecl>(DC));
55   return GD;
56 }
57 
58 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
59   raw_ostream &OS;
60   llvm::SmallString<64> Buffer;
61 
62   msvc_hashing_ostream(raw_ostream &OS)
63       : llvm::raw_svector_ostream(Buffer), OS(OS) {}
64   ~msvc_hashing_ostream() override {
65     StringRef MangledName = str();
66     bool StartsWithEscape = MangledName.startswith("\01");
67     if (StartsWithEscape)
68       MangledName = MangledName.drop_front(1);
69     if (MangledName.size() < 4096) {
70       OS << str();
71       return;
72     }
73 
74     llvm::MD5 Hasher;
75     llvm::MD5::MD5Result Hash;
76     Hasher.update(MangledName);
77     Hasher.final(Hash);
78 
79     SmallString<32> HexString;
80     llvm::MD5::stringifyResult(Hash, HexString);
81 
82     if (StartsWithEscape)
83       OS << '\01';
84     OS << "??@" << HexString << '@';
85   }
86 };
87 
88 static const DeclContext *
89 getLambdaDefaultArgumentDeclContext(const Decl *D) {
90   if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
91     if (RD->isLambda())
92       if (const auto *Parm =
93               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
94         return Parm->getDeclContext();
95   return nullptr;
96 }
97 
98 /// Retrieve the declaration context that should be used when mangling
99 /// the given declaration.
100 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
101   // The ABI assumes that lambda closure types that occur within
102   // default arguments live in the context of the function. However, due to
103   // the way in which Clang parses and creates function declarations, this is
104   // not the case: the lambda closure type ends up living in the context
105   // where the function itself resides, because the function declaration itself
106   // had not yet been created. Fix the context here.
107   if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
108     return LDADC;
109 
110   // Perform the same check for block literals.
111   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
112     if (ParmVarDecl *ContextParam =
113             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
114       return ContextParam->getDeclContext();
115   }
116 
117   const DeclContext *DC = D->getDeclContext();
118   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
119       isa<OMPDeclareMapperDecl>(DC)) {
120     return getEffectiveDeclContext(cast<Decl>(DC));
121   }
122 
123   return DC->getRedeclContext();
124 }
125 
126 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
127   return getEffectiveDeclContext(cast<Decl>(DC));
128 }
129 
130 static const FunctionDecl *getStructor(const NamedDecl *ND) {
131   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
132     return FTD->getTemplatedDecl()->getCanonicalDecl();
133 
134   const auto *FD = cast<FunctionDecl>(ND);
135   if (const auto *FTD = FD->getPrimaryTemplate())
136     return FTD->getTemplatedDecl()->getCanonicalDecl();
137 
138   return FD->getCanonicalDecl();
139 }
140 
141 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
142 /// Microsoft Visual C++ ABI.
143 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
144   typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
145   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
146   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
147   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
148   llvm::DenseMap<GlobalDecl, unsigned> SEHFilterIds;
149   llvm::DenseMap<GlobalDecl, unsigned> SEHFinallyIds;
150   SmallString<16> AnonymousNamespaceHash;
151 
152 public:
153   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
154                              bool IsAux = false);
155   bool shouldMangleCXXName(const NamedDecl *D) override;
156   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
157   void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
158   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
159                                 const MethodVFTableLocation &ML,
160                                 raw_ostream &Out) override;
161   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
162                    raw_ostream &) override;
163   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
164                           const ThisAdjustment &ThisAdjustment,
165                           raw_ostream &) override;
166   void mangleCXXVFTable(const CXXRecordDecl *Derived,
167                         ArrayRef<const CXXRecordDecl *> BasePath,
168                         raw_ostream &Out) override;
169   void mangleCXXVBTable(const CXXRecordDecl *Derived,
170                         ArrayRef<const CXXRecordDecl *> BasePath,
171                         raw_ostream &Out) override;
172   void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
173                                        const CXXRecordDecl *DstRD,
174                                        raw_ostream &Out) override;
175   void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
176                           bool IsUnaligned, uint32_t NumEntries,
177                           raw_ostream &Out) override;
178   void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
179                                    raw_ostream &Out) override;
180   void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
181                               CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
182                               int32_t VBPtrOffset, uint32_t VBIndex,
183                               raw_ostream &Out) override;
184   void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
185   void mangleCXXRTTIName(QualType T, raw_ostream &Out,
186                          bool NormalizeIntegers) override;
187   void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
188                                         uint32_t NVOffset, int32_t VBPtrOffset,
189                                         uint32_t VBTableOffset, uint32_t Flags,
190                                         raw_ostream &Out) override;
191   void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
192                                    raw_ostream &Out) override;
193   void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
194                                              raw_ostream &Out) override;
195   void
196   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
197                                      ArrayRef<const CXXRecordDecl *> BasePath,
198                                      raw_ostream &Out) override;
199   void mangleTypeName(QualType T, raw_ostream &,
200                       bool NormalizeIntegers) override;
201   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
202                                 raw_ostream &) override;
203   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
204   void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
205                                            raw_ostream &Out) override;
206   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
207   void mangleDynamicAtExitDestructor(const VarDecl *D,
208                                      raw_ostream &Out) override;
209   void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
210                                  raw_ostream &Out) override;
211   void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
212                              raw_ostream &Out) override;
213   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
214   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
215     const DeclContext *DC = getEffectiveDeclContext(ND);
216     if (!DC->isFunctionOrMethod())
217       return false;
218 
219     // Lambda closure types are already numbered, give out a phony number so
220     // that they demangle nicely.
221     if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
222       if (RD->isLambda()) {
223         disc = 1;
224         return true;
225       }
226     }
227 
228     // Use the canonical number for externally visible decls.
229     if (ND->isExternallyVisible()) {
230       disc = getASTContext().getManglingNumber(ND, isAux());
231       return true;
232     }
233 
234     // Anonymous tags are already numbered.
235     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
236       if (!Tag->hasNameForLinkage() &&
237           !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
238           !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
239         return false;
240     }
241 
242     // Make up a reasonable number for internal decls.
243     unsigned &discriminator = Uniquifier[ND];
244     if (!discriminator)
245       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
246     disc = discriminator + 1;
247     return true;
248   }
249 
250   std::string getLambdaString(const CXXRecordDecl *Lambda) override {
251     assert(Lambda->isLambda() && "RD must be a lambda!");
252     std::string Name("<lambda_");
253 
254     Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
255     unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
256     unsigned LambdaId;
257     const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
258     const FunctionDecl *Func =
259         Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
260 
261     if (Func) {
262       unsigned DefaultArgNo =
263           Func->getNumParams() - Parm->getFunctionScopeIndex();
264       Name += llvm::utostr(DefaultArgNo);
265       Name += "_";
266     }
267 
268     if (LambdaManglingNumber)
269       LambdaId = LambdaManglingNumber;
270     else
271       LambdaId = getLambdaIdForDebugInfo(Lambda);
272 
273     Name += llvm::utostr(LambdaId);
274     Name += ">";
275     return Name;
276   }
277 
278   unsigned getLambdaId(const CXXRecordDecl *RD) {
279     assert(RD->isLambda() && "RD must be a lambda!");
280     assert(!RD->isExternallyVisible() && "RD must not be visible!");
281     assert(RD->getLambdaManglingNumber() == 0 &&
282            "RD must not have a mangling number!");
283     std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
284         Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
285     return Result.first->second;
286   }
287 
288   unsigned getLambdaIdForDebugInfo(const CXXRecordDecl *RD) {
289     assert(RD->isLambda() && "RD must be a lambda!");
290     assert(!RD->isExternallyVisible() && "RD must not be visible!");
291     assert(RD->getLambdaManglingNumber() == 0 &&
292            "RD must not have a mangling number!");
293     // The lambda should exist, but return 0 in case it doesn't.
294     return LambdaIds.lookup(RD);
295   }
296 
297   /// Return a character sequence that is (somewhat) unique to the TU suitable
298   /// for mangling anonymous namespaces.
299   StringRef getAnonymousNamespaceHash() const {
300     return AnonymousNamespaceHash;
301   }
302 
303 private:
304   void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
305 };
306 
307 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
308 /// Microsoft Visual C++ ABI.
309 class MicrosoftCXXNameMangler {
310   MicrosoftMangleContextImpl &Context;
311   raw_ostream &Out;
312 
313   /// The "structor" is the top-level declaration being mangled, if
314   /// that's not a template specialization; otherwise it's the pattern
315   /// for that specialization.
316   const NamedDecl *Structor;
317   unsigned StructorType;
318 
319   typedef llvm::SmallVector<std::string, 10> BackRefVec;
320   BackRefVec NameBackReferences;
321 
322   typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
323   ArgBackRefMap FunArgBackReferences;
324   ArgBackRefMap TemplateArgBackReferences;
325 
326   typedef llvm::DenseMap<const void *, StringRef> TemplateArgStringMap;
327   TemplateArgStringMap TemplateArgStrings;
328   llvm::BumpPtrAllocator TemplateArgStringStorageAlloc;
329   llvm::StringSaver TemplateArgStringStorage;
330 
331   typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet;
332   PassObjectSizeArgsSet PassObjectSizeArgs;
333 
334   ASTContext &getASTContext() const { return Context.getASTContext(); }
335 
336   const bool PointersAre64Bit;
337 
338 public:
339   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
340 
341   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
342       : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
343         TemplateArgStringStorage(TemplateArgStringStorageAlloc),
344         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
345                              LangAS::Default) == 64) {}
346 
347   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
348                           const CXXConstructorDecl *D, CXXCtorType Type)
349       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
350         TemplateArgStringStorage(TemplateArgStringStorageAlloc),
351         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
352                              LangAS::Default) == 64) {}
353 
354   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
355                           const CXXDestructorDecl *D, CXXDtorType Type)
356       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
357         TemplateArgStringStorage(TemplateArgStringStorageAlloc),
358         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
359                              LangAS::Default) == 64) {}
360 
361   raw_ostream &getStream() const { return Out; }
362 
363   void mangle(GlobalDecl GD, StringRef Prefix = "?");
364   void mangleName(GlobalDecl GD);
365   void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
366   void mangleVariableEncoding(const VarDecl *VD);
367   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
368                                StringRef Prefix = "$");
369   void mangleMemberDataPointerInClassNTTP(const CXXRecordDecl *,
370                                           const ValueDecl *);
371   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
372                                    const CXXMethodDecl *MD,
373                                    StringRef Prefix = "$");
374   void mangleMemberFunctionPointerInClassNTTP(const CXXRecordDecl *RD,
375                                               const CXXMethodDecl *MD);
376   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
377                                 const MethodVFTableLocation &ML);
378   void mangleNumber(int64_t Number);
379   void mangleNumber(llvm::APSInt Number);
380   void mangleFloat(llvm::APFloat Number);
381   void mangleBits(llvm::APInt Number);
382   void mangleTagTypeKind(TagTypeKind TK);
383   void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
384                                ArrayRef<StringRef> NestedNames = std::nullopt);
385   void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
386   void mangleType(QualType T, SourceRange Range,
387                   QualifierMangleMode QMM = QMM_Mangle);
388   void mangleFunctionType(const FunctionType *T,
389                           const FunctionDecl *D = nullptr,
390                           bool ForceThisQuals = false,
391                           bool MangleExceptionSpec = true);
392   void mangleNestedName(GlobalDecl GD);
393 
394 private:
395   bool isStructorDecl(const NamedDecl *ND) const {
396     return ND == Structor || getStructor(ND) == Structor;
397   }
398 
399   bool is64BitPointer(Qualifiers Quals) const {
400     LangAS AddrSpace = Quals.getAddressSpace();
401     return AddrSpace == LangAS::ptr64 ||
402            (PointersAre64Bit && !(AddrSpace == LangAS::ptr32_sptr ||
403                                   AddrSpace == LangAS::ptr32_uptr));
404   }
405 
406   void mangleUnqualifiedName(GlobalDecl GD) {
407     mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName());
408   }
409   void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
410   void mangleSourceName(StringRef Name);
411   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
412   void mangleCXXDtorType(CXXDtorType T);
413   void mangleQualifiers(Qualifiers Quals, bool IsMember);
414   void mangleRefQualifier(RefQualifierKind RefQualifier);
415   void manglePointerCVQualifiers(Qualifiers Quals);
416   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
417 
418   void mangleUnscopedTemplateName(GlobalDecl GD);
419   void
420   mangleTemplateInstantiationName(GlobalDecl GD,
421                                   const TemplateArgumentList &TemplateArgs);
422   void mangleObjCMethodName(const ObjCMethodDecl *MD);
423 
424   void mangleFunctionArgumentType(QualType T, SourceRange Range);
425   void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
426 
427   bool isArtificialTagType(QualType T) const;
428 
429   // Declare manglers for every type class.
430 #define ABSTRACT_TYPE(CLASS, PARENT)
431 #define NON_CANONICAL_TYPE(CLASS, PARENT)
432 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
433                                             Qualifiers Quals, \
434                                             SourceRange Range);
435 #include "clang/AST/TypeNodes.inc"
436 #undef ABSTRACT_TYPE
437 #undef NON_CANONICAL_TYPE
438 #undef TYPE
439 
440   void mangleType(const TagDecl *TD);
441   void mangleDecayedArrayType(const ArrayType *T);
442   void mangleArrayType(const ArrayType *T);
443   void mangleFunctionClass(const FunctionDecl *FD);
444   void mangleCallingConvention(CallingConv CC);
445   void mangleCallingConvention(const FunctionType *T);
446   void mangleIntegerLiteral(const llvm::APSInt &Number,
447                             const NonTypeTemplateParmDecl *PD = nullptr,
448                             QualType TemplateArgType = QualType());
449   void mangleExpression(const Expr *E, const NonTypeTemplateParmDecl *PD);
450   void mangleThrowSpecification(const FunctionProtoType *T);
451 
452   void mangleTemplateArgs(const TemplateDecl *TD,
453                           const TemplateArgumentList &TemplateArgs);
454   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
455                          const NamedDecl *Parm);
456   void mangleTemplateArgValue(QualType T, const APValue &V,
457                               bool WithScalarType = false);
458 
459   void mangleObjCProtocol(const ObjCProtocolDecl *PD);
460   void mangleObjCLifetime(const QualType T, Qualifiers Quals,
461                           SourceRange Range);
462   void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
463                             SourceRange Range);
464 };
465 }
466 
467 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
468                                                        DiagnosticsEngine &Diags,
469                                                        bool IsAux)
470     : MicrosoftMangleContext(Context, Diags, IsAux) {
471   // To mangle anonymous namespaces, hash the path to the main source file. The
472   // path should be whatever (probably relative) path was passed on the command
473   // line. The goal is for the compiler to produce the same output regardless of
474   // working directory, so use the uncanonicalized relative path.
475   //
476   // It's important to make the mangled names unique because, when CodeView
477   // debug info is in use, the debugger uses mangled type names to distinguish
478   // between otherwise identically named types in anonymous namespaces.
479   //
480   // These symbols are always internal, so there is no need for the hash to
481   // match what MSVC produces. For the same reason, clang is free to change the
482   // hash at any time without breaking compatibility with old versions of clang.
483   // The generated names are intended to look similar to what MSVC generates,
484   // which are something like "?A0x01234567@".
485   SourceManager &SM = Context.getSourceManager();
486   if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
487     // Truncate the hash so we get 8 characters of hexadecimal.
488     uint32_t TruncatedHash = uint32_t(xxh3_64bits(FE->getName()));
489     AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
490   } else {
491     // If we don't have a path to the main file, we'll just use 0.
492     AnonymousNamespaceHash = "0";
493   }
494 }
495 
496 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
497   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
498     LanguageLinkage L = FD->getLanguageLinkage();
499     // Overloadable functions need mangling.
500     if (FD->hasAttr<OverloadableAttr>())
501       return true;
502 
503     // The ABI expects that we would never mangle "typical" user-defined entry
504     // points regardless of visibility or freestanding-ness.
505     //
506     // N.B. This is distinct from asking about "main".  "main" has a lot of
507     // special rules associated with it in the standard while these
508     // user-defined entry points are outside of the purview of the standard.
509     // For example, there can be only one definition for "main" in a standards
510     // compliant program; however nothing forbids the existence of wmain and
511     // WinMain in the same translation unit.
512     if (FD->isMSVCRTEntryPoint())
513       return false;
514 
515     // C++ functions and those whose names are not a simple identifier need
516     // mangling.
517     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
518       return true;
519 
520     // C functions are not mangled.
521     if (L == CLanguageLinkage)
522       return false;
523   }
524 
525   // Otherwise, no mangling is done outside C++ mode.
526   if (!getASTContext().getLangOpts().CPlusPlus)
527     return false;
528 
529   const VarDecl *VD = dyn_cast<VarDecl>(D);
530   if (VD && !isa<DecompositionDecl>(D)) {
531     // C variables are not mangled.
532     if (VD->isExternC())
533       return false;
534 
535     // Variables at global scope with internal linkage are not mangled.
536     const DeclContext *DC = getEffectiveDeclContext(D);
537     // Check for extern variable declared locally.
538     if (DC->isFunctionOrMethod() && D->hasLinkage())
539       while (!DC->isNamespace() && !DC->isTranslationUnit())
540         DC = getEffectiveParentContext(DC);
541 
542     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
543         !isa<VarTemplateSpecializationDecl>(D) &&
544         D->getIdentifier() != nullptr)
545       return false;
546   }
547 
548   return true;
549 }
550 
551 bool
552 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
553   return true;
554 }
555 
556 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
557   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
558   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
559   // Therefore it's really important that we don't decorate the
560   // name with leading underscores or leading/trailing at signs. So, by
561   // default, we emit an asm marker at the start so we get the name right.
562   // Callers can override this with a custom prefix.
563 
564   // <mangled-name> ::= ? <name> <type-encoding>
565   Out << Prefix;
566   mangleName(GD);
567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
568     mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
569   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
570     mangleVariableEncoding(VD);
571   else if (isa<MSGuidDecl>(D))
572     // MSVC appears to mangle GUIDs as if they were variables of type
573     // 'const struct __s_GUID'.
574     Out << "3U__s_GUID@@B";
575   else if (isa<TemplateParamObjectDecl>(D)) {
576     // Template parameter objects don't get a <type-encoding>; their type is
577     // specified as part of their value.
578   } else
579     llvm_unreachable("Tried to mangle unexpected NamedDecl!");
580 }
581 
582 void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
583                                                      bool ShouldMangle) {
584   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
585   // <type-encoding> ::= <function-class> <function-type>
586 
587   // Since MSVC operates on the type as written and not the canonical type, it
588   // actually matters which decl we have here.  MSVC appears to choose the
589   // first, since it is most likely to be the declaration in a header file.
590   FD = FD->getFirstDecl();
591 
592   // We should never ever see a FunctionNoProtoType at this point.
593   // We don't even know how to mangle their types anyway :).
594   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
595 
596   // extern "C" functions can hold entities that must be mangled.
597   // As it stands, these functions still need to get expressed in the full
598   // external name.  They have their class and type omitted, replaced with '9'.
599   if (ShouldMangle) {
600     // We would like to mangle all extern "C" functions using this additional
601     // component but this would break compatibility with MSVC's behavior.
602     // Instead, do this when we know that compatibility isn't important (in
603     // other words, when it is an overloaded extern "C" function).
604     if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
605       Out << "$$J0";
606 
607     mangleFunctionClass(FD);
608 
609     mangleFunctionType(FT, FD, false, false);
610   } else {
611     Out << '9';
612   }
613 }
614 
615 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
616   // <type-encoding> ::= <storage-class> <variable-type>
617   // <storage-class> ::= 0  # private static member
618   //                 ::= 1  # protected static member
619   //                 ::= 2  # public static member
620   //                 ::= 3  # global
621   //                 ::= 4  # static local
622 
623   // The first character in the encoding (after the name) is the storage class.
624   if (VD->isStaticDataMember()) {
625     // If it's a static member, it also encodes the access level.
626     switch (VD->getAccess()) {
627       default:
628       case AS_private: Out << '0'; break;
629       case AS_protected: Out << '1'; break;
630       case AS_public: Out << '2'; break;
631     }
632   }
633   else if (!VD->isStaticLocal())
634     Out << '3';
635   else
636     Out << '4';
637   // Now mangle the type.
638   // <variable-type> ::= <type> <cvr-qualifiers>
639   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
640   // Pointers and references are odd. The type of 'int * const foo;' gets
641   // mangled as 'QAHA' instead of 'PAHB', for example.
642   SourceRange SR = VD->getSourceRange();
643   QualType Ty = VD->getType();
644   if (Ty->isPointerType() || Ty->isReferenceType() ||
645       Ty->isMemberPointerType()) {
646     mangleType(Ty, SR, QMM_Drop);
647     manglePointerExtQualifiers(
648         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
649     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
650       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
651       // Member pointers are suffixed with a back reference to the member
652       // pointer's class name.
653       mangleName(MPT->getClass()->getAsCXXRecordDecl());
654     } else
655       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
656   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
657     // Global arrays are funny, too.
658     mangleDecayedArrayType(AT);
659     if (AT->getElementType()->isArrayType())
660       Out << 'A';
661     else
662       mangleQualifiers(Ty.getQualifiers(), false);
663   } else {
664     mangleType(Ty, SR, QMM_Drop);
665     mangleQualifiers(Ty.getQualifiers(), false);
666   }
667 }
668 
669 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
670                                                       const ValueDecl *VD,
671                                                       StringRef Prefix) {
672   // <member-data-pointer> ::= <integer-literal>
673   //                       ::= $F <number> <number>
674   //                       ::= $G <number> <number> <number>
675 
676   int64_t FieldOffset;
677   int64_t VBTableOffset;
678   MSInheritanceModel IM = RD->getMSInheritanceModel();
679   if (VD) {
680     FieldOffset = getASTContext().getFieldOffset(VD);
681     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
682            "cannot take address of bitfield");
683     FieldOffset /= getASTContext().getCharWidth();
684 
685     VBTableOffset = 0;
686 
687     if (IM == MSInheritanceModel::Virtual)
688       FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
689   } else {
690     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
691 
692     VBTableOffset = -1;
693   }
694 
695   char Code = '\0';
696   switch (IM) {
697   case MSInheritanceModel::Single:      Code = '0'; break;
698   case MSInheritanceModel::Multiple:    Code = '0'; break;
699   case MSInheritanceModel::Virtual:     Code = 'F'; break;
700   case MSInheritanceModel::Unspecified: Code = 'G'; break;
701   }
702 
703   Out << Prefix << Code;
704 
705   mangleNumber(FieldOffset);
706 
707   // The C++ standard doesn't allow base-to-derived member pointer conversions
708   // in template parameter contexts, so the vbptr offset of data member pointers
709   // is always zero.
710   if (inheritanceModelHasVBPtrOffsetField(IM))
711     mangleNumber(0);
712   if (inheritanceModelHasVBTableOffsetField(IM))
713     mangleNumber(VBTableOffset);
714 }
715 
716 void MicrosoftCXXNameMangler::mangleMemberDataPointerInClassNTTP(
717     const CXXRecordDecl *RD, const ValueDecl *VD) {
718   MSInheritanceModel IM = RD->getMSInheritanceModel();
719   // <nttp-class-member-data-pointer> ::= <member-data-pointer>
720   //                                  ::= N
721   //                                  ::= 8 <postfix> @ <unqualified-name> @
722 
723   if (IM != MSInheritanceModel::Single && IM != MSInheritanceModel::Multiple)
724     return mangleMemberDataPointer(RD, VD, "");
725 
726   if (!VD) {
727     Out << 'N';
728     return;
729   }
730 
731   Out << '8';
732   mangleNestedName(VD);
733   Out << '@';
734   mangleUnqualifiedName(VD);
735   Out << '@';
736 }
737 
738 void
739 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
740                                                      const CXXMethodDecl *MD,
741                                                      StringRef Prefix) {
742   // <member-function-pointer> ::= $1? <name>
743   //                           ::= $H? <name> <number>
744   //                           ::= $I? <name> <number> <number>
745   //                           ::= $J? <name> <number> <number> <number>
746 
747   MSInheritanceModel IM = RD->getMSInheritanceModel();
748 
749   char Code = '\0';
750   switch (IM) {
751   case MSInheritanceModel::Single:      Code = '1'; break;
752   case MSInheritanceModel::Multiple:    Code = 'H'; break;
753   case MSInheritanceModel::Virtual:     Code = 'I'; break;
754   case MSInheritanceModel::Unspecified: Code = 'J'; break;
755   }
756 
757   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
758   // thunk.
759   uint64_t NVOffset = 0;
760   uint64_t VBTableOffset = 0;
761   uint64_t VBPtrOffset = 0;
762   if (MD) {
763     Out << Prefix << Code << '?';
764     if (MD->isVirtual()) {
765       MicrosoftVTableContext *VTContext =
766           cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
767       MethodVFTableLocation ML =
768           VTContext->getMethodVFTableLocation(GlobalDecl(MD));
769       mangleVirtualMemPtrThunk(MD, ML);
770       NVOffset = ML.VFPtrOffset.getQuantity();
771       VBTableOffset = ML.VBTableIndex * 4;
772       if (ML.VBase) {
773         const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
774         VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
775       }
776     } else {
777       mangleName(MD);
778       mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
779     }
780 
781     if (VBTableOffset == 0 && IM == MSInheritanceModel::Virtual)
782       NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
783   } else {
784     // Null single inheritance member functions are encoded as a simple nullptr.
785     if (IM == MSInheritanceModel::Single) {
786       Out << Prefix << "0A@";
787       return;
788     }
789     if (IM == MSInheritanceModel::Unspecified)
790       VBTableOffset = -1;
791     Out << Prefix << Code;
792   }
793 
794   if (inheritanceModelHasNVOffsetField(/*IsMemberFunction=*/true, IM))
795     mangleNumber(static_cast<uint32_t>(NVOffset));
796   if (inheritanceModelHasVBPtrOffsetField(IM))
797     mangleNumber(VBPtrOffset);
798   if (inheritanceModelHasVBTableOffsetField(IM))
799     mangleNumber(VBTableOffset);
800 }
801 
802 void MicrosoftCXXNameMangler::mangleMemberFunctionPointerInClassNTTP(
803     const CXXRecordDecl *RD, const CXXMethodDecl *MD) {
804   // <nttp-class-member-function-pointer> ::= <member-function-pointer>
805   //                           ::= N
806   //                           ::= E? <virtual-mem-ptr-thunk>
807   //                           ::= E? <mangled-name> <type-encoding>
808 
809   if (!MD) {
810     if (RD->getMSInheritanceModel() != MSInheritanceModel::Single)
811       return mangleMemberFunctionPointer(RD, MD, "");
812 
813     Out << 'N';
814     return;
815   }
816 
817   Out << "E?";
818   if (MD->isVirtual()) {
819     MicrosoftVTableContext *VTContext =
820         cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
821     MethodVFTableLocation ML =
822         VTContext->getMethodVFTableLocation(GlobalDecl(MD));
823     mangleVirtualMemPtrThunk(MD, ML);
824   } else {
825     mangleName(MD);
826     mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
827   }
828 }
829 
830 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
831     const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
832   // Get the vftable offset.
833   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
834       getASTContext().getTargetInfo().getPointerWidth(LangAS::Default));
835   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
836 
837   Out << "?_9";
838   mangleName(MD->getParent());
839   Out << "$B";
840   mangleNumber(OffsetInVFTable);
841   Out << 'A';
842   mangleCallingConvention(MD->getType()->castAs<FunctionProtoType>());
843 }
844 
845 void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) {
846   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
847 
848   // Always start with the unqualified name.
849   mangleUnqualifiedName(GD);
850 
851   mangleNestedName(GD);
852 
853   // Terminate the whole name with an '@'.
854   Out << '@';
855 }
856 
857 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
858   mangleNumber(llvm::APSInt(llvm::APInt(64, Number), /*IsUnsigned*/false));
859 }
860 
861 void MicrosoftCXXNameMangler::mangleNumber(llvm::APSInt Number) {
862   // MSVC never mangles any integer wider than 64 bits. In general it appears
863   // to convert every integer to signed 64 bit before mangling (including
864   // unsigned 64 bit values). Do the same, but preserve bits beyond the bottom
865   // 64.
866   unsigned Width = std::max(Number.getBitWidth(), 64U);
867   llvm::APInt Value = Number.extend(Width);
868 
869   // <non-negative integer> ::= A@              # when Number == 0
870   //                        ::= <decimal digit> # when 1 <= Number <= 10
871   //                        ::= <hex digit>+ @  # when Number >= 10
872   //
873   // <number>               ::= [?] <non-negative integer>
874 
875   if (Value.isNegative()) {
876     Value = -Value;
877     Out << '?';
878   }
879   mangleBits(Value);
880 }
881 
882 void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) {
883   using llvm::APFloat;
884 
885   switch (APFloat::SemanticsToEnum(Number.getSemantics())) {
886   case APFloat::S_IEEEsingle: Out << 'A'; break;
887   case APFloat::S_IEEEdouble: Out << 'B'; break;
888 
889   // The following are all Clang extensions. We try to pick manglings that are
890   // unlikely to conflict with MSVC's scheme.
891   case APFloat::S_IEEEhalf: Out << 'V'; break;
892   case APFloat::S_BFloat: Out << 'W'; break;
893   case APFloat::S_x87DoubleExtended: Out << 'X'; break;
894   case APFloat::S_IEEEquad: Out << 'Y'; break;
895   case APFloat::S_PPCDoubleDouble: Out << 'Z'; break;
896   case APFloat::S_Float8E5M2:
897   case APFloat::S_Float8E4M3FN:
898   case APFloat::S_Float8E5M2FNUZ:
899   case APFloat::S_Float8E4M3FNUZ:
900   case APFloat::S_Float8E4M3B11FNUZ:
901   case APFloat::S_FloatTF32:
902     llvm_unreachable("Tried to mangle unexpected APFloat semantics");
903   }
904 
905   mangleBits(Number.bitcastToAPInt());
906 }
907 
908 void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) {
909   if (Value == 0)
910     Out << "A@";
911   else if (Value.uge(1) && Value.ule(10))
912     Out << (Value - 1);
913   else {
914     // Numbers that are not encoded as decimal digits are represented as nibbles
915     // in the range of ASCII characters 'A' to 'P'.
916     // The number 0x123450 would be encoded as 'BCDEFA'
917     llvm::SmallString<32> EncodedNumberBuffer;
918     for (; Value != 0; Value.lshrInPlace(4))
919       EncodedNumberBuffer.push_back('A' + (Value & 0xf).getZExtValue());
920     std::reverse(EncodedNumberBuffer.begin(), EncodedNumberBuffer.end());
921     Out.write(EncodedNumberBuffer.data(), EncodedNumberBuffer.size());
922     Out << '@';
923   }
924 }
925 
926 static GlobalDecl isTemplate(GlobalDecl GD,
927                              const TemplateArgumentList *&TemplateArgs) {
928   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
929   // Check if we have a function template.
930   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
931     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
932       TemplateArgs = FD->getTemplateSpecializationArgs();
933       return GD.getWithDecl(TD);
934     }
935   }
936 
937   // Check if we have a class template.
938   if (const ClassTemplateSpecializationDecl *Spec =
939           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
940     TemplateArgs = &Spec->getTemplateArgs();
941     return GD.getWithDecl(Spec->getSpecializedTemplate());
942   }
943 
944   // Check if we have a variable template.
945   if (const VarTemplateSpecializationDecl *Spec =
946           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
947     TemplateArgs = &Spec->getTemplateArgs();
948     return GD.getWithDecl(Spec->getSpecializedTemplate());
949   }
950 
951   return GlobalDecl();
952 }
953 
954 void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
955                                                     DeclarationName Name) {
956   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
957   //  <unqualified-name> ::= <operator-name>
958   //                     ::= <ctor-dtor-name>
959   //                     ::= <source-name>
960   //                     ::= <template-name>
961 
962   // Check if we have a template.
963   const TemplateArgumentList *TemplateArgs = nullptr;
964   if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
965     // Function templates aren't considered for name back referencing.  This
966     // makes sense since function templates aren't likely to occur multiple
967     // times in a symbol.
968     if (isa<FunctionTemplateDecl>(TD.getDecl())) {
969       mangleTemplateInstantiationName(TD, *TemplateArgs);
970       Out << '@';
971       return;
972     }
973 
974     // Here comes the tricky thing: if we need to mangle something like
975     //   void foo(A::X<Y>, B::X<Y>),
976     // the X<Y> part is aliased. However, if you need to mangle
977     //   void foo(A::X<A::Y>, A::X<B::Y>),
978     // the A::X<> part is not aliased.
979     // That is, from the mangler's perspective we have a structure like this:
980     //   namespace[s] -> type[ -> template-parameters]
981     // but from the Clang perspective we have
982     //   type [ -> template-parameters]
983     //      \-> namespace[s]
984     // What we do is we create a new mangler, mangle the same type (without
985     // a namespace suffix) to a string using the extra mangler and then use
986     // the mangled type name as a key to check the mangling of different types
987     // for aliasing.
988 
989     // It's important to key cache reads off ND, not TD -- the same TD can
990     // be used with different TemplateArgs, but ND uniquely identifies
991     // TD / TemplateArg pairs.
992     ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND);
993     if (Found == TemplateArgBackReferences.end()) {
994 
995       TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND);
996       if (Found == TemplateArgStrings.end()) {
997         // Mangle full template name into temporary buffer.
998         llvm::SmallString<64> TemplateMangling;
999         llvm::raw_svector_ostream Stream(TemplateMangling);
1000         MicrosoftCXXNameMangler Extra(Context, Stream);
1001         Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
1002 
1003         // Use the string backref vector to possibly get a back reference.
1004         mangleSourceName(TemplateMangling);
1005 
1006         // Memoize back reference for this type if one exist, else memoize
1007         // the mangling itself.
1008         BackRefVec::iterator StringFound =
1009             llvm::find(NameBackReferences, TemplateMangling);
1010         if (StringFound != NameBackReferences.end()) {
1011           TemplateArgBackReferences[ND] =
1012               StringFound - NameBackReferences.begin();
1013         } else {
1014           TemplateArgStrings[ND] =
1015               TemplateArgStringStorage.save(TemplateMangling.str());
1016         }
1017       } else {
1018         Out << Found->second << '@'; // Outputs a StringRef.
1019       }
1020     } else {
1021       Out << Found->second; // Outputs a back reference (an int).
1022     }
1023     return;
1024   }
1025 
1026   switch (Name.getNameKind()) {
1027     case DeclarationName::Identifier: {
1028       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1029         bool IsDeviceStub =
1030             ND &&
1031             ((isa<FunctionDecl>(ND) && ND->hasAttr<CUDAGlobalAttr>()) ||
1032              (isa<FunctionTemplateDecl>(ND) &&
1033               cast<FunctionTemplateDecl>(ND)
1034                   ->getTemplatedDecl()
1035                   ->hasAttr<CUDAGlobalAttr>())) &&
1036             GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1037         if (IsDeviceStub)
1038           mangleSourceName(
1039               (llvm::Twine("__device_stub__") + II->getName()).str());
1040         else
1041           mangleSourceName(II->getName());
1042         break;
1043       }
1044 
1045       // Otherwise, an anonymous entity.  We must have a declaration.
1046       assert(ND && "mangling empty name without declaration");
1047 
1048       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1049         if (NS->isAnonymousNamespace()) {
1050           Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
1051           break;
1052         }
1053       }
1054 
1055       if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
1056         // Decomposition declarations are considered anonymous, and get
1057         // numbered with a $S prefix.
1058         llvm::SmallString<64> Name("$S");
1059         // Get a unique id for the anonymous struct.
1060         Name += llvm::utostr(Context.getAnonymousStructId(DD) + 1);
1061         mangleSourceName(Name);
1062         break;
1063       }
1064 
1065       if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1066         // We must have an anonymous union or struct declaration.
1067         const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
1068         assert(RD && "expected variable decl to have a record type");
1069         // Anonymous types with no tag or typedef get the name of their
1070         // declarator mangled in.  If they have no declarator, number them with
1071         // a $S prefix.
1072         llvm::SmallString<64> Name("$S");
1073         // Get a unique id for the anonymous struct.
1074         Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
1075         mangleSourceName(Name.str());
1076         break;
1077       }
1078 
1079       if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(ND)) {
1080         // Mangle a GUID object as if it were a variable with the corresponding
1081         // mangled name.
1082         SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1083         llvm::raw_svector_ostream GUIDOS(GUID);
1084         Context.mangleMSGuidDecl(GD, GUIDOS);
1085         mangleSourceName(GUID);
1086         break;
1087       }
1088 
1089       if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1090         Out << "?__N";
1091         mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1092                                TPO->getValue());
1093         break;
1094       }
1095 
1096       // We must have an anonymous struct.
1097       const TagDecl *TD = cast<TagDecl>(ND);
1098       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1099         assert(TD->getDeclContext() == D->getDeclContext() &&
1100                "Typedef should not be in another decl context!");
1101         assert(D->getDeclName().getAsIdentifierInfo() &&
1102                "Typedef was not named!");
1103         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
1104         break;
1105       }
1106 
1107       if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1108         if (Record->isLambda()) {
1109           llvm::SmallString<10> Name("<lambda_");
1110 
1111           Decl *LambdaContextDecl = Record->getLambdaContextDecl();
1112           unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
1113           unsigned LambdaId;
1114           const ParmVarDecl *Parm =
1115               dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
1116           const FunctionDecl *Func =
1117               Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
1118 
1119           if (Func) {
1120             unsigned DefaultArgNo =
1121                 Func->getNumParams() - Parm->getFunctionScopeIndex();
1122             Name += llvm::utostr(DefaultArgNo);
1123             Name += "_";
1124           }
1125 
1126           if (LambdaManglingNumber)
1127             LambdaId = LambdaManglingNumber;
1128           else
1129             LambdaId = Context.getLambdaId(Record);
1130 
1131           Name += llvm::utostr(LambdaId);
1132           Name += ">";
1133 
1134           mangleSourceName(Name);
1135 
1136           // If the context is a variable or a class member and not a parameter,
1137           // it is encoded in a qualified name.
1138           if (LambdaManglingNumber && LambdaContextDecl) {
1139             if ((isa<VarDecl>(LambdaContextDecl) ||
1140                  isa<FieldDecl>(LambdaContextDecl)) &&
1141                 !isa<ParmVarDecl>(LambdaContextDecl)) {
1142               mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
1143             }
1144           }
1145           break;
1146         }
1147       }
1148 
1149       llvm::SmallString<64> Name;
1150       if (DeclaratorDecl *DD =
1151               Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
1152         // Anonymous types without a name for linkage purposes have their
1153         // declarator mangled in if they have one.
1154         Name += "<unnamed-type-";
1155         Name += DD->getName();
1156       } else if (TypedefNameDecl *TND =
1157                      Context.getASTContext().getTypedefNameForUnnamedTagDecl(
1158                          TD)) {
1159         // Anonymous types without a name for linkage purposes have their
1160         // associate typedef mangled in if they have one.
1161         Name += "<unnamed-type-";
1162         Name += TND->getName();
1163       } else if (isa<EnumDecl>(TD) &&
1164                  cast<EnumDecl>(TD)->enumerator_begin() !=
1165                      cast<EnumDecl>(TD)->enumerator_end()) {
1166         // Anonymous non-empty enums mangle in the first enumerator.
1167         auto *ED = cast<EnumDecl>(TD);
1168         Name += "<unnamed-enum-";
1169         Name += ED->enumerator_begin()->getName();
1170       } else {
1171         // Otherwise, number the types using a $S prefix.
1172         Name += "<unnamed-type-$S";
1173         Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
1174       }
1175       Name += ">";
1176       mangleSourceName(Name.str());
1177       break;
1178     }
1179 
1180     case DeclarationName::ObjCZeroArgSelector:
1181     case DeclarationName::ObjCOneArgSelector:
1182     case DeclarationName::ObjCMultiArgSelector: {
1183       // This is reachable only when constructing an outlined SEH finally
1184       // block.  Nothing depends on this mangling and it's used only with
1185       // functinos with internal linkage.
1186       llvm::SmallString<64> Name;
1187       mangleSourceName(Name.str());
1188       break;
1189     }
1190 
1191     case DeclarationName::CXXConstructorName:
1192       if (isStructorDecl(ND)) {
1193         if (StructorType == Ctor_CopyingClosure) {
1194           Out << "?_O";
1195           return;
1196         }
1197         if (StructorType == Ctor_DefaultClosure) {
1198           Out << "?_F";
1199           return;
1200         }
1201       }
1202       Out << "?0";
1203       return;
1204 
1205     case DeclarationName::CXXDestructorName:
1206       if (isStructorDecl(ND))
1207         // If the named decl is the C++ destructor we're mangling,
1208         // use the type we were given.
1209         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1210       else
1211         // Otherwise, use the base destructor name. This is relevant if a
1212         // class with a destructor is declared within a destructor.
1213         mangleCXXDtorType(Dtor_Base);
1214       break;
1215 
1216     case DeclarationName::CXXConversionFunctionName:
1217       // <operator-name> ::= ?B # (cast)
1218       // The target type is encoded as the return type.
1219       Out << "?B";
1220       break;
1221 
1222     case DeclarationName::CXXOperatorName:
1223       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
1224       break;
1225 
1226     case DeclarationName::CXXLiteralOperatorName: {
1227       Out << "?__K";
1228       mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
1229       break;
1230     }
1231 
1232     case DeclarationName::CXXDeductionGuideName:
1233       llvm_unreachable("Can't mangle a deduction guide name!");
1234 
1235     case DeclarationName::CXXUsingDirective:
1236       llvm_unreachable("Can't mangle a using directive name!");
1237   }
1238 }
1239 
1240 // <postfix> ::= <unqualified-name> [<postfix>]
1241 //           ::= <substitution> [<postfix>]
1242 void MicrosoftCXXNameMangler::mangleNestedName(GlobalDecl GD) {
1243   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1244 
1245   if (const auto *ID = dyn_cast<IndirectFieldDecl>(ND))
1246     for (unsigned I = 1, IE = ID->getChainingSize(); I < IE; ++I)
1247       mangleSourceName("<unnamed-tag>");
1248 
1249   const DeclContext *DC = getEffectiveDeclContext(ND);
1250   while (!DC->isTranslationUnit()) {
1251     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1252       unsigned Disc;
1253       if (Context.getNextDiscriminator(ND, Disc)) {
1254         Out << '?';
1255         mangleNumber(Disc);
1256         Out << '?';
1257       }
1258     }
1259 
1260     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1261       auto Discriminate =
1262           [](StringRef Name, const unsigned Discriminator,
1263              const unsigned ParameterDiscriminator) -> std::string {
1264         std::string Buffer;
1265         llvm::raw_string_ostream Stream(Buffer);
1266         Stream << Name;
1267         if (Discriminator)
1268           Stream << '_' << Discriminator;
1269         if (ParameterDiscriminator)
1270           Stream << '_' << ParameterDiscriminator;
1271         return Stream.str();
1272       };
1273 
1274       unsigned Discriminator = BD->getBlockManglingNumber();
1275       if (!Discriminator)
1276         Discriminator = Context.getBlockId(BD, /*Local=*/false);
1277 
1278       // Mangle the parameter position as a discriminator to deal with unnamed
1279       // parameters.  Rather than mangling the unqualified parameter name,
1280       // always use the position to give a uniform mangling.
1281       unsigned ParameterDiscriminator = 0;
1282       if (const auto *MC = BD->getBlockManglingContextDecl())
1283         if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1284           if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1285             ParameterDiscriminator =
1286                 F->getNumParams() - P->getFunctionScopeIndex();
1287 
1288       DC = getEffectiveDeclContext(BD);
1289 
1290       Out << '?';
1291       mangleSourceName(Discriminate("_block_invoke", Discriminator,
1292                                     ParameterDiscriminator));
1293       // If we have a block mangling context, encode that now.  This allows us
1294       // to discriminate between named static data initializers in the same
1295       // scope.  This is handled differently from parameters, which use
1296       // positions to discriminate between multiple instances.
1297       if (const auto *MC = BD->getBlockManglingContextDecl())
1298         if (!isa<ParmVarDecl>(MC))
1299           if (const auto *ND = dyn_cast<NamedDecl>(MC))
1300             mangleUnqualifiedName(ND);
1301       // MS ABI and Itanium manglings are in inverted scopes.  In the case of a
1302       // RecordDecl, mangle the entire scope hierarchy at this point rather than
1303       // just the unqualified name to get the ordering correct.
1304       if (const auto *RD = dyn_cast<RecordDecl>(DC))
1305         mangleName(RD);
1306       else
1307         Out << '@';
1308       // void __cdecl
1309       Out << "YAX";
1310       // struct __block_literal *
1311       Out << 'P';
1312       // __ptr64
1313       if (PointersAre64Bit)
1314         Out << 'E';
1315       Out << 'A';
1316       mangleArtificialTagType(TTK_Struct,
1317                              Discriminate("__block_literal", Discriminator,
1318                                           ParameterDiscriminator));
1319       Out << "@Z";
1320 
1321       // If the effective context was a Record, we have fully mangled the
1322       // qualified name and do not need to continue.
1323       if (isa<RecordDecl>(DC))
1324         break;
1325       continue;
1326     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1327       mangleObjCMethodName(Method);
1328     } else if (isa<NamedDecl>(DC)) {
1329       ND = cast<NamedDecl>(DC);
1330       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1331         mangle(getGlobalDeclAsDeclContext(FD), "?");
1332         break;
1333       } else {
1334         mangleUnqualifiedName(ND);
1335         // Lambdas in default arguments conceptually belong to the function the
1336         // parameter corresponds to.
1337         if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1338           DC = LDADC;
1339           continue;
1340         }
1341       }
1342     }
1343     DC = DC->getParent();
1344   }
1345 }
1346 
1347 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1348   // Microsoft uses the names on the case labels for these dtor variants.  Clang
1349   // uses the Itanium terminology internally.  Everything in this ABI delegates
1350   // towards the base dtor.
1351   switch (T) {
1352   // <operator-name> ::= ?1  # destructor
1353   case Dtor_Base: Out << "?1"; return;
1354   // <operator-name> ::= ?_D # vbase destructor
1355   case Dtor_Complete: Out << "?_D"; return;
1356   // <operator-name> ::= ?_G # scalar deleting destructor
1357   case Dtor_Deleting: Out << "?_G"; return;
1358   // <operator-name> ::= ?_E # vector deleting destructor
1359   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
1360   // it.
1361   case Dtor_Comdat:
1362     llvm_unreachable("not expecting a COMDAT");
1363   }
1364   llvm_unreachable("Unsupported dtor type?");
1365 }
1366 
1367 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1368                                                  SourceLocation Loc) {
1369   switch (OO) {
1370   //                     ?0 # constructor
1371   //                     ?1 # destructor
1372   // <operator-name> ::= ?2 # new
1373   case OO_New: Out << "?2"; break;
1374   // <operator-name> ::= ?3 # delete
1375   case OO_Delete: Out << "?3"; break;
1376   // <operator-name> ::= ?4 # =
1377   case OO_Equal: Out << "?4"; break;
1378   // <operator-name> ::= ?5 # >>
1379   case OO_GreaterGreater: Out << "?5"; break;
1380   // <operator-name> ::= ?6 # <<
1381   case OO_LessLess: Out << "?6"; break;
1382   // <operator-name> ::= ?7 # !
1383   case OO_Exclaim: Out << "?7"; break;
1384   // <operator-name> ::= ?8 # ==
1385   case OO_EqualEqual: Out << "?8"; break;
1386   // <operator-name> ::= ?9 # !=
1387   case OO_ExclaimEqual: Out << "?9"; break;
1388   // <operator-name> ::= ?A # []
1389   case OO_Subscript: Out << "?A"; break;
1390   //                     ?B # conversion
1391   // <operator-name> ::= ?C # ->
1392   case OO_Arrow: Out << "?C"; break;
1393   // <operator-name> ::= ?D # *
1394   case OO_Star: Out << "?D"; break;
1395   // <operator-name> ::= ?E # ++
1396   case OO_PlusPlus: Out << "?E"; break;
1397   // <operator-name> ::= ?F # --
1398   case OO_MinusMinus: Out << "?F"; break;
1399   // <operator-name> ::= ?G # -
1400   case OO_Minus: Out << "?G"; break;
1401   // <operator-name> ::= ?H # +
1402   case OO_Plus: Out << "?H"; break;
1403   // <operator-name> ::= ?I # &
1404   case OO_Amp: Out << "?I"; break;
1405   // <operator-name> ::= ?J # ->*
1406   case OO_ArrowStar: Out << "?J"; break;
1407   // <operator-name> ::= ?K # /
1408   case OO_Slash: Out << "?K"; break;
1409   // <operator-name> ::= ?L # %
1410   case OO_Percent: Out << "?L"; break;
1411   // <operator-name> ::= ?M # <
1412   case OO_Less: Out << "?M"; break;
1413   // <operator-name> ::= ?N # <=
1414   case OO_LessEqual: Out << "?N"; break;
1415   // <operator-name> ::= ?O # >
1416   case OO_Greater: Out << "?O"; break;
1417   // <operator-name> ::= ?P # >=
1418   case OO_GreaterEqual: Out << "?P"; break;
1419   // <operator-name> ::= ?Q # ,
1420   case OO_Comma: Out << "?Q"; break;
1421   // <operator-name> ::= ?R # ()
1422   case OO_Call: Out << "?R"; break;
1423   // <operator-name> ::= ?S # ~
1424   case OO_Tilde: Out << "?S"; break;
1425   // <operator-name> ::= ?T # ^
1426   case OO_Caret: Out << "?T"; break;
1427   // <operator-name> ::= ?U # |
1428   case OO_Pipe: Out << "?U"; break;
1429   // <operator-name> ::= ?V # &&
1430   case OO_AmpAmp: Out << "?V"; break;
1431   // <operator-name> ::= ?W # ||
1432   case OO_PipePipe: Out << "?W"; break;
1433   // <operator-name> ::= ?X # *=
1434   case OO_StarEqual: Out << "?X"; break;
1435   // <operator-name> ::= ?Y # +=
1436   case OO_PlusEqual: Out << "?Y"; break;
1437   // <operator-name> ::= ?Z # -=
1438   case OO_MinusEqual: Out << "?Z"; break;
1439   // <operator-name> ::= ?_0 # /=
1440   case OO_SlashEqual: Out << "?_0"; break;
1441   // <operator-name> ::= ?_1 # %=
1442   case OO_PercentEqual: Out << "?_1"; break;
1443   // <operator-name> ::= ?_2 # >>=
1444   case OO_GreaterGreaterEqual: Out << "?_2"; break;
1445   // <operator-name> ::= ?_3 # <<=
1446   case OO_LessLessEqual: Out << "?_3"; break;
1447   // <operator-name> ::= ?_4 # &=
1448   case OO_AmpEqual: Out << "?_4"; break;
1449   // <operator-name> ::= ?_5 # |=
1450   case OO_PipeEqual: Out << "?_5"; break;
1451   // <operator-name> ::= ?_6 # ^=
1452   case OO_CaretEqual: Out << "?_6"; break;
1453   //                     ?_7 # vftable
1454   //                     ?_8 # vbtable
1455   //                     ?_9 # vcall
1456   //                     ?_A # typeof
1457   //                     ?_B # local static guard
1458   //                     ?_C # string
1459   //                     ?_D # vbase destructor
1460   //                     ?_E # vector deleting destructor
1461   //                     ?_F # default constructor closure
1462   //                     ?_G # scalar deleting destructor
1463   //                     ?_H # vector constructor iterator
1464   //                     ?_I # vector destructor iterator
1465   //                     ?_J # vector vbase constructor iterator
1466   //                     ?_K # virtual displacement map
1467   //                     ?_L # eh vector constructor iterator
1468   //                     ?_M # eh vector destructor iterator
1469   //                     ?_N # eh vector vbase constructor iterator
1470   //                     ?_O # copy constructor closure
1471   //                     ?_P<name> # udt returning <name>
1472   //                     ?_Q # <unknown>
1473   //                     ?_R0 # RTTI Type Descriptor
1474   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1475   //                     ?_R2 # RTTI Base Class Array
1476   //                     ?_R3 # RTTI Class Hierarchy Descriptor
1477   //                     ?_R4 # RTTI Complete Object Locator
1478   //                     ?_S # local vftable
1479   //                     ?_T # local vftable constructor closure
1480   // <operator-name> ::= ?_U # new[]
1481   case OO_Array_New: Out << "?_U"; break;
1482   // <operator-name> ::= ?_V # delete[]
1483   case OO_Array_Delete: Out << "?_V"; break;
1484   // <operator-name> ::= ?__L # co_await
1485   case OO_Coawait: Out << "?__L"; break;
1486   // <operator-name> ::= ?__M # <=>
1487   case OO_Spaceship: Out << "?__M"; break;
1488 
1489   case OO_Conditional: {
1490     DiagnosticsEngine &Diags = Context.getDiags();
1491     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1492       "cannot mangle this conditional operator yet");
1493     Diags.Report(Loc, DiagID);
1494     break;
1495   }
1496 
1497   case OO_None:
1498   case NUM_OVERLOADED_OPERATORS:
1499     llvm_unreachable("Not an overloaded operator");
1500   }
1501 }
1502 
1503 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1504   // <source name> ::= <identifier> @
1505   BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
1506   if (Found == NameBackReferences.end()) {
1507     if (NameBackReferences.size() < 10)
1508       NameBackReferences.push_back(std::string(Name));
1509     Out << Name << '@';
1510   } else {
1511     Out << (Found - NameBackReferences.begin());
1512   }
1513 }
1514 
1515 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1516   Context.mangleObjCMethodNameAsSourceName(MD, Out);
1517 }
1518 
1519 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1520     GlobalDecl GD, const TemplateArgumentList &TemplateArgs) {
1521   // <template-name> ::= <unscoped-template-name> <template-args>
1522   //                 ::= <substitution>
1523   // Always start with the unqualified name.
1524 
1525   // Templates have their own context for back references.
1526   ArgBackRefMap OuterFunArgsContext;
1527   ArgBackRefMap OuterTemplateArgsContext;
1528   BackRefVec OuterTemplateContext;
1529   PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1530   NameBackReferences.swap(OuterTemplateContext);
1531   FunArgBackReferences.swap(OuterFunArgsContext);
1532   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1533   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1534 
1535   mangleUnscopedTemplateName(GD);
1536   mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs);
1537 
1538   // Restore the previous back reference contexts.
1539   NameBackReferences.swap(OuterTemplateContext);
1540   FunArgBackReferences.swap(OuterFunArgsContext);
1541   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1542   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1543 }
1544 
1545 void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) {
1546   // <unscoped-template-name> ::= ?$ <unqualified-name>
1547   Out << "?$";
1548   mangleUnqualifiedName(GD);
1549 }
1550 
1551 void MicrosoftCXXNameMangler::mangleIntegerLiteral(
1552     const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD,
1553     QualType TemplateArgType) {
1554   // <integer-literal> ::= $0 <number>
1555   Out << "$";
1556 
1557   // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when
1558   // argument is integer.
1559   if (getASTContext().getLangOpts().isCompatibleWithMSVC(
1560           LangOptions::MSVC2019) &&
1561       PD && PD->getType()->getTypeClass() == Type::Auto &&
1562       !TemplateArgType.isNull()) {
1563     Out << "M";
1564     mangleType(TemplateArgType, SourceRange(), QMM_Drop);
1565   }
1566 
1567   Out << "0";
1568 
1569   mangleNumber(Value);
1570 }
1571 
1572 void MicrosoftCXXNameMangler::mangleExpression(
1573     const Expr *E, const NonTypeTemplateParmDecl *PD) {
1574   // See if this is a constant expression.
1575   if (std::optional<llvm::APSInt> Value =
1576           E->getIntegerConstantExpr(Context.getASTContext())) {
1577     mangleIntegerLiteral(*Value, PD, E->getType());
1578     return;
1579   }
1580 
1581   // As bad as this diagnostic is, it's better than crashing.
1582   DiagnosticsEngine &Diags = Context.getDiags();
1583   unsigned DiagID = Diags.getCustomDiagID(
1584       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1585   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1586                                         << E->getSourceRange();
1587 }
1588 
1589 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1590     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1591   // <template-args> ::= <template-arg>+
1592   const TemplateParameterList *TPL = TD->getTemplateParameters();
1593   assert(TPL->size() == TemplateArgs.size() &&
1594          "size mismatch between args and parms!");
1595 
1596   for (size_t i = 0; i < TemplateArgs.size(); ++i) {
1597     const TemplateArgument &TA = TemplateArgs[i];
1598 
1599     // Separate consecutive packs by $$Z.
1600     if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
1601         TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
1602       Out << "$$Z";
1603 
1604     mangleTemplateArg(TD, TA, TPL->getParam(i));
1605   }
1606 }
1607 
1608 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1609                                                 const TemplateArgument &TA,
1610                                                 const NamedDecl *Parm) {
1611   // <template-arg> ::= <type>
1612   //                ::= <integer-literal>
1613   //                ::= <member-data-pointer>
1614   //                ::= <member-function-pointer>
1615   //                ::= $ <constant-value>
1616   //                ::= <template-args>
1617   //
1618   // <constant-value> ::= 0 <number>                   # integer
1619   //                  ::= 1 <mangled-name>             # address of D
1620   //                  ::= 2 <type> <typed-constant-value>* @ # struct
1621   //                  ::= 3 <type> <constant-value>* @ # array
1622   //                  ::= 4 ???                        # string
1623   //                  ::= 5 <constant-value> @         # address of subobject
1624   //                  ::= 6 <constant-value> <unqualified-name> @ # a.b
1625   //                  ::= 7 <type> [<unqualified-name> <constant-value>] @
1626   //                      # union, with or without an active member
1627   //                  # pointer to member, symbolically
1628   //                  ::= 8 <class> <unqualified-name> @
1629   //                  ::= A <type> <non-negative integer>  # float
1630   //                  ::= B <type> <non-negative integer>  # double
1631   //                  # pointer to member, by component value
1632   //                  ::= F <number> <number>
1633   //                  ::= G <number> <number> <number>
1634   //                  ::= H <mangled-name> <number>
1635   //                  ::= I <mangled-name> <number> <number>
1636   //                  ::= J <mangled-name> <number> <number> <number>
1637   //
1638   // <typed-constant-value> ::= [<type>] <constant-value>
1639   //
1640   // The <type> appears to be included in a <typed-constant-value> only in the
1641   // '0', '1', '8', 'A', 'B', and 'E' cases.
1642 
1643   switch (TA.getKind()) {
1644   case TemplateArgument::Null:
1645     llvm_unreachable("Can't mangle null template arguments!");
1646   case TemplateArgument::TemplateExpansion:
1647     llvm_unreachable("Can't mangle template expansion arguments!");
1648   case TemplateArgument::Type: {
1649     QualType T = TA.getAsType();
1650     mangleType(T, SourceRange(), QMM_Escape);
1651     break;
1652   }
1653   case TemplateArgument::Declaration: {
1654     const NamedDecl *ND = TA.getAsDecl();
1655     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1656       mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1657                                   ->getMostRecentNonInjectedDecl(),
1658                               cast<ValueDecl>(ND));
1659     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1660       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1661       if (MD && MD->isInstance()) {
1662         mangleMemberFunctionPointer(
1663             MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1664       } else {
1665         Out << "$1?";
1666         mangleName(FD);
1667         mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1668       }
1669     } else if (TA.getParamTypeForDecl()->isRecordType()) {
1670       Out << "$";
1671       auto *TPO = cast<TemplateParamObjectDecl>(ND);
1672       mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1673                              TPO->getValue());
1674     } else {
1675       mangle(ND, "$1?");
1676     }
1677     break;
1678   }
1679   case TemplateArgument::Integral: {
1680     QualType T = TA.getIntegralType();
1681     mangleIntegerLiteral(TA.getAsIntegral(),
1682                          cast<NonTypeTemplateParmDecl>(Parm), T);
1683     break;
1684   }
1685   case TemplateArgument::NullPtr: {
1686     QualType T = TA.getNullPtrType();
1687     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1688       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1689       if (MPT->isMemberFunctionPointerType() &&
1690           !isa<FunctionTemplateDecl>(TD)) {
1691         mangleMemberFunctionPointer(RD, nullptr);
1692         return;
1693       }
1694       if (MPT->isMemberDataPointer()) {
1695         if (!isa<FunctionTemplateDecl>(TD)) {
1696           mangleMemberDataPointer(RD, nullptr);
1697           return;
1698         }
1699         // nullptr data pointers are always represented with a single field
1700         // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1701         // distinguish the case where the data member is at offset zero in the
1702         // record.
1703         // However, we are free to use 0 *if* we would use multiple fields for
1704         // non-nullptr member pointers.
1705         if (!RD->nullFieldOffsetIsZero()) {
1706           mangleIntegerLiteral(llvm::APSInt::get(-1),
1707                                cast<NonTypeTemplateParmDecl>(Parm), T);
1708           return;
1709         }
1710       }
1711     }
1712     mangleIntegerLiteral(llvm::APSInt::getUnsigned(0),
1713                          cast<NonTypeTemplateParmDecl>(Parm), T);
1714     break;
1715   }
1716   case TemplateArgument::Expression:
1717     mangleExpression(TA.getAsExpr(), cast<NonTypeTemplateParmDecl>(Parm));
1718     break;
1719   case TemplateArgument::Pack: {
1720     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1721     if (TemplateArgs.empty()) {
1722       if (isa<TemplateTypeParmDecl>(Parm) ||
1723           isa<TemplateTemplateParmDecl>(Parm))
1724         // MSVC 2015 changed the mangling for empty expanded template packs,
1725         // use the old mangling for link compatibility for old versions.
1726         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1727                     LangOptions::MSVC2015)
1728                     ? "$$V"
1729                     : "$$$V");
1730       else if (isa<NonTypeTemplateParmDecl>(Parm))
1731         Out << "$S";
1732       else
1733         llvm_unreachable("unexpected template parameter decl!");
1734     } else {
1735       for (const TemplateArgument &PA : TemplateArgs)
1736         mangleTemplateArg(TD, PA, Parm);
1737     }
1738     break;
1739   }
1740   case TemplateArgument::Template: {
1741     const NamedDecl *ND =
1742         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1743     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1744       mangleType(TD);
1745     } else if (isa<TypeAliasDecl>(ND)) {
1746       Out << "$$Y";
1747       mangleName(ND);
1748     } else {
1749       llvm_unreachable("unexpected template template NamedDecl!");
1750     }
1751     break;
1752   }
1753   }
1754 }
1755 
1756 void MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
1757                                                      const APValue &V,
1758                                                      bool WithScalarType) {
1759   switch (V.getKind()) {
1760   case APValue::None:
1761   case APValue::Indeterminate:
1762     // FIXME: MSVC doesn't allow this, so we can't be sure how it should be
1763     // mangled.
1764     if (WithScalarType)
1765       mangleType(T, SourceRange(), QMM_Escape);
1766     Out << '@';
1767     return;
1768 
1769   case APValue::Int:
1770     if (WithScalarType)
1771       mangleType(T, SourceRange(), QMM_Escape);
1772     Out << '0';
1773     mangleNumber(V.getInt());
1774     return;
1775 
1776   case APValue::Float:
1777     if (WithScalarType)
1778       mangleType(T, SourceRange(), QMM_Escape);
1779     mangleFloat(V.getFloat());
1780     return;
1781 
1782   case APValue::LValue: {
1783     if (WithScalarType)
1784       mangleType(T, SourceRange(), QMM_Escape);
1785 
1786     // We don't know how to mangle past-the-end pointers yet.
1787     if (V.isLValueOnePastTheEnd())
1788       break;
1789 
1790     APValue::LValueBase Base = V.getLValueBase();
1791     if (!V.hasLValuePath() || V.getLValuePath().empty()) {
1792       // Taking the address of a complete object has a special-case mangling.
1793       if (Base.isNull()) {
1794         // MSVC emits 0A@ for null pointers. Generalize this for arbitrary
1795         // integers cast to pointers.
1796         // FIXME: This mangles 0 cast to a pointer the same as a null pointer,
1797         // even in cases where the two are different values.
1798         Out << "0";
1799         mangleNumber(V.getLValueOffset().getQuantity());
1800       } else if (!V.hasLValuePath()) {
1801         // FIXME: This can only happen as an extension. Invent a mangling.
1802         break;
1803       } else if (auto *VD = Base.dyn_cast<const ValueDecl*>()) {
1804         Out << "E";
1805         mangle(VD);
1806       } else {
1807         break;
1808       }
1809     } else {
1810       if (T->isPointerType())
1811         Out << "5";
1812 
1813       SmallVector<char, 2> EntryTypes;
1814       SmallVector<std::function<void()>, 2> EntryManglers;
1815       QualType ET = Base.getType();
1816       for (APValue::LValuePathEntry E : V.getLValuePath()) {
1817         if (auto *AT = ET->getAsArrayTypeUnsafe()) {
1818           EntryTypes.push_back('C');
1819           EntryManglers.push_back([this, I = E.getAsArrayIndex()] {
1820             Out << '0';
1821             mangleNumber(I);
1822             Out << '@';
1823           });
1824           ET = AT->getElementType();
1825           continue;
1826         }
1827 
1828         const Decl *D = E.getAsBaseOrMember().getPointer();
1829         if (auto *FD = dyn_cast<FieldDecl>(D)) {
1830           ET = FD->getType();
1831           if (const auto *RD = ET->getAsRecordDecl())
1832             if (RD->isAnonymousStructOrUnion())
1833               continue;
1834         } else {
1835           ET = getASTContext().getRecordType(cast<CXXRecordDecl>(D));
1836           // Bug in MSVC: fully qualified name of base class should be used for
1837           // mangling to prevent collisions e.g. on base classes with same names
1838           // in different namespaces.
1839         }
1840 
1841         EntryTypes.push_back('6');
1842         EntryManglers.push_back([this, D] {
1843           mangleUnqualifiedName(cast<NamedDecl>(D));
1844           Out << '@';
1845         });
1846       }
1847 
1848       for (auto I = EntryTypes.rbegin(), E = EntryTypes.rend(); I != E; ++I)
1849         Out << *I;
1850 
1851       auto *VD = Base.dyn_cast<const ValueDecl*>();
1852       if (!VD)
1853         break;
1854       Out << "E";
1855       mangle(VD);
1856 
1857       for (const std::function<void()> &Mangler : EntryManglers)
1858         Mangler();
1859       if (T->isPointerType())
1860         Out << '@';
1861     }
1862 
1863     return;
1864   }
1865 
1866   case APValue::MemberPointer: {
1867     if (WithScalarType)
1868       mangleType(T, SourceRange(), QMM_Escape);
1869 
1870     const CXXRecordDecl *RD =
1871         T->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
1872     const ValueDecl *D = V.getMemberPointerDecl();
1873     if (T->isMemberDataPointerType())
1874       mangleMemberDataPointerInClassNTTP(RD, D);
1875     else
1876       mangleMemberFunctionPointerInClassNTTP(RD,
1877                                              cast_or_null<CXXMethodDecl>(D));
1878     return;
1879   }
1880 
1881   case APValue::Struct: {
1882     Out << '2';
1883     mangleType(T, SourceRange(), QMM_Escape);
1884     const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
1885     assert(RD && "unexpected type for record value");
1886 
1887     unsigned BaseIndex = 0;
1888     for (const CXXBaseSpecifier &B : RD->bases())
1889       mangleTemplateArgValue(B.getType(), V.getStructBase(BaseIndex++));
1890     for (const FieldDecl *FD : RD->fields())
1891       if (!FD->isUnnamedBitfield())
1892         mangleTemplateArgValue(FD->getType(),
1893                                V.getStructField(FD->getFieldIndex()),
1894                                /*WithScalarType*/ true);
1895     Out << '@';
1896     return;
1897   }
1898 
1899   case APValue::Union:
1900     Out << '7';
1901     mangleType(T, SourceRange(), QMM_Escape);
1902     if (const FieldDecl *FD = V.getUnionField()) {
1903       mangleUnqualifiedName(FD);
1904       mangleTemplateArgValue(FD->getType(), V.getUnionValue());
1905     }
1906     Out << '@';
1907     return;
1908 
1909   case APValue::ComplexInt:
1910     // We mangle complex types as structs, so mangle the value as a struct too.
1911     Out << '2';
1912     mangleType(T, SourceRange(), QMM_Escape);
1913     Out << '0';
1914     mangleNumber(V.getComplexIntReal());
1915     Out << '0';
1916     mangleNumber(V.getComplexIntImag());
1917     Out << '@';
1918     return;
1919 
1920   case APValue::ComplexFloat:
1921     Out << '2';
1922     mangleType(T, SourceRange(), QMM_Escape);
1923     mangleFloat(V.getComplexFloatReal());
1924     mangleFloat(V.getComplexFloatImag());
1925     Out << '@';
1926     return;
1927 
1928   case APValue::Array: {
1929     Out << '3';
1930     QualType ElemT = getASTContext().getAsArrayType(T)->getElementType();
1931     mangleType(ElemT, SourceRange(), QMM_Escape);
1932     for (unsigned I = 0, N = V.getArraySize(); I != N; ++I) {
1933       const APValue &ElemV = I < V.getArrayInitializedElts()
1934                                  ? V.getArrayInitializedElt(I)
1935                                  : V.getArrayFiller();
1936       mangleTemplateArgValue(ElemT, ElemV);
1937       Out << '@';
1938     }
1939     Out << '@';
1940     return;
1941   }
1942 
1943   case APValue::Vector: {
1944     // __m128 is mangled as a struct containing an array. We follow this
1945     // approach for all vector types.
1946     Out << '2';
1947     mangleType(T, SourceRange(), QMM_Escape);
1948     Out << '3';
1949     QualType ElemT = T->castAs<VectorType>()->getElementType();
1950     mangleType(ElemT, SourceRange(), QMM_Escape);
1951     for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) {
1952       const APValue &ElemV = V.getVectorElt(I);
1953       mangleTemplateArgValue(ElemT, ElemV);
1954       Out << '@';
1955     }
1956     Out << "@@";
1957     return;
1958   }
1959 
1960   case APValue::AddrLabelDiff:
1961   case APValue::FixedPoint:
1962     break;
1963   }
1964 
1965   DiagnosticsEngine &Diags = Context.getDiags();
1966   unsigned DiagID = Diags.getCustomDiagID(
1967       DiagnosticsEngine::Error, "cannot mangle this template argument yet");
1968   Diags.Report(DiagID);
1969 }
1970 
1971 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1972   llvm::SmallString<64> TemplateMangling;
1973   llvm::raw_svector_ostream Stream(TemplateMangling);
1974   MicrosoftCXXNameMangler Extra(Context, Stream);
1975 
1976   Stream << "?$";
1977   Extra.mangleSourceName("Protocol");
1978   Extra.mangleArtificialTagType(TTK_Struct, PD->getName());
1979 
1980   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1981 }
1982 
1983 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1984                                                  Qualifiers Quals,
1985                                                  SourceRange Range) {
1986   llvm::SmallString<64> TemplateMangling;
1987   llvm::raw_svector_ostream Stream(TemplateMangling);
1988   MicrosoftCXXNameMangler Extra(Context, Stream);
1989 
1990   Stream << "?$";
1991   switch (Quals.getObjCLifetime()) {
1992   case Qualifiers::OCL_None:
1993   case Qualifiers::OCL_ExplicitNone:
1994     break;
1995   case Qualifiers::OCL_Autoreleasing:
1996     Extra.mangleSourceName("Autoreleasing");
1997     break;
1998   case Qualifiers::OCL_Strong:
1999     Extra.mangleSourceName("Strong");
2000     break;
2001   case Qualifiers::OCL_Weak:
2002     Extra.mangleSourceName("Weak");
2003     break;
2004   }
2005   Extra.manglePointerCVQualifiers(Quals);
2006   Extra.manglePointerExtQualifiers(Quals, Type);
2007   Extra.mangleType(Type, Range);
2008 
2009   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
2010 }
2011 
2012 void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
2013                                                    Qualifiers Quals,
2014                                                    SourceRange Range) {
2015   llvm::SmallString<64> TemplateMangling;
2016   llvm::raw_svector_ostream Stream(TemplateMangling);
2017   MicrosoftCXXNameMangler Extra(Context, Stream);
2018 
2019   Stream << "?$";
2020   Extra.mangleSourceName("KindOf");
2021   Extra.mangleType(QualType(T, 0)
2022                        .stripObjCKindOfType(getASTContext())
2023                        ->castAs<ObjCObjectType>(),
2024                    Quals, Range);
2025 
2026   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
2027 }
2028 
2029 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
2030                                                bool IsMember) {
2031   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
2032   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
2033   // 'I' means __restrict (32/64-bit).
2034   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
2035   // keyword!
2036   // <base-cvr-qualifiers> ::= A  # near
2037   //                       ::= B  # near const
2038   //                       ::= C  # near volatile
2039   //                       ::= D  # near const volatile
2040   //                       ::= E  # far (16-bit)
2041   //                       ::= F  # far const (16-bit)
2042   //                       ::= G  # far volatile (16-bit)
2043   //                       ::= H  # far const volatile (16-bit)
2044   //                       ::= I  # huge (16-bit)
2045   //                       ::= J  # huge const (16-bit)
2046   //                       ::= K  # huge volatile (16-bit)
2047   //                       ::= L  # huge const volatile (16-bit)
2048   //                       ::= M <basis> # based
2049   //                       ::= N <basis> # based const
2050   //                       ::= O <basis> # based volatile
2051   //                       ::= P <basis> # based const volatile
2052   //                       ::= Q  # near member
2053   //                       ::= R  # near const member
2054   //                       ::= S  # near volatile member
2055   //                       ::= T  # near const volatile member
2056   //                       ::= U  # far member (16-bit)
2057   //                       ::= V  # far const member (16-bit)
2058   //                       ::= W  # far volatile member (16-bit)
2059   //                       ::= X  # far const volatile member (16-bit)
2060   //                       ::= Y  # huge member (16-bit)
2061   //                       ::= Z  # huge const member (16-bit)
2062   //                       ::= 0  # huge volatile member (16-bit)
2063   //                       ::= 1  # huge const volatile member (16-bit)
2064   //                       ::= 2 <basis> # based member
2065   //                       ::= 3 <basis> # based const member
2066   //                       ::= 4 <basis> # based volatile member
2067   //                       ::= 5 <basis> # based const volatile member
2068   //                       ::= 6  # near function (pointers only)
2069   //                       ::= 7  # far function (pointers only)
2070   //                       ::= 8  # near method (pointers only)
2071   //                       ::= 9  # far method (pointers only)
2072   //                       ::= _A <basis> # based function (pointers only)
2073   //                       ::= _B <basis> # based function (far?) (pointers only)
2074   //                       ::= _C <basis> # based method (pointers only)
2075   //                       ::= _D <basis> # based method (far?) (pointers only)
2076   //                       ::= _E # block (Clang)
2077   // <basis> ::= 0 # __based(void)
2078   //         ::= 1 # __based(segment)?
2079   //         ::= 2 <name> # __based(name)
2080   //         ::= 3 # ?
2081   //         ::= 4 # ?
2082   //         ::= 5 # not really based
2083   bool HasConst = Quals.hasConst(),
2084        HasVolatile = Quals.hasVolatile();
2085 
2086   if (!IsMember) {
2087     if (HasConst && HasVolatile) {
2088       Out << 'D';
2089     } else if (HasVolatile) {
2090       Out << 'C';
2091     } else if (HasConst) {
2092       Out << 'B';
2093     } else {
2094       Out << 'A';
2095     }
2096   } else {
2097     if (HasConst && HasVolatile) {
2098       Out << 'T';
2099     } else if (HasVolatile) {
2100       Out << 'S';
2101     } else if (HasConst) {
2102       Out << 'R';
2103     } else {
2104       Out << 'Q';
2105     }
2106   }
2107 
2108   // FIXME: For now, just drop all extension qualifiers on the floor.
2109 }
2110 
2111 void
2112 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2113   // <ref-qualifier> ::= G                # lvalue reference
2114   //                 ::= H                # rvalue-reference
2115   switch (RefQualifier) {
2116   case RQ_None:
2117     break;
2118 
2119   case RQ_LValue:
2120     Out << 'G';
2121     break;
2122 
2123   case RQ_RValue:
2124     Out << 'H';
2125     break;
2126   }
2127 }
2128 
2129 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
2130                                                          QualType PointeeType) {
2131   // Check if this is a default 64-bit pointer or has __ptr64 qualifier.
2132   bool is64Bit = PointeeType.isNull() ? PointersAre64Bit :
2133       is64BitPointer(PointeeType.getQualifiers());
2134   if (is64Bit && (PointeeType.isNull() || !PointeeType->isFunctionType()))
2135     Out << 'E';
2136 
2137   if (Quals.hasRestrict())
2138     Out << 'I';
2139 
2140   if (Quals.hasUnaligned() ||
2141       (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
2142     Out << 'F';
2143 }
2144 
2145 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
2146   // <pointer-cv-qualifiers> ::= P  # no qualifiers
2147   //                         ::= Q  # const
2148   //                         ::= R  # volatile
2149   //                         ::= S  # const volatile
2150   bool HasConst = Quals.hasConst(),
2151        HasVolatile = Quals.hasVolatile();
2152 
2153   if (HasConst && HasVolatile) {
2154     Out << 'S';
2155   } else if (HasVolatile) {
2156     Out << 'R';
2157   } else if (HasConst) {
2158     Out << 'Q';
2159   } else {
2160     Out << 'P';
2161   }
2162 }
2163 
2164 void MicrosoftCXXNameMangler::mangleFunctionArgumentType(QualType T,
2165                                                          SourceRange Range) {
2166   // MSVC will backreference two canonically equivalent types that have slightly
2167   // different manglings when mangled alone.
2168 
2169   // Decayed types do not match up with non-decayed versions of the same type.
2170   //
2171   // e.g.
2172   // void (*x)(void) will not form a backreference with void x(void)
2173   void *TypePtr;
2174   if (const auto *DT = T->getAs<DecayedType>()) {
2175     QualType OriginalType = DT->getOriginalType();
2176     // All decayed ArrayTypes should be treated identically; as-if they were
2177     // a decayed IncompleteArrayType.
2178     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
2179       OriginalType = getASTContext().getIncompleteArrayType(
2180           AT->getElementType(), AT->getSizeModifier(),
2181           AT->getIndexTypeCVRQualifiers());
2182 
2183     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
2184     // If the original parameter was textually written as an array,
2185     // instead treat the decayed parameter like it's const.
2186     //
2187     // e.g.
2188     // int [] -> int * const
2189     if (OriginalType->isArrayType())
2190       T = T.withConst();
2191   } else {
2192     TypePtr = T.getCanonicalType().getAsOpaquePtr();
2193   }
2194 
2195   ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2196 
2197   if (Found == FunArgBackReferences.end()) {
2198     size_t OutSizeBefore = Out.tell();
2199 
2200     mangleType(T, Range, QMM_Drop);
2201 
2202     // See if it's worth creating a back reference.
2203     // Only types longer than 1 character are considered
2204     // and only 10 back references slots are available:
2205     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
2206     if (LongerThanOneChar && FunArgBackReferences.size() < 10) {
2207       size_t Size = FunArgBackReferences.size();
2208       FunArgBackReferences[TypePtr] = Size;
2209     }
2210   } else {
2211     Out << Found->second;
2212   }
2213 }
2214 
2215 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
2216     const PassObjectSizeAttr *POSA) {
2217   int Type = POSA->getType();
2218   bool Dynamic = POSA->isDynamic();
2219 
2220   auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first;
2221   auto *TypePtr = (const void *)&*Iter;
2222   ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2223 
2224   if (Found == FunArgBackReferences.end()) {
2225     std::string Name =
2226         Dynamic ? "__pass_dynamic_object_size" : "__pass_object_size";
2227     mangleArtificialTagType(TTK_Enum, Name + llvm::utostr(Type), {"__clang"});
2228 
2229     if (FunArgBackReferences.size() < 10) {
2230       size_t Size = FunArgBackReferences.size();
2231       FunArgBackReferences[TypePtr] = Size;
2232     }
2233   } else {
2234     Out << Found->second;
2235   }
2236 }
2237 
2238 void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
2239                                                      Qualifiers Quals,
2240                                                      SourceRange Range) {
2241   // Address space is mangled as an unqualified templated type in the __clang
2242   // namespace. The demangled version of this is:
2243   // In the case of a language specific address space:
2244   // __clang::struct _AS[language_addr_space]<Type>
2245   // where:
2246   //  <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
2247   //    <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2248   //                                "private"| "generic" | "device" | "host" ]
2249   //    <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2250   //    Note that the above were chosen to match the Itanium mangling for this.
2251   //
2252   // In the case of a non-language specific address space:
2253   //  __clang::struct _AS<TargetAS, Type>
2254   assert(Quals.hasAddressSpace() && "Not valid without address space");
2255   llvm::SmallString<32> ASMangling;
2256   llvm::raw_svector_ostream Stream(ASMangling);
2257   MicrosoftCXXNameMangler Extra(Context, Stream);
2258   Stream << "?$";
2259 
2260   LangAS AS = Quals.getAddressSpace();
2261   if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2262     unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2263     Extra.mangleSourceName("_AS");
2264     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS));
2265   } else {
2266     switch (AS) {
2267     default:
2268       llvm_unreachable("Not a language specific address space");
2269     case LangAS::opencl_global:
2270       Extra.mangleSourceName("_ASCLglobal");
2271       break;
2272     case LangAS::opencl_global_device:
2273       Extra.mangleSourceName("_ASCLdevice");
2274       break;
2275     case LangAS::opencl_global_host:
2276       Extra.mangleSourceName("_ASCLhost");
2277       break;
2278     case LangAS::opencl_local:
2279       Extra.mangleSourceName("_ASCLlocal");
2280       break;
2281     case LangAS::opencl_constant:
2282       Extra.mangleSourceName("_ASCLconstant");
2283       break;
2284     case LangAS::opencl_private:
2285       Extra.mangleSourceName("_ASCLprivate");
2286       break;
2287     case LangAS::opencl_generic:
2288       Extra.mangleSourceName("_ASCLgeneric");
2289       break;
2290     case LangAS::cuda_device:
2291       Extra.mangleSourceName("_ASCUdevice");
2292       break;
2293     case LangAS::cuda_constant:
2294       Extra.mangleSourceName("_ASCUconstant");
2295       break;
2296     case LangAS::cuda_shared:
2297       Extra.mangleSourceName("_ASCUshared");
2298       break;
2299     case LangAS::ptr32_sptr:
2300     case LangAS::ptr32_uptr:
2301     case LangAS::ptr64:
2302       llvm_unreachable("don't mangle ptr address spaces with _AS");
2303     }
2304   }
2305 
2306   Extra.mangleType(T, Range, QMM_Escape);
2307   mangleQualifiers(Qualifiers(), false);
2308   mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
2309 }
2310 
2311 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
2312                                          QualifierMangleMode QMM) {
2313   // Don't use the canonical types.  MSVC includes things like 'const' on
2314   // pointer arguments to function pointers that canonicalization strips away.
2315   T = T.getDesugaredType(getASTContext());
2316   Qualifiers Quals = T.getLocalQualifiers();
2317 
2318   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
2319     // If there were any Quals, getAsArrayType() pushed them onto the array
2320     // element type.
2321     if (QMM == QMM_Mangle)
2322       Out << 'A';
2323     else if (QMM == QMM_Escape || QMM == QMM_Result)
2324       Out << "$$B";
2325     mangleArrayType(AT);
2326     return;
2327   }
2328 
2329   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
2330                    T->isReferenceType() || T->isBlockPointerType();
2331 
2332   switch (QMM) {
2333   case QMM_Drop:
2334     if (Quals.hasObjCLifetime())
2335       Quals = Quals.withoutObjCLifetime();
2336     break;
2337   case QMM_Mangle:
2338     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
2339       Out << '6';
2340       mangleFunctionType(FT);
2341       return;
2342     }
2343     mangleQualifiers(Quals, false);
2344     break;
2345   case QMM_Escape:
2346     if (!IsPointer && Quals) {
2347       Out << "$$C";
2348       mangleQualifiers(Quals, false);
2349     }
2350     break;
2351   case QMM_Result:
2352     // Presence of __unaligned qualifier shouldn't affect mangling here.
2353     Quals.removeUnaligned();
2354     if (Quals.hasObjCLifetime())
2355       Quals = Quals.withoutObjCLifetime();
2356     if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
2357       Out << '?';
2358       mangleQualifiers(Quals, false);
2359     }
2360     break;
2361   }
2362 
2363   const Type *ty = T.getTypePtr();
2364 
2365   switch (ty->getTypeClass()) {
2366 #define ABSTRACT_TYPE(CLASS, PARENT)
2367 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2368   case Type::CLASS: \
2369     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2370     return;
2371 #define TYPE(CLASS, PARENT) \
2372   case Type::CLASS: \
2373     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
2374     break;
2375 #include "clang/AST/TypeNodes.inc"
2376 #undef ABSTRACT_TYPE
2377 #undef NON_CANONICAL_TYPE
2378 #undef TYPE
2379   }
2380 }
2381 
2382 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
2383                                          SourceRange Range) {
2384   //  <type>         ::= <builtin-type>
2385   //  <builtin-type> ::= X  # void
2386   //                 ::= C  # signed char
2387   //                 ::= D  # char
2388   //                 ::= E  # unsigned char
2389   //                 ::= F  # short
2390   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
2391   //                 ::= H  # int
2392   //                 ::= I  # unsigned int
2393   //                 ::= J  # long
2394   //                 ::= K  # unsigned long
2395   //                     L  # <none>
2396   //                 ::= M  # float
2397   //                 ::= N  # double
2398   //                 ::= O  # long double (__float80 is mangled differently)
2399   //                 ::= _J # long long, __int64
2400   //                 ::= _K # unsigned long long, __int64
2401   //                 ::= _L # __int128
2402   //                 ::= _M # unsigned __int128
2403   //                 ::= _N # bool
2404   //                     _O # <array in parameter>
2405   //                 ::= _Q # char8_t
2406   //                 ::= _S # char16_t
2407   //                 ::= _T # __float80 (Intel)
2408   //                 ::= _U # char32_t
2409   //                 ::= _W # wchar_t
2410   //                 ::= _Z # __float80 (Digital Mars)
2411   switch (T->getKind()) {
2412   case BuiltinType::Void:
2413     Out << 'X';
2414     break;
2415   case BuiltinType::SChar:
2416     Out << 'C';
2417     break;
2418   case BuiltinType::Char_U:
2419   case BuiltinType::Char_S:
2420     Out << 'D';
2421     break;
2422   case BuiltinType::UChar:
2423     Out << 'E';
2424     break;
2425   case BuiltinType::Short:
2426     Out << 'F';
2427     break;
2428   case BuiltinType::UShort:
2429     Out << 'G';
2430     break;
2431   case BuiltinType::Int:
2432     Out << 'H';
2433     break;
2434   case BuiltinType::UInt:
2435     Out << 'I';
2436     break;
2437   case BuiltinType::Long:
2438     Out << 'J';
2439     break;
2440   case BuiltinType::ULong:
2441     Out << 'K';
2442     break;
2443   case BuiltinType::Float:
2444     Out << 'M';
2445     break;
2446   case BuiltinType::Double:
2447     Out << 'N';
2448     break;
2449   // TODO: Determine size and mangle accordingly
2450   case BuiltinType::LongDouble:
2451     Out << 'O';
2452     break;
2453   case BuiltinType::LongLong:
2454     Out << "_J";
2455     break;
2456   case BuiltinType::ULongLong:
2457     Out << "_K";
2458     break;
2459   case BuiltinType::Int128:
2460     Out << "_L";
2461     break;
2462   case BuiltinType::UInt128:
2463     Out << "_M";
2464     break;
2465   case BuiltinType::Bool:
2466     Out << "_N";
2467     break;
2468   case BuiltinType::Char8:
2469     Out << "_Q";
2470     break;
2471   case BuiltinType::Char16:
2472     Out << "_S";
2473     break;
2474   case BuiltinType::Char32:
2475     Out << "_U";
2476     break;
2477   case BuiltinType::WChar_S:
2478   case BuiltinType::WChar_U:
2479     Out << "_W";
2480     break;
2481 
2482 #define BUILTIN_TYPE(Id, SingletonId)
2483 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2484   case BuiltinType::Id:
2485 #include "clang/AST/BuiltinTypes.def"
2486   case BuiltinType::Dependent:
2487     llvm_unreachable("placeholder types shouldn't get to name mangling");
2488 
2489   case BuiltinType::ObjCId:
2490     mangleArtificialTagType(TTK_Struct, "objc_object");
2491     break;
2492   case BuiltinType::ObjCClass:
2493     mangleArtificialTagType(TTK_Struct, "objc_class");
2494     break;
2495   case BuiltinType::ObjCSel:
2496     mangleArtificialTagType(TTK_Struct, "objc_selector");
2497     break;
2498 
2499 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2500   case BuiltinType::Id: \
2501     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2502     break;
2503 #include "clang/Basic/OpenCLImageTypes.def"
2504   case BuiltinType::OCLSampler:
2505     Out << "PA";
2506     mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2507     break;
2508   case BuiltinType::OCLEvent:
2509     Out << "PA";
2510     mangleArtificialTagType(TTK_Struct, "ocl_event");
2511     break;
2512   case BuiltinType::OCLClkEvent:
2513     Out << "PA";
2514     mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2515     break;
2516   case BuiltinType::OCLQueue:
2517     Out << "PA";
2518     mangleArtificialTagType(TTK_Struct, "ocl_queue");
2519     break;
2520   case BuiltinType::OCLReserveID:
2521     Out << "PA";
2522     mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2523     break;
2524 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2525   case BuiltinType::Id: \
2526     mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2527     break;
2528 #include "clang/Basic/OpenCLExtensionTypes.def"
2529 
2530   case BuiltinType::NullPtr:
2531     Out << "$$T";
2532     break;
2533 
2534   case BuiltinType::Float16:
2535     mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2536     break;
2537 
2538   case BuiltinType::Half:
2539     if (!getASTContext().getLangOpts().HLSL)
2540       mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2541     else if (getASTContext().getLangOpts().NativeHalfType)
2542       Out << "$f16@";
2543     else
2544       Out << "$halff@";
2545     break;
2546 
2547   case BuiltinType::BFloat16:
2548     mangleArtificialTagType(TTK_Struct, "__bf16", {"__clang"});
2549     break;
2550 
2551 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS)          \
2552   case BuiltinType::Id:                                                        \
2553     mangleArtificialTagType(TTK_Struct, MangledName);                          \
2554     mangleArtificialTagType(TTK_Struct, MangledName, {"__clang"});             \
2555     break;
2556 
2557 #include "clang/Basic/WebAssemblyReferenceTypes.def"
2558 #define SVE_TYPE(Name, Id, SingletonId) \
2559   case BuiltinType::Id:
2560 #include "clang/Basic/AArch64SVEACLETypes.def"
2561 #define PPC_VECTOR_TYPE(Name, Id, Size) \
2562   case BuiltinType::Id:
2563 #include "clang/Basic/PPCTypes.def"
2564 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2565 #include "clang/Basic/RISCVVTypes.def"
2566   case BuiltinType::ShortAccum:
2567   case BuiltinType::Accum:
2568   case BuiltinType::LongAccum:
2569   case BuiltinType::UShortAccum:
2570   case BuiltinType::UAccum:
2571   case BuiltinType::ULongAccum:
2572   case BuiltinType::ShortFract:
2573   case BuiltinType::Fract:
2574   case BuiltinType::LongFract:
2575   case BuiltinType::UShortFract:
2576   case BuiltinType::UFract:
2577   case BuiltinType::ULongFract:
2578   case BuiltinType::SatShortAccum:
2579   case BuiltinType::SatAccum:
2580   case BuiltinType::SatLongAccum:
2581   case BuiltinType::SatUShortAccum:
2582   case BuiltinType::SatUAccum:
2583   case BuiltinType::SatULongAccum:
2584   case BuiltinType::SatShortFract:
2585   case BuiltinType::SatFract:
2586   case BuiltinType::SatLongFract:
2587   case BuiltinType::SatUShortFract:
2588   case BuiltinType::SatUFract:
2589   case BuiltinType::SatULongFract:
2590   case BuiltinType::Ibm128:
2591   case BuiltinType::Float128: {
2592     DiagnosticsEngine &Diags = Context.getDiags();
2593     unsigned DiagID = Diags.getCustomDiagID(
2594         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2595     Diags.Report(Range.getBegin(), DiagID)
2596         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2597     break;
2598   }
2599   }
2600 }
2601 
2602 // <type>          ::= <function-type>
2603 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2604                                          SourceRange) {
2605   // Structors only appear in decls, so at this point we know it's not a
2606   // structor type.
2607   // FIXME: This may not be lambda-friendly.
2608   if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) {
2609     Out << "$$A8@@";
2610     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2611   } else {
2612     Out << "$$A6";
2613     mangleFunctionType(T);
2614   }
2615 }
2616 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2617                                          Qualifiers, SourceRange) {
2618   Out << "$$A6";
2619   mangleFunctionType(T);
2620 }
2621 
2622 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2623                                                  const FunctionDecl *D,
2624                                                  bool ForceThisQuals,
2625                                                  bool MangleExceptionSpec) {
2626   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2627   //                     <return-type> <argument-list> <throw-spec>
2628   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2629 
2630   SourceRange Range;
2631   if (D) Range = D->getSourceRange();
2632 
2633   bool IsInLambda = false;
2634   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2635   CallingConv CC = T->getCallConv();
2636   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2637     if (MD->getParent()->isLambda())
2638       IsInLambda = true;
2639     if (MD->isInstance())
2640       HasThisQuals = true;
2641     if (isa<CXXDestructorDecl>(MD)) {
2642       IsStructor = true;
2643     } else if (isa<CXXConstructorDecl>(MD)) {
2644       IsStructor = true;
2645       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2646                        StructorType == Ctor_DefaultClosure) &&
2647                       isStructorDecl(MD);
2648       if (IsCtorClosure)
2649         CC = getASTContext().getDefaultCallingConvention(
2650             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2651     }
2652   }
2653 
2654   // If this is a C++ instance method, mangle the CVR qualifiers for the
2655   // this pointer.
2656   if (HasThisQuals) {
2657     Qualifiers Quals = Proto->getMethodQuals();
2658     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2659     mangleRefQualifier(Proto->getRefQualifier());
2660     mangleQualifiers(Quals, /*IsMember=*/false);
2661   }
2662 
2663   mangleCallingConvention(CC);
2664 
2665   // <return-type> ::= <type>
2666   //               ::= @ # structors (they have no declared return type)
2667   if (IsStructor) {
2668     if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2669       // The scalar deleting destructor takes an extra int argument which is not
2670       // reflected in the AST.
2671       if (StructorType == Dtor_Deleting) {
2672         Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2673         return;
2674       }
2675       // The vbase destructor returns void which is not reflected in the AST.
2676       if (StructorType == Dtor_Complete) {
2677         Out << "XXZ";
2678         return;
2679       }
2680     }
2681     if (IsCtorClosure) {
2682       // Default constructor closure and copy constructor closure both return
2683       // void.
2684       Out << 'X';
2685 
2686       if (StructorType == Ctor_DefaultClosure) {
2687         // Default constructor closure always has no arguments.
2688         Out << 'X';
2689       } else if (StructorType == Ctor_CopyingClosure) {
2690         // Copy constructor closure always takes an unqualified reference.
2691         mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
2692                                        Proto->getParamType(0)
2693                                            ->castAs<LValueReferenceType>()
2694                                            ->getPointeeType(),
2695                                        /*SpelledAsLValue=*/true),
2696                                    Range);
2697         Out << '@';
2698       } else {
2699         llvm_unreachable("unexpected constructor closure!");
2700       }
2701       Out << 'Z';
2702       return;
2703     }
2704     Out << '@';
2705   } else if (IsInLambda && D && isa<CXXConversionDecl>(D)) {
2706     // The only lambda conversion operators are to function pointers, which
2707     // can differ by their calling convention and are typically deduced.  So
2708     // we make sure that this type gets mangled properly.
2709     mangleType(T->getReturnType(), Range, QMM_Result);
2710   } else {
2711     QualType ResultType = T->getReturnType();
2712     if (IsInLambda && isa<CXXConversionDecl>(D)) {
2713       // The only lambda conversion operators are to function pointers, which
2714       // can differ by their calling convention and are typically deduced.  So
2715       // we make sure that this type gets mangled properly.
2716       mangleType(ResultType, Range, QMM_Result);
2717     } else if (const auto *AT = dyn_cast_or_null<AutoType>(
2718                    ResultType->getContainedAutoType())) {
2719       Out << '?';
2720       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2721       Out << '?';
2722       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2723              "shouldn't need to mangle __auto_type!");
2724       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2725       Out << '@';
2726     } else if (IsInLambda) {
2727       Out << '@';
2728     } else {
2729       if (ResultType->isVoidType())
2730         ResultType = ResultType.getUnqualifiedType();
2731       mangleType(ResultType, Range, QMM_Result);
2732     }
2733   }
2734 
2735   // <argument-list> ::= X # void
2736   //                 ::= <type>+ @
2737   //                 ::= <type>* Z # varargs
2738   if (!Proto) {
2739     // Function types without prototypes can arise when mangling a function type
2740     // within an overloadable function in C. We mangle these as the absence of
2741     // any parameter types (not even an empty parameter list).
2742     Out << '@';
2743   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2744     Out << 'X';
2745   } else {
2746     // Happens for function pointer type arguments for example.
2747     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2748       mangleFunctionArgumentType(Proto->getParamType(I), Range);
2749       // Mangle each pass_object_size parameter as if it's a parameter of enum
2750       // type passed directly after the parameter with the pass_object_size
2751       // attribute. The aforementioned enum's name is __pass_object_size, and we
2752       // pretend it resides in a top-level namespace called __clang.
2753       //
2754       // FIXME: Is there a defined extension notation for the MS ABI, or is it
2755       // necessary to just cross our fingers and hope this type+namespace
2756       // combination doesn't conflict with anything?
2757       if (D)
2758         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2759           manglePassObjectSizeArg(P);
2760     }
2761     // <builtin-type>      ::= Z  # ellipsis
2762     if (Proto->isVariadic())
2763       Out << 'Z';
2764     else
2765       Out << '@';
2766   }
2767 
2768   if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2769       getASTContext().getLangOpts().isCompatibleWithMSVC(
2770           LangOptions::MSVC2017_5))
2771     mangleThrowSpecification(Proto);
2772   else
2773     Out << 'Z';
2774 }
2775 
2776 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2777   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2778   //                                            # pointer. in 64-bit mode *all*
2779   //                                            # 'this' pointers are 64-bit.
2780   //                   ::= <global-function>
2781   // <member-function> ::= A # private: near
2782   //                   ::= B # private: far
2783   //                   ::= C # private: static near
2784   //                   ::= D # private: static far
2785   //                   ::= E # private: virtual near
2786   //                   ::= F # private: virtual far
2787   //                   ::= I # protected: near
2788   //                   ::= J # protected: far
2789   //                   ::= K # protected: static near
2790   //                   ::= L # protected: static far
2791   //                   ::= M # protected: virtual near
2792   //                   ::= N # protected: virtual far
2793   //                   ::= Q # public: near
2794   //                   ::= R # public: far
2795   //                   ::= S # public: static near
2796   //                   ::= T # public: static far
2797   //                   ::= U # public: virtual near
2798   //                   ::= V # public: virtual far
2799   // <global-function> ::= Y # global near
2800   //                   ::= Z # global far
2801   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2802     bool IsVirtual = MD->isVirtual();
2803     // When mangling vbase destructor variants, ignore whether or not the
2804     // underlying destructor was defined to be virtual.
2805     if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2806         StructorType == Dtor_Complete) {
2807       IsVirtual = false;
2808     }
2809     switch (MD->getAccess()) {
2810       case AS_none:
2811         llvm_unreachable("Unsupported access specifier");
2812       case AS_private:
2813         if (MD->isStatic())
2814           Out << 'C';
2815         else if (IsVirtual)
2816           Out << 'E';
2817         else
2818           Out << 'A';
2819         break;
2820       case AS_protected:
2821         if (MD->isStatic())
2822           Out << 'K';
2823         else if (IsVirtual)
2824           Out << 'M';
2825         else
2826           Out << 'I';
2827         break;
2828       case AS_public:
2829         if (MD->isStatic())
2830           Out << 'S';
2831         else if (IsVirtual)
2832           Out << 'U';
2833         else
2834           Out << 'Q';
2835     }
2836   } else {
2837     Out << 'Y';
2838   }
2839 }
2840 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2841   // <calling-convention> ::= A # __cdecl
2842   //                      ::= B # __export __cdecl
2843   //                      ::= C # __pascal
2844   //                      ::= D # __export __pascal
2845   //                      ::= E # __thiscall
2846   //                      ::= F # __export __thiscall
2847   //                      ::= G # __stdcall
2848   //                      ::= H # __export __stdcall
2849   //                      ::= I # __fastcall
2850   //                      ::= J # __export __fastcall
2851   //                      ::= Q # __vectorcall
2852   //                      ::= S # __attribute__((__swiftcall__)) // Clang-only
2853   //                      ::= T # __attribute__((__swiftasynccall__))
2854   //                            // Clang-only
2855   //                      ::= w # __regcall
2856   // The 'export' calling conventions are from a bygone era
2857   // (*cough*Win16*cough*) when functions were declared for export with
2858   // that keyword. (It didn't actually export them, it just made them so
2859   // that they could be in a DLL and somebody from another module could call
2860   // them.)
2861 
2862   switch (CC) {
2863     default:
2864       llvm_unreachable("Unsupported CC for mangling");
2865     case CC_Win64:
2866     case CC_X86_64SysV:
2867     case CC_C: Out << 'A'; break;
2868     case CC_X86Pascal: Out << 'C'; break;
2869     case CC_X86ThisCall: Out << 'E'; break;
2870     case CC_X86StdCall: Out << 'G'; break;
2871     case CC_X86FastCall: Out << 'I'; break;
2872     case CC_X86VectorCall: Out << 'Q'; break;
2873     case CC_Swift: Out << 'S'; break;
2874     case CC_SwiftAsync: Out << 'W'; break;
2875     case CC_PreserveMost: Out << 'U'; break;
2876     case CC_X86RegCall: Out << 'w'; break;
2877   }
2878 }
2879 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2880   mangleCallingConvention(T->getCallConv());
2881 }
2882 
2883 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2884                                                 const FunctionProtoType *FT) {
2885   // <throw-spec> ::= Z # (default)
2886   //              ::= _E # noexcept
2887   if (FT->canThrow())
2888     Out << 'Z';
2889   else
2890     Out << "_E";
2891 }
2892 
2893 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2894                                          Qualifiers, SourceRange Range) {
2895   // Probably should be mangled as a template instantiation; need to see what
2896   // VC does first.
2897   DiagnosticsEngine &Diags = Context.getDiags();
2898   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2899     "cannot mangle this unresolved dependent type yet");
2900   Diags.Report(Range.getBegin(), DiagID)
2901     << Range;
2902 }
2903 
2904 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2905 // <union-type>  ::= T <name>
2906 // <struct-type> ::= U <name>
2907 // <class-type>  ::= V <name>
2908 // <enum-type>   ::= W4 <name>
2909 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2910   switch (TTK) {
2911     case TTK_Union:
2912       Out << 'T';
2913       break;
2914     case TTK_Struct:
2915     case TTK_Interface:
2916       Out << 'U';
2917       break;
2918     case TTK_Class:
2919       Out << 'V';
2920       break;
2921     case TTK_Enum:
2922       Out << "W4";
2923       break;
2924   }
2925 }
2926 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2927                                          SourceRange) {
2928   mangleType(cast<TagType>(T)->getDecl());
2929 }
2930 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2931                                          SourceRange) {
2932   mangleType(cast<TagType>(T)->getDecl());
2933 }
2934 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2935   mangleTagTypeKind(TD->getTagKind());
2936   mangleName(TD);
2937 }
2938 
2939 // If you add a call to this, consider updating isArtificialTagType() too.
2940 void MicrosoftCXXNameMangler::mangleArtificialTagType(
2941     TagTypeKind TK, StringRef UnqualifiedName,
2942     ArrayRef<StringRef> NestedNames) {
2943   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2944   mangleTagTypeKind(TK);
2945 
2946   // Always start with the unqualified name.
2947   mangleSourceName(UnqualifiedName);
2948 
2949   for (StringRef N : llvm::reverse(NestedNames))
2950     mangleSourceName(N);
2951 
2952   // Terminate the whole name with an '@'.
2953   Out << '@';
2954 }
2955 
2956 // <type>       ::= <array-type>
2957 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2958 //                  [Y <dimension-count> <dimension>+]
2959 //                  <element-type> # as global, E is never required
2960 // It's supposed to be the other way around, but for some strange reason, it
2961 // isn't. Today this behavior is retained for the sole purpose of backwards
2962 // compatibility.
2963 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2964   // This isn't a recursive mangling, so now we have to do it all in this
2965   // one call.
2966   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2967   mangleType(T->getElementType(), SourceRange());
2968 }
2969 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2970                                          SourceRange) {
2971   llvm_unreachable("Should have been special cased");
2972 }
2973 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2974                                          SourceRange) {
2975   llvm_unreachable("Should have been special cased");
2976 }
2977 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2978                                          Qualifiers, SourceRange) {
2979   llvm_unreachable("Should have been special cased");
2980 }
2981 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2982                                          Qualifiers, SourceRange) {
2983   llvm_unreachable("Should have been special cased");
2984 }
2985 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2986   QualType ElementTy(T, 0);
2987   SmallVector<llvm::APInt, 3> Dimensions;
2988   for (;;) {
2989     if (ElementTy->isConstantArrayType()) {
2990       const ConstantArrayType *CAT =
2991           getASTContext().getAsConstantArrayType(ElementTy);
2992       Dimensions.push_back(CAT->getSize());
2993       ElementTy = CAT->getElementType();
2994     } else if (ElementTy->isIncompleteArrayType()) {
2995       const IncompleteArrayType *IAT =
2996           getASTContext().getAsIncompleteArrayType(ElementTy);
2997       Dimensions.push_back(llvm::APInt(32, 0));
2998       ElementTy = IAT->getElementType();
2999     } else if (ElementTy->isVariableArrayType()) {
3000       const VariableArrayType *VAT =
3001         getASTContext().getAsVariableArrayType(ElementTy);
3002       Dimensions.push_back(llvm::APInt(32, 0));
3003       ElementTy = VAT->getElementType();
3004     } else if (ElementTy->isDependentSizedArrayType()) {
3005       // The dependent expression has to be folded into a constant (TODO).
3006       const DependentSizedArrayType *DSAT =
3007         getASTContext().getAsDependentSizedArrayType(ElementTy);
3008       DiagnosticsEngine &Diags = Context.getDiags();
3009       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3010         "cannot mangle this dependent-length array yet");
3011       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
3012         << DSAT->getBracketsRange();
3013       return;
3014     } else {
3015       break;
3016     }
3017   }
3018   Out << 'Y';
3019   // <dimension-count> ::= <number> # number of extra dimensions
3020   mangleNumber(Dimensions.size());
3021   for (const llvm::APInt &Dimension : Dimensions)
3022     mangleNumber(Dimension.getLimitedValue());
3023   mangleType(ElementTy, SourceRange(), QMM_Escape);
3024 }
3025 
3026 // <type>                   ::= <pointer-to-member-type>
3027 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
3028 //                                                          <class name> <type>
3029 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
3030                                          Qualifiers Quals, SourceRange Range) {
3031   QualType PointeeType = T->getPointeeType();
3032   manglePointerCVQualifiers(Quals);
3033   manglePointerExtQualifiers(Quals, PointeeType);
3034   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
3035     Out << '8';
3036     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
3037     mangleFunctionType(FPT, nullptr, true);
3038   } else {
3039     mangleQualifiers(PointeeType.getQualifiers(), true);
3040     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
3041     mangleType(PointeeType, Range, QMM_Drop);
3042   }
3043 }
3044 
3045 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
3046                                          Qualifiers, SourceRange Range) {
3047   DiagnosticsEngine &Diags = Context.getDiags();
3048   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3049     "cannot mangle this template type parameter type yet");
3050   Diags.Report(Range.getBegin(), DiagID)
3051     << Range;
3052 }
3053 
3054 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
3055                                          Qualifiers, SourceRange Range) {
3056   DiagnosticsEngine &Diags = Context.getDiags();
3057   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3058     "cannot mangle this substituted parameter pack yet");
3059   Diags.Report(Range.getBegin(), DiagID)
3060     << Range;
3061 }
3062 
3063 // <type> ::= <pointer-type>
3064 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
3065 //                       # the E is required for 64-bit non-static pointers
3066 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
3067                                          SourceRange Range) {
3068   QualType PointeeType = T->getPointeeType();
3069   manglePointerCVQualifiers(Quals);
3070   manglePointerExtQualifiers(Quals, PointeeType);
3071 
3072   // For pointer size address spaces, go down the same type mangling path as
3073   // non address space types.
3074   LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
3075   if (isPtrSizeAddressSpace(AddrSpace) || AddrSpace == LangAS::Default)
3076     mangleType(PointeeType, Range);
3077   else
3078     mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
3079 }
3080 
3081 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
3082                                          Qualifiers Quals, SourceRange Range) {
3083   QualType PointeeType = T->getPointeeType();
3084   switch (Quals.getObjCLifetime()) {
3085   case Qualifiers::OCL_None:
3086   case Qualifiers::OCL_ExplicitNone:
3087     break;
3088   case Qualifiers::OCL_Autoreleasing:
3089   case Qualifiers::OCL_Strong:
3090   case Qualifiers::OCL_Weak:
3091     return mangleObjCLifetime(PointeeType, Quals, Range);
3092   }
3093   manglePointerCVQualifiers(Quals);
3094   manglePointerExtQualifiers(Quals, PointeeType);
3095   mangleType(PointeeType, Range);
3096 }
3097 
3098 // <type> ::= <reference-type>
3099 // <reference-type> ::= A E? <cvr-qualifiers> <type>
3100 //                 # the E is required for 64-bit non-static lvalue references
3101 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
3102                                          Qualifiers Quals, SourceRange Range) {
3103   QualType PointeeType = T->getPointeeType();
3104   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3105   Out << 'A';
3106   manglePointerExtQualifiers(Quals, PointeeType);
3107   mangleType(PointeeType, Range);
3108 }
3109 
3110 // <type> ::= <r-value-reference-type>
3111 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
3112 //                 # the E is required for 64-bit non-static rvalue references
3113 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
3114                                          Qualifiers Quals, SourceRange Range) {
3115   QualType PointeeType = T->getPointeeType();
3116   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3117   Out << "$$Q";
3118   manglePointerExtQualifiers(Quals, PointeeType);
3119   mangleType(PointeeType, Range);
3120 }
3121 
3122 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
3123                                          SourceRange Range) {
3124   QualType ElementType = T->getElementType();
3125 
3126   llvm::SmallString<64> TemplateMangling;
3127   llvm::raw_svector_ostream Stream(TemplateMangling);
3128   MicrosoftCXXNameMangler Extra(Context, Stream);
3129   Stream << "?$";
3130   Extra.mangleSourceName("_Complex");
3131   Extra.mangleType(ElementType, Range, QMM_Escape);
3132 
3133   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3134 }
3135 
3136 // Returns true for types that mangleArtificialTagType() gets called for with
3137 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
3138 // mangling matters.
3139 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
3140 // support.)
3141 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
3142   const Type *ty = T.getTypePtr();
3143   switch (ty->getTypeClass()) {
3144   default:
3145     return false;
3146 
3147   case Type::Vector: {
3148     // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
3149     // but since mangleType(VectorType*) always calls mangleArtificialTagType()
3150     // just always return true (the other vector types are clang-only).
3151     return true;
3152   }
3153   }
3154 }
3155 
3156 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
3157                                          SourceRange Range) {
3158   QualType EltTy = T->getElementType();
3159   const BuiltinType *ET = EltTy->getAs<BuiltinType>();
3160   const BitIntType *BitIntTy = EltTy->getAs<BitIntType>();
3161   assert((ET || BitIntTy) &&
3162          "vectors with non-builtin/_BitInt elements are unsupported");
3163   uint64_t Width = getASTContext().getTypeSize(T);
3164   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
3165   // doesn't match the Intel types uses a custom mangling below.
3166   size_t OutSizeBefore = Out.tell();
3167   if (!isa<ExtVectorType>(T)) {
3168     if (getASTContext().getTargetInfo().getTriple().isX86() && ET) {
3169       if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
3170         mangleArtificialTagType(TTK_Union, "__m64");
3171       } else if (Width >= 128) {
3172         if (ET->getKind() == BuiltinType::Float)
3173           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
3174         else if (ET->getKind() == BuiltinType::LongLong)
3175           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
3176         else if (ET->getKind() == BuiltinType::Double)
3177           mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
3178       }
3179     }
3180   }
3181 
3182   bool IsBuiltin = Out.tell() != OutSizeBefore;
3183   if (!IsBuiltin) {
3184     // The MS ABI doesn't have a special mangling for vector types, so we define
3185     // our own mangling to handle uses of __vector_size__ on user-specified
3186     // types, and for extensions like __v4sf.
3187 
3188     llvm::SmallString<64> TemplateMangling;
3189     llvm::raw_svector_ostream Stream(TemplateMangling);
3190     MicrosoftCXXNameMangler Extra(Context, Stream);
3191     Stream << "?$";
3192     Extra.mangleSourceName("__vector");
3193     Extra.mangleType(QualType(ET ? static_cast<const Type *>(ET) : BitIntTy, 0),
3194                      Range, QMM_Escape);
3195     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()));
3196 
3197     mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
3198   }
3199 }
3200 
3201 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
3202                                          Qualifiers Quals, SourceRange Range) {
3203   mangleType(static_cast<const VectorType *>(T), Quals, Range);
3204 }
3205 
3206 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
3207                                          Qualifiers, SourceRange Range) {
3208   DiagnosticsEngine &Diags = Context.getDiags();
3209   unsigned DiagID = Diags.getCustomDiagID(
3210       DiagnosticsEngine::Error,
3211       "cannot mangle this dependent-sized vector type yet");
3212   Diags.Report(Range.getBegin(), DiagID) << Range;
3213 }
3214 
3215 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
3216                                          Qualifiers, SourceRange Range) {
3217   DiagnosticsEngine &Diags = Context.getDiags();
3218   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3219     "cannot mangle this dependent-sized extended vector type yet");
3220   Diags.Report(Range.getBegin(), DiagID)
3221     << Range;
3222 }
3223 
3224 void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
3225                                          Qualifiers quals, SourceRange Range) {
3226   DiagnosticsEngine &Diags = Context.getDiags();
3227   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3228                                           "Cannot mangle this matrix type yet");
3229   Diags.Report(Range.getBegin(), DiagID) << Range;
3230 }
3231 
3232 void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
3233                                          Qualifiers quals, SourceRange Range) {
3234   DiagnosticsEngine &Diags = Context.getDiags();
3235   unsigned DiagID = Diags.getCustomDiagID(
3236       DiagnosticsEngine::Error,
3237       "Cannot mangle this dependent-sized matrix type yet");
3238   Diags.Report(Range.getBegin(), DiagID) << Range;
3239 }
3240 
3241 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
3242                                          Qualifiers, SourceRange Range) {
3243   DiagnosticsEngine &Diags = Context.getDiags();
3244   unsigned DiagID = Diags.getCustomDiagID(
3245       DiagnosticsEngine::Error,
3246       "cannot mangle this dependent address space type yet");
3247   Diags.Report(Range.getBegin(), DiagID) << Range;
3248 }
3249 
3250 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
3251                                          SourceRange) {
3252   // ObjC interfaces have structs underlying them.
3253   mangleTagTypeKind(TTK_Struct);
3254   mangleName(T->getDecl());
3255 }
3256 
3257 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
3258                                          Qualifiers Quals, SourceRange Range) {
3259   if (T->isKindOfType())
3260     return mangleObjCKindOfType(T, Quals, Range);
3261 
3262   if (T->qual_empty() && !T->isSpecialized())
3263     return mangleType(T->getBaseType(), Range, QMM_Drop);
3264 
3265   ArgBackRefMap OuterFunArgsContext;
3266   ArgBackRefMap OuterTemplateArgsContext;
3267   BackRefVec OuterTemplateContext;
3268 
3269   FunArgBackReferences.swap(OuterFunArgsContext);
3270   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3271   NameBackReferences.swap(OuterTemplateContext);
3272 
3273   mangleTagTypeKind(TTK_Struct);
3274 
3275   Out << "?$";
3276   if (T->isObjCId())
3277     mangleSourceName("objc_object");
3278   else if (T->isObjCClass())
3279     mangleSourceName("objc_class");
3280   else
3281     mangleSourceName(T->getInterface()->getName());
3282 
3283   for (const auto &Q : T->quals())
3284     mangleObjCProtocol(Q);
3285 
3286   if (T->isSpecialized())
3287     for (const auto &TA : T->getTypeArgs())
3288       mangleType(TA, Range, QMM_Drop);
3289 
3290   Out << '@';
3291 
3292   Out << '@';
3293 
3294   FunArgBackReferences.swap(OuterFunArgsContext);
3295   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3296   NameBackReferences.swap(OuterTemplateContext);
3297 }
3298 
3299 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
3300                                          Qualifiers Quals, SourceRange Range) {
3301   QualType PointeeType = T->getPointeeType();
3302   manglePointerCVQualifiers(Quals);
3303   manglePointerExtQualifiers(Quals, PointeeType);
3304 
3305   Out << "_E";
3306 
3307   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
3308 }
3309 
3310 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
3311                                          Qualifiers, SourceRange) {
3312   llvm_unreachable("Cannot mangle injected class name type.");
3313 }
3314 
3315 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
3316                                          Qualifiers, SourceRange Range) {
3317   DiagnosticsEngine &Diags = Context.getDiags();
3318   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3319     "cannot mangle this template specialization type yet");
3320   Diags.Report(Range.getBegin(), DiagID)
3321     << Range;
3322 }
3323 
3324 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
3325                                          SourceRange Range) {
3326   DiagnosticsEngine &Diags = Context.getDiags();
3327   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3328     "cannot mangle this dependent name type yet");
3329   Diags.Report(Range.getBegin(), DiagID)
3330     << Range;
3331 }
3332 
3333 void MicrosoftCXXNameMangler::mangleType(
3334     const DependentTemplateSpecializationType *T, Qualifiers,
3335     SourceRange Range) {
3336   DiagnosticsEngine &Diags = Context.getDiags();
3337   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3338     "cannot mangle this dependent template specialization type yet");
3339   Diags.Report(Range.getBegin(), DiagID)
3340     << Range;
3341 }
3342 
3343 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
3344                                          SourceRange Range) {
3345   DiagnosticsEngine &Diags = Context.getDiags();
3346   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3347     "cannot mangle this pack expansion yet");
3348   Diags.Report(Range.getBegin(), DiagID)
3349     << Range;
3350 }
3351 
3352 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
3353                                          SourceRange Range) {
3354   DiagnosticsEngine &Diags = Context.getDiags();
3355   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3356     "cannot mangle this typeof(type) yet");
3357   Diags.Report(Range.getBegin(), DiagID)
3358     << Range;
3359 }
3360 
3361 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
3362                                          SourceRange Range) {
3363   DiagnosticsEngine &Diags = Context.getDiags();
3364   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3365     "cannot mangle this typeof(expression) yet");
3366   Diags.Report(Range.getBegin(), DiagID)
3367     << Range;
3368 }
3369 
3370 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
3371                                          SourceRange Range) {
3372   DiagnosticsEngine &Diags = Context.getDiags();
3373   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3374     "cannot mangle this decltype() yet");
3375   Diags.Report(Range.getBegin(), DiagID)
3376     << Range;
3377 }
3378 
3379 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
3380                                          Qualifiers, SourceRange Range) {
3381   DiagnosticsEngine &Diags = Context.getDiags();
3382   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3383     "cannot mangle this unary transform type yet");
3384   Diags.Report(Range.getBegin(), DiagID)
3385     << Range;
3386 }
3387 
3388 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
3389                                          SourceRange Range) {
3390   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3391 
3392   DiagnosticsEngine &Diags = Context.getDiags();
3393   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3394     "cannot mangle this 'auto' type yet");
3395   Diags.Report(Range.getBegin(), DiagID)
3396     << Range;
3397 }
3398 
3399 void MicrosoftCXXNameMangler::mangleType(
3400     const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
3401   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3402 
3403   DiagnosticsEngine &Diags = Context.getDiags();
3404   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3405     "cannot mangle this deduced class template specialization type yet");
3406   Diags.Report(Range.getBegin(), DiagID)
3407     << Range;
3408 }
3409 
3410 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
3411                                          SourceRange Range) {
3412   QualType ValueType = T->getValueType();
3413 
3414   llvm::SmallString<64> TemplateMangling;
3415   llvm::raw_svector_ostream Stream(TemplateMangling);
3416   MicrosoftCXXNameMangler Extra(Context, Stream);
3417   Stream << "?$";
3418   Extra.mangleSourceName("_Atomic");
3419   Extra.mangleType(ValueType, Range, QMM_Escape);
3420 
3421   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3422 }
3423 
3424 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
3425                                          SourceRange Range) {
3426   QualType ElementType = T->getElementType();
3427 
3428   llvm::SmallString<64> TemplateMangling;
3429   llvm::raw_svector_ostream Stream(TemplateMangling);
3430   MicrosoftCXXNameMangler Extra(Context, Stream);
3431   Stream << "?$";
3432   Extra.mangleSourceName("ocl_pipe");
3433   Extra.mangleType(ElementType, Range, QMM_Escape);
3434   Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()));
3435 
3436   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3437 }
3438 
3439 void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
3440                                                raw_ostream &Out) {
3441   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
3442   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3443                                  getASTContext().getSourceManager(),
3444                                  "Mangling declaration");
3445 
3446   msvc_hashing_ostream MHO(Out);
3447 
3448   if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
3449     auto Type = GD.getCtorType();
3450     MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
3451     return mangler.mangle(GD);
3452   }
3453 
3454   if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
3455     auto Type = GD.getDtorType();
3456     MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
3457     return mangler.mangle(GD);
3458   }
3459 
3460   MicrosoftCXXNameMangler Mangler(*this, MHO);
3461   return Mangler.mangle(GD);
3462 }
3463 
3464 void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers,
3465                                          SourceRange Range) {
3466   llvm::SmallString<64> TemplateMangling;
3467   llvm::raw_svector_ostream Stream(TemplateMangling);
3468   MicrosoftCXXNameMangler Extra(Context, Stream);
3469   Stream << "?$";
3470   if (T->isUnsigned())
3471     Extra.mangleSourceName("_UBitInt");
3472   else
3473     Extra.mangleSourceName("_BitInt");
3474   Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()));
3475 
3476   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3477 }
3478 
3479 void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T,
3480                                          Qualifiers, SourceRange Range) {
3481   DiagnosticsEngine &Diags = Context.getDiags();
3482   unsigned DiagID = Diags.getCustomDiagID(
3483       DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet");
3484   Diags.Report(Range.getBegin(), DiagID) << Range;
3485 }
3486 
3487 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
3488 //                       <virtual-adjustment>
3489 // <no-adjustment>      ::= A # private near
3490 //                      ::= B # private far
3491 //                      ::= I # protected near
3492 //                      ::= J # protected far
3493 //                      ::= Q # public near
3494 //                      ::= R # public far
3495 // <static-adjustment>  ::= G <static-offset> # private near
3496 //                      ::= H <static-offset> # private far
3497 //                      ::= O <static-offset> # protected near
3498 //                      ::= P <static-offset> # protected far
3499 //                      ::= W <static-offset> # public near
3500 //                      ::= X <static-offset> # public far
3501 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
3502 //                      ::= $1 <virtual-shift> <static-offset> # private far
3503 //                      ::= $2 <virtual-shift> <static-offset> # protected near
3504 //                      ::= $3 <virtual-shift> <static-offset> # protected far
3505 //                      ::= $4 <virtual-shift> <static-offset> # public near
3506 //                      ::= $5 <virtual-shift> <static-offset> # public far
3507 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
3508 // <vtordisp-shift>     ::= <offset-to-vtordisp>
3509 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
3510 //                          <offset-to-vtordisp>
3511 static void mangleThunkThisAdjustment(AccessSpecifier AS,
3512                                       const ThisAdjustment &Adjustment,
3513                                       MicrosoftCXXNameMangler &Mangler,
3514                                       raw_ostream &Out) {
3515   if (!Adjustment.Virtual.isEmpty()) {
3516     Out << '$';
3517     char AccessSpec;
3518     switch (AS) {
3519     case AS_none:
3520       llvm_unreachable("Unsupported access specifier");
3521     case AS_private:
3522       AccessSpec = '0';
3523       break;
3524     case AS_protected:
3525       AccessSpec = '2';
3526       break;
3527     case AS_public:
3528       AccessSpec = '4';
3529     }
3530     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
3531       Out << 'R' << AccessSpec;
3532       Mangler.mangleNumber(
3533           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
3534       Mangler.mangleNumber(
3535           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
3536       Mangler.mangleNumber(
3537           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3538       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
3539     } else {
3540       Out << AccessSpec;
3541       Mangler.mangleNumber(
3542           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3543       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3544     }
3545   } else if (Adjustment.NonVirtual != 0) {
3546     switch (AS) {
3547     case AS_none:
3548       llvm_unreachable("Unsupported access specifier");
3549     case AS_private:
3550       Out << 'G';
3551       break;
3552     case AS_protected:
3553       Out << 'O';
3554       break;
3555     case AS_public:
3556       Out << 'W';
3557     }
3558     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3559   } else {
3560     switch (AS) {
3561     case AS_none:
3562       llvm_unreachable("Unsupported access specifier");
3563     case AS_private:
3564       Out << 'A';
3565       break;
3566     case AS_protected:
3567       Out << 'I';
3568       break;
3569     case AS_public:
3570       Out << 'Q';
3571     }
3572   }
3573 }
3574 
3575 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3576     const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3577     raw_ostream &Out) {
3578   msvc_hashing_ostream MHO(Out);
3579   MicrosoftCXXNameMangler Mangler(*this, MHO);
3580   Mangler.getStream() << '?';
3581   Mangler.mangleVirtualMemPtrThunk(MD, ML);
3582 }
3583 
3584 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3585                                              const ThunkInfo &Thunk,
3586                                              raw_ostream &Out) {
3587   msvc_hashing_ostream MHO(Out);
3588   MicrosoftCXXNameMangler Mangler(*this, MHO);
3589   Mangler.getStream() << '?';
3590   Mangler.mangleName(MD);
3591 
3592   // Usually the thunk uses the access specifier of the new method, but if this
3593   // is a covariant return thunk, then MSVC always uses the public access
3594   // specifier, and we do the same.
3595   AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3596   mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3597 
3598   if (!Thunk.Return.isEmpty())
3599     assert(Thunk.Method != nullptr &&
3600            "Thunk info should hold the overridee decl");
3601 
3602   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3603   Mangler.mangleFunctionType(
3604       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3605 }
3606 
3607 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3608     const CXXDestructorDecl *DD, CXXDtorType Type,
3609     const ThisAdjustment &Adjustment, raw_ostream &Out) {
3610   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3611   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3612   // mangling manually until we support both deleting dtor types.
3613   assert(Type == Dtor_Deleting);
3614   msvc_hashing_ostream MHO(Out);
3615   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3616   Mangler.getStream() << "??_E";
3617   Mangler.mangleName(DD->getParent());
3618   mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3619   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3620 }
3621 
3622 void MicrosoftMangleContextImpl::mangleCXXVFTable(
3623     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3624     raw_ostream &Out) {
3625   // <mangled-name> ::= ?_7 <class-name> <storage-class>
3626   //                    <cvr-qualifiers> [<name>] @
3627   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3628   // is always '6' for vftables.
3629   msvc_hashing_ostream MHO(Out);
3630   MicrosoftCXXNameMangler Mangler(*this, MHO);
3631   if (Derived->hasAttr<DLLImportAttr>())
3632     Mangler.getStream() << "??_S";
3633   else
3634     Mangler.getStream() << "??_7";
3635   Mangler.mangleName(Derived);
3636   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3637   for (const CXXRecordDecl *RD : BasePath)
3638     Mangler.mangleName(RD);
3639   Mangler.getStream() << '@';
3640 }
3641 
3642 void MicrosoftMangleContextImpl::mangleCXXVBTable(
3643     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3644     raw_ostream &Out) {
3645   // <mangled-name> ::= ?_8 <class-name> <storage-class>
3646   //                    <cvr-qualifiers> [<name>] @
3647   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3648   // is always '7' for vbtables.
3649   msvc_hashing_ostream MHO(Out);
3650   MicrosoftCXXNameMangler Mangler(*this, MHO);
3651   Mangler.getStream() << "??_8";
3652   Mangler.mangleName(Derived);
3653   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3654   for (const CXXRecordDecl *RD : BasePath)
3655     Mangler.mangleName(RD);
3656   Mangler.getStream() << '@';
3657 }
3658 
3659 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3660   msvc_hashing_ostream MHO(Out);
3661   MicrosoftCXXNameMangler Mangler(*this, MHO);
3662   Mangler.getStream() << "??_R0";
3663   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3664   Mangler.getStream() << "@8";
3665 }
3666 
3667 void MicrosoftMangleContextImpl::mangleCXXRTTIName(
3668     QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
3669   MicrosoftCXXNameMangler Mangler(*this, Out);
3670   Mangler.getStream() << '.';
3671   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3672 }
3673 
3674 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3675     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3676   msvc_hashing_ostream MHO(Out);
3677   MicrosoftCXXNameMangler Mangler(*this, MHO);
3678   Mangler.getStream() << "??_K";
3679   Mangler.mangleName(SrcRD);
3680   Mangler.getStream() << "$C";
3681   Mangler.mangleName(DstRD);
3682 }
3683 
3684 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3685                                                     bool IsVolatile,
3686                                                     bool IsUnaligned,
3687                                                     uint32_t NumEntries,
3688                                                     raw_ostream &Out) {
3689   msvc_hashing_ostream MHO(Out);
3690   MicrosoftCXXNameMangler Mangler(*this, MHO);
3691   Mangler.getStream() << "_TI";
3692   if (IsConst)
3693     Mangler.getStream() << 'C';
3694   if (IsVolatile)
3695     Mangler.getStream() << 'V';
3696   if (IsUnaligned)
3697     Mangler.getStream() << 'U';
3698   Mangler.getStream() << NumEntries;
3699   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3700 }
3701 
3702 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3703     QualType T, uint32_t NumEntries, raw_ostream &Out) {
3704   msvc_hashing_ostream MHO(Out);
3705   MicrosoftCXXNameMangler Mangler(*this, MHO);
3706   Mangler.getStream() << "_CTA";
3707   Mangler.getStream() << NumEntries;
3708   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3709 }
3710 
3711 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3712     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3713     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3714     raw_ostream &Out) {
3715   MicrosoftCXXNameMangler Mangler(*this, Out);
3716   Mangler.getStream() << "_CT";
3717 
3718   llvm::SmallString<64> RTTIMangling;
3719   {
3720     llvm::raw_svector_ostream Stream(RTTIMangling);
3721     msvc_hashing_ostream MHO(Stream);
3722     mangleCXXRTTI(T, MHO);
3723   }
3724   Mangler.getStream() << RTTIMangling;
3725 
3726   // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
3727   // both older and newer versions include it.
3728   // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
3729   // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
3730   // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
3731   // Or 1912, 1913 already?).
3732   bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
3733                           LangOptions::MSVC2015) &&
3734                       !getASTContext().getLangOpts().isCompatibleWithMSVC(
3735                           LangOptions::MSVC2017_7);
3736   llvm::SmallString<64> CopyCtorMangling;
3737   if (!OmitCopyCtor && CD) {
3738     llvm::raw_svector_ostream Stream(CopyCtorMangling);
3739     msvc_hashing_ostream MHO(Stream);
3740     mangleCXXName(GlobalDecl(CD, CT), MHO);
3741   }
3742   Mangler.getStream() << CopyCtorMangling;
3743 
3744   Mangler.getStream() << Size;
3745   if (VBPtrOffset == -1) {
3746     if (NVOffset) {
3747       Mangler.getStream() << NVOffset;
3748     }
3749   } else {
3750     Mangler.getStream() << NVOffset;
3751     Mangler.getStream() << VBPtrOffset;
3752     Mangler.getStream() << VBIndex;
3753   }
3754 }
3755 
3756 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3757     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3758     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3759   msvc_hashing_ostream MHO(Out);
3760   MicrosoftCXXNameMangler Mangler(*this, MHO);
3761   Mangler.getStream() << "??_R1";
3762   Mangler.mangleNumber(NVOffset);
3763   Mangler.mangleNumber(VBPtrOffset);
3764   Mangler.mangleNumber(VBTableOffset);
3765   Mangler.mangleNumber(Flags);
3766   Mangler.mangleName(Derived);
3767   Mangler.getStream() << "8";
3768 }
3769 
3770 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3771     const CXXRecordDecl *Derived, raw_ostream &Out) {
3772   msvc_hashing_ostream MHO(Out);
3773   MicrosoftCXXNameMangler Mangler(*this, MHO);
3774   Mangler.getStream() << "??_R2";
3775   Mangler.mangleName(Derived);
3776   Mangler.getStream() << "8";
3777 }
3778 
3779 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3780     const CXXRecordDecl *Derived, raw_ostream &Out) {
3781   msvc_hashing_ostream MHO(Out);
3782   MicrosoftCXXNameMangler Mangler(*this, MHO);
3783   Mangler.getStream() << "??_R3";
3784   Mangler.mangleName(Derived);
3785   Mangler.getStream() << "8";
3786 }
3787 
3788 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3789     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3790     raw_ostream &Out) {
3791   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3792   //                    <cvr-qualifiers> [<name>] @
3793   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3794   // is always '6' for vftables.
3795   llvm::SmallString<64> VFTableMangling;
3796   llvm::raw_svector_ostream Stream(VFTableMangling);
3797   mangleCXXVFTable(Derived, BasePath, Stream);
3798 
3799   if (VFTableMangling.startswith("??@")) {
3800     assert(VFTableMangling.endswith("@"));
3801     Out << VFTableMangling << "??_R4@";
3802     return;
3803   }
3804 
3805   assert(VFTableMangling.startswith("??_7") ||
3806          VFTableMangling.startswith("??_S"));
3807 
3808   Out << "??_R4" << VFTableMangling.str().drop_front(4);
3809 }
3810 
3811 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3812     GlobalDecl EnclosingDecl, raw_ostream &Out) {
3813   msvc_hashing_ostream MHO(Out);
3814   MicrosoftCXXNameMangler Mangler(*this, MHO);
3815   // The function body is in the same comdat as the function with the handler,
3816   // so the numbering here doesn't have to be the same across TUs.
3817   //
3818   // <mangled-name> ::= ?filt$ <filter-number> @0
3819   Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3820   Mangler.mangleName(EnclosingDecl);
3821 }
3822 
3823 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3824     GlobalDecl EnclosingDecl, raw_ostream &Out) {
3825   msvc_hashing_ostream MHO(Out);
3826   MicrosoftCXXNameMangler Mangler(*this, MHO);
3827   // The function body is in the same comdat as the function with the handler,
3828   // so the numbering here doesn't have to be the same across TUs.
3829   //
3830   // <mangled-name> ::= ?fin$ <filter-number> @0
3831   Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3832   Mangler.mangleName(EnclosingDecl);
3833 }
3834 
3835 void MicrosoftMangleContextImpl::mangleTypeName(
3836     QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
3837   // This is just a made up unique string for the purposes of tbaa.  undname
3838   // does *not* know how to demangle it.
3839   MicrosoftCXXNameMangler Mangler(*this, Out);
3840   Mangler.getStream() << '?';
3841   Mangler.mangleType(T, SourceRange());
3842 }
3843 
3844 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3845     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3846   msvc_hashing_ostream MHO(Out);
3847   MicrosoftCXXNameMangler Mangler(*this, MHO);
3848 
3849   Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3850   Mangler.mangle(VD, "");
3851 }
3852 
3853 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3854     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3855   msvc_hashing_ostream MHO(Out);
3856   MicrosoftCXXNameMangler Mangler(*this, MHO);
3857 
3858   Mangler.getStream() << "?$TSS" << GuardNum << '@';
3859   Mangler.mangleNestedName(VD);
3860   Mangler.getStream() << "@4HA";
3861 }
3862 
3863 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3864                                                            raw_ostream &Out) {
3865   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3866   //              ::= ?__J <postfix> @5 <scope-depth>
3867   //              ::= ?$S <guard-num> @ <postfix> @4IA
3868 
3869   // The first mangling is what MSVC uses to guard static locals in inline
3870   // functions.  It uses a different mangling in external functions to support
3871   // guarding more than 32 variables.  MSVC rejects inline functions with more
3872   // than 32 static locals.  We don't fully implement the second mangling
3873   // because those guards are not externally visible, and instead use LLVM's
3874   // default renaming when creating a new guard variable.
3875   msvc_hashing_ostream MHO(Out);
3876   MicrosoftCXXNameMangler Mangler(*this, MHO);
3877 
3878   bool Visible = VD->isExternallyVisible();
3879   if (Visible) {
3880     Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3881   } else {
3882     Mangler.getStream() << "?$S1@";
3883   }
3884   unsigned ScopeDepth = 0;
3885   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3886     // If we do not have a discriminator and are emitting a guard variable for
3887     // use at global scope, then mangling the nested name will not be enough to
3888     // remove ambiguities.
3889     Mangler.mangle(VD, "");
3890   else
3891     Mangler.mangleNestedName(VD);
3892   Mangler.getStream() << (Visible ? "@5" : "@4IA");
3893   if (ScopeDepth)
3894     Mangler.mangleNumber(ScopeDepth);
3895 }
3896 
3897 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3898                                                     char CharCode,
3899                                                     raw_ostream &Out) {
3900   msvc_hashing_ostream MHO(Out);
3901   MicrosoftCXXNameMangler Mangler(*this, MHO);
3902   Mangler.getStream() << "??__" << CharCode;
3903   if (D->isStaticDataMember()) {
3904     Mangler.getStream() << '?';
3905     Mangler.mangleName(D);
3906     Mangler.mangleVariableEncoding(D);
3907     Mangler.getStream() << "@@";
3908   } else {
3909     Mangler.mangleName(D);
3910   }
3911   // This is the function class mangling.  These stubs are global, non-variadic,
3912   // cdecl functions that return void and take no args.
3913   Mangler.getStream() << "YAXXZ";
3914 }
3915 
3916 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3917                                                           raw_ostream &Out) {
3918   // <initializer-name> ::= ?__E <name> YAXXZ
3919   mangleInitFiniStub(D, 'E', Out);
3920 }
3921 
3922 void
3923 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3924                                                           raw_ostream &Out) {
3925   // <destructor-name> ::= ?__F <name> YAXXZ
3926   mangleInitFiniStub(D, 'F', Out);
3927 }
3928 
3929 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3930                                                      raw_ostream &Out) {
3931   // <char-type> ::= 0   # char, char16_t, char32_t
3932   //                     # (little endian char data in mangling)
3933   //             ::= 1   # wchar_t (big endian char data in mangling)
3934   //
3935   // <literal-length> ::= <non-negative integer>  # the length of the literal
3936   //
3937   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3938   //                                              # trailing null bytes
3939   //
3940   // <encoded-string> ::= <simple character>           # uninteresting character
3941   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3942   //                                                   # encode the byte for the
3943   //                                                   # character
3944   //                  ::= '?' [a-z]                    # \xe1 - \xfa
3945   //                  ::= '?' [A-Z]                    # \xc1 - \xda
3946   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3947   //
3948   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3949   //               <encoded-string> '@'
3950   MicrosoftCXXNameMangler Mangler(*this, Out);
3951   Mangler.getStream() << "??_C@_";
3952 
3953   // The actual string length might be different from that of the string literal
3954   // in cases like:
3955   // char foo[3] = "foobar";
3956   // char bar[42] = "foobar";
3957   // Where it is truncated or zero-padded to fit the array. This is the length
3958   // used for mangling, and any trailing null-bytes also need to be mangled.
3959   unsigned StringLength = getASTContext()
3960                               .getAsConstantArrayType(SL->getType())
3961                               ->getSize()
3962                               .getZExtValue();
3963   unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3964 
3965   // <char-type>: The "kind" of string literal is encoded into the mangled name.
3966   if (SL->isWide())
3967     Mangler.getStream() << '1';
3968   else
3969     Mangler.getStream() << '0';
3970 
3971   // <literal-length>: The next part of the mangled name consists of the length
3972   // of the string in bytes.
3973   Mangler.mangleNumber(StringByteLength);
3974 
3975   auto GetLittleEndianByte = [&SL](unsigned Index) {
3976     unsigned CharByteWidth = SL->getCharByteWidth();
3977     if (Index / CharByteWidth >= SL->getLength())
3978       return static_cast<char>(0);
3979     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3980     unsigned OffsetInCodeUnit = Index % CharByteWidth;
3981     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3982   };
3983 
3984   auto GetBigEndianByte = [&SL](unsigned Index) {
3985     unsigned CharByteWidth = SL->getCharByteWidth();
3986     if (Index / CharByteWidth >= SL->getLength())
3987       return static_cast<char>(0);
3988     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3989     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3990     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3991   };
3992 
3993   // CRC all the bytes of the StringLiteral.
3994   llvm::JamCRC JC;
3995   for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3996     JC.update(GetLittleEndianByte(I));
3997 
3998   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3999   // scheme.
4000   Mangler.mangleNumber(JC.getCRC());
4001 
4002   // <encoded-string>: The mangled name also contains the first 32 bytes
4003   // (including null-terminator bytes) of the encoded StringLiteral.
4004   // Each character is encoded by splitting them into bytes and then encoding
4005   // the constituent bytes.
4006   auto MangleByte = [&Mangler](char Byte) {
4007     // There are five different manglings for characters:
4008     // - [a-zA-Z0-9_$]: A one-to-one mapping.
4009     // - ?[a-z]: The range from \xe1 to \xfa.
4010     // - ?[A-Z]: The range from \xc1 to \xda.
4011     // - ?[0-9]: The set of [,/\:. \n\t'-].
4012     // - ?$XX: A fallback which maps nibbles.
4013     if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) {
4014       Mangler.getStream() << Byte;
4015     } else if (isLetter(Byte & 0x7f)) {
4016       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
4017     } else {
4018       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
4019                                    ' ', '\n', '\t', '\'', '-'};
4020       const char *Pos = llvm::find(SpecialChars, Byte);
4021       if (Pos != std::end(SpecialChars)) {
4022         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
4023       } else {
4024         Mangler.getStream() << "?$";
4025         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
4026         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
4027       }
4028     }
4029   };
4030 
4031   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
4032   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
4033   unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
4034   for (unsigned I = 0; I != NumBytesToMangle; ++I) {
4035     if (SL->isWide())
4036       MangleByte(GetBigEndianByte(I));
4037     else
4038       MangleByte(GetLittleEndianByte(I));
4039   }
4040 
4041   Mangler.getStream() << '@';
4042 }
4043 
4044 MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
4045                                                        DiagnosticsEngine &Diags,
4046                                                        bool IsAux) {
4047   return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
4048 }
4049