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