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