]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp
Merge clang trunk r300422 and resolve conflicts.
[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 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
954   // <postfix> ::= <unqualified-name> [<postfix>]
955   //           ::= <substitution> [<postfix>]
956   const DeclContext *DC = getEffectiveDeclContext(ND);
957
958   while (!DC->isTranslationUnit()) {
959     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
960       unsigned Disc;
961       if (Context.getNextDiscriminator(ND, Disc)) {
962         Out << '?';
963         mangleNumber(Disc);
964         Out << '?';
965       }
966     }
967
968     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
969       DiagnosticsEngine &Diags = Context.getDiags();
970       unsigned DiagID =
971           Diags.getCustomDiagID(DiagnosticsEngine::Error,
972                                 "cannot mangle a local inside this block yet");
973       Diags.Report(BD->getLocation(), DiagID);
974
975       // FIXME: This is completely, utterly, wrong; see ItaniumMangle
976       // for how this should be done.
977       Out << "__block_invoke" << Context.getBlockId(BD, false);
978       Out << '@';
979     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
980       mangleObjCMethodName(Method);
981     } else if (isa<NamedDecl>(DC)) {
982       ND = cast<NamedDecl>(DC);
983       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
984         mangle(FD, "?");
985         break;
986       } else {
987         mangleUnqualifiedName(ND);
988         // Lambdas in default arguments conceptually belong to the function the
989         // parameter corresponds to.
990         if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
991           DC = LDADC;
992           continue;
993         }
994       }
995     }
996     DC = DC->getParent();
997   }
998 }
999
1000 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1001   // Microsoft uses the names on the case labels for these dtor variants.  Clang
1002   // uses the Itanium terminology internally.  Everything in this ABI delegates
1003   // towards the base dtor.
1004   switch (T) {
1005   // <operator-name> ::= ?1  # destructor
1006   case Dtor_Base: Out << "?1"; return;
1007   // <operator-name> ::= ?_D # vbase destructor
1008   case Dtor_Complete: Out << "?_D"; return;
1009   // <operator-name> ::= ?_G # scalar deleting destructor
1010   case Dtor_Deleting: Out << "?_G"; return;
1011   // <operator-name> ::= ?_E # vector deleting destructor
1012   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
1013   // it.
1014   case Dtor_Comdat:
1015     llvm_unreachable("not expecting a COMDAT");
1016   }
1017   llvm_unreachable("Unsupported dtor type?");
1018 }
1019
1020 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1021                                                  SourceLocation Loc) {
1022   switch (OO) {
1023   //                     ?0 # constructor
1024   //                     ?1 # destructor
1025   // <operator-name> ::= ?2 # new
1026   case OO_New: Out << "?2"; break;
1027   // <operator-name> ::= ?3 # delete
1028   case OO_Delete: Out << "?3"; break;
1029   // <operator-name> ::= ?4 # =
1030   case OO_Equal: Out << "?4"; break;
1031   // <operator-name> ::= ?5 # >>
1032   case OO_GreaterGreater: Out << "?5"; break;
1033   // <operator-name> ::= ?6 # <<
1034   case OO_LessLess: Out << "?6"; break;
1035   // <operator-name> ::= ?7 # !
1036   case OO_Exclaim: Out << "?7"; break;
1037   // <operator-name> ::= ?8 # ==
1038   case OO_EqualEqual: Out << "?8"; break;
1039   // <operator-name> ::= ?9 # !=
1040   case OO_ExclaimEqual: Out << "?9"; break;
1041   // <operator-name> ::= ?A # []
1042   case OO_Subscript: Out << "?A"; break;
1043   //                     ?B # conversion
1044   // <operator-name> ::= ?C # ->
1045   case OO_Arrow: Out << "?C"; break;
1046   // <operator-name> ::= ?D # *
1047   case OO_Star: Out << "?D"; break;
1048   // <operator-name> ::= ?E # ++
1049   case OO_PlusPlus: Out << "?E"; break;
1050   // <operator-name> ::= ?F # --
1051   case OO_MinusMinus: Out << "?F"; break;
1052   // <operator-name> ::= ?G # -
1053   case OO_Minus: Out << "?G"; break;
1054   // <operator-name> ::= ?H # +
1055   case OO_Plus: Out << "?H"; break;
1056   // <operator-name> ::= ?I # &
1057   case OO_Amp: Out << "?I"; break;
1058   // <operator-name> ::= ?J # ->*
1059   case OO_ArrowStar: Out << "?J"; break;
1060   // <operator-name> ::= ?K # /
1061   case OO_Slash: Out << "?K"; break;
1062   // <operator-name> ::= ?L # %
1063   case OO_Percent: Out << "?L"; break;
1064   // <operator-name> ::= ?M # <
1065   case OO_Less: Out << "?M"; break;
1066   // <operator-name> ::= ?N # <=
1067   case OO_LessEqual: Out << "?N"; break;
1068   // <operator-name> ::= ?O # >
1069   case OO_Greater: Out << "?O"; break;
1070   // <operator-name> ::= ?P # >=
1071   case OO_GreaterEqual: Out << "?P"; break;
1072   // <operator-name> ::= ?Q # ,
1073   case OO_Comma: Out << "?Q"; break;
1074   // <operator-name> ::= ?R # ()
1075   case OO_Call: Out << "?R"; break;
1076   // <operator-name> ::= ?S # ~
1077   case OO_Tilde: Out << "?S"; break;
1078   // <operator-name> ::= ?T # ^
1079   case OO_Caret: Out << "?T"; break;
1080   // <operator-name> ::= ?U # |
1081   case OO_Pipe: Out << "?U"; break;
1082   // <operator-name> ::= ?V # &&
1083   case OO_AmpAmp: Out << "?V"; break;
1084   // <operator-name> ::= ?W # ||
1085   case OO_PipePipe: Out << "?W"; break;
1086   // <operator-name> ::= ?X # *=
1087   case OO_StarEqual: Out << "?X"; break;
1088   // <operator-name> ::= ?Y # +=
1089   case OO_PlusEqual: Out << "?Y"; break;
1090   // <operator-name> ::= ?Z # -=
1091   case OO_MinusEqual: Out << "?Z"; break;
1092   // <operator-name> ::= ?_0 # /=
1093   case OO_SlashEqual: Out << "?_0"; break;
1094   // <operator-name> ::= ?_1 # %=
1095   case OO_PercentEqual: Out << "?_1"; break;
1096   // <operator-name> ::= ?_2 # >>=
1097   case OO_GreaterGreaterEqual: Out << "?_2"; break;
1098   // <operator-name> ::= ?_3 # <<=
1099   case OO_LessLessEqual: Out << "?_3"; break;
1100   // <operator-name> ::= ?_4 # &=
1101   case OO_AmpEqual: Out << "?_4"; break;
1102   // <operator-name> ::= ?_5 # |=
1103   case OO_PipeEqual: Out << "?_5"; break;
1104   // <operator-name> ::= ?_6 # ^=
1105   case OO_CaretEqual: Out << "?_6"; break;
1106   //                     ?_7 # vftable
1107   //                     ?_8 # vbtable
1108   //                     ?_9 # vcall
1109   //                     ?_A # typeof
1110   //                     ?_B # local static guard
1111   //                     ?_C # string
1112   //                     ?_D # vbase destructor
1113   //                     ?_E # vector deleting destructor
1114   //                     ?_F # default constructor closure
1115   //                     ?_G # scalar deleting destructor
1116   //                     ?_H # vector constructor iterator
1117   //                     ?_I # vector destructor iterator
1118   //                     ?_J # vector vbase constructor iterator
1119   //                     ?_K # virtual displacement map
1120   //                     ?_L # eh vector constructor iterator
1121   //                     ?_M # eh vector destructor iterator
1122   //                     ?_N # eh vector vbase constructor iterator
1123   //                     ?_O # copy constructor closure
1124   //                     ?_P<name> # udt returning <name>
1125   //                     ?_Q # <unknown>
1126   //                     ?_R0 # RTTI Type Descriptor
1127   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1128   //                     ?_R2 # RTTI Base Class Array
1129   //                     ?_R3 # RTTI Class Hierarchy Descriptor
1130   //                     ?_R4 # RTTI Complete Object Locator
1131   //                     ?_S # local vftable
1132   //                     ?_T # local vftable constructor closure
1133   // <operator-name> ::= ?_U # new[]
1134   case OO_Array_New: Out << "?_U"; break;
1135   // <operator-name> ::= ?_V # delete[]
1136   case OO_Array_Delete: Out << "?_V"; break;
1137   // <operator-name> ::= ?__L # co_await
1138   case OO_Coawait: Out << "?__L"; break;
1139
1140   case OO_Conditional: {
1141     DiagnosticsEngine &Diags = Context.getDiags();
1142     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1143       "cannot mangle this conditional operator yet");
1144     Diags.Report(Loc, DiagID);
1145     break;
1146   }
1147
1148   case OO_None:
1149   case NUM_OVERLOADED_OPERATORS:
1150     llvm_unreachable("Not an overloaded operator");
1151   }
1152 }
1153
1154 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1155   // <source name> ::= <identifier> @
1156   BackRefVec::iterator Found =
1157       std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1158   if (Found == NameBackReferences.end()) {
1159     if (NameBackReferences.size() < 10)
1160       NameBackReferences.push_back(Name);
1161     Out << Name << '@';
1162   } else {
1163     Out << (Found - NameBackReferences.begin());
1164   }
1165 }
1166
1167 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1168   Context.mangleObjCMethodName(MD, Out);
1169 }
1170
1171 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1172     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1173   // <template-name> ::= <unscoped-template-name> <template-args>
1174   //                 ::= <substitution>
1175   // Always start with the unqualified name.
1176
1177   // Templates have their own context for back references.
1178   ArgBackRefMap OuterArgsContext;
1179   BackRefVec OuterTemplateContext;
1180   PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1181   NameBackReferences.swap(OuterTemplateContext);
1182   TypeBackReferences.swap(OuterArgsContext);
1183   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1184
1185   mangleUnscopedTemplateName(TD);
1186   mangleTemplateArgs(TD, TemplateArgs);
1187
1188   // Restore the previous back reference contexts.
1189   NameBackReferences.swap(OuterTemplateContext);
1190   TypeBackReferences.swap(OuterArgsContext);
1191   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1192 }
1193
1194 void
1195 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1196   // <unscoped-template-name> ::= ?$ <unqualified-name>
1197   Out << "?$";
1198   mangleUnqualifiedName(TD);
1199 }
1200
1201 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1202                                                    bool IsBoolean) {
1203   // <integer-literal> ::= $0 <number>
1204   Out << "$0";
1205   // Make sure booleans are encoded as 0/1.
1206   if (IsBoolean && Value.getBoolValue())
1207     mangleNumber(1);
1208   else if (Value.isSigned())
1209     mangleNumber(Value.getSExtValue());
1210   else
1211     mangleNumber(Value.getZExtValue());
1212 }
1213
1214 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1215   // See if this is a constant expression.
1216   llvm::APSInt Value;
1217   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1218     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1219     return;
1220   }
1221
1222   // Look through no-op casts like template parameter substitutions.
1223   E = E->IgnoreParenNoopCasts(Context.getASTContext());
1224
1225   const CXXUuidofExpr *UE = nullptr;
1226   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1227     if (UO->getOpcode() == UO_AddrOf)
1228       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1229   } else
1230     UE = dyn_cast<CXXUuidofExpr>(E);
1231
1232   if (UE) {
1233     // If we had to peek through an address-of operator, treat this like we are
1234     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1235     //
1236     // N.B. This matches up with the handling of TemplateArgument::Declaration
1237     // in mangleTemplateArg
1238     if (UE == E)
1239       Out << "$E?";
1240     else
1241       Out << "$1?";
1242
1243     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1244     // const __s_GUID _GUID_{lower case UUID with underscores}
1245     StringRef Uuid = UE->getUuidStr();
1246     std::string Name = "_GUID_" + Uuid.lower();
1247     std::replace(Name.begin(), Name.end(), '-', '_');
1248
1249     mangleSourceName(Name);
1250     // Terminate the whole name with an '@'.
1251     Out << '@';
1252     // It's a global variable.
1253     Out << '3';
1254     // It's a struct called __s_GUID.
1255     mangleArtificalTagType(TTK_Struct, "__s_GUID");
1256     // It's const.
1257     Out << 'B';
1258     return;
1259   }
1260
1261   // As bad as this diagnostic is, it's better than crashing.
1262   DiagnosticsEngine &Diags = Context.getDiags();
1263   unsigned DiagID = Diags.getCustomDiagID(
1264       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1265   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1266                                         << E->getSourceRange();
1267 }
1268
1269 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1270     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1271   // <template-args> ::= <template-arg>+
1272   const TemplateParameterList *TPL = TD->getTemplateParameters();
1273   assert(TPL->size() == TemplateArgs.size() &&
1274          "size mismatch between args and parms!");
1275
1276   unsigned Idx = 0;
1277   for (const TemplateArgument &TA : TemplateArgs.asArray())
1278     mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1279 }
1280
1281 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1282                                                 const TemplateArgument &TA,
1283                                                 const NamedDecl *Parm) {
1284   // <template-arg> ::= <type>
1285   //                ::= <integer-literal>
1286   //                ::= <member-data-pointer>
1287   //                ::= <member-function-pointer>
1288   //                ::= $E? <name> <type-encoding>
1289   //                ::= $1? <name> <type-encoding>
1290   //                ::= $0A@
1291   //                ::= <template-args>
1292
1293   switch (TA.getKind()) {
1294   case TemplateArgument::Null:
1295     llvm_unreachable("Can't mangle null template arguments!");
1296   case TemplateArgument::TemplateExpansion:
1297     llvm_unreachable("Can't mangle template expansion arguments!");
1298   case TemplateArgument::Type: {
1299     QualType T = TA.getAsType();
1300     mangleType(T, SourceRange(), QMM_Escape);
1301     break;
1302   }
1303   case TemplateArgument::Declaration: {
1304     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1305     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1306       mangleMemberDataPointer(
1307           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1308           cast<ValueDecl>(ND));
1309     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1310       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1311       if (MD && MD->isInstance()) {
1312         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1313       } else {
1314         Out << "$1?";
1315         mangleName(FD);
1316         mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1317       }
1318     } else {
1319       mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1320     }
1321     break;
1322   }
1323   case TemplateArgument::Integral:
1324     mangleIntegerLiteral(TA.getAsIntegral(),
1325                          TA.getIntegralType()->isBooleanType());
1326     break;
1327   case TemplateArgument::NullPtr: {
1328     QualType T = TA.getNullPtrType();
1329     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1330       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1331       if (MPT->isMemberFunctionPointerType() &&
1332           !isa<FunctionTemplateDecl>(TD)) {
1333         mangleMemberFunctionPointer(RD, nullptr);
1334         return;
1335       }
1336       if (MPT->isMemberDataPointer()) {
1337         if (!isa<FunctionTemplateDecl>(TD)) {
1338           mangleMemberDataPointer(RD, nullptr);
1339           return;
1340         }
1341         // nullptr data pointers are always represented with a single field
1342         // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1343         // distinguish the case where the data member is at offset zero in the
1344         // record.
1345         // However, we are free to use 0 *if* we would use multiple fields for
1346         // non-nullptr member pointers.
1347         if (!RD->nullFieldOffsetIsZero()) {
1348           mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1349           return;
1350         }
1351       }
1352     }
1353     mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1354     break;
1355   }
1356   case TemplateArgument::Expression:
1357     mangleExpression(TA.getAsExpr());
1358     break;
1359   case TemplateArgument::Pack: {
1360     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1361     if (TemplateArgs.empty()) {
1362       if (isa<TemplateTypeParmDecl>(Parm) ||
1363           isa<TemplateTemplateParmDecl>(Parm))
1364         // MSVC 2015 changed the mangling for empty expanded template packs,
1365         // use the old mangling for link compatibility for old versions.
1366         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1367                     LangOptions::MSVC2015)
1368                     ? "$$V"
1369                     : "$$$V");
1370       else if (isa<NonTypeTemplateParmDecl>(Parm))
1371         Out << "$S";
1372       else
1373         llvm_unreachable("unexpected template parameter decl!");
1374     } else {
1375       for (const TemplateArgument &PA : TemplateArgs)
1376         mangleTemplateArg(TD, PA, Parm);
1377     }
1378     break;
1379   }
1380   case TemplateArgument::Template: {
1381     const NamedDecl *ND =
1382         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1383     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1384       mangleType(TD);
1385     } else if (isa<TypeAliasDecl>(ND)) {
1386       Out << "$$Y";
1387       mangleName(ND);
1388     } else {
1389       llvm_unreachable("unexpected template template NamedDecl!");
1390     }
1391     break;
1392   }
1393   }
1394 }
1395
1396 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1397                                                bool IsMember) {
1398   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1399   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1400   // 'I' means __restrict (32/64-bit).
1401   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1402   // keyword!
1403   // <base-cvr-qualifiers> ::= A  # near
1404   //                       ::= B  # near const
1405   //                       ::= C  # near volatile
1406   //                       ::= D  # near const volatile
1407   //                       ::= E  # far (16-bit)
1408   //                       ::= F  # far const (16-bit)
1409   //                       ::= G  # far volatile (16-bit)
1410   //                       ::= H  # far const volatile (16-bit)
1411   //                       ::= I  # huge (16-bit)
1412   //                       ::= J  # huge const (16-bit)
1413   //                       ::= K  # huge volatile (16-bit)
1414   //                       ::= L  # huge const volatile (16-bit)
1415   //                       ::= M <basis> # based
1416   //                       ::= N <basis> # based const
1417   //                       ::= O <basis> # based volatile
1418   //                       ::= P <basis> # based const volatile
1419   //                       ::= Q  # near member
1420   //                       ::= R  # near const member
1421   //                       ::= S  # near volatile member
1422   //                       ::= T  # near const volatile member
1423   //                       ::= U  # far member (16-bit)
1424   //                       ::= V  # far const member (16-bit)
1425   //                       ::= W  # far volatile member (16-bit)
1426   //                       ::= X  # far const volatile member (16-bit)
1427   //                       ::= Y  # huge member (16-bit)
1428   //                       ::= Z  # huge const member (16-bit)
1429   //                       ::= 0  # huge volatile member (16-bit)
1430   //                       ::= 1  # huge const volatile member (16-bit)
1431   //                       ::= 2 <basis> # based member
1432   //                       ::= 3 <basis> # based const member
1433   //                       ::= 4 <basis> # based volatile member
1434   //                       ::= 5 <basis> # based const volatile member
1435   //                       ::= 6  # near function (pointers only)
1436   //                       ::= 7  # far function (pointers only)
1437   //                       ::= 8  # near method (pointers only)
1438   //                       ::= 9  # far method (pointers only)
1439   //                       ::= _A <basis> # based function (pointers only)
1440   //                       ::= _B <basis> # based function (far?) (pointers only)
1441   //                       ::= _C <basis> # based method (pointers only)
1442   //                       ::= _D <basis> # based method (far?) (pointers only)
1443   //                       ::= _E # block (Clang)
1444   // <basis> ::= 0 # __based(void)
1445   //         ::= 1 # __based(segment)?
1446   //         ::= 2 <name> # __based(name)
1447   //         ::= 3 # ?
1448   //         ::= 4 # ?
1449   //         ::= 5 # not really based
1450   bool HasConst = Quals.hasConst(),
1451        HasVolatile = Quals.hasVolatile();
1452
1453   if (!IsMember) {
1454     if (HasConst && HasVolatile) {
1455       Out << 'D';
1456     } else if (HasVolatile) {
1457       Out << 'C';
1458     } else if (HasConst) {
1459       Out << 'B';
1460     } else {
1461       Out << 'A';
1462     }
1463   } else {
1464     if (HasConst && HasVolatile) {
1465       Out << 'T';
1466     } else if (HasVolatile) {
1467       Out << 'S';
1468     } else if (HasConst) {
1469       Out << 'R';
1470     } else {
1471       Out << 'Q';
1472     }
1473   }
1474
1475   // FIXME: For now, just drop all extension qualifiers on the floor.
1476 }
1477
1478 void
1479 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1480   // <ref-qualifier> ::= G                # lvalue reference
1481   //                 ::= H                # rvalue-reference
1482   switch (RefQualifier) {
1483   case RQ_None:
1484     break;
1485
1486   case RQ_LValue:
1487     Out << 'G';
1488     break;
1489
1490   case RQ_RValue:
1491     Out << 'H';
1492     break;
1493   }
1494 }
1495
1496 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1497                                                          QualType PointeeType) {
1498   bool HasRestrict = Quals.hasRestrict();
1499   if (PointersAre64Bit &&
1500       (PointeeType.isNull() || !PointeeType->isFunctionType()))
1501     Out << 'E';
1502
1503   if (HasRestrict)
1504     Out << 'I';
1505
1506   if (Quals.hasUnaligned() ||
1507       (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1508     Out << 'F';
1509 }
1510
1511 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1512   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1513   //                         ::= Q  # const
1514   //                         ::= R  # volatile
1515   //                         ::= S  # const volatile
1516   bool HasConst = Quals.hasConst(),
1517        HasVolatile = Quals.hasVolatile();
1518
1519   if (HasConst && HasVolatile) {
1520     Out << 'S';
1521   } else if (HasVolatile) {
1522     Out << 'R';
1523   } else if (HasConst) {
1524     Out << 'Q';
1525   } else {
1526     Out << 'P';
1527   }
1528 }
1529
1530 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1531                                                  SourceRange Range) {
1532   // MSVC will backreference two canonically equivalent types that have slightly
1533   // different manglings when mangled alone.
1534
1535   // Decayed types do not match up with non-decayed versions of the same type.
1536   //
1537   // e.g.
1538   // void (*x)(void) will not form a backreference with void x(void)
1539   void *TypePtr;
1540   if (const auto *DT = T->getAs<DecayedType>()) {
1541     QualType OriginalType = DT->getOriginalType();
1542     // All decayed ArrayTypes should be treated identically; as-if they were
1543     // a decayed IncompleteArrayType.
1544     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1545       OriginalType = getASTContext().getIncompleteArrayType(
1546           AT->getElementType(), AT->getSizeModifier(),
1547           AT->getIndexTypeCVRQualifiers());
1548
1549     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1550     // If the original parameter was textually written as an array,
1551     // instead treat the decayed parameter like it's const.
1552     //
1553     // e.g.
1554     // int [] -> int * const
1555     if (OriginalType->isArrayType())
1556       T = T.withConst();
1557   } else {
1558     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1559   }
1560
1561   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1562
1563   if (Found == TypeBackReferences.end()) {
1564     size_t OutSizeBefore = Out.tell();
1565
1566     mangleType(T, Range, QMM_Drop);
1567
1568     // See if it's worth creating a back reference.
1569     // Only types longer than 1 character are considered
1570     // and only 10 back references slots are available:
1571     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1572     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1573       size_t Size = TypeBackReferences.size();
1574       TypeBackReferences[TypePtr] = Size;
1575     }
1576   } else {
1577     Out << Found->second;
1578   }
1579 }
1580
1581 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1582     const PassObjectSizeAttr *POSA) {
1583   int Type = POSA->getType();
1584
1585   auto Iter = PassObjectSizeArgs.insert(Type).first;
1586   auto *TypePtr = (const void *)&*Iter;
1587   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1588
1589   if (Found == TypeBackReferences.end()) {
1590     mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1591                            {"__clang"});
1592
1593     if (TypeBackReferences.size() < 10) {
1594       size_t Size = TypeBackReferences.size();
1595       TypeBackReferences[TypePtr] = Size;
1596     }
1597   } else {
1598     Out << Found->second;
1599   }
1600 }
1601
1602 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1603                                          QualifierMangleMode QMM) {
1604   // Don't use the canonical types.  MSVC includes things like 'const' on
1605   // pointer arguments to function pointers that canonicalization strips away.
1606   T = T.getDesugaredType(getASTContext());
1607   Qualifiers Quals = T.getLocalQualifiers();
1608   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1609     // If there were any Quals, getAsArrayType() pushed them onto the array
1610     // element type.
1611     if (QMM == QMM_Mangle)
1612       Out << 'A';
1613     else if (QMM == QMM_Escape || QMM == QMM_Result)
1614       Out << "$$B";
1615     mangleArrayType(AT);
1616     return;
1617   }
1618
1619   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1620                    T->isReferenceType() || T->isBlockPointerType();
1621
1622   switch (QMM) {
1623   case QMM_Drop:
1624     break;
1625   case QMM_Mangle:
1626     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1627       Out << '6';
1628       mangleFunctionType(FT);
1629       return;
1630     }
1631     mangleQualifiers(Quals, false);
1632     break;
1633   case QMM_Escape:
1634     if (!IsPointer && Quals) {
1635       Out << "$$C";
1636       mangleQualifiers(Quals, false);
1637     }
1638     break;
1639   case QMM_Result:
1640     // Presence of __unaligned qualifier shouldn't affect mangling here.
1641     Quals.removeUnaligned();
1642     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1643       Out << '?';
1644       mangleQualifiers(Quals, false);
1645     }
1646     break;
1647   }
1648
1649   const Type *ty = T.getTypePtr();
1650
1651   switch (ty->getTypeClass()) {
1652 #define ABSTRACT_TYPE(CLASS, PARENT)
1653 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1654   case Type::CLASS: \
1655     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1656     return;
1657 #define TYPE(CLASS, PARENT) \
1658   case Type::CLASS: \
1659     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1660     break;
1661 #include "clang/AST/TypeNodes.def"
1662 #undef ABSTRACT_TYPE
1663 #undef NON_CANONICAL_TYPE
1664 #undef TYPE
1665   }
1666 }
1667
1668 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1669                                          SourceRange Range) {
1670   //  <type>         ::= <builtin-type>
1671   //  <builtin-type> ::= X  # void
1672   //                 ::= C  # signed char
1673   //                 ::= D  # char
1674   //                 ::= E  # unsigned char
1675   //                 ::= F  # short
1676   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1677   //                 ::= H  # int
1678   //                 ::= I  # unsigned int
1679   //                 ::= J  # long
1680   //                 ::= K  # unsigned long
1681   //                     L  # <none>
1682   //                 ::= M  # float
1683   //                 ::= N  # double
1684   //                 ::= O  # long double (__float80 is mangled differently)
1685   //                 ::= _J # long long, __int64
1686   //                 ::= _K # unsigned long long, __int64
1687   //                 ::= _L # __int128
1688   //                 ::= _M # unsigned __int128
1689   //                 ::= _N # bool
1690   //                     _O # <array in parameter>
1691   //                 ::= _T # __float80 (Intel)
1692   //                 ::= _W # wchar_t
1693   //                 ::= _Z # __float80 (Digital Mars)
1694   switch (T->getKind()) {
1695   case BuiltinType::Void:
1696     Out << 'X';
1697     break;
1698   case BuiltinType::SChar:
1699     Out << 'C';
1700     break;
1701   case BuiltinType::Char_U:
1702   case BuiltinType::Char_S:
1703     Out << 'D';
1704     break;
1705   case BuiltinType::UChar:
1706     Out << 'E';
1707     break;
1708   case BuiltinType::Short:
1709     Out << 'F';
1710     break;
1711   case BuiltinType::UShort:
1712     Out << 'G';
1713     break;
1714   case BuiltinType::Int:
1715     Out << 'H';
1716     break;
1717   case BuiltinType::UInt:
1718     Out << 'I';
1719     break;
1720   case BuiltinType::Long:
1721     Out << 'J';
1722     break;
1723   case BuiltinType::ULong:
1724     Out << 'K';
1725     break;
1726   case BuiltinType::Float:
1727     Out << 'M';
1728     break;
1729   case BuiltinType::Double:
1730     Out << 'N';
1731     break;
1732   // TODO: Determine size and mangle accordingly
1733   case BuiltinType::LongDouble:
1734     Out << 'O';
1735     break;
1736   case BuiltinType::LongLong:
1737     Out << "_J";
1738     break;
1739   case BuiltinType::ULongLong:
1740     Out << "_K";
1741     break;
1742   case BuiltinType::Int128:
1743     Out << "_L";
1744     break;
1745   case BuiltinType::UInt128:
1746     Out << "_M";
1747     break;
1748   case BuiltinType::Bool:
1749     Out << "_N";
1750     break;
1751   case BuiltinType::Char16:
1752     Out << "_S";
1753     break;
1754   case BuiltinType::Char32:
1755     Out << "_U";
1756     break;
1757   case BuiltinType::WChar_S:
1758   case BuiltinType::WChar_U:
1759     Out << "_W";
1760     break;
1761
1762 #define BUILTIN_TYPE(Id, SingletonId)
1763 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1764   case BuiltinType::Id:
1765 #include "clang/AST/BuiltinTypes.def"
1766   case BuiltinType::Dependent:
1767     llvm_unreachable("placeholder types shouldn't get to name mangling");
1768
1769   case BuiltinType::ObjCId:
1770     Out << "PA";
1771     mangleArtificalTagType(TTK_Struct, "objc_object");
1772     break;
1773   case BuiltinType::ObjCClass:
1774     Out << "PA";
1775     mangleArtificalTagType(TTK_Struct, "objc_class");
1776     break;
1777   case BuiltinType::ObjCSel:
1778     Out << "PA";
1779     mangleArtificalTagType(TTK_Struct, "objc_selector");
1780     break;
1781
1782 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1783   case BuiltinType::Id: \
1784     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
1785     break;
1786 #include "clang/Basic/OpenCLImageTypes.def"
1787   case BuiltinType::OCLSampler:
1788     Out << "PA";
1789     mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1790     break;
1791   case BuiltinType::OCLEvent:
1792     Out << "PA";
1793     mangleArtificalTagType(TTK_Struct, "ocl_event");
1794     break;
1795   case BuiltinType::OCLClkEvent:
1796     Out << "PA";
1797     mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1798     break;
1799   case BuiltinType::OCLQueue:
1800     Out << "PA";
1801     mangleArtificalTagType(TTK_Struct, "ocl_queue");
1802     break;
1803   case BuiltinType::OCLReserveID:
1804     Out << "PA";
1805     mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1806     break;
1807
1808   case BuiltinType::NullPtr:
1809     Out << "$$T";
1810     break;
1811
1812   case BuiltinType::Float128:
1813   case BuiltinType::Half: {
1814     DiagnosticsEngine &Diags = Context.getDiags();
1815     unsigned DiagID = Diags.getCustomDiagID(
1816         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1817     Diags.Report(Range.getBegin(), DiagID)
1818         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1819     break;
1820   }
1821   }
1822 }
1823
1824 // <type>          ::= <function-type>
1825 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1826                                          SourceRange) {
1827   // Structors only appear in decls, so at this point we know it's not a
1828   // structor type.
1829   // FIXME: This may not be lambda-friendly.
1830   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1831     Out << "$$A8@@";
1832     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1833   } else {
1834     Out << "$$A6";
1835     mangleFunctionType(T);
1836   }
1837 }
1838 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1839                                          Qualifiers, SourceRange) {
1840   Out << "$$A6";
1841   mangleFunctionType(T);
1842 }
1843
1844 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1845                                                  const FunctionDecl *D,
1846                                                  bool ForceThisQuals) {
1847   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1848   //                     <return-type> <argument-list> <throw-spec>
1849   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1850
1851   SourceRange Range;
1852   if (D) Range = D->getSourceRange();
1853
1854   bool IsInLambda = false;
1855   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1856   CallingConv CC = T->getCallConv();
1857   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1858     if (MD->getParent()->isLambda())
1859       IsInLambda = true;
1860     if (MD->isInstance())
1861       HasThisQuals = true;
1862     if (isa<CXXDestructorDecl>(MD)) {
1863       IsStructor = true;
1864     } else if (isa<CXXConstructorDecl>(MD)) {
1865       IsStructor = true;
1866       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1867                        StructorType == Ctor_DefaultClosure) &&
1868                       isStructorDecl(MD);
1869       if (IsCtorClosure)
1870         CC = getASTContext().getDefaultCallingConvention(
1871             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1872     }
1873   }
1874
1875   // If this is a C++ instance method, mangle the CVR qualifiers for the
1876   // this pointer.
1877   if (HasThisQuals) {
1878     Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals());
1879     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1880     mangleRefQualifier(Proto->getRefQualifier());
1881     mangleQualifiers(Quals, /*IsMember=*/false);
1882   }
1883
1884   mangleCallingConvention(CC);
1885
1886   // <return-type> ::= <type>
1887   //               ::= @ # structors (they have no declared return type)
1888   if (IsStructor) {
1889     if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
1890       // The scalar deleting destructor takes an extra int argument which is not
1891       // reflected in the AST.
1892       if (StructorType == Dtor_Deleting) {
1893         Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1894         return;
1895       }
1896       // The vbase destructor returns void which is not reflected in the AST.
1897       if (StructorType == Dtor_Complete) {
1898         Out << "XXZ";
1899         return;
1900       }
1901     }
1902     if (IsCtorClosure) {
1903       // Default constructor closure and copy constructor closure both return
1904       // void.
1905       Out << 'X';
1906
1907       if (StructorType == Ctor_DefaultClosure) {
1908         // Default constructor closure always has no arguments.
1909         Out << 'X';
1910       } else if (StructorType == Ctor_CopyingClosure) {
1911         // Copy constructor closure always takes an unqualified reference.
1912         mangleArgumentType(getASTContext().getLValueReferenceType(
1913                                Proto->getParamType(0)
1914                                    ->getAs<LValueReferenceType>()
1915                                    ->getPointeeType(),
1916                                /*SpelledAsLValue=*/true),
1917                            Range);
1918         Out << '@';
1919       } else {
1920         llvm_unreachable("unexpected constructor closure!");
1921       }
1922       Out << 'Z';
1923       return;
1924     }
1925     Out << '@';
1926   } else {
1927     QualType ResultType = T->getReturnType();
1928     if (const auto *AT =
1929             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1930       Out << '?';
1931       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1932       Out << '?';
1933       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
1934              "shouldn't need to mangle __auto_type!");
1935       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1936       Out << '@';
1937     } else if (IsInLambda) {
1938       Out << '@';
1939     } else {
1940       if (ResultType->isVoidType())
1941         ResultType = ResultType.getUnqualifiedType();
1942       mangleType(ResultType, Range, QMM_Result);
1943     }
1944   }
1945
1946   // <argument-list> ::= X # void
1947   //                 ::= <type>+ @
1948   //                 ::= <type>* Z # varargs
1949   if (!Proto) {
1950     // Function types without prototypes can arise when mangling a function type
1951     // within an overloadable function in C. We mangle these as the absence of
1952     // any parameter types (not even an empty parameter list).
1953     Out << '@';
1954   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1955     Out << 'X';
1956   } else {
1957     // Happens for function pointer type arguments for example.
1958     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
1959       mangleArgumentType(Proto->getParamType(I), Range);
1960       // Mangle each pass_object_size parameter as if it's a parameter of enum
1961       // type passed directly after the parameter with the pass_object_size
1962       // attribute. The aforementioned enum's name is __pass_object_size, and we
1963       // pretend it resides in a top-level namespace called __clang.
1964       //
1965       // FIXME: Is there a defined extension notation for the MS ABI, or is it
1966       // necessary to just cross our fingers and hope this type+namespace
1967       // combination doesn't conflict with anything?
1968       if (D)
1969         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
1970           manglePassObjectSizeArg(P);
1971     }
1972     // <builtin-type>      ::= Z  # ellipsis
1973     if (Proto->isVariadic())
1974       Out << 'Z';
1975     else
1976       Out << '@';
1977   }
1978
1979   mangleThrowSpecification(Proto);
1980 }
1981
1982 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1983   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1984   //                                            # pointer. in 64-bit mode *all*
1985   //                                            # 'this' pointers are 64-bit.
1986   //                   ::= <global-function>
1987   // <member-function> ::= A # private: near
1988   //                   ::= B # private: far
1989   //                   ::= C # private: static near
1990   //                   ::= D # private: static far
1991   //                   ::= E # private: virtual near
1992   //                   ::= F # private: virtual far
1993   //                   ::= I # protected: near
1994   //                   ::= J # protected: far
1995   //                   ::= K # protected: static near
1996   //                   ::= L # protected: static far
1997   //                   ::= M # protected: virtual near
1998   //                   ::= N # protected: virtual far
1999   //                   ::= Q # public: near
2000   //                   ::= R # public: far
2001   //                   ::= S # public: static near
2002   //                   ::= T # public: static far
2003   //                   ::= U # public: virtual near
2004   //                   ::= V # public: virtual far
2005   // <global-function> ::= Y # global near
2006   //                   ::= Z # global far
2007   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2008     bool IsVirtual = MD->isVirtual();
2009     // When mangling vbase destructor variants, ignore whether or not the
2010     // underlying destructor was defined to be virtual.
2011     if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2012         StructorType == Dtor_Complete) {
2013       IsVirtual = false;
2014     }
2015     switch (MD->getAccess()) {
2016       case AS_none:
2017         llvm_unreachable("Unsupported access specifier");
2018       case AS_private:
2019         if (MD->isStatic())
2020           Out << 'C';
2021         else if (IsVirtual)
2022           Out << 'E';
2023         else
2024           Out << 'A';
2025         break;
2026       case AS_protected:
2027         if (MD->isStatic())
2028           Out << 'K';
2029         else if (IsVirtual)
2030           Out << 'M';
2031         else
2032           Out << 'I';
2033         break;
2034       case AS_public:
2035         if (MD->isStatic())
2036           Out << 'S';
2037         else if (IsVirtual)
2038           Out << 'U';
2039         else
2040           Out << 'Q';
2041     }
2042   } else {
2043     Out << 'Y';
2044   }
2045 }
2046 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2047   // <calling-convention> ::= A # __cdecl
2048   //                      ::= B # __export __cdecl
2049   //                      ::= C # __pascal
2050   //                      ::= D # __export __pascal
2051   //                      ::= E # __thiscall
2052   //                      ::= F # __export __thiscall
2053   //                      ::= G # __stdcall
2054   //                      ::= H # __export __stdcall
2055   //                      ::= I # __fastcall
2056   //                      ::= J # __export __fastcall
2057   //                      ::= Q # __vectorcall
2058   //                      ::= w # __regcall
2059   // The 'export' calling conventions are from a bygone era
2060   // (*cough*Win16*cough*) when functions were declared for export with
2061   // that keyword. (It didn't actually export them, it just made them so
2062   // that they could be in a DLL and somebody from another module could call
2063   // them.)
2064
2065   switch (CC) {
2066     default:
2067       llvm_unreachable("Unsupported CC for mangling");
2068     case CC_X86_64Win64:
2069     case CC_X86_64SysV:
2070     case CC_C: Out << 'A'; break;
2071     case CC_X86Pascal: Out << 'C'; break;
2072     case CC_X86ThisCall: Out << 'E'; break;
2073     case CC_X86StdCall: Out << 'G'; break;
2074     case CC_X86FastCall: Out << 'I'; break;
2075     case CC_X86VectorCall: Out << 'Q'; break;
2076     case CC_X86RegCall: Out << 'w'; break;
2077   }
2078 }
2079 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2080   mangleCallingConvention(T->getCallConv());
2081 }
2082 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2083                                                 const FunctionProtoType *FT) {
2084   // <throw-spec> ::= Z # throw(...) (default)
2085   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
2086   //              ::= <type>+
2087   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2088   // all actually mangled as 'Z'. (They're ignored because their associated
2089   // functionality isn't implemented, and probably never will be.)
2090   Out << 'Z';
2091 }
2092
2093 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2094                                          Qualifiers, SourceRange Range) {
2095   // Probably should be mangled as a template instantiation; need to see what
2096   // VC does first.
2097   DiagnosticsEngine &Diags = Context.getDiags();
2098   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2099     "cannot mangle this unresolved dependent type yet");
2100   Diags.Report(Range.getBegin(), DiagID)
2101     << Range;
2102 }
2103
2104 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2105 // <union-type>  ::= T <name>
2106 // <struct-type> ::= U <name>
2107 // <class-type>  ::= V <name>
2108 // <enum-type>   ::= W4 <name>
2109 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2110   switch (TTK) {
2111     case TTK_Union:
2112       Out << 'T';
2113       break;
2114     case TTK_Struct:
2115     case TTK_Interface:
2116       Out << 'U';
2117       break;
2118     case TTK_Class:
2119       Out << 'V';
2120       break;
2121     case TTK_Enum:
2122       Out << "W4";
2123       break;
2124   }
2125 }
2126 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2127                                          SourceRange) {
2128   mangleType(cast<TagType>(T)->getDecl());
2129 }
2130 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2131                                          SourceRange) {
2132   mangleType(cast<TagType>(T)->getDecl());
2133 }
2134 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2135   mangleTagTypeKind(TD->getTagKind());
2136   mangleName(TD);
2137 }
2138 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2139     TagTypeKind TK, StringRef UnqualifiedName, ArrayRef<StringRef> NestedNames) {
2140   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2141   mangleTagTypeKind(TK);
2142
2143   // Always start with the unqualified name.
2144   mangleSourceName(UnqualifiedName);
2145
2146   for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2147     mangleSourceName(*I);
2148
2149   // Terminate the whole name with an '@'.
2150   Out << '@';
2151 }
2152
2153 // <type>       ::= <array-type>
2154 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2155 //                  [Y <dimension-count> <dimension>+]
2156 //                  <element-type> # as global, E is never required
2157 // It's supposed to be the other way around, but for some strange reason, it
2158 // isn't. Today this behavior is retained for the sole purpose of backwards
2159 // compatibility.
2160 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2161   // This isn't a recursive mangling, so now we have to do it all in this
2162   // one call.
2163   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2164   mangleType(T->getElementType(), SourceRange());
2165 }
2166 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2167                                          SourceRange) {
2168   llvm_unreachable("Should have been special cased");
2169 }
2170 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2171                                          SourceRange) {
2172   llvm_unreachable("Should have been special cased");
2173 }
2174 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2175                                          Qualifiers, SourceRange) {
2176   llvm_unreachable("Should have been special cased");
2177 }
2178 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2179                                          Qualifiers, SourceRange) {
2180   llvm_unreachable("Should have been special cased");
2181 }
2182 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2183   QualType ElementTy(T, 0);
2184   SmallVector<llvm::APInt, 3> Dimensions;
2185   for (;;) {
2186     if (ElementTy->isConstantArrayType()) {
2187       const ConstantArrayType *CAT =
2188           getASTContext().getAsConstantArrayType(ElementTy);
2189       Dimensions.push_back(CAT->getSize());
2190       ElementTy = CAT->getElementType();
2191     } else if (ElementTy->isIncompleteArrayType()) {
2192       const IncompleteArrayType *IAT =
2193           getASTContext().getAsIncompleteArrayType(ElementTy);
2194       Dimensions.push_back(llvm::APInt(32, 0));
2195       ElementTy = IAT->getElementType();
2196     } else if (ElementTy->isVariableArrayType()) {
2197       const VariableArrayType *VAT =
2198         getASTContext().getAsVariableArrayType(ElementTy);
2199       Dimensions.push_back(llvm::APInt(32, 0));
2200       ElementTy = VAT->getElementType();
2201     } else if (ElementTy->isDependentSizedArrayType()) {
2202       // The dependent expression has to be folded into a constant (TODO).
2203       const DependentSizedArrayType *DSAT =
2204         getASTContext().getAsDependentSizedArrayType(ElementTy);
2205       DiagnosticsEngine &Diags = Context.getDiags();
2206       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2207         "cannot mangle this dependent-length array yet");
2208       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2209         << DSAT->getBracketsRange();
2210       return;
2211     } else {
2212       break;
2213     }
2214   }
2215   Out << 'Y';
2216   // <dimension-count> ::= <number> # number of extra dimensions
2217   mangleNumber(Dimensions.size());
2218   for (const llvm::APInt &Dimension : Dimensions)
2219     mangleNumber(Dimension.getLimitedValue());
2220   mangleType(ElementTy, SourceRange(), QMM_Escape);
2221 }
2222
2223 // <type>                   ::= <pointer-to-member-type>
2224 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2225 //                                                          <class name> <type>
2226 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2227                                          SourceRange Range) {
2228   QualType PointeeType = T->getPointeeType();
2229   manglePointerCVQualifiers(Quals);
2230   manglePointerExtQualifiers(Quals, PointeeType);
2231   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2232     Out << '8';
2233     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2234     mangleFunctionType(FPT, nullptr, true);
2235   } else {
2236     mangleQualifiers(PointeeType.getQualifiers(), true);
2237     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2238     mangleType(PointeeType, Range, QMM_Drop);
2239   }
2240 }
2241
2242 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2243                                          Qualifiers, SourceRange Range) {
2244   DiagnosticsEngine &Diags = Context.getDiags();
2245   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2246     "cannot mangle this template type parameter type yet");
2247   Diags.Report(Range.getBegin(), DiagID)
2248     << Range;
2249 }
2250
2251 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2252                                          Qualifiers, SourceRange Range) {
2253   DiagnosticsEngine &Diags = Context.getDiags();
2254   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2255     "cannot mangle this substituted parameter pack yet");
2256   Diags.Report(Range.getBegin(), DiagID)
2257     << Range;
2258 }
2259
2260 // <type> ::= <pointer-type>
2261 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2262 //                       # the E is required for 64-bit non-static pointers
2263 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2264                                          SourceRange Range) {
2265   QualType PointeeType = T->getPointeeType();
2266   manglePointerCVQualifiers(Quals);
2267   manglePointerExtQualifiers(Quals, PointeeType);
2268   mangleType(PointeeType, Range);
2269 }
2270 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2271                                          Qualifiers Quals, SourceRange Range) {
2272   QualType PointeeType = T->getPointeeType();
2273   manglePointerCVQualifiers(Quals);
2274   manglePointerExtQualifiers(Quals, PointeeType);
2275   // Object pointers never have qualifiers.
2276   Out << 'A';
2277   mangleType(PointeeType, Range);
2278 }
2279
2280 // <type> ::= <reference-type>
2281 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2282 //                 # the E is required for 64-bit non-static lvalue references
2283 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2284                                          Qualifiers Quals, SourceRange Range) {
2285   QualType PointeeType = T->getPointeeType();
2286   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2287   Out << 'A';
2288   manglePointerExtQualifiers(Quals, PointeeType);
2289   mangleType(PointeeType, Range);
2290 }
2291
2292 // <type> ::= <r-value-reference-type>
2293 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2294 //                 # the E is required for 64-bit non-static rvalue references
2295 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2296                                          Qualifiers Quals, SourceRange Range) {
2297   QualType PointeeType = T->getPointeeType();
2298   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2299   Out << "$$Q";
2300   manglePointerExtQualifiers(Quals, PointeeType);
2301   mangleType(PointeeType, Range);
2302 }
2303
2304 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2305                                          SourceRange Range) {
2306   QualType ElementType = T->getElementType();
2307
2308   llvm::SmallString<64> TemplateMangling;
2309   llvm::raw_svector_ostream Stream(TemplateMangling);
2310   MicrosoftCXXNameMangler Extra(Context, Stream);
2311   Stream << "?$";
2312   Extra.mangleSourceName("_Complex");
2313   Extra.mangleType(ElementType, Range, QMM_Escape);
2314
2315   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2316 }
2317
2318 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2319                                          SourceRange Range) {
2320   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2321   assert(ET && "vectors with non-builtin elements are unsupported");
2322   uint64_t Width = getASTContext().getTypeSize(T);
2323   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2324   // doesn't match the Intel types uses a custom mangling below.
2325   size_t OutSizeBefore = Out.tell();
2326   llvm::Triple::ArchType AT =
2327       getASTContext().getTargetInfo().getTriple().getArch();
2328   if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2329     if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2330       mangleArtificalTagType(TTK_Union, "__m64");
2331     } else if (Width >= 128) {
2332       if (ET->getKind() == BuiltinType::Float)
2333         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width));
2334       else if (ET->getKind() == BuiltinType::LongLong)
2335         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2336       else if (ET->getKind() == BuiltinType::Double)
2337         mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2338     }
2339   }
2340
2341   bool IsBuiltin = Out.tell() != OutSizeBefore;
2342   if (!IsBuiltin) {
2343     // The MS ABI doesn't have a special mangling for vector types, so we define
2344     // our own mangling to handle uses of __vector_size__ on user-specified
2345     // types, and for extensions like __v4sf.
2346
2347     llvm::SmallString<64> TemplateMangling;
2348     llvm::raw_svector_ostream Stream(TemplateMangling);
2349     MicrosoftCXXNameMangler Extra(Context, Stream);
2350     Stream << "?$";
2351     Extra.mangleSourceName("__vector");
2352     Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2353     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2354                                /*IsBoolean=*/false);
2355
2356     mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"});
2357   }
2358 }
2359
2360 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2361                                          Qualifiers Quals, SourceRange Range) {
2362   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2363 }
2364 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2365                                          Qualifiers, SourceRange Range) {
2366   DiagnosticsEngine &Diags = Context.getDiags();
2367   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2368     "cannot mangle this dependent-sized extended vector type yet");
2369   Diags.Report(Range.getBegin(), DiagID)
2370     << Range;
2371 }
2372
2373 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2374                                          SourceRange) {
2375   // ObjC interfaces have structs underlying them.
2376   mangleTagTypeKind(TTK_Struct);
2377   mangleName(T->getDecl());
2378 }
2379
2380 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2381                                          SourceRange Range) {
2382   // We don't allow overloading by different protocol qualification,
2383   // so mangling them isn't necessary.
2384   mangleType(T->getBaseType(), Range);
2385 }
2386
2387 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2388                                          Qualifiers Quals, SourceRange Range) {
2389   QualType PointeeType = T->getPointeeType();
2390   manglePointerCVQualifiers(Quals);
2391   manglePointerExtQualifiers(Quals, PointeeType);
2392
2393   Out << "_E";
2394
2395   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2396 }
2397
2398 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2399                                          Qualifiers, SourceRange) {
2400   llvm_unreachable("Cannot mangle injected class name type.");
2401 }
2402
2403 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2404                                          Qualifiers, SourceRange Range) {
2405   DiagnosticsEngine &Diags = Context.getDiags();
2406   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2407     "cannot mangle this template specialization type yet");
2408   Diags.Report(Range.getBegin(), DiagID)
2409     << Range;
2410 }
2411
2412 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2413                                          SourceRange Range) {
2414   DiagnosticsEngine &Diags = Context.getDiags();
2415   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2416     "cannot mangle this dependent name type yet");
2417   Diags.Report(Range.getBegin(), DiagID)
2418     << Range;
2419 }
2420
2421 void MicrosoftCXXNameMangler::mangleType(
2422     const DependentTemplateSpecializationType *T, Qualifiers,
2423     SourceRange Range) {
2424   DiagnosticsEngine &Diags = Context.getDiags();
2425   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2426     "cannot mangle this dependent template specialization type yet");
2427   Diags.Report(Range.getBegin(), DiagID)
2428     << Range;
2429 }
2430
2431 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2432                                          SourceRange Range) {
2433   DiagnosticsEngine &Diags = Context.getDiags();
2434   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2435     "cannot mangle this pack expansion yet");
2436   Diags.Report(Range.getBegin(), DiagID)
2437     << Range;
2438 }
2439
2440 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2441                                          SourceRange Range) {
2442   DiagnosticsEngine &Diags = Context.getDiags();
2443   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2444     "cannot mangle this typeof(type) yet");
2445   Diags.Report(Range.getBegin(), DiagID)
2446     << Range;
2447 }
2448
2449 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2450                                          SourceRange Range) {
2451   DiagnosticsEngine &Diags = Context.getDiags();
2452   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2453     "cannot mangle this typeof(expression) yet");
2454   Diags.Report(Range.getBegin(), DiagID)
2455     << Range;
2456 }
2457
2458 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2459                                          SourceRange Range) {
2460   DiagnosticsEngine &Diags = Context.getDiags();
2461   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2462     "cannot mangle this decltype() yet");
2463   Diags.Report(Range.getBegin(), DiagID)
2464     << Range;
2465 }
2466
2467 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2468                                          Qualifiers, SourceRange Range) {
2469   DiagnosticsEngine &Diags = Context.getDiags();
2470   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2471     "cannot mangle this unary transform type yet");
2472   Diags.Report(Range.getBegin(), DiagID)
2473     << Range;
2474 }
2475
2476 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2477                                          SourceRange Range) {
2478   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2479
2480   DiagnosticsEngine &Diags = Context.getDiags();
2481   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2482     "cannot mangle this 'auto' type yet");
2483   Diags.Report(Range.getBegin(), DiagID)
2484     << Range;
2485 }
2486
2487 void MicrosoftCXXNameMangler::mangleType(
2488     const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2489   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2490
2491   DiagnosticsEngine &Diags = Context.getDiags();
2492   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2493     "cannot mangle this deduced class template specialization type yet");
2494   Diags.Report(Range.getBegin(), DiagID)
2495     << Range;
2496 }
2497
2498 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2499                                          SourceRange Range) {
2500   QualType ValueType = T->getValueType();
2501
2502   llvm::SmallString<64> TemplateMangling;
2503   llvm::raw_svector_ostream Stream(TemplateMangling);
2504   MicrosoftCXXNameMangler Extra(Context, Stream);
2505   Stream << "?$";
2506   Extra.mangleSourceName("_Atomic");
2507   Extra.mangleType(ValueType, Range, QMM_Escape);
2508
2509   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2510 }
2511
2512 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2513                                          SourceRange Range) {
2514   DiagnosticsEngine &Diags = Context.getDiags();
2515   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2516     "cannot mangle this OpenCL pipe type yet");
2517   Diags.Report(Range.getBegin(), DiagID)
2518     << Range;
2519 }
2520
2521 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2522                                                raw_ostream &Out) {
2523   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2524          "Invalid mangleName() call, argument is not a variable or function!");
2525   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2526          "Invalid mangleName() call on 'structor decl!");
2527
2528   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2529                                  getASTContext().getSourceManager(),
2530                                  "Mangling declaration");
2531
2532   msvc_hashing_ostream MHO(Out);
2533   MicrosoftCXXNameMangler Mangler(*this, MHO);
2534   return Mangler.mangle(D);
2535 }
2536
2537 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2538 //                       <virtual-adjustment>
2539 // <no-adjustment>      ::= A # private near
2540 //                      ::= B # private far
2541 //                      ::= I # protected near
2542 //                      ::= J # protected far
2543 //                      ::= Q # public near
2544 //                      ::= R # public far
2545 // <static-adjustment>  ::= G <static-offset> # private near
2546 //                      ::= H <static-offset> # private far
2547 //                      ::= O <static-offset> # protected near
2548 //                      ::= P <static-offset> # protected far
2549 //                      ::= W <static-offset> # public near
2550 //                      ::= X <static-offset> # public far
2551 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2552 //                      ::= $1 <virtual-shift> <static-offset> # private far
2553 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2554 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2555 //                      ::= $4 <virtual-shift> <static-offset> # public near
2556 //                      ::= $5 <virtual-shift> <static-offset> # public far
2557 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2558 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2559 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2560 //                          <offset-to-vtordisp>
2561 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2562                                       const ThisAdjustment &Adjustment,
2563                                       MicrosoftCXXNameMangler &Mangler,
2564                                       raw_ostream &Out) {
2565   if (!Adjustment.Virtual.isEmpty()) {
2566     Out << '$';
2567     char AccessSpec;
2568     switch (MD->getAccess()) {
2569     case AS_none:
2570       llvm_unreachable("Unsupported access specifier");
2571     case AS_private:
2572       AccessSpec = '0';
2573       break;
2574     case AS_protected:
2575       AccessSpec = '2';
2576       break;
2577     case AS_public:
2578       AccessSpec = '4';
2579     }
2580     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2581       Out << 'R' << AccessSpec;
2582       Mangler.mangleNumber(
2583           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2584       Mangler.mangleNumber(
2585           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2586       Mangler.mangleNumber(
2587           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2588       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2589     } else {
2590       Out << AccessSpec;
2591       Mangler.mangleNumber(
2592           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2593       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2594     }
2595   } else if (Adjustment.NonVirtual != 0) {
2596     switch (MD->getAccess()) {
2597     case AS_none:
2598       llvm_unreachable("Unsupported access specifier");
2599     case AS_private:
2600       Out << 'G';
2601       break;
2602     case AS_protected:
2603       Out << 'O';
2604       break;
2605     case AS_public:
2606       Out << 'W';
2607     }
2608     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2609   } else {
2610     switch (MD->getAccess()) {
2611     case AS_none:
2612       llvm_unreachable("Unsupported access specifier");
2613     case AS_private:
2614       Out << 'A';
2615       break;
2616     case AS_protected:
2617       Out << 'I';
2618       break;
2619     case AS_public:
2620       Out << 'Q';
2621     }
2622   }
2623 }
2624
2625 void
2626 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2627                                                      raw_ostream &Out) {
2628   MicrosoftVTableContext *VTContext =
2629       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2630   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2631       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2632
2633   msvc_hashing_ostream MHO(Out);
2634   MicrosoftCXXNameMangler Mangler(*this, MHO);
2635   Mangler.getStream() << "\01?";
2636   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2637 }
2638
2639 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2640                                              const ThunkInfo &Thunk,
2641                                              raw_ostream &Out) {
2642   msvc_hashing_ostream MHO(Out);
2643   MicrosoftCXXNameMangler Mangler(*this, MHO);
2644   Mangler.getStream() << "\01?";
2645   Mangler.mangleName(MD);
2646   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, MHO);
2647   if (!Thunk.Return.isEmpty())
2648     assert(Thunk.Method != nullptr &&
2649            "Thunk info should hold the overridee decl");
2650
2651   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2652   Mangler.mangleFunctionType(
2653       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2654 }
2655
2656 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2657     const CXXDestructorDecl *DD, CXXDtorType Type,
2658     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2659   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2660   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2661   // mangling manually until we support both deleting dtor types.
2662   assert(Type == Dtor_Deleting);
2663   msvc_hashing_ostream MHO(Out);
2664   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
2665   Mangler.getStream() << "\01??_E";
2666   Mangler.mangleName(DD->getParent());
2667   mangleThunkThisAdjustment(DD, Adjustment, Mangler, MHO);
2668   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2669 }
2670
2671 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2672     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2673     raw_ostream &Out) {
2674   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2675   //                    <cvr-qualifiers> [<name>] @
2676   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2677   // is always '6' for vftables.
2678   msvc_hashing_ostream MHO(Out);
2679   MicrosoftCXXNameMangler Mangler(*this, MHO);
2680   if (Derived->hasAttr<DLLImportAttr>())
2681     Mangler.getStream() << "\01??_S";
2682   else
2683     Mangler.getStream() << "\01??_7";
2684   Mangler.mangleName(Derived);
2685   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2686   for (const CXXRecordDecl *RD : BasePath)
2687     Mangler.mangleName(RD);
2688   Mangler.getStream() << '@';
2689 }
2690
2691 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2692     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2693     raw_ostream &Out) {
2694   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2695   //                    <cvr-qualifiers> [<name>] @
2696   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2697   // is always '7' for vbtables.
2698   msvc_hashing_ostream MHO(Out);
2699   MicrosoftCXXNameMangler Mangler(*this, MHO);
2700   Mangler.getStream() << "\01??_8";
2701   Mangler.mangleName(Derived);
2702   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2703   for (const CXXRecordDecl *RD : BasePath)
2704     Mangler.mangleName(RD);
2705   Mangler.getStream() << '@';
2706 }
2707
2708 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2709   msvc_hashing_ostream MHO(Out);
2710   MicrosoftCXXNameMangler Mangler(*this, MHO);
2711   Mangler.getStream() << "\01??_R0";
2712   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2713   Mangler.getStream() << "@8";
2714 }
2715
2716 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2717                                                    raw_ostream &Out) {
2718   MicrosoftCXXNameMangler Mangler(*this, Out);
2719   Mangler.getStream() << '.';
2720   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2721 }
2722
2723 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2724     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2725   msvc_hashing_ostream MHO(Out);
2726   MicrosoftCXXNameMangler Mangler(*this, MHO);
2727   Mangler.getStream() << "\01??_K";
2728   Mangler.mangleName(SrcRD);
2729   Mangler.getStream() << "$C";
2730   Mangler.mangleName(DstRD);
2731 }
2732
2733 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
2734                                                     bool IsVolatile,
2735                                                     bool IsUnaligned,
2736                                                     uint32_t NumEntries,
2737                                                     raw_ostream &Out) {
2738   msvc_hashing_ostream MHO(Out);
2739   MicrosoftCXXNameMangler Mangler(*this, MHO);
2740   Mangler.getStream() << "_TI";
2741   if (IsConst)
2742     Mangler.getStream() << 'C';
2743   if (IsVolatile)
2744     Mangler.getStream() << 'V';
2745   if (IsUnaligned)
2746     Mangler.getStream() << 'U';
2747   Mangler.getStream() << NumEntries;
2748   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2749 }
2750
2751 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2752     QualType T, uint32_t NumEntries, raw_ostream &Out) {
2753   msvc_hashing_ostream MHO(Out);
2754   MicrosoftCXXNameMangler Mangler(*this, MHO);
2755   Mangler.getStream() << "_CTA";
2756   Mangler.getStream() << NumEntries;
2757   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2758 }
2759
2760 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2761     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2762     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2763     raw_ostream &Out) {
2764   MicrosoftCXXNameMangler Mangler(*this, Out);
2765   Mangler.getStream() << "_CT";
2766
2767   llvm::SmallString<64> RTTIMangling;
2768   {
2769     llvm::raw_svector_ostream Stream(RTTIMangling);
2770     msvc_hashing_ostream MHO(Stream);
2771     mangleCXXRTTI(T, MHO);
2772   }
2773   Mangler.getStream() << RTTIMangling.substr(1);
2774
2775   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
2776   // in fact, superfluous but I'm not sure the change was made consciously.
2777   llvm::SmallString<64> CopyCtorMangling;
2778   if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
2779           LangOptions::MSVC2015) &&
2780       CD) {
2781     llvm::raw_svector_ostream Stream(CopyCtorMangling);
2782     msvc_hashing_ostream MHO(Stream);
2783     mangleCXXCtor(CD, CT, MHO);
2784   }
2785   Mangler.getStream() << CopyCtorMangling.substr(1);
2786
2787   Mangler.getStream() << Size;
2788   if (VBPtrOffset == -1) {
2789     if (NVOffset) {
2790       Mangler.getStream() << NVOffset;
2791     }
2792   } else {
2793     Mangler.getStream() << NVOffset;
2794     Mangler.getStream() << VBPtrOffset;
2795     Mangler.getStream() << VBIndex;
2796   }
2797 }
2798
2799 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2800     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2801     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2802   msvc_hashing_ostream MHO(Out);
2803   MicrosoftCXXNameMangler Mangler(*this, MHO);
2804   Mangler.getStream() << "\01??_R1";
2805   Mangler.mangleNumber(NVOffset);
2806   Mangler.mangleNumber(VBPtrOffset);
2807   Mangler.mangleNumber(VBTableOffset);
2808   Mangler.mangleNumber(Flags);
2809   Mangler.mangleName(Derived);
2810   Mangler.getStream() << "8";
2811 }
2812
2813 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2814     const CXXRecordDecl *Derived, raw_ostream &Out) {
2815   msvc_hashing_ostream MHO(Out);
2816   MicrosoftCXXNameMangler Mangler(*this, MHO);
2817   Mangler.getStream() << "\01??_R2";
2818   Mangler.mangleName(Derived);
2819   Mangler.getStream() << "8";
2820 }
2821
2822 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2823     const CXXRecordDecl *Derived, raw_ostream &Out) {
2824   msvc_hashing_ostream MHO(Out);
2825   MicrosoftCXXNameMangler Mangler(*this, MHO);
2826   Mangler.getStream() << "\01??_R3";
2827   Mangler.mangleName(Derived);
2828   Mangler.getStream() << "8";
2829 }
2830
2831 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2832     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2833     raw_ostream &Out) {
2834   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2835   //                    <cvr-qualifiers> [<name>] @
2836   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2837   // is always '6' for vftables.
2838   llvm::SmallString<64> VFTableMangling;
2839   llvm::raw_svector_ostream Stream(VFTableMangling);
2840   mangleCXXVFTable(Derived, BasePath, Stream);
2841
2842   if (VFTableMangling.startswith("\01??@")) {
2843     assert(VFTableMangling.endswith("@"));
2844     Out << VFTableMangling << "??_R4@";
2845     return;
2846   }
2847
2848   assert(VFTableMangling.startswith("\01??_7") ||
2849          VFTableMangling.startswith("\01??_S"));
2850
2851   Out << "\01??_R4" << StringRef(VFTableMangling).drop_front(5);
2852 }
2853
2854 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2855     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2856   msvc_hashing_ostream MHO(Out);
2857   MicrosoftCXXNameMangler Mangler(*this, MHO);
2858   // The function body is in the same comdat as the function with the handler,
2859   // so the numbering here doesn't have to be the same across TUs.
2860   //
2861   // <mangled-name> ::= ?filt$ <filter-number> @0
2862   Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2863   Mangler.mangleName(EnclosingDecl);
2864 }
2865
2866 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2867     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2868   msvc_hashing_ostream MHO(Out);
2869   MicrosoftCXXNameMangler Mangler(*this, MHO);
2870   // The function body is in the same comdat as the function with the handler,
2871   // so the numbering here doesn't have to be the same across TUs.
2872   //
2873   // <mangled-name> ::= ?fin$ <filter-number> @0
2874   Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2875   Mangler.mangleName(EnclosingDecl);
2876 }
2877
2878 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2879   // This is just a made up unique string for the purposes of tbaa.  undname
2880   // does *not* know how to demangle it.
2881   MicrosoftCXXNameMangler Mangler(*this, Out);
2882   Mangler.getStream() << '?';
2883   Mangler.mangleType(T, SourceRange());
2884 }
2885
2886 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2887                                                CXXCtorType Type,
2888                                                raw_ostream &Out) {
2889   msvc_hashing_ostream MHO(Out);
2890   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
2891   mangler.mangle(D);
2892 }
2893
2894 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2895                                                CXXDtorType Type,
2896                                                raw_ostream &Out) {
2897   msvc_hashing_ostream MHO(Out);
2898   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
2899   mangler.mangle(D);
2900 }
2901
2902 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
2903     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
2904   msvc_hashing_ostream MHO(Out);
2905   MicrosoftCXXNameMangler Mangler(*this, MHO);
2906
2907   Mangler.getStream() << "\01?$RT" << ManglingNumber << '@';
2908   Mangler.mangle(VD, "");
2909 }
2910
2911 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2912     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2913   msvc_hashing_ostream MHO(Out);
2914   MicrosoftCXXNameMangler Mangler(*this, MHO);
2915
2916   Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2917   Mangler.mangleNestedName(VD);
2918   Mangler.getStream() << "@4HA";
2919 }
2920
2921 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2922                                                            raw_ostream &Out) {
2923   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2924   //              ::= ?__J <postfix> @5 <scope-depth>
2925   //              ::= ?$S <guard-num> @ <postfix> @4IA
2926
2927   // The first mangling is what MSVC uses to guard static locals in inline
2928   // functions.  It uses a different mangling in external functions to support
2929   // guarding more than 32 variables.  MSVC rejects inline functions with more
2930   // than 32 static locals.  We don't fully implement the second mangling
2931   // because those guards are not externally visible, and instead use LLVM's
2932   // default renaming when creating a new guard variable.
2933   msvc_hashing_ostream MHO(Out);
2934   MicrosoftCXXNameMangler Mangler(*this, MHO);
2935
2936   bool Visible = VD->isExternallyVisible();
2937   if (Visible) {
2938     Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2939   } else {
2940     Mangler.getStream() << "\01?$S1@";
2941   }
2942   unsigned ScopeDepth = 0;
2943   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2944     // If we do not have a discriminator and are emitting a guard variable for
2945     // use at global scope, then mangling the nested name will not be enough to
2946     // remove ambiguities.
2947     Mangler.mangle(VD, "");
2948   else
2949     Mangler.mangleNestedName(VD);
2950   Mangler.getStream() << (Visible ? "@5" : "@4IA");
2951   if (ScopeDepth)
2952     Mangler.mangleNumber(ScopeDepth);
2953 }
2954
2955 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2956                                                     char CharCode,
2957                                                     raw_ostream &Out) {
2958   msvc_hashing_ostream MHO(Out);
2959   MicrosoftCXXNameMangler Mangler(*this, MHO);
2960   Mangler.getStream() << "\01??__" << CharCode;
2961   Mangler.mangleName(D);
2962   if (D->isStaticDataMember()) {
2963     Mangler.mangleVariableEncoding(D);
2964     Mangler.getStream() << '@';
2965   }
2966   // This is the function class mangling.  These stubs are global, non-variadic,
2967   // cdecl functions that return void and take no args.
2968   Mangler.getStream() << "YAXXZ";
2969 }
2970
2971 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2972                                                           raw_ostream &Out) {
2973   // <initializer-name> ::= ?__E <name> YAXXZ
2974   mangleInitFiniStub(D, 'E', Out);
2975 }
2976
2977 void
2978 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2979                                                           raw_ostream &Out) {
2980   // <destructor-name> ::= ?__F <name> YAXXZ
2981   mangleInitFiniStub(D, 'F', Out);
2982 }
2983
2984 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2985                                                      raw_ostream &Out) {
2986   // <char-type> ::= 0   # char
2987   //             ::= 1   # wchar_t
2988   //             ::= ??? # char16_t/char32_t will need a mangling too...
2989   //
2990   // <literal-length> ::= <non-negative integer>  # the length of the literal
2991   //
2992   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2993   //                                              # null-terminator
2994   //
2995   // <encoded-string> ::= <simple character>           # uninteresting character
2996   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2997   //                                                   # encode the byte for the
2998   //                                                   # character
2999   //                  ::= '?' [a-z]                    # \xe1 - \xfa
3000   //                  ::= '?' [A-Z]                    # \xc1 - \xda
3001   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3002   //
3003   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3004   //               <encoded-string> '@'
3005   MicrosoftCXXNameMangler Mangler(*this, Out);
3006   Mangler.getStream() << "\01??_C@_";
3007
3008   // <char-type>: The "kind" of string literal is encoded into the mangled name.
3009   if (SL->isWide())
3010     Mangler.getStream() << '1';
3011   else
3012     Mangler.getStream() << '0';
3013
3014   // <literal-length>: The next part of the mangled name consists of the length
3015   // of the string.
3016   // The StringLiteral does not consider the NUL terminator byte(s) but the
3017   // mangling does.
3018   // N.B. The length is in terms of bytes, not characters.
3019   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
3020
3021   auto GetLittleEndianByte = [&SL](unsigned Index) {
3022     unsigned CharByteWidth = SL->getCharByteWidth();
3023     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3024     unsigned OffsetInCodeUnit = Index % CharByteWidth;
3025     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3026   };
3027
3028   auto GetBigEndianByte = [&SL](unsigned Index) {
3029     unsigned CharByteWidth = SL->getCharByteWidth();
3030     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3031     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3032     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3033   };
3034
3035   // CRC all the bytes of the StringLiteral.
3036   llvm::JamCRC JC;
3037   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
3038     JC.update(GetLittleEndianByte(I));
3039
3040   // The NUL terminator byte(s) were not present earlier,
3041   // we need to manually process those bytes into the CRC.
3042   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
3043        ++NullTerminator)
3044     JC.update('\x00');
3045
3046   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3047   // scheme.
3048   Mangler.mangleNumber(JC.getCRC());
3049
3050   // <encoded-string>: The mangled name also contains the first 32 _characters_
3051   // (including null-terminator bytes) of the StringLiteral.
3052   // Each character is encoded by splitting them into bytes and then encoding
3053   // the constituent bytes.
3054   auto MangleByte = [&Mangler](char Byte) {
3055     // There are five different manglings for characters:
3056     // - [a-zA-Z0-9_$]: A one-to-one mapping.
3057     // - ?[a-z]: The range from \xe1 to \xfa.
3058     // - ?[A-Z]: The range from \xc1 to \xda.
3059     // - ?[0-9]: The set of [,/\:. \n\t'-].
3060     // - ?$XX: A fallback which maps nibbles.
3061     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3062       Mangler.getStream() << Byte;
3063     } else if (isLetter(Byte & 0x7f)) {
3064       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3065     } else {
3066       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3067                                    ' ', '\n', '\t', '\'', '-'};
3068       const char *Pos =
3069           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
3070       if (Pos != std::end(SpecialChars)) {
3071         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3072       } else {
3073         Mangler.getStream() << "?$";
3074         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3075         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3076       }
3077     }
3078   };
3079
3080   // Enforce our 32 character max.
3081   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
3082   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
3083        ++I)
3084     if (SL->isWide())
3085       MangleByte(GetBigEndianByte(I));
3086     else
3087       MangleByte(GetLittleEndianByte(I));
3088
3089   // Encode the NUL terminator if there is room.
3090   if (NumCharsToMangle < 32)
3091     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
3092          ++NullTerminator)
3093       MangleByte(0);
3094
3095   Mangler.getStream() << '@';
3096 }
3097
3098 MicrosoftMangleContext *
3099 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3100   return new MicrosoftMangleContextImpl(Context, Diags);
3101 }