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