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