]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp
Upgrade our copies of clang, llvm, lld, lldb, compiler-rt, libc++,
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / MicrosoftMangle.cpp
1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/Mangle.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/VTableBuilder.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/JamCRC.h"
32 #include "llvm/Support/xxhash.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
35
36 using namespace clang;
37
38 namespace {
39
40 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
41   raw_ostream &OS;
42   llvm::SmallString<64> Buffer;
43
44   msvc_hashing_ostream(raw_ostream &OS)
45       : llvm::raw_svector_ostream(Buffer), OS(OS) {}
46   ~msvc_hashing_ostream() override {
47     StringRef MangledName = str();
48     bool StartsWithEscape = MangledName.startswith("\01");
49     if (StartsWithEscape)
50       MangledName = MangledName.drop_front(1);
51     if (MangledName.size() <= 4096) {
52       OS << str();
53       return;
54     }
55
56     llvm::MD5 Hasher;
57     llvm::MD5::MD5Result Hash;
58     Hasher.update(MangledName);
59     Hasher.final(Hash);
60
61     SmallString<32> HexString;
62     llvm::MD5::stringifyResult(Hash, HexString);
63
64     if (StartsWithEscape)
65       OS << '\01';
66     OS << "??@" << HexString << '@';
67   }
68 };
69
70 static const DeclContext *
71 getLambdaDefaultArgumentDeclContext(const Decl *D) {
72   if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
73     if (RD->isLambda())
74       if (const auto *Parm =
75               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
76         return Parm->getDeclContext();
77   return nullptr;
78 }
79
80 /// Retrieve the declaration context that should be used when mangling
81 /// the given declaration.
82 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
83   // The ABI assumes that lambda closure types that occur within
84   // default arguments live in the context of the function. However, due to
85   // the way in which Clang parses and creates function declarations, this is
86   // not the case: the lambda closure type ends up living in the context
87   // where the function itself resides, because the function declaration itself
88   // had not yet been created. Fix the context here.
89   if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
90     return LDADC;
91
92   // Perform the same check for block literals.
93   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
94     if (ParmVarDecl *ContextParam =
95             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
96       return ContextParam->getDeclContext();
97   }
98
99   const DeclContext *DC = D->getDeclContext();
100   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
101     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<int> 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
1765   auto Iter = PassObjectSizeArgs.insert(Type).first;
1766   auto *TypePtr = (const void *)&*Iter;
1767   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1768
1769   if (Found == TypeBackReferences.end()) {
1770     mangleArtificialTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1771                            {"__clang"});
1772
1773     if (TypeBackReferences.size() < 10) {
1774       size_t Size = TypeBackReferences.size();
1775       TypeBackReferences[TypePtr] = Size;
1776     }
1777   } else {
1778     Out << Found->second;
1779   }
1780 }
1781
1782 void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
1783                                                      Qualifiers Quals,
1784                                                      SourceRange Range) {
1785   // Address space is mangled as an unqualified templated type in the __clang
1786   // namespace. The demangled version of this is:
1787   // In the case of a language specific address space:
1788   // __clang::struct _AS[language_addr_space]<Type>
1789   // where:
1790   //  <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
1791   //    <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
1792   //                                "private"| "generic" ]
1793   //    <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1794   //    Note that the above were chosen to match the Itanium mangling for this.
1795   //
1796   // In the case of a non-language specific address space:
1797   //  __clang::struct _AS<TargetAS, Type>
1798   assert(Quals.hasAddressSpace() && "Not valid without address space");
1799   llvm::SmallString<32> ASMangling;
1800   llvm::raw_svector_ostream Stream(ASMangling);
1801   MicrosoftCXXNameMangler Extra(Context, Stream);
1802   Stream << "?$";
1803
1804   LangAS AS = Quals.getAddressSpace();
1805   if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1806     unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1807     Extra.mangleSourceName("_AS");
1808     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS),
1809                                /*IsBoolean*/ false);
1810   } else {
1811     switch (AS) {
1812     default:
1813       llvm_unreachable("Not a language specific address space");
1814     case LangAS::opencl_global:
1815       Extra.mangleSourceName("_ASCLglobal");
1816       break;
1817     case LangAS::opencl_local:
1818       Extra.mangleSourceName("_ASCLlocal");
1819       break;
1820     case LangAS::opencl_constant:
1821       Extra.mangleSourceName("_ASCLconstant");
1822       break;
1823     case LangAS::opencl_private:
1824       Extra.mangleSourceName("_ASCLprivate");
1825       break;
1826     case LangAS::opencl_generic:
1827       Extra.mangleSourceName("_ASCLgeneric");
1828       break;
1829     case LangAS::cuda_device:
1830       Extra.mangleSourceName("_ASCUdevice");
1831       break;
1832     case LangAS::cuda_constant:
1833       Extra.mangleSourceName("_ASCUconstant");
1834       break;
1835     case LangAS::cuda_shared:
1836       Extra.mangleSourceName("_ASCUshared");
1837       break;
1838     }
1839   }
1840
1841   Extra.mangleType(T, Range, QMM_Escape);
1842   mangleQualifiers(Qualifiers(), false);
1843   mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
1844 }
1845
1846 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1847                                          QualifierMangleMode QMM) {
1848   // Don't use the canonical types.  MSVC includes things like 'const' on
1849   // pointer arguments to function pointers that canonicalization strips away.
1850   T = T.getDesugaredType(getASTContext());
1851   Qualifiers Quals = T.getLocalQualifiers();
1852
1853   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1854     // If there were any Quals, getAsArrayType() pushed them onto the array
1855     // element type.
1856     if (QMM == QMM_Mangle)
1857       Out << 'A';
1858     else if (QMM == QMM_Escape || QMM == QMM_Result)
1859       Out << "$$B";
1860     mangleArrayType(AT);
1861     return;
1862   }
1863
1864   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1865                    T->isReferenceType() || T->isBlockPointerType();
1866
1867   switch (QMM) {
1868   case QMM_Drop:
1869     if (Quals.hasObjCLifetime())
1870       Quals = Quals.withoutObjCLifetime();
1871     break;
1872   case QMM_Mangle:
1873     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1874       Out << '6';
1875       mangleFunctionType(FT);
1876       return;
1877     }
1878     mangleQualifiers(Quals, false);
1879     break;
1880   case QMM_Escape:
1881     if (!IsPointer && Quals) {
1882       Out << "$$C";
1883       mangleQualifiers(Quals, false);
1884     }
1885     break;
1886   case QMM_Result:
1887     // Presence of __unaligned qualifier shouldn't affect mangling here.
1888     Quals.removeUnaligned();
1889     if (Quals.hasObjCLifetime())
1890       Quals = Quals.withoutObjCLifetime();
1891     if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1892       Out << '?';
1893       mangleQualifiers(Quals, false);
1894     }
1895     break;
1896   }
1897
1898   const Type *ty = T.getTypePtr();
1899
1900   switch (ty->getTypeClass()) {
1901 #define ABSTRACT_TYPE(CLASS, PARENT)
1902 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1903   case Type::CLASS: \
1904     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1905     return;
1906 #define TYPE(CLASS, PARENT) \
1907   case Type::CLASS: \
1908     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1909     break;
1910 #include "clang/AST/TypeNodes.def"
1911 #undef ABSTRACT_TYPE
1912 #undef NON_CANONICAL_TYPE
1913 #undef TYPE
1914   }
1915 }
1916
1917 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1918                                          SourceRange Range) {
1919   //  <type>         ::= <builtin-type>
1920   //  <builtin-type> ::= X  # void
1921   //                 ::= C  # signed char
1922   //                 ::= D  # char
1923   //                 ::= E  # unsigned char
1924   //                 ::= F  # short
1925   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1926   //                 ::= H  # int
1927   //                 ::= I  # unsigned int
1928   //                 ::= J  # long
1929   //                 ::= K  # unsigned long
1930   //                     L  # <none>
1931   //                 ::= M  # float
1932   //                 ::= N  # double
1933   //                 ::= O  # long double (__float80 is mangled differently)
1934   //                 ::= _J # long long, __int64
1935   //                 ::= _K # unsigned long long, __int64
1936   //                 ::= _L # __int128
1937   //                 ::= _M # unsigned __int128
1938   //                 ::= _N # bool
1939   //                     _O # <array in parameter>
1940   //                 ::= _Q # char8_t
1941   //                 ::= _S # char16_t
1942   //                 ::= _T # __float80 (Intel)
1943   //                 ::= _U # char32_t
1944   //                 ::= _W # wchar_t
1945   //                 ::= _Z # __float80 (Digital Mars)
1946   switch (T->getKind()) {
1947   case BuiltinType::Void:
1948     Out << 'X';
1949     break;
1950   case BuiltinType::SChar:
1951     Out << 'C';
1952     break;
1953   case BuiltinType::Char_U:
1954   case BuiltinType::Char_S:
1955     Out << 'D';
1956     break;
1957   case BuiltinType::UChar:
1958     Out << 'E';
1959     break;
1960   case BuiltinType::Short:
1961     Out << 'F';
1962     break;
1963   case BuiltinType::UShort:
1964     Out << 'G';
1965     break;
1966   case BuiltinType::Int:
1967     Out << 'H';
1968     break;
1969   case BuiltinType::UInt:
1970     Out << 'I';
1971     break;
1972   case BuiltinType::Long:
1973     Out << 'J';
1974     break;
1975   case BuiltinType::ULong:
1976     Out << 'K';
1977     break;
1978   case BuiltinType::Float:
1979     Out << 'M';
1980     break;
1981   case BuiltinType::Double:
1982     Out << 'N';
1983     break;
1984   // TODO: Determine size and mangle accordingly
1985   case BuiltinType::LongDouble:
1986     Out << 'O';
1987     break;
1988   case BuiltinType::LongLong:
1989     Out << "_J";
1990     break;
1991   case BuiltinType::ULongLong:
1992     Out << "_K";
1993     break;
1994   case BuiltinType::Int128:
1995     Out << "_L";
1996     break;
1997   case BuiltinType::UInt128:
1998     Out << "_M";
1999     break;
2000   case BuiltinType::Bool:
2001     Out << "_N";
2002     break;
2003   case BuiltinType::Char8:
2004     Out << "_Q";
2005     break;
2006   case BuiltinType::Char16:
2007     Out << "_S";
2008     break;
2009   case BuiltinType::Char32:
2010     Out << "_U";
2011     break;
2012   case BuiltinType::WChar_S:
2013   case BuiltinType::WChar_U:
2014     Out << "_W";
2015     break;
2016
2017 #define BUILTIN_TYPE(Id, SingletonId)
2018 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2019   case BuiltinType::Id:
2020 #include "clang/AST/BuiltinTypes.def"
2021   case BuiltinType::Dependent:
2022     llvm_unreachable("placeholder types shouldn't get to name mangling");
2023
2024   case BuiltinType::ObjCId:
2025     mangleArtificialTagType(TTK_Struct, "objc_object");
2026     break;
2027   case BuiltinType::ObjCClass:
2028     mangleArtificialTagType(TTK_Struct, "objc_class");
2029     break;
2030   case BuiltinType::ObjCSel:
2031     mangleArtificialTagType(TTK_Struct, "objc_selector");
2032     break;
2033
2034 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2035   case BuiltinType::Id: \
2036     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2037     break;
2038 #include "clang/Basic/OpenCLImageTypes.def"
2039   case BuiltinType::OCLSampler:
2040     Out << "PA";
2041     mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2042     break;
2043   case BuiltinType::OCLEvent:
2044     Out << "PA";
2045     mangleArtificialTagType(TTK_Struct, "ocl_event");
2046     break;
2047   case BuiltinType::OCLClkEvent:
2048     Out << "PA";
2049     mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2050     break;
2051   case BuiltinType::OCLQueue:
2052     Out << "PA";
2053     mangleArtificialTagType(TTK_Struct, "ocl_queue");
2054     break;
2055   case BuiltinType::OCLReserveID:
2056     Out << "PA";
2057     mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2058     break;
2059 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2060   case BuiltinType::Id: \
2061     mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2062     break;
2063 #include "clang/Basic/OpenCLExtensionTypes.def"
2064
2065   case BuiltinType::NullPtr:
2066     Out << "$$T";
2067     break;
2068
2069   case BuiltinType::Float16:
2070     mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2071     break;
2072
2073   case BuiltinType::Half:
2074     mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2075     break;
2076
2077   case BuiltinType::ShortAccum:
2078   case BuiltinType::Accum:
2079   case BuiltinType::LongAccum:
2080   case BuiltinType::UShortAccum:
2081   case BuiltinType::UAccum:
2082   case BuiltinType::ULongAccum:
2083   case BuiltinType::ShortFract:
2084   case BuiltinType::Fract:
2085   case BuiltinType::LongFract:
2086   case BuiltinType::UShortFract:
2087   case BuiltinType::UFract:
2088   case BuiltinType::ULongFract:
2089   case BuiltinType::SatShortAccum:
2090   case BuiltinType::SatAccum:
2091   case BuiltinType::SatLongAccum:
2092   case BuiltinType::SatUShortAccum:
2093   case BuiltinType::SatUAccum:
2094   case BuiltinType::SatULongAccum:
2095   case BuiltinType::SatShortFract:
2096   case BuiltinType::SatFract:
2097   case BuiltinType::SatLongFract:
2098   case BuiltinType::SatUShortFract:
2099   case BuiltinType::SatUFract:
2100   case BuiltinType::SatULongFract:
2101   case BuiltinType::Float128: {
2102     DiagnosticsEngine &Diags = Context.getDiags();
2103     unsigned DiagID = Diags.getCustomDiagID(
2104         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2105     Diags.Report(Range.getBegin(), DiagID)
2106         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2107     break;
2108   }
2109   }
2110 }
2111
2112 // <type>          ::= <function-type>
2113 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2114                                          SourceRange) {
2115   // Structors only appear in decls, so at this point we know it's not a
2116   // structor type.
2117   // FIXME: This may not be lambda-friendly.
2118   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
2119     Out << "$$A8@@";
2120     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2121   } else {
2122     Out << "$$A6";
2123     mangleFunctionType(T);
2124   }
2125 }
2126 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2127                                          Qualifiers, SourceRange) {
2128   Out << "$$A6";
2129   mangleFunctionType(T);
2130 }
2131
2132 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2133                                                  const FunctionDecl *D,
2134                                                  bool ForceThisQuals,
2135                                                  bool MangleExceptionSpec) {
2136   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2137   //                     <return-type> <argument-list> <throw-spec>
2138   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2139
2140   SourceRange Range;
2141   if (D) Range = D->getSourceRange();
2142
2143   bool IsInLambda = false;
2144   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2145   CallingConv CC = T->getCallConv();
2146   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2147     if (MD->getParent()->isLambda())
2148       IsInLambda = true;
2149     if (MD->isInstance())
2150       HasThisQuals = true;
2151     if (isa<CXXDestructorDecl>(MD)) {
2152       IsStructor = true;
2153     } else if (isa<CXXConstructorDecl>(MD)) {
2154       IsStructor = true;
2155       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2156                        StructorType == Ctor_DefaultClosure) &&
2157                       isStructorDecl(MD);
2158       if (IsCtorClosure)
2159         CC = getASTContext().getDefaultCallingConvention(
2160             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2161     }
2162   }
2163
2164   // If this is a C++ instance method, mangle the CVR qualifiers for the
2165   // this pointer.
2166   if (HasThisQuals) {
2167     Qualifiers Quals = Proto->getTypeQuals();
2168     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2169     mangleRefQualifier(Proto->getRefQualifier());
2170     mangleQualifiers(Quals, /*IsMember=*/false);
2171   }
2172
2173   mangleCallingConvention(CC);
2174
2175   // <return-type> ::= <type>
2176   //               ::= @ # structors (they have no declared return type)
2177   if (IsStructor) {
2178     if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2179       // The scalar deleting destructor takes an extra int argument which is not
2180       // reflected in the AST.
2181       if (StructorType == Dtor_Deleting) {
2182         Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2183         return;
2184       }
2185       // The vbase destructor returns void which is not reflected in the AST.
2186       if (StructorType == Dtor_Complete) {
2187         Out << "XXZ";
2188         return;
2189       }
2190     }
2191     if (IsCtorClosure) {
2192       // Default constructor closure and copy constructor closure both return
2193       // void.
2194       Out << 'X';
2195
2196       if (StructorType == Ctor_DefaultClosure) {
2197         // Default constructor closure always has no arguments.
2198         Out << 'X';
2199       } else if (StructorType == Ctor_CopyingClosure) {
2200         // Copy constructor closure always takes an unqualified reference.
2201         mangleArgumentType(getASTContext().getLValueReferenceType(
2202                                Proto->getParamType(0)
2203                                    ->getAs<LValueReferenceType>()
2204                                    ->getPointeeType(),
2205                                /*SpelledAsLValue=*/true),
2206                            Range);
2207         Out << '@';
2208       } else {
2209         llvm_unreachable("unexpected constructor closure!");
2210       }
2211       Out << 'Z';
2212       return;
2213     }
2214     Out << '@';
2215   } else {
2216     QualType ResultType = T->getReturnType();
2217     if (const auto *AT =
2218             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2219       Out << '?';
2220       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2221       Out << '?';
2222       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2223              "shouldn't need to mangle __auto_type!");
2224       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2225       Out << '@';
2226     } else if (IsInLambda) {
2227       Out << '@';
2228     } else {
2229       if (ResultType->isVoidType())
2230         ResultType = ResultType.getUnqualifiedType();
2231       mangleType(ResultType, Range, QMM_Result);
2232     }
2233   }
2234
2235   // <argument-list> ::= X # void
2236   //                 ::= <type>+ @
2237   //                 ::= <type>* Z # varargs
2238   if (!Proto) {
2239     // Function types without prototypes can arise when mangling a function type
2240     // within an overloadable function in C. We mangle these as the absence of
2241     // any parameter types (not even an empty parameter list).
2242     Out << '@';
2243   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2244     Out << 'X';
2245   } else {
2246     // Happens for function pointer type arguments for example.
2247     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2248       mangleArgumentType(Proto->getParamType(I), Range);
2249       // Mangle each pass_object_size parameter as if it's a parameter of enum
2250       // type passed directly after the parameter with the pass_object_size
2251       // attribute. The aforementioned enum's name is __pass_object_size, and we
2252       // pretend it resides in a top-level namespace called __clang.
2253       //
2254       // FIXME: Is there a defined extension notation for the MS ABI, or is it
2255       // necessary to just cross our fingers and hope this type+namespace
2256       // combination doesn't conflict with anything?
2257       if (D)
2258         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2259           manglePassObjectSizeArg(P);
2260     }
2261     // <builtin-type>      ::= Z  # ellipsis
2262     if (Proto->isVariadic())
2263       Out << 'Z';
2264     else
2265       Out << '@';
2266   }
2267
2268   if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2269       getASTContext().getLangOpts().isCompatibleWithMSVC(
2270           LangOptions::MSVC2017_5))
2271     mangleThrowSpecification(Proto);
2272   else
2273     Out << 'Z';
2274 }
2275
2276 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2277   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2278   //                                            # pointer. in 64-bit mode *all*
2279   //                                            # 'this' pointers are 64-bit.
2280   //                   ::= <global-function>
2281   // <member-function> ::= A # private: near
2282   //                   ::= B # private: far
2283   //                   ::= C # private: static near
2284   //                   ::= D # private: static far
2285   //                   ::= E # private: virtual near
2286   //                   ::= F # private: virtual far
2287   //                   ::= I # protected: near
2288   //                   ::= J # protected: far
2289   //                   ::= K # protected: static near
2290   //                   ::= L # protected: static far
2291   //                   ::= M # protected: virtual near
2292   //                   ::= N # protected: virtual far
2293   //                   ::= Q # public: near
2294   //                   ::= R # public: far
2295   //                   ::= S # public: static near
2296   //                   ::= T # public: static far
2297   //                   ::= U # public: virtual near
2298   //                   ::= V # public: virtual far
2299   // <global-function> ::= Y # global near
2300   //                   ::= Z # global far
2301   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2302     bool IsVirtual = MD->isVirtual();
2303     // When mangling vbase destructor variants, ignore whether or not the
2304     // underlying destructor was defined to be virtual.
2305     if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2306         StructorType == Dtor_Complete) {
2307       IsVirtual = false;
2308     }
2309     switch (MD->getAccess()) {
2310       case AS_none:
2311         llvm_unreachable("Unsupported access specifier");
2312       case AS_private:
2313         if (MD->isStatic())
2314           Out << 'C';
2315         else if (IsVirtual)
2316           Out << 'E';
2317         else
2318           Out << 'A';
2319         break;
2320       case AS_protected:
2321         if (MD->isStatic())
2322           Out << 'K';
2323         else if (IsVirtual)
2324           Out << 'M';
2325         else
2326           Out << 'I';
2327         break;
2328       case AS_public:
2329         if (MD->isStatic())
2330           Out << 'S';
2331         else if (IsVirtual)
2332           Out << 'U';
2333         else
2334           Out << 'Q';
2335     }
2336   } else {
2337     Out << 'Y';
2338   }
2339 }
2340 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2341   // <calling-convention> ::= A # __cdecl
2342   //                      ::= B # __export __cdecl
2343   //                      ::= C # __pascal
2344   //                      ::= D # __export __pascal
2345   //                      ::= E # __thiscall
2346   //                      ::= F # __export __thiscall
2347   //                      ::= G # __stdcall
2348   //                      ::= H # __export __stdcall
2349   //                      ::= I # __fastcall
2350   //                      ::= J # __export __fastcall
2351   //                      ::= Q # __vectorcall
2352   //                      ::= w # __regcall
2353   // The 'export' calling conventions are from a bygone era
2354   // (*cough*Win16*cough*) when functions were declared for export with
2355   // that keyword. (It didn't actually export them, it just made them so
2356   // that they could be in a DLL and somebody from another module could call
2357   // them.)
2358
2359   switch (CC) {
2360     default:
2361       llvm_unreachable("Unsupported CC for mangling");
2362     case CC_Win64:
2363     case CC_X86_64SysV:
2364     case CC_C: Out << 'A'; break;
2365     case CC_X86Pascal: Out << 'C'; break;
2366     case CC_X86ThisCall: Out << 'E'; break;
2367     case CC_X86StdCall: Out << 'G'; break;
2368     case CC_X86FastCall: Out << 'I'; break;
2369     case CC_X86VectorCall: Out << 'Q'; break;
2370     case CC_Swift: Out << 'S'; break;
2371     case CC_PreserveMost: Out << 'U'; break;
2372     case CC_X86RegCall: Out << 'w'; break;
2373   }
2374 }
2375 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2376   mangleCallingConvention(T->getCallConv());
2377 }
2378
2379 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2380                                                 const FunctionProtoType *FT) {
2381   // <throw-spec> ::= Z # (default)
2382   //              ::= _E # noexcept
2383   if (FT->canThrow())
2384     Out << 'Z';
2385   else
2386     Out << "_E";
2387 }
2388
2389 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2390                                          Qualifiers, SourceRange Range) {
2391   // Probably should be mangled as a template instantiation; need to see what
2392   // VC does first.
2393   DiagnosticsEngine &Diags = Context.getDiags();
2394   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2395     "cannot mangle this unresolved dependent type yet");
2396   Diags.Report(Range.getBegin(), DiagID)
2397     << Range;
2398 }
2399
2400 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2401 // <union-type>  ::= T <name>
2402 // <struct-type> ::= U <name>
2403 // <class-type>  ::= V <name>
2404 // <enum-type>   ::= W4 <name>
2405 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2406   switch (TTK) {
2407     case TTK_Union:
2408       Out << 'T';
2409       break;
2410     case TTK_Struct:
2411     case TTK_Interface:
2412       Out << 'U';
2413       break;
2414     case TTK_Class:
2415       Out << 'V';
2416       break;
2417     case TTK_Enum:
2418       Out << "W4";
2419       break;
2420   }
2421 }
2422 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2423                                          SourceRange) {
2424   mangleType(cast<TagType>(T)->getDecl());
2425 }
2426 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2427                                          SourceRange) {
2428   mangleType(cast<TagType>(T)->getDecl());
2429 }
2430 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2431   mangleTagTypeKind(TD->getTagKind());
2432   mangleName(TD);
2433 }
2434
2435 // If you add a call to this, consider updating isArtificialTagType() too.
2436 void MicrosoftCXXNameMangler::mangleArtificialTagType(
2437     TagTypeKind TK, StringRef UnqualifiedName,
2438     ArrayRef<StringRef> NestedNames) {
2439   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2440   mangleTagTypeKind(TK);
2441
2442   // Always start with the unqualified name.
2443   mangleSourceName(UnqualifiedName);
2444
2445   for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2446     mangleSourceName(*I);
2447
2448   // Terminate the whole name with an '@'.
2449   Out << '@';
2450 }
2451
2452 // <type>       ::= <array-type>
2453 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2454 //                  [Y <dimension-count> <dimension>+]
2455 //                  <element-type> # as global, E is never required
2456 // It's supposed to be the other way around, but for some strange reason, it
2457 // isn't. Today this behavior is retained for the sole purpose of backwards
2458 // compatibility.
2459 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2460   // This isn't a recursive mangling, so now we have to do it all in this
2461   // one call.
2462   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2463   mangleType(T->getElementType(), SourceRange());
2464 }
2465 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2466                                          SourceRange) {
2467   llvm_unreachable("Should have been special cased");
2468 }
2469 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2470                                          SourceRange) {
2471   llvm_unreachable("Should have been special cased");
2472 }
2473 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2474                                          Qualifiers, SourceRange) {
2475   llvm_unreachable("Should have been special cased");
2476 }
2477 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2478                                          Qualifiers, SourceRange) {
2479   llvm_unreachable("Should have been special cased");
2480 }
2481 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2482   QualType ElementTy(T, 0);
2483   SmallVector<llvm::APInt, 3> Dimensions;
2484   for (;;) {
2485     if (ElementTy->isConstantArrayType()) {
2486       const ConstantArrayType *CAT =
2487           getASTContext().getAsConstantArrayType(ElementTy);
2488       Dimensions.push_back(CAT->getSize());
2489       ElementTy = CAT->getElementType();
2490     } else if (ElementTy->isIncompleteArrayType()) {
2491       const IncompleteArrayType *IAT =
2492           getASTContext().getAsIncompleteArrayType(ElementTy);
2493       Dimensions.push_back(llvm::APInt(32, 0));
2494       ElementTy = IAT->getElementType();
2495     } else if (ElementTy->isVariableArrayType()) {
2496       const VariableArrayType *VAT =
2497         getASTContext().getAsVariableArrayType(ElementTy);
2498       Dimensions.push_back(llvm::APInt(32, 0));
2499       ElementTy = VAT->getElementType();
2500     } else if (ElementTy->isDependentSizedArrayType()) {
2501       // The dependent expression has to be folded into a constant (TODO).
2502       const DependentSizedArrayType *DSAT =
2503         getASTContext().getAsDependentSizedArrayType(ElementTy);
2504       DiagnosticsEngine &Diags = Context.getDiags();
2505       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2506         "cannot mangle this dependent-length array yet");
2507       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2508         << DSAT->getBracketsRange();
2509       return;
2510     } else {
2511       break;
2512     }
2513   }
2514   Out << 'Y';
2515   // <dimension-count> ::= <number> # number of extra dimensions
2516   mangleNumber(Dimensions.size());
2517   for (const llvm::APInt &Dimension : Dimensions)
2518     mangleNumber(Dimension.getLimitedValue());
2519   mangleType(ElementTy, SourceRange(), QMM_Escape);
2520 }
2521
2522 // <type>                   ::= <pointer-to-member-type>
2523 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2524 //                                                          <class name> <type>
2525 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2526                                          Qualifiers Quals, SourceRange Range) {
2527   QualType PointeeType = T->getPointeeType();
2528   manglePointerCVQualifiers(Quals);
2529   manglePointerExtQualifiers(Quals, PointeeType);
2530   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2531     Out << '8';
2532     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2533     mangleFunctionType(FPT, nullptr, true);
2534   } else {
2535     mangleQualifiers(PointeeType.getQualifiers(), true);
2536     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2537     mangleType(PointeeType, Range, QMM_Drop);
2538   }
2539 }
2540
2541 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2542                                          Qualifiers, SourceRange Range) {
2543   DiagnosticsEngine &Diags = Context.getDiags();
2544   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2545     "cannot mangle this template type parameter type yet");
2546   Diags.Report(Range.getBegin(), DiagID)
2547     << Range;
2548 }
2549
2550 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2551                                          Qualifiers, SourceRange Range) {
2552   DiagnosticsEngine &Diags = Context.getDiags();
2553   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2554     "cannot mangle this substituted parameter pack yet");
2555   Diags.Report(Range.getBegin(), DiagID)
2556     << Range;
2557 }
2558
2559 // <type> ::= <pointer-type>
2560 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2561 //                       # the E is required for 64-bit non-static pointers
2562 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2563                                          SourceRange Range) {
2564   QualType PointeeType = T->getPointeeType();
2565   manglePointerCVQualifiers(Quals);
2566   manglePointerExtQualifiers(Quals, PointeeType);
2567
2568   if (PointeeType.getQualifiers().hasAddressSpace())
2569     mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2570   else
2571     mangleType(PointeeType, Range);
2572 }
2573
2574 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2575                                          Qualifiers Quals, SourceRange Range) {
2576   QualType PointeeType = T->getPointeeType();
2577   switch (Quals.getObjCLifetime()) {
2578   case Qualifiers::OCL_None:
2579   case Qualifiers::OCL_ExplicitNone:
2580     break;
2581   case Qualifiers::OCL_Autoreleasing:
2582   case Qualifiers::OCL_Strong:
2583   case Qualifiers::OCL_Weak:
2584     return mangleObjCLifetime(PointeeType, Quals, Range);
2585   }
2586   manglePointerCVQualifiers(Quals);
2587   manglePointerExtQualifiers(Quals, PointeeType);
2588   mangleType(PointeeType, Range);
2589 }
2590
2591 // <type> ::= <reference-type>
2592 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2593 //                 # the E is required for 64-bit non-static lvalue references
2594 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2595                                          Qualifiers Quals, SourceRange Range) {
2596   QualType PointeeType = T->getPointeeType();
2597   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2598   Out << 'A';
2599   manglePointerExtQualifiers(Quals, PointeeType);
2600   mangleType(PointeeType, Range);
2601 }
2602
2603 // <type> ::= <r-value-reference-type>
2604 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2605 //                 # the E is required for 64-bit non-static rvalue references
2606 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2607                                          Qualifiers Quals, SourceRange Range) {
2608   QualType PointeeType = T->getPointeeType();
2609   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2610   Out << "$$Q";
2611   manglePointerExtQualifiers(Quals, PointeeType);
2612   mangleType(PointeeType, Range);
2613 }
2614
2615 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2616                                          SourceRange Range) {
2617   QualType ElementType = T->getElementType();
2618
2619   llvm::SmallString<64> TemplateMangling;
2620   llvm::raw_svector_ostream Stream(TemplateMangling);
2621   MicrosoftCXXNameMangler Extra(Context, Stream);
2622   Stream << "?$";
2623   Extra.mangleSourceName("_Complex");
2624   Extra.mangleType(ElementType, Range, QMM_Escape);
2625
2626   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2627 }
2628
2629 // Returns true for types that mangleArtificialTagType() gets called for with
2630 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2631 // mangling matters.
2632 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2633 // support.)
2634 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2635   const Type *ty = T.getTypePtr();
2636   switch (ty->getTypeClass()) {
2637   default:
2638     return false;
2639
2640   case Type::Vector: {
2641     // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2642     // but since mangleType(VectorType*) always calls mangleArtificialTagType()
2643     // just always return true (the other vector types are clang-only).
2644     return true;
2645   }
2646   }
2647 }
2648
2649 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2650                                          SourceRange Range) {
2651   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2652   assert(ET && "vectors with non-builtin elements are unsupported");
2653   uint64_t Width = getASTContext().getTypeSize(T);
2654   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2655   // doesn't match the Intel types uses a custom mangling below.
2656   size_t OutSizeBefore = Out.tell();
2657   if (!isa<ExtVectorType>(T)) {
2658     llvm::Triple::ArchType AT =
2659         getASTContext().getTargetInfo().getTriple().getArch();
2660     if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2661       if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2662         mangleArtificialTagType(TTK_Union, "__m64");
2663       } else if (Width >= 128) {
2664         if (ET->getKind() == BuiltinType::Float)
2665           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
2666         else if (ET->getKind() == BuiltinType::LongLong)
2667           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2668         else if (ET->getKind() == BuiltinType::Double)
2669           mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2670       }
2671     }
2672   }
2673
2674   bool IsBuiltin = Out.tell() != OutSizeBefore;
2675   if (!IsBuiltin) {
2676     // The MS ABI doesn't have a special mangling for vector types, so we define
2677     // our own mangling to handle uses of __vector_size__ on user-specified
2678     // types, and for extensions like __v4sf.
2679
2680     llvm::SmallString<64> TemplateMangling;
2681     llvm::raw_svector_ostream Stream(TemplateMangling);
2682     MicrosoftCXXNameMangler Extra(Context, Stream);
2683     Stream << "?$";
2684     Extra.mangleSourceName("__vector");
2685     Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2686     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2687                                /*IsBoolean=*/false);
2688
2689     mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
2690   }
2691 }
2692
2693 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2694                                          Qualifiers Quals, SourceRange Range) {
2695   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2696 }
2697
2698 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2699                                          Qualifiers, SourceRange Range) {
2700   DiagnosticsEngine &Diags = Context.getDiags();
2701   unsigned DiagID = Diags.getCustomDiagID(
2702       DiagnosticsEngine::Error,
2703       "cannot mangle this dependent-sized vector type yet");
2704   Diags.Report(Range.getBegin(), DiagID) << Range;
2705 }
2706
2707 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2708                                          Qualifiers, SourceRange Range) {
2709   DiagnosticsEngine &Diags = Context.getDiags();
2710   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2711     "cannot mangle this dependent-sized extended vector type yet");
2712   Diags.Report(Range.getBegin(), DiagID)
2713     << Range;
2714 }
2715
2716 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2717                                          Qualifiers, SourceRange Range) {
2718   DiagnosticsEngine &Diags = Context.getDiags();
2719   unsigned DiagID = Diags.getCustomDiagID(
2720       DiagnosticsEngine::Error,
2721       "cannot mangle this dependent address space type yet");
2722   Diags.Report(Range.getBegin(), DiagID) << Range;
2723 }
2724
2725 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2726                                          SourceRange) {
2727   // ObjC interfaces have structs underlying them.
2728   mangleTagTypeKind(TTK_Struct);
2729   mangleName(T->getDecl());
2730 }
2731
2732 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
2733                                          Qualifiers Quals, SourceRange Range) {
2734   if (T->isKindOfType())
2735     return mangleObjCKindOfType(T, Quals, Range);
2736
2737   if (T->qual_empty() && !T->isSpecialized())
2738     return mangleType(T->getBaseType(), Range, QMM_Drop);
2739
2740   ArgBackRefMap OuterArgsContext;
2741   BackRefVec OuterTemplateContext;
2742
2743   TypeBackReferences.swap(OuterArgsContext);
2744   NameBackReferences.swap(OuterTemplateContext);
2745
2746   mangleTagTypeKind(TTK_Struct);
2747
2748   Out << "?$";
2749   if (T->isObjCId())
2750     mangleSourceName("objc_object");
2751   else if (T->isObjCClass())
2752     mangleSourceName("objc_class");
2753   else
2754     mangleSourceName(T->getInterface()->getName());
2755
2756   for (const auto &Q : T->quals())
2757     mangleObjCProtocol(Q);
2758
2759   if (T->isSpecialized())
2760     for (const auto &TA : T->getTypeArgs())
2761       mangleType(TA, Range, QMM_Drop);
2762
2763   Out << '@';
2764
2765   Out << '@';
2766
2767   TypeBackReferences.swap(OuterArgsContext);
2768   NameBackReferences.swap(OuterTemplateContext);
2769 }
2770
2771 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2772                                          Qualifiers Quals, SourceRange Range) {
2773   QualType PointeeType = T->getPointeeType();
2774   manglePointerCVQualifiers(Quals);
2775   manglePointerExtQualifiers(Quals, PointeeType);
2776
2777   Out << "_E";
2778
2779   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2780 }
2781
2782 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2783                                          Qualifiers, SourceRange) {
2784   llvm_unreachable("Cannot mangle injected class name type.");
2785 }
2786
2787 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2788                                          Qualifiers, SourceRange Range) {
2789   DiagnosticsEngine &Diags = Context.getDiags();
2790   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2791     "cannot mangle this template specialization type yet");
2792   Diags.Report(Range.getBegin(), DiagID)
2793     << Range;
2794 }
2795
2796 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2797                                          SourceRange Range) {
2798   DiagnosticsEngine &Diags = Context.getDiags();
2799   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2800     "cannot mangle this dependent name type yet");
2801   Diags.Report(Range.getBegin(), DiagID)
2802     << Range;
2803 }
2804
2805 void MicrosoftCXXNameMangler::mangleType(
2806     const DependentTemplateSpecializationType *T, Qualifiers,
2807     SourceRange Range) {
2808   DiagnosticsEngine &Diags = Context.getDiags();
2809   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2810     "cannot mangle this dependent template specialization type yet");
2811   Diags.Report(Range.getBegin(), DiagID)
2812     << Range;
2813 }
2814
2815 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2816                                          SourceRange Range) {
2817   DiagnosticsEngine &Diags = Context.getDiags();
2818   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2819     "cannot mangle this pack expansion yet");
2820   Diags.Report(Range.getBegin(), DiagID)
2821     << Range;
2822 }
2823
2824 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2825                                          SourceRange Range) {
2826   DiagnosticsEngine &Diags = Context.getDiags();
2827   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2828     "cannot mangle this typeof(type) yet");
2829   Diags.Report(Range.getBegin(), DiagID)
2830     << Range;
2831 }
2832
2833 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2834                                          SourceRange Range) {
2835   DiagnosticsEngine &Diags = Context.getDiags();
2836   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2837     "cannot mangle this typeof(expression) yet");
2838   Diags.Report(Range.getBegin(), DiagID)
2839     << Range;
2840 }
2841
2842 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2843                                          SourceRange Range) {
2844   DiagnosticsEngine &Diags = Context.getDiags();
2845   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2846     "cannot mangle this decltype() yet");
2847   Diags.Report(Range.getBegin(), DiagID)
2848     << Range;
2849 }
2850
2851 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2852                                          Qualifiers, SourceRange Range) {
2853   DiagnosticsEngine &Diags = Context.getDiags();
2854   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2855     "cannot mangle this unary transform type yet");
2856   Diags.Report(Range.getBegin(), DiagID)
2857     << Range;
2858 }
2859
2860 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2861                                          SourceRange Range) {
2862   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2863
2864   DiagnosticsEngine &Diags = Context.getDiags();
2865   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2866     "cannot mangle this 'auto' type yet");
2867   Diags.Report(Range.getBegin(), DiagID)
2868     << Range;
2869 }
2870
2871 void MicrosoftCXXNameMangler::mangleType(
2872     const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2873   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2874
2875   DiagnosticsEngine &Diags = Context.getDiags();
2876   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2877     "cannot mangle this deduced class template specialization type yet");
2878   Diags.Report(Range.getBegin(), DiagID)
2879     << Range;
2880 }
2881
2882 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2883                                          SourceRange Range) {
2884   QualType ValueType = T->getValueType();
2885
2886   llvm::SmallString<64> TemplateMangling;
2887   llvm::raw_svector_ostream Stream(TemplateMangling);
2888   MicrosoftCXXNameMangler Extra(Context, Stream);
2889   Stream << "?$";
2890   Extra.mangleSourceName("_Atomic");
2891   Extra.mangleType(ValueType, Range, QMM_Escape);
2892
2893   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2894 }
2895
2896 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2897                                          SourceRange Range) {
2898   DiagnosticsEngine &Diags = Context.getDiags();
2899   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2900     "cannot mangle this OpenCL pipe type yet");
2901   Diags.Report(Range.getBegin(), DiagID)
2902     << Range;
2903 }
2904
2905 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2906                                                raw_ostream &Out) {
2907   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2908          "Invalid mangleName() call, argument is not a variable or function!");
2909   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2910          "Invalid mangleName() call on 'structor decl!");
2911
2912   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2913                                  getASTContext().getSourceManager(),
2914                                  "Mangling declaration");
2915
2916   msvc_hashing_ostream MHO(Out);
2917   MicrosoftCXXNameMangler Mangler(*this, MHO);
2918   return Mangler.mangle(D);
2919 }
2920
2921 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2922 //                       <virtual-adjustment>
2923 // <no-adjustment>      ::= A # private near
2924 //                      ::= B # private far
2925 //                      ::= I # protected near
2926 //                      ::= J # protected far
2927 //                      ::= Q # public near
2928 //                      ::= R # public far
2929 // <static-adjustment>  ::= G <static-offset> # private near
2930 //                      ::= H <static-offset> # private far
2931 //                      ::= O <static-offset> # protected near
2932 //                      ::= P <static-offset> # protected far
2933 //                      ::= W <static-offset> # public near
2934 //                      ::= X <static-offset> # public far
2935 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2936 //                      ::= $1 <virtual-shift> <static-offset> # private far
2937 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2938 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2939 //                      ::= $4 <virtual-shift> <static-offset> # public near
2940 //                      ::= $5 <virtual-shift> <static-offset> # public far
2941 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2942 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2943 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2944 //                          <offset-to-vtordisp>
2945 static void mangleThunkThisAdjustment(AccessSpecifier AS,
2946                                       const ThisAdjustment &Adjustment,
2947                                       MicrosoftCXXNameMangler &Mangler,
2948                                       raw_ostream &Out) {
2949   if (!Adjustment.Virtual.isEmpty()) {
2950     Out << '$';
2951     char AccessSpec;
2952     switch (AS) {
2953     case AS_none:
2954       llvm_unreachable("Unsupported access specifier");
2955     case AS_private:
2956       AccessSpec = '0';
2957       break;
2958     case AS_protected:
2959       AccessSpec = '2';
2960       break;
2961     case AS_public:
2962       AccessSpec = '4';
2963     }
2964     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2965       Out << 'R' << AccessSpec;
2966       Mangler.mangleNumber(
2967           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2968       Mangler.mangleNumber(
2969           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2970       Mangler.mangleNumber(
2971           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2972       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2973     } else {
2974       Out << AccessSpec;
2975       Mangler.mangleNumber(
2976           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2977       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2978     }
2979   } else if (Adjustment.NonVirtual != 0) {
2980     switch (AS) {
2981     case AS_none:
2982       llvm_unreachable("Unsupported access specifier");
2983     case AS_private:
2984       Out << 'G';
2985       break;
2986     case AS_protected:
2987       Out << 'O';
2988       break;
2989     case AS_public:
2990       Out << 'W';
2991     }
2992     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2993   } else {
2994     switch (AS) {
2995     case AS_none:
2996       llvm_unreachable("Unsupported access specifier");
2997     case AS_private:
2998       Out << 'A';
2999       break;
3000     case AS_protected:
3001       Out << 'I';
3002       break;
3003     case AS_public:
3004       Out << 'Q';
3005     }
3006   }
3007 }
3008
3009 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3010     const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3011     raw_ostream &Out) {
3012   msvc_hashing_ostream MHO(Out);
3013   MicrosoftCXXNameMangler Mangler(*this, MHO);
3014   Mangler.getStream() << '?';
3015   Mangler.mangleVirtualMemPtrThunk(MD, ML);
3016 }
3017
3018 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3019                                              const ThunkInfo &Thunk,
3020                                              raw_ostream &Out) {
3021   msvc_hashing_ostream MHO(Out);
3022   MicrosoftCXXNameMangler Mangler(*this, MHO);
3023   Mangler.getStream() << '?';
3024   Mangler.mangleName(MD);
3025
3026   // Usually the thunk uses the access specifier of the new method, but if this
3027   // is a covariant return thunk, then MSVC always uses the public access
3028   // specifier, and we do the same.
3029   AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3030   mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3031
3032   if (!Thunk.Return.isEmpty())
3033     assert(Thunk.Method != nullptr &&
3034            "Thunk info should hold the overridee decl");
3035
3036   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3037   Mangler.mangleFunctionType(
3038       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3039 }
3040
3041 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3042     const CXXDestructorDecl *DD, CXXDtorType Type,
3043     const ThisAdjustment &Adjustment, raw_ostream &Out) {
3044   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3045   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3046   // mangling manually until we support both deleting dtor types.
3047   assert(Type == Dtor_Deleting);
3048   msvc_hashing_ostream MHO(Out);
3049   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3050   Mangler.getStream() << "??_E";
3051   Mangler.mangleName(DD->getParent());
3052   mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3053   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3054 }
3055
3056 void MicrosoftMangleContextImpl::mangleCXXVFTable(
3057     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3058     raw_ostream &Out) {
3059   // <mangled-name> ::= ?_7 <class-name> <storage-class>
3060   //                    <cvr-qualifiers> [<name>] @
3061   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3062   // is always '6' for vftables.
3063   msvc_hashing_ostream MHO(Out);
3064   MicrosoftCXXNameMangler Mangler(*this, MHO);
3065   if (Derived->hasAttr<DLLImportAttr>())
3066     Mangler.getStream() << "??_S";
3067   else
3068     Mangler.getStream() << "??_7";
3069   Mangler.mangleName(Derived);
3070   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3071   for (const CXXRecordDecl *RD : BasePath)
3072     Mangler.mangleName(RD);
3073   Mangler.getStream() << '@';
3074 }
3075
3076 void MicrosoftMangleContextImpl::mangleCXXVBTable(
3077     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3078     raw_ostream &Out) {
3079   // <mangled-name> ::= ?_8 <class-name> <storage-class>
3080   //                    <cvr-qualifiers> [<name>] @
3081   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3082   // is always '7' for vbtables.
3083   msvc_hashing_ostream MHO(Out);
3084   MicrosoftCXXNameMangler Mangler(*this, MHO);
3085   Mangler.getStream() << "??_8";
3086   Mangler.mangleName(Derived);
3087   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3088   for (const CXXRecordDecl *RD : BasePath)
3089     Mangler.mangleName(RD);
3090   Mangler.getStream() << '@';
3091 }
3092
3093 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3094   msvc_hashing_ostream MHO(Out);
3095   MicrosoftCXXNameMangler Mangler(*this, MHO);
3096   Mangler.getStream() << "??_R0";
3097   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3098   Mangler.getStream() << "@8";
3099 }
3100
3101 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3102                                                    raw_ostream &Out) {
3103   MicrosoftCXXNameMangler Mangler(*this, Out);
3104   Mangler.getStream() << '.';
3105   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3106 }
3107
3108 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3109     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3110   msvc_hashing_ostream MHO(Out);
3111   MicrosoftCXXNameMangler Mangler(*this, MHO);
3112   Mangler.getStream() << "??_K";
3113   Mangler.mangleName(SrcRD);
3114   Mangler.getStream() << "$C";
3115   Mangler.mangleName(DstRD);
3116 }
3117
3118 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3119                                                     bool IsVolatile,
3120                                                     bool IsUnaligned,
3121                                                     uint32_t NumEntries,
3122                                                     raw_ostream &Out) {
3123   msvc_hashing_ostream MHO(Out);
3124   MicrosoftCXXNameMangler Mangler(*this, MHO);
3125   Mangler.getStream() << "_TI";
3126   if (IsConst)
3127     Mangler.getStream() << 'C';
3128   if (IsVolatile)
3129     Mangler.getStream() << 'V';
3130   if (IsUnaligned)
3131     Mangler.getStream() << 'U';
3132   Mangler.getStream() << NumEntries;
3133   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3134 }
3135
3136 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3137     QualType T, uint32_t NumEntries, raw_ostream &Out) {
3138   msvc_hashing_ostream MHO(Out);
3139   MicrosoftCXXNameMangler Mangler(*this, MHO);
3140   Mangler.getStream() << "_CTA";
3141   Mangler.getStream() << NumEntries;
3142   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3143 }
3144
3145 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3146     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3147     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3148     raw_ostream &Out) {
3149   MicrosoftCXXNameMangler Mangler(*this, Out);
3150   Mangler.getStream() << "_CT";
3151
3152   llvm::SmallString<64> RTTIMangling;
3153   {
3154     llvm::raw_svector_ostream Stream(RTTIMangling);
3155     msvc_hashing_ostream MHO(Stream);
3156     mangleCXXRTTI(T, MHO);
3157   }
3158   Mangler.getStream() << RTTIMangling;
3159
3160   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
3161   // in fact, superfluous but I'm not sure the change was made consciously.
3162   llvm::SmallString<64> CopyCtorMangling;
3163   if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
3164           LangOptions::MSVC2015) &&
3165       CD) {
3166     llvm::raw_svector_ostream Stream(CopyCtorMangling);
3167     msvc_hashing_ostream MHO(Stream);
3168     mangleCXXCtor(CD, CT, MHO);
3169   }
3170   Mangler.getStream() << CopyCtorMangling;
3171
3172   Mangler.getStream() << Size;
3173   if (VBPtrOffset == -1) {
3174     if (NVOffset) {
3175       Mangler.getStream() << NVOffset;
3176     }
3177   } else {
3178     Mangler.getStream() << NVOffset;
3179     Mangler.getStream() << VBPtrOffset;
3180     Mangler.getStream() << VBIndex;
3181   }
3182 }
3183
3184 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3185     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3186     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3187   msvc_hashing_ostream MHO(Out);
3188   MicrosoftCXXNameMangler Mangler(*this, MHO);
3189   Mangler.getStream() << "??_R1";
3190   Mangler.mangleNumber(NVOffset);
3191   Mangler.mangleNumber(VBPtrOffset);
3192   Mangler.mangleNumber(VBTableOffset);
3193   Mangler.mangleNumber(Flags);
3194   Mangler.mangleName(Derived);
3195   Mangler.getStream() << "8";
3196 }
3197
3198 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3199     const CXXRecordDecl *Derived, raw_ostream &Out) {
3200   msvc_hashing_ostream MHO(Out);
3201   MicrosoftCXXNameMangler Mangler(*this, MHO);
3202   Mangler.getStream() << "??_R2";
3203   Mangler.mangleName(Derived);
3204   Mangler.getStream() << "8";
3205 }
3206
3207 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3208     const CXXRecordDecl *Derived, raw_ostream &Out) {
3209   msvc_hashing_ostream MHO(Out);
3210   MicrosoftCXXNameMangler Mangler(*this, MHO);
3211   Mangler.getStream() << "??_R3";
3212   Mangler.mangleName(Derived);
3213   Mangler.getStream() << "8";
3214 }
3215
3216 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3217     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3218     raw_ostream &Out) {
3219   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3220   //                    <cvr-qualifiers> [<name>] @
3221   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3222   // is always '6' for vftables.
3223   llvm::SmallString<64> VFTableMangling;
3224   llvm::raw_svector_ostream Stream(VFTableMangling);
3225   mangleCXXVFTable(Derived, BasePath, Stream);
3226
3227   if (VFTableMangling.startswith("??@")) {
3228     assert(VFTableMangling.endswith("@"));
3229     Out << VFTableMangling << "??_R4@";
3230     return;
3231   }
3232
3233   assert(VFTableMangling.startswith("??_7") ||
3234          VFTableMangling.startswith("??_S"));
3235
3236   Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3237 }
3238
3239 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3240     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3241   msvc_hashing_ostream MHO(Out);
3242   MicrosoftCXXNameMangler Mangler(*this, MHO);
3243   // The function body is in the same comdat as the function with the handler,
3244   // so the numbering here doesn't have to be the same across TUs.
3245   //
3246   // <mangled-name> ::= ?filt$ <filter-number> @0
3247   Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3248   Mangler.mangleName(EnclosingDecl);
3249 }
3250
3251 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3252     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3253   msvc_hashing_ostream MHO(Out);
3254   MicrosoftCXXNameMangler Mangler(*this, MHO);
3255   // The function body is in the same comdat as the function with the handler,
3256   // so the numbering here doesn't have to be the same across TUs.
3257   //
3258   // <mangled-name> ::= ?fin$ <filter-number> @0
3259   Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3260   Mangler.mangleName(EnclosingDecl);
3261 }
3262
3263 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3264   // This is just a made up unique string for the purposes of tbaa.  undname
3265   // does *not* know how to demangle it.
3266   MicrosoftCXXNameMangler Mangler(*this, Out);
3267   Mangler.getStream() << '?';
3268   Mangler.mangleType(T, SourceRange());
3269 }
3270
3271 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3272                                                CXXCtorType Type,
3273                                                raw_ostream &Out) {
3274   msvc_hashing_ostream MHO(Out);
3275   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3276   mangler.mangle(D);
3277 }
3278
3279 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3280                                                CXXDtorType Type,
3281                                                raw_ostream &Out) {
3282   msvc_hashing_ostream MHO(Out);
3283   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3284   mangler.mangle(D);
3285 }
3286
3287 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3288     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3289   msvc_hashing_ostream MHO(Out);
3290   MicrosoftCXXNameMangler Mangler(*this, MHO);
3291
3292   Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3293   Mangler.mangle(VD, "");
3294 }
3295
3296 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3297     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3298   msvc_hashing_ostream MHO(Out);
3299   MicrosoftCXXNameMangler Mangler(*this, MHO);
3300
3301   Mangler.getStream() << "?$TSS" << GuardNum << '@';
3302   Mangler.mangleNestedName(VD);
3303   Mangler.getStream() << "@4HA";
3304 }
3305
3306 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3307                                                            raw_ostream &Out) {
3308   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3309   //              ::= ?__J <postfix> @5 <scope-depth>
3310   //              ::= ?$S <guard-num> @ <postfix> @4IA
3311
3312   // The first mangling is what MSVC uses to guard static locals in inline
3313   // functions.  It uses a different mangling in external functions to support
3314   // guarding more than 32 variables.  MSVC rejects inline functions with more
3315   // than 32 static locals.  We don't fully implement the second mangling
3316   // because those guards are not externally visible, and instead use LLVM's
3317   // default renaming when creating a new guard variable.
3318   msvc_hashing_ostream MHO(Out);
3319   MicrosoftCXXNameMangler Mangler(*this, MHO);
3320
3321   bool Visible = VD->isExternallyVisible();
3322   if (Visible) {
3323     Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3324   } else {
3325     Mangler.getStream() << "?$S1@";
3326   }
3327   unsigned ScopeDepth = 0;
3328   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3329     // If we do not have a discriminator and are emitting a guard variable for
3330     // use at global scope, then mangling the nested name will not be enough to
3331     // remove ambiguities.
3332     Mangler.mangle(VD, "");
3333   else
3334     Mangler.mangleNestedName(VD);
3335   Mangler.getStream() << (Visible ? "@5" : "@4IA");
3336   if (ScopeDepth)
3337     Mangler.mangleNumber(ScopeDepth);
3338 }
3339
3340 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3341                                                     char CharCode,
3342                                                     raw_ostream &Out) {
3343   msvc_hashing_ostream MHO(Out);
3344   MicrosoftCXXNameMangler Mangler(*this, MHO);
3345   Mangler.getStream() << "??__" << CharCode;
3346   if (D->isStaticDataMember()) {
3347     Mangler.getStream() << '?';
3348     Mangler.mangleName(D);
3349     Mangler.mangleVariableEncoding(D);
3350     Mangler.getStream() << "@@";
3351   } else {
3352     Mangler.mangleName(D);
3353   }
3354   // This is the function class mangling.  These stubs are global, non-variadic,
3355   // cdecl functions that return void and take no args.
3356   Mangler.getStream() << "YAXXZ";
3357 }
3358
3359 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3360                                                           raw_ostream &Out) {
3361   // <initializer-name> ::= ?__E <name> YAXXZ
3362   mangleInitFiniStub(D, 'E', Out);
3363 }
3364
3365 void
3366 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3367                                                           raw_ostream &Out) {
3368   // <destructor-name> ::= ?__F <name> YAXXZ
3369   mangleInitFiniStub(D, 'F', Out);
3370 }
3371
3372 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3373                                                      raw_ostream &Out) {
3374   // <char-type> ::= 0   # char, char16_t, char32_t
3375   //                     # (little endian char data in mangling)
3376   //             ::= 1   # wchar_t (big endian char data in mangling)
3377   //
3378   // <literal-length> ::= <non-negative integer>  # the length of the literal
3379   //
3380   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3381   //                                              # trailing null bytes
3382   //
3383   // <encoded-string> ::= <simple character>           # uninteresting character
3384   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3385   //                                                   # encode the byte for the
3386   //                                                   # character
3387   //                  ::= '?' [a-z]                    # \xe1 - \xfa
3388   //                  ::= '?' [A-Z]                    # \xc1 - \xda
3389   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3390   //
3391   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3392   //               <encoded-string> '@'
3393   MicrosoftCXXNameMangler Mangler(*this, Out);
3394   Mangler.getStream() << "??_C@_";
3395
3396   // The actual string length might be different from that of the string literal
3397   // in cases like:
3398   // char foo[3] = "foobar";
3399   // char bar[42] = "foobar";
3400   // Where it is truncated or zero-padded to fit the array. This is the length
3401   // used for mangling, and any trailing null-bytes also need to be mangled.
3402   unsigned StringLength = getASTContext()
3403                               .getAsConstantArrayType(SL->getType())
3404                               ->getSize()
3405                               .getZExtValue();
3406   unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3407
3408   // <char-type>: The "kind" of string literal is encoded into the mangled name.
3409   if (SL->isWide())
3410     Mangler.getStream() << '1';
3411   else
3412     Mangler.getStream() << '0';
3413
3414   // <literal-length>: The next part of the mangled name consists of the length
3415   // of the string in bytes.
3416   Mangler.mangleNumber(StringByteLength);
3417
3418   auto GetLittleEndianByte = [&SL](unsigned Index) {
3419     unsigned CharByteWidth = SL->getCharByteWidth();
3420     if (Index / CharByteWidth >= SL->getLength())
3421       return static_cast<char>(0);
3422     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3423     unsigned OffsetInCodeUnit = Index % CharByteWidth;
3424     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3425   };
3426
3427   auto GetBigEndianByte = [&SL](unsigned Index) {
3428     unsigned CharByteWidth = SL->getCharByteWidth();
3429     if (Index / CharByteWidth >= SL->getLength())
3430       return static_cast<char>(0);
3431     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3432     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3433     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3434   };
3435
3436   // CRC all the bytes of the StringLiteral.
3437   llvm::JamCRC JC;
3438   for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3439     JC.update(GetLittleEndianByte(I));
3440
3441   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3442   // scheme.
3443   Mangler.mangleNumber(JC.getCRC());
3444
3445   // <encoded-string>: The mangled name also contains the first 32 bytes
3446   // (including null-terminator bytes) of the encoded StringLiteral.
3447   // Each character is encoded by splitting them into bytes and then encoding
3448   // the constituent bytes.
3449   auto MangleByte = [&Mangler](char Byte) {
3450     // There are five different manglings for characters:
3451     // - [a-zA-Z0-9_$]: A one-to-one mapping.
3452     // - ?[a-z]: The range from \xe1 to \xfa.
3453     // - ?[A-Z]: The range from \xc1 to \xda.
3454     // - ?[0-9]: The set of [,/\:. \n\t'-].
3455     // - ?$XX: A fallback which maps nibbles.
3456     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3457       Mangler.getStream() << Byte;
3458     } else if (isLetter(Byte & 0x7f)) {
3459       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3460     } else {
3461       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3462                                    ' ', '\n', '\t', '\'', '-'};
3463       const char *Pos =
3464           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
3465       if (Pos != std::end(SpecialChars)) {
3466         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3467       } else {
3468         Mangler.getStream() << "?$";
3469         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3470         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3471       }
3472     }
3473   };
3474
3475   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3476   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3477   unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3478   for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3479     if (SL->isWide())
3480       MangleByte(GetBigEndianByte(I));
3481     else
3482       MangleByte(GetLittleEndianByte(I));
3483   }
3484
3485   Mangler.getStream() << '@';
3486 }
3487
3488 MicrosoftMangleContext *
3489 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3490   return new MicrosoftMangleContextImpl(Context, Diags);
3491 }