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