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