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