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   ASTContext &getASTContext() const { return Context.getASTContext(); }
228 
229   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
230   // this check into mangleQualifiers().
231   const bool PointersAre64Bit;
232 
233 public:
234   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
235 
236   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
237       : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
238         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
239                          64) {}
240 
241   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
242                           const CXXConstructorDecl *D, CXXCtorType Type)
243       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
244         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
245                          64) {}
246 
247   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
248                           const CXXDestructorDecl *D, CXXDtorType Type)
249       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
250         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
251                          64) {}
252 
253   raw_ostream &getStream() const { return Out; }
254 
255   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
256   void mangleName(const NamedDecl *ND);
257   void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
258   void mangleVariableEncoding(const VarDecl *VD);
259   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
260   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
261                                    const CXXMethodDecl *MD);
262   void mangleVirtualMemPtrThunk(
263       const CXXMethodDecl *MD,
264       const MicrosoftVTableContext::MethodVFTableLocation &ML);
265   void mangleNumber(int64_t Number);
266   void mangleType(QualType T, SourceRange Range,
267                   QualifierMangleMode QMM = QMM_Mangle);
268   void mangleFunctionType(const FunctionType *T,
269                           const FunctionDecl *D = nullptr,
270                           bool ForceThisQuals = false);
271   void mangleNestedName(const NamedDecl *ND);
272 
273 private:
274   void mangleUnqualifiedName(const NamedDecl *ND) {
275     mangleUnqualifiedName(ND, ND->getDeclName());
276   }
277   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
278   void mangleSourceName(StringRef Name);
279   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
280   void mangleCXXDtorType(CXXDtorType T);
281   void mangleQualifiers(Qualifiers Quals, bool IsMember);
282   void mangleRefQualifier(RefQualifierKind RefQualifier);
283   void manglePointerCVQualifiers(Qualifiers Quals);
284   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
285 
286   void mangleUnscopedTemplateName(const TemplateDecl *ND);
287   void
288   mangleTemplateInstantiationName(const TemplateDecl *TD,
289                                   const TemplateArgumentList &TemplateArgs);
290   void mangleObjCMethodName(const ObjCMethodDecl *MD);
291 
292   void mangleArgumentType(QualType T, SourceRange Range);
293 
294   // Declare manglers for every type class.
295 #define ABSTRACT_TYPE(CLASS, PARENT)
296 #define NON_CANONICAL_TYPE(CLASS, PARENT)
297 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
298                                             Qualifiers Quals, \
299                                             SourceRange Range);
300 #include "clang/AST/TypeNodes.def"
301 #undef ABSTRACT_TYPE
302 #undef NON_CANONICAL_TYPE
303 #undef TYPE
304 
305   void mangleType(const TagDecl *TD);
306   void mangleDecayedArrayType(const ArrayType *T);
307   void mangleArrayType(const ArrayType *T);
308   void mangleFunctionClass(const FunctionDecl *FD);
309   void mangleCallingConvention(CallingConv CC);
310   void mangleCallingConvention(const FunctionType *T);
311   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
312   void mangleExpression(const Expr *E);
313   void mangleThrowSpecification(const FunctionProtoType *T);
314 
315   void mangleTemplateArgs(const TemplateDecl *TD,
316                           const TemplateArgumentList &TemplateArgs);
317   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
318                          const NamedDecl *Parm);
319 };
320 }
321 
322 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
323   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
324     LanguageLinkage L = FD->getLanguageLinkage();
325     // Overloadable functions need mangling.
326     if (FD->hasAttr<OverloadableAttr>())
327       return true;
328 
329     // The ABI expects that we would never mangle "typical" user-defined entry
330     // points regardless of visibility or freestanding-ness.
331     //
332     // N.B. This is distinct from asking about "main".  "main" has a lot of
333     // special rules associated with it in the standard while these
334     // user-defined entry points are outside of the purview of the standard.
335     // For example, there can be only one definition for "main" in a standards
336     // compliant program; however nothing forbids the existence of wmain and
337     // WinMain in the same translation unit.
338     if (FD->isMSVCRTEntryPoint())
339       return false;
340 
341     // C++ functions and those whose names are not a simple identifier need
342     // mangling.
343     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
344       return true;
345 
346     // C functions are not mangled.
347     if (L == CLanguageLinkage)
348       return false;
349   }
350 
351   // Otherwise, no mangling is done outside C++ mode.
352   if (!getASTContext().getLangOpts().CPlusPlus)
353     return false;
354 
355   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
356     // C variables are not mangled.
357     if (VD->isExternC())
358       return false;
359 
360     // Variables at global scope with non-internal linkage are not mangled.
361     const DeclContext *DC = getEffectiveDeclContext(D);
362     // Check for extern variable declared locally.
363     if (DC->isFunctionOrMethod() && D->hasLinkage())
364       while (!DC->isNamespace() && !DC->isTranslationUnit())
365         DC = getEffectiveParentContext(DC);
366 
367     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
368         !isa<VarTemplateSpecializationDecl>(D) &&
369         D->getIdentifier() != nullptr)
370       return false;
371   }
372 
373   return true;
374 }
375 
376 bool
377 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
378   return true;
379 }
380 
381 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
382   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
383   // Therefore it's really important that we don't decorate the
384   // name with leading underscores or leading/trailing at signs. So, by
385   // default, we emit an asm marker at the start so we get the name right.
386   // Callers can override this with a custom prefix.
387 
388   // <mangled-name> ::= ? <name> <type-encoding>
389   Out << Prefix;
390   mangleName(D);
391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
392     mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
393   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
394     mangleVariableEncoding(VD);
395   else {
396     // TODO: Fields? Can MSVC even mangle them?
397     // Issue a diagnostic for now.
398     DiagnosticsEngine &Diags = Context.getDiags();
399     unsigned DiagID = Diags.getCustomDiagID(
400         DiagnosticsEngine::Error, "cannot mangle this declaration yet");
401     Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
402   }
403 }
404 
405 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
406                                                      bool ShouldMangle) {
407   // <type-encoding> ::= <function-class> <function-type>
408 
409   // Since MSVC operates on the type as written and not the canonical type, it
410   // actually matters which decl we have here.  MSVC appears to choose the
411   // first, since it is most likely to be the declaration in a header file.
412   FD = FD->getFirstDecl();
413 
414   // We should never ever see a FunctionNoProtoType at this point.
415   // We don't even know how to mangle their types anyway :).
416   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
417 
418   // extern "C" functions can hold entities that must be mangled.
419   // As it stands, these functions still need to get expressed in the full
420   // external name.  They have their class and type omitted, replaced with '9'.
421   if (ShouldMangle) {
422     // We would like to mangle all extern "C" functions using this additional
423     // component but this would break compatibility with MSVC's behavior.
424     // Instead, do this when we know that compatibility isn't important (in
425     // other words, when it is an overloaded extern "C" funciton).
426     if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
427       Out << "$$J0";
428 
429     mangleFunctionClass(FD);
430 
431     mangleFunctionType(FT, FD);
432   } else {
433     Out << '9';
434   }
435 }
436 
437 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
438   // <type-encoding> ::= <storage-class> <variable-type>
439   // <storage-class> ::= 0  # private static member
440   //                 ::= 1  # protected static member
441   //                 ::= 2  # public static member
442   //                 ::= 3  # global
443   //                 ::= 4  # static local
444 
445   // The first character in the encoding (after the name) is the storage class.
446   if (VD->isStaticDataMember()) {
447     // If it's a static member, it also encodes the access level.
448     switch (VD->getAccess()) {
449       default:
450       case AS_private: Out << '0'; break;
451       case AS_protected: Out << '1'; break;
452       case AS_public: Out << '2'; break;
453     }
454   }
455   else if (!VD->isStaticLocal())
456     Out << '3';
457   else
458     Out << '4';
459   // Now mangle the type.
460   // <variable-type> ::= <type> <cvr-qualifiers>
461   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
462   // Pointers and references are odd. The type of 'int * const foo;' gets
463   // mangled as 'QAHA' instead of 'PAHB', for example.
464   SourceRange SR = VD->getSourceRange();
465   QualType Ty = VD->getType();
466   if (Ty->isPointerType() || Ty->isReferenceType() ||
467       Ty->isMemberPointerType()) {
468     mangleType(Ty, SR, QMM_Drop);
469     manglePointerExtQualifiers(
470         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
471     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
472       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
473       // Member pointers are suffixed with a back reference to the member
474       // pointer's class name.
475       mangleName(MPT->getClass()->getAsCXXRecordDecl());
476     } else
477       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
478   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
479     // Global arrays are funny, too.
480     mangleDecayedArrayType(AT);
481     if (AT->getElementType()->isArrayType())
482       Out << 'A';
483     else
484       mangleQualifiers(Ty.getQualifiers(), false);
485   } else {
486     mangleType(Ty, SR, QMM_Drop);
487     mangleQualifiers(Ty.getQualifiers(), false);
488   }
489 }
490 
491 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
492                                                       const ValueDecl *VD) {
493   // <member-data-pointer> ::= <integer-literal>
494   //                       ::= $F <number> <number>
495   //                       ::= $G <number> <number> <number>
496 
497   int64_t FieldOffset;
498   int64_t VBTableOffset;
499   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
500   if (VD) {
501     FieldOffset = getASTContext().getFieldOffset(VD);
502     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
503            "cannot take address of bitfield");
504     FieldOffset /= getASTContext().getCharWidth();
505 
506     VBTableOffset = 0;
507 
508     if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
509       FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
510   } else {
511     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
512 
513     VBTableOffset = -1;
514   }
515 
516   char Code = '\0';
517   switch (IM) {
518   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
519   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
520   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
521   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
522   }
523 
524   Out << '$' << Code;
525 
526   mangleNumber(FieldOffset);
527 
528   // The C++ standard doesn't allow base-to-derived member pointer conversions
529   // in template parameter contexts, so the vbptr offset of data member pointers
530   // is always zero.
531   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
532     mangleNumber(0);
533   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
534     mangleNumber(VBTableOffset);
535 }
536 
537 void
538 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
539                                                      const CXXMethodDecl *MD) {
540   // <member-function-pointer> ::= $1? <name>
541   //                           ::= $H? <name> <number>
542   //                           ::= $I? <name> <number> <number>
543   //                           ::= $J? <name> <number> <number> <number>
544 
545   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
546 
547   char Code = '\0';
548   switch (IM) {
549   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
550   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
551   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
552   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
553   }
554 
555   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
556   // thunk.
557   uint64_t NVOffset = 0;
558   uint64_t VBTableOffset = 0;
559   uint64_t VBPtrOffset = 0;
560   if (MD) {
561     Out << '$' << Code << '?';
562     if (MD->isVirtual()) {
563       MicrosoftVTableContext *VTContext =
564           cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
565       const MicrosoftVTableContext::MethodVFTableLocation &ML =
566           VTContext->getMethodVFTableLocation(GlobalDecl(MD));
567       mangleVirtualMemPtrThunk(MD, ML);
568       NVOffset = ML.VFPtrOffset.getQuantity();
569       VBTableOffset = ML.VBTableIndex * 4;
570       if (ML.VBase) {
571         const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
572         VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
573       }
574     } else {
575       mangleName(MD);
576       mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
577     }
578 
579     if (VBTableOffset == 0 &&
580         IM == MSInheritanceAttr::Keyword_virtual_inheritance)
581       NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
582   } else {
583     // Null single inheritance member functions are encoded as a simple nullptr.
584     if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
585       Out << "$0A@";
586       return;
587     }
588     if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
589       VBTableOffset = -1;
590     Out << '$' << Code;
591   }
592 
593   if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
594     mangleNumber(static_cast<uint32_t>(NVOffset));
595   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
596     mangleNumber(VBPtrOffset);
597   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
598     mangleNumber(VBTableOffset);
599 }
600 
601 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
602     const CXXMethodDecl *MD,
603     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
604   // Get the vftable offset.
605   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
606       getASTContext().getTargetInfo().getPointerWidth(0));
607   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
608 
609   Out << "?_9";
610   mangleName(MD->getParent());
611   Out << "$B";
612   mangleNumber(OffsetInVFTable);
613   Out << 'A';
614   mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
615 }
616 
617 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
618   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
619 
620   // Always start with the unqualified name.
621   mangleUnqualifiedName(ND);
622 
623   mangleNestedName(ND);
624 
625   // Terminate the whole name with an '@'.
626   Out << '@';
627 }
628 
629 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
630   // <non-negative integer> ::= A@              # when Number == 0
631   //                        ::= <decimal digit> # when 1 <= Number <= 10
632   //                        ::= <hex digit>+ @  # when Number >= 10
633   //
634   // <number>               ::= [?] <non-negative integer>
635 
636   uint64_t Value = static_cast<uint64_t>(Number);
637   if (Number < 0) {
638     Value = -Value;
639     Out << '?';
640   }
641 
642   if (Value == 0)
643     Out << "A@";
644   else if (Value >= 1 && Value <= 10)
645     Out << (Value - 1);
646   else {
647     // Numbers that are not encoded as decimal digits are represented as nibbles
648     // in the range of ASCII characters 'A' to 'P'.
649     // The number 0x123450 would be encoded as 'BCDEFA'
650     char EncodedNumberBuffer[sizeof(uint64_t) * 2];
651     MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
652     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
653     for (; Value != 0; Value >>= 4)
654       *I++ = 'A' + (Value & 0xf);
655     Out.write(I.base(), I - BufferRef.rbegin());
656     Out << '@';
657   }
658 }
659 
660 static const TemplateDecl *
661 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
662   // Check if we have a function template.
663   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
664     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
665       TemplateArgs = FD->getTemplateSpecializationArgs();
666       return TD;
667     }
668   }
669 
670   // Check if we have a class template.
671   if (const ClassTemplateSpecializationDecl *Spec =
672           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
673     TemplateArgs = &Spec->getTemplateArgs();
674     return Spec->getSpecializedTemplate();
675   }
676 
677   // Check if we have a variable template.
678   if (const VarTemplateSpecializationDecl *Spec =
679           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
680     TemplateArgs = &Spec->getTemplateArgs();
681     return Spec->getSpecializedTemplate();
682   }
683 
684   return nullptr;
685 }
686 
687 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
688                                                     DeclarationName Name) {
689   //  <unqualified-name> ::= <operator-name>
690   //                     ::= <ctor-dtor-name>
691   //                     ::= <source-name>
692   //                     ::= <template-name>
693 
694   // Check if we have a template.
695   const TemplateArgumentList *TemplateArgs = nullptr;
696   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
697     // Function templates aren't considered for name back referencing.  This
698     // makes sense since function templates aren't likely to occur multiple
699     // times in a symbol.
700     // FIXME: Test alias template mangling with MSVC 2013.
701     if (!isa<ClassTemplateDecl>(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   NameBackReferences.swap(OuterTemplateContext);
1091   TypeBackReferences.swap(OuterArgsContext);
1092 
1093   mangleUnscopedTemplateName(TD);
1094   mangleTemplateArgs(TD, TemplateArgs);
1095 
1096   // Restore the previous back reference contexts.
1097   NameBackReferences.swap(OuterTemplateContext);
1098   TypeBackReferences.swap(OuterArgsContext);
1099 }
1100 
1101 void
1102 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1103   // <unscoped-template-name> ::= ?$ <unqualified-name>
1104   Out << "?$";
1105   mangleUnqualifiedName(TD);
1106 }
1107 
1108 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1109                                                    bool IsBoolean) {
1110   // <integer-literal> ::= $0 <number>
1111   Out << "$0";
1112   // Make sure booleans are encoded as 0/1.
1113   if (IsBoolean && Value.getBoolValue())
1114     mangleNumber(1);
1115   else if (Value.isSigned())
1116     mangleNumber(Value.getSExtValue());
1117   else
1118     mangleNumber(Value.getZExtValue());
1119 }
1120 
1121 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1122   // See if this is a constant expression.
1123   llvm::APSInt Value;
1124   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1125     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1126     return;
1127   }
1128 
1129   // Look through no-op casts like template parameter substitutions.
1130   E = E->IgnoreParenNoopCasts(Context.getASTContext());
1131 
1132   const CXXUuidofExpr *UE = nullptr;
1133   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1134     if (UO->getOpcode() == UO_AddrOf)
1135       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1136   } else
1137     UE = dyn_cast<CXXUuidofExpr>(E);
1138 
1139   if (UE) {
1140     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1141     // const __s_GUID _GUID_{lower case UUID with underscores}
1142     StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1143     std::string Name = "_GUID_" + Uuid.lower();
1144     std::replace(Name.begin(), Name.end(), '-', '_');
1145 
1146     // If we had to peek through an address-of operator, treat this like we are
1147     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1148     //
1149     // N.B. This matches up with the handling of TemplateArgument::Declaration
1150     // in mangleTemplateArg
1151     if (UE == E)
1152       Out << "$E?";
1153     else
1154       Out << "$1?";
1155     Out << Name << "@@3U__s_GUID@@B";
1156     return;
1157   }
1158 
1159   // As bad as this diagnostic is, it's better than crashing.
1160   DiagnosticsEngine &Diags = Context.getDiags();
1161   unsigned DiagID = Diags.getCustomDiagID(
1162       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1163   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1164                                         << E->getSourceRange();
1165 }
1166 
1167 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1168     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1169   // <template-args> ::= <template-arg>+
1170   const TemplateParameterList *TPL = TD->getTemplateParameters();
1171   assert(TPL->size() == TemplateArgs.size() &&
1172          "size mismatch between args and parms!");
1173 
1174   unsigned Idx = 0;
1175   for (const TemplateArgument &TA : TemplateArgs.asArray())
1176     mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1177 }
1178 
1179 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1180                                                 const TemplateArgument &TA,
1181                                                 const NamedDecl *Parm) {
1182   // <template-arg> ::= <type>
1183   //                ::= <integer-literal>
1184   //                ::= <member-data-pointer>
1185   //                ::= <member-function-pointer>
1186   //                ::= $E? <name> <type-encoding>
1187   //                ::= $1? <name> <type-encoding>
1188   //                ::= $0A@
1189   //                ::= <template-args>
1190 
1191   switch (TA.getKind()) {
1192   case TemplateArgument::Null:
1193     llvm_unreachable("Can't mangle null template arguments!");
1194   case TemplateArgument::TemplateExpansion:
1195     llvm_unreachable("Can't mangle template expansion arguments!");
1196   case TemplateArgument::Type: {
1197     QualType T = TA.getAsType();
1198     mangleType(T, SourceRange(), QMM_Escape);
1199     break;
1200   }
1201   case TemplateArgument::Declaration: {
1202     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1203     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1204       mangleMemberDataPointer(
1205           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1206           cast<ValueDecl>(ND));
1207     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1208       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1209       if (MD && MD->isInstance()) {
1210         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1211       } else {
1212         Out << "$1?";
1213         mangleName(FD);
1214         mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1215       }
1216     } else {
1217       mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1218     }
1219     break;
1220   }
1221   case TemplateArgument::Integral:
1222     mangleIntegerLiteral(TA.getAsIntegral(),
1223                          TA.getIntegralType()->isBooleanType());
1224     break;
1225   case TemplateArgument::NullPtr: {
1226     QualType T = TA.getNullPtrType();
1227     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1228       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1229       if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
1230         mangleMemberFunctionPointer(RD, nullptr);
1231         return;
1232       }
1233       if (MPT->isMemberDataPointer()) {
1234         if (isa<ClassTemplateDecl>(TD)) {
1235           mangleMemberDataPointer(RD, nullptr);
1236           return;
1237         }
1238         // nullptr data pointers are always represented with a single field
1239         // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1240         // distinguish the case where the data member is at offset zero in the
1241         // record.
1242         // However, we are free to use 0 *if* we would use multiple fields for
1243         // non-nullptr member pointers.
1244         if (!RD->nullFieldOffsetIsZero()) {
1245           mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1246           return;
1247         }
1248       }
1249     }
1250     mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1251     break;
1252   }
1253   case TemplateArgument::Expression:
1254     mangleExpression(TA.getAsExpr());
1255     break;
1256   case TemplateArgument::Pack: {
1257     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1258     if (TemplateArgs.empty()) {
1259       if (isa<TemplateTypeParmDecl>(Parm) ||
1260           isa<TemplateTemplateParmDecl>(Parm))
1261         // MSVC 2015 changed the mangling for empty expanded template packs,
1262         // use the old mangling for link compatibility for old versions.
1263         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1264                     LangOptions::MSVC2015)
1265                     ? "$$V"
1266                     : "$$$V");
1267       else if (isa<NonTypeTemplateParmDecl>(Parm))
1268         Out << "$S";
1269       else
1270         llvm_unreachable("unexpected template parameter decl!");
1271     } else {
1272       for (const TemplateArgument &PA : TemplateArgs)
1273         mangleTemplateArg(TD, PA, Parm);
1274     }
1275     break;
1276   }
1277   case TemplateArgument::Template: {
1278     const NamedDecl *ND =
1279         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1280     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1281       mangleType(TD);
1282     } else if (isa<TypeAliasDecl>(ND)) {
1283       Out << "$$Y";
1284       mangleName(ND);
1285     } else {
1286       llvm_unreachable("unexpected template template NamedDecl!");
1287     }
1288     break;
1289   }
1290   }
1291 }
1292 
1293 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1294                                                bool IsMember) {
1295   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1296   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1297   // 'I' means __restrict (32/64-bit).
1298   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1299   // keyword!
1300   // <base-cvr-qualifiers> ::= A  # near
1301   //                       ::= B  # near const
1302   //                       ::= C  # near volatile
1303   //                       ::= D  # near const volatile
1304   //                       ::= E  # far (16-bit)
1305   //                       ::= F  # far const (16-bit)
1306   //                       ::= G  # far volatile (16-bit)
1307   //                       ::= H  # far const volatile (16-bit)
1308   //                       ::= I  # huge (16-bit)
1309   //                       ::= J  # huge const (16-bit)
1310   //                       ::= K  # huge volatile (16-bit)
1311   //                       ::= L  # huge const volatile (16-bit)
1312   //                       ::= M <basis> # based
1313   //                       ::= N <basis> # based const
1314   //                       ::= O <basis> # based volatile
1315   //                       ::= P <basis> # based const volatile
1316   //                       ::= Q  # near member
1317   //                       ::= R  # near const member
1318   //                       ::= S  # near volatile member
1319   //                       ::= T  # near const volatile member
1320   //                       ::= U  # far member (16-bit)
1321   //                       ::= V  # far const member (16-bit)
1322   //                       ::= W  # far volatile member (16-bit)
1323   //                       ::= X  # far const volatile member (16-bit)
1324   //                       ::= Y  # huge member (16-bit)
1325   //                       ::= Z  # huge const member (16-bit)
1326   //                       ::= 0  # huge volatile member (16-bit)
1327   //                       ::= 1  # huge const volatile member (16-bit)
1328   //                       ::= 2 <basis> # based member
1329   //                       ::= 3 <basis> # based const member
1330   //                       ::= 4 <basis> # based volatile member
1331   //                       ::= 5 <basis> # based const volatile member
1332   //                       ::= 6  # near function (pointers only)
1333   //                       ::= 7  # far function (pointers only)
1334   //                       ::= 8  # near method (pointers only)
1335   //                       ::= 9  # far method (pointers only)
1336   //                       ::= _A <basis> # based function (pointers only)
1337   //                       ::= _B <basis> # based function (far?) (pointers only)
1338   //                       ::= _C <basis> # based method (pointers only)
1339   //                       ::= _D <basis> # based method (far?) (pointers only)
1340   //                       ::= _E # block (Clang)
1341   // <basis> ::= 0 # __based(void)
1342   //         ::= 1 # __based(segment)?
1343   //         ::= 2 <name> # __based(name)
1344   //         ::= 3 # ?
1345   //         ::= 4 # ?
1346   //         ::= 5 # not really based
1347   bool HasConst = Quals.hasConst(),
1348        HasVolatile = Quals.hasVolatile();
1349 
1350   if (!IsMember) {
1351     if (HasConst && HasVolatile) {
1352       Out << 'D';
1353     } else if (HasVolatile) {
1354       Out << 'C';
1355     } else if (HasConst) {
1356       Out << 'B';
1357     } else {
1358       Out << 'A';
1359     }
1360   } else {
1361     if (HasConst && HasVolatile) {
1362       Out << 'T';
1363     } else if (HasVolatile) {
1364       Out << 'S';
1365     } else if (HasConst) {
1366       Out << 'R';
1367     } else {
1368       Out << 'Q';
1369     }
1370   }
1371 
1372   // FIXME: For now, just drop all extension qualifiers on the floor.
1373 }
1374 
1375 void
1376 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1377   // <ref-qualifier> ::= G                # lvalue reference
1378   //                 ::= H                # rvalue-reference
1379   switch (RefQualifier) {
1380   case RQ_None:
1381     break;
1382 
1383   case RQ_LValue:
1384     Out << 'G';
1385     break;
1386 
1387   case RQ_RValue:
1388     Out << 'H';
1389     break;
1390   }
1391 }
1392 
1393 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1394                                                          QualType PointeeType) {
1395   bool HasRestrict = Quals.hasRestrict();
1396   if (PointersAre64Bit &&
1397       (PointeeType.isNull() || !PointeeType->isFunctionType()))
1398     Out << 'E';
1399 
1400   if (HasRestrict)
1401     Out << 'I';
1402 }
1403 
1404 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1405   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1406   //                         ::= Q  # const
1407   //                         ::= R  # volatile
1408   //                         ::= S  # const volatile
1409   bool HasConst = Quals.hasConst(),
1410        HasVolatile = Quals.hasVolatile();
1411 
1412   if (HasConst && HasVolatile) {
1413     Out << 'S';
1414   } else if (HasVolatile) {
1415     Out << 'R';
1416   } else if (HasConst) {
1417     Out << 'Q';
1418   } else {
1419     Out << 'P';
1420   }
1421 }
1422 
1423 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1424                                                  SourceRange Range) {
1425   // MSVC will backreference two canonically equivalent types that have slightly
1426   // different manglings when mangled alone.
1427 
1428   // Decayed types do not match up with non-decayed versions of the same type.
1429   //
1430   // e.g.
1431   // void (*x)(void) will not form a backreference with void x(void)
1432   void *TypePtr;
1433   if (const auto *DT = T->getAs<DecayedType>()) {
1434     QualType OriginalType = DT->getOriginalType();
1435     // All decayed ArrayTypes should be treated identically; as-if they were
1436     // a decayed IncompleteArrayType.
1437     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1438       OriginalType = getASTContext().getIncompleteArrayType(
1439           AT->getElementType(), AT->getSizeModifier(),
1440           AT->getIndexTypeCVRQualifiers());
1441 
1442     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1443     // If the original parameter was textually written as an array,
1444     // instead treat the decayed parameter like it's const.
1445     //
1446     // e.g.
1447     // int [] -> int * const
1448     if (OriginalType->isArrayType())
1449       T = T.withConst();
1450   } else {
1451     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1452   }
1453 
1454   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1455 
1456   if (Found == TypeBackReferences.end()) {
1457     size_t OutSizeBefore = Out.tell();
1458 
1459     mangleType(T, Range, QMM_Drop);
1460 
1461     // See if it's worth creating a back reference.
1462     // Only types longer than 1 character are considered
1463     // and only 10 back references slots are available:
1464     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1465     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1466       size_t Size = TypeBackReferences.size();
1467       TypeBackReferences[TypePtr] = Size;
1468     }
1469   } else {
1470     Out << Found->second;
1471   }
1472 }
1473 
1474 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1475                                          QualifierMangleMode QMM) {
1476   // Don't use the canonical types.  MSVC includes things like 'const' on
1477   // pointer arguments to function pointers that canonicalization strips away.
1478   T = T.getDesugaredType(getASTContext());
1479   Qualifiers Quals = T.getLocalQualifiers();
1480   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1481     // If there were any Quals, getAsArrayType() pushed them onto the array
1482     // element type.
1483     if (QMM == QMM_Mangle)
1484       Out << 'A';
1485     else if (QMM == QMM_Escape || QMM == QMM_Result)
1486       Out << "$$B";
1487     mangleArrayType(AT);
1488     return;
1489   }
1490 
1491   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1492                    T->isReferenceType() || T->isBlockPointerType();
1493 
1494   switch (QMM) {
1495   case QMM_Drop:
1496     break;
1497   case QMM_Mangle:
1498     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1499       Out << '6';
1500       mangleFunctionType(FT);
1501       return;
1502     }
1503     mangleQualifiers(Quals, false);
1504     break;
1505   case QMM_Escape:
1506     if (!IsPointer && Quals) {
1507       Out << "$$C";
1508       mangleQualifiers(Quals, false);
1509     }
1510     break;
1511   case QMM_Result:
1512     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1513       Out << '?';
1514       mangleQualifiers(Quals, false);
1515     }
1516     break;
1517   }
1518 
1519   const Type *ty = T.getTypePtr();
1520 
1521   switch (ty->getTypeClass()) {
1522 #define ABSTRACT_TYPE(CLASS, PARENT)
1523 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1524   case Type::CLASS: \
1525     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1526     return;
1527 #define TYPE(CLASS, PARENT) \
1528   case Type::CLASS: \
1529     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1530     break;
1531 #include "clang/AST/TypeNodes.def"
1532 #undef ABSTRACT_TYPE
1533 #undef NON_CANONICAL_TYPE
1534 #undef TYPE
1535   }
1536 }
1537 
1538 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1539                                          SourceRange Range) {
1540   //  <type>         ::= <builtin-type>
1541   //  <builtin-type> ::= X  # void
1542   //                 ::= C  # signed char
1543   //                 ::= D  # char
1544   //                 ::= E  # unsigned char
1545   //                 ::= F  # short
1546   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1547   //                 ::= H  # int
1548   //                 ::= I  # unsigned int
1549   //                 ::= J  # long
1550   //                 ::= K  # unsigned long
1551   //                     L  # <none>
1552   //                 ::= M  # float
1553   //                 ::= N  # double
1554   //                 ::= O  # long double (__float80 is mangled differently)
1555   //                 ::= _J # long long, __int64
1556   //                 ::= _K # unsigned long long, __int64
1557   //                 ::= _L # __int128
1558   //                 ::= _M # unsigned __int128
1559   //                 ::= _N # bool
1560   //                     _O # <array in parameter>
1561   //                 ::= _T # __float80 (Intel)
1562   //                 ::= _W # wchar_t
1563   //                 ::= _Z # __float80 (Digital Mars)
1564   switch (T->getKind()) {
1565   case BuiltinType::Void:
1566     Out << 'X';
1567     break;
1568   case BuiltinType::SChar:
1569     Out << 'C';
1570     break;
1571   case BuiltinType::Char_U:
1572   case BuiltinType::Char_S:
1573     Out << 'D';
1574     break;
1575   case BuiltinType::UChar:
1576     Out << 'E';
1577     break;
1578   case BuiltinType::Short:
1579     Out << 'F';
1580     break;
1581   case BuiltinType::UShort:
1582     Out << 'G';
1583     break;
1584   case BuiltinType::Int:
1585     Out << 'H';
1586     break;
1587   case BuiltinType::UInt:
1588     Out << 'I';
1589     break;
1590   case BuiltinType::Long:
1591     Out << 'J';
1592     break;
1593   case BuiltinType::ULong:
1594     Out << 'K';
1595     break;
1596   case BuiltinType::Float:
1597     Out << 'M';
1598     break;
1599   case BuiltinType::Double:
1600     Out << 'N';
1601     break;
1602   // TODO: Determine size and mangle accordingly
1603   case BuiltinType::LongDouble:
1604     Out << 'O';
1605     break;
1606   case BuiltinType::LongLong:
1607     Out << "_J";
1608     break;
1609   case BuiltinType::ULongLong:
1610     Out << "_K";
1611     break;
1612   case BuiltinType::Int128:
1613     Out << "_L";
1614     break;
1615   case BuiltinType::UInt128:
1616     Out << "_M";
1617     break;
1618   case BuiltinType::Bool:
1619     Out << "_N";
1620     break;
1621   case BuiltinType::Char16:
1622     Out << "_S";
1623     break;
1624   case BuiltinType::Char32:
1625     Out << "_U";
1626     break;
1627   case BuiltinType::WChar_S:
1628   case BuiltinType::WChar_U:
1629     Out << "_W";
1630     break;
1631 
1632 #define BUILTIN_TYPE(Id, SingletonId)
1633 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1634   case BuiltinType::Id:
1635 #include "clang/AST/BuiltinTypes.def"
1636   case BuiltinType::Dependent:
1637     llvm_unreachable("placeholder types shouldn't get to name mangling");
1638 
1639   case BuiltinType::ObjCId:
1640     Out << "PAUobjc_object@@";
1641     break;
1642   case BuiltinType::ObjCClass:
1643     Out << "PAUobjc_class@@";
1644     break;
1645   case BuiltinType::ObjCSel:
1646     Out << "PAUobjc_selector@@";
1647     break;
1648 
1649   case BuiltinType::OCLImage1d:
1650     Out << "PAUocl_image1d@@";
1651     break;
1652   case BuiltinType::OCLImage1dArray:
1653     Out << "PAUocl_image1darray@@";
1654     break;
1655   case BuiltinType::OCLImage1dBuffer:
1656     Out << "PAUocl_image1dbuffer@@";
1657     break;
1658   case BuiltinType::OCLImage2d:
1659     Out << "PAUocl_image2d@@";
1660     break;
1661   case BuiltinType::OCLImage2dArray:
1662     Out << "PAUocl_image2darray@@";
1663     break;
1664   case BuiltinType::OCLImage2dDepth:
1665     Out << "PAUocl_image2ddepth@@";
1666     break;
1667   case BuiltinType::OCLImage2dArrayDepth:
1668     Out << "PAUocl_image2darraydepth@@";
1669     break;
1670   case BuiltinType::OCLImage2dMSAA:
1671     Out << "PAUocl_image2dmsaa@@";
1672     break;
1673   case BuiltinType::OCLImage2dArrayMSAA:
1674     Out << "PAUocl_image2darraymsaa@@";
1675     break;
1676   case BuiltinType::OCLImage2dMSAADepth:
1677     Out << "PAUocl_image2dmsaadepth@@";
1678     break;
1679   case BuiltinType::OCLImage2dArrayMSAADepth:
1680     Out << "PAUocl_image2darraymsaadepth@@";
1681     break;
1682   case BuiltinType::OCLImage3d:
1683     Out << "PAUocl_image3d@@";
1684     break;
1685   case BuiltinType::OCLSampler:
1686     Out << "PAUocl_sampler@@";
1687     break;
1688   case BuiltinType::OCLEvent:
1689     Out << "PAUocl_event@@";
1690     break;
1691   case BuiltinType::OCLClkEvent:
1692     Out << "PAUocl_clkevent@@";
1693     break;
1694   case BuiltinType::OCLQueue:
1695     Out << "PAUocl_queue@@";
1696     break;
1697   case BuiltinType::OCLNDRange:
1698     Out << "PAUocl_ndrange@@";
1699     break;
1700   case BuiltinType::OCLReserveID:
1701     Out << "PAUocl_reserveid@@";
1702     break;
1703 
1704   case BuiltinType::NullPtr:
1705     Out << "$$T";
1706     break;
1707 
1708   case BuiltinType::Half: {
1709     DiagnosticsEngine &Diags = Context.getDiags();
1710     unsigned DiagID = Diags.getCustomDiagID(
1711         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1712     Diags.Report(Range.getBegin(), DiagID)
1713         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1714     break;
1715   }
1716   }
1717 }
1718 
1719 // <type>          ::= <function-type>
1720 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1721                                          SourceRange) {
1722   // Structors only appear in decls, so at this point we know it's not a
1723   // structor type.
1724   // FIXME: This may not be lambda-friendly.
1725   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1726     Out << "$$A8@@";
1727     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1728   } else {
1729     Out << "$$A6";
1730     mangleFunctionType(T);
1731   }
1732 }
1733 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1734                                          Qualifiers, SourceRange) {
1735   Out << "$$A6";
1736   mangleFunctionType(T);
1737 }
1738 
1739 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1740                                                  const FunctionDecl *D,
1741                                                  bool ForceThisQuals) {
1742   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1743   //                     <return-type> <argument-list> <throw-spec>
1744   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1745 
1746   SourceRange Range;
1747   if (D) Range = D->getSourceRange();
1748 
1749   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1750   CallingConv CC = T->getCallConv();
1751   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1752     if (MD->isInstance())
1753       HasThisQuals = true;
1754     if (isa<CXXDestructorDecl>(MD)) {
1755       IsStructor = true;
1756     } else if (isa<CXXConstructorDecl>(MD)) {
1757       IsStructor = true;
1758       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1759                        StructorType == Ctor_DefaultClosure) &&
1760                       getStructor(MD) == Structor;
1761       if (IsCtorClosure)
1762         CC = getASTContext().getDefaultCallingConvention(
1763             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1764     }
1765   }
1766 
1767   // If this is a C++ instance method, mangle the CVR qualifiers for the
1768   // this pointer.
1769   if (HasThisQuals) {
1770     Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1771     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1772     mangleRefQualifier(Proto->getRefQualifier());
1773     mangleQualifiers(Quals, /*IsMember=*/false);
1774   }
1775 
1776   mangleCallingConvention(CC);
1777 
1778   // <return-type> ::= <type>
1779   //               ::= @ # structors (they have no declared return type)
1780   if (IsStructor) {
1781     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1782         StructorType == Dtor_Deleting) {
1783       // The scalar deleting destructor takes an extra int argument.
1784       // However, the FunctionType generated has 0 arguments.
1785       // FIXME: This is a temporary hack.
1786       // Maybe should fix the FunctionType creation instead?
1787       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1788       return;
1789     }
1790     if (IsCtorClosure) {
1791       // Default constructor closure and copy constructor closure both return
1792       // void.
1793       Out << 'X';
1794 
1795       if (StructorType == Ctor_DefaultClosure) {
1796         // Default constructor closure always has no arguments.
1797         Out << 'X';
1798       } else if (StructorType == Ctor_CopyingClosure) {
1799         // Copy constructor closure always takes an unqualified reference.
1800         mangleArgumentType(getASTContext().getLValueReferenceType(
1801                                Proto->getParamType(0)
1802                                    ->getAs<LValueReferenceType>()
1803                                    ->getPointeeType(),
1804                                /*SpelledAsLValue=*/true),
1805                            Range);
1806         Out << '@';
1807       } else {
1808         llvm_unreachable("unexpected constructor closure!");
1809       }
1810       Out << 'Z';
1811       return;
1812     }
1813     Out << '@';
1814   } else {
1815     QualType ResultType = T->getReturnType();
1816     if (const auto *AT =
1817             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1818       Out << '?';
1819       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1820       Out << '?';
1821       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1822       Out << '@';
1823     } else {
1824       if (ResultType->isVoidType())
1825         ResultType = ResultType.getUnqualifiedType();
1826       mangleType(ResultType, Range, QMM_Result);
1827     }
1828   }
1829 
1830   // <argument-list> ::= X # void
1831   //                 ::= <type>+ @
1832   //                 ::= <type>* Z # varargs
1833   if (!Proto) {
1834     // Function types without prototypes can arise when mangling a function type
1835     // within an overloadable function in C. We mangle these as the absence of
1836     // any parameter types (not even an empty parameter list).
1837     Out << '@';
1838   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1839     Out << 'X';
1840   } else {
1841     // Happens for function pointer type arguments for example.
1842     for (const QualType &Arg : Proto->param_types())
1843       mangleArgumentType(Arg, Range);
1844     // <builtin-type>      ::= Z  # ellipsis
1845     if (Proto->isVariadic())
1846       Out << 'Z';
1847     else
1848       Out << '@';
1849   }
1850 
1851   mangleThrowSpecification(Proto);
1852 }
1853 
1854 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1855   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1856   //                                            # pointer. in 64-bit mode *all*
1857   //                                            # 'this' pointers are 64-bit.
1858   //                   ::= <global-function>
1859   // <member-function> ::= A # private: near
1860   //                   ::= B # private: far
1861   //                   ::= C # private: static near
1862   //                   ::= D # private: static far
1863   //                   ::= E # private: virtual near
1864   //                   ::= F # private: virtual far
1865   //                   ::= I # protected: near
1866   //                   ::= J # protected: far
1867   //                   ::= K # protected: static near
1868   //                   ::= L # protected: static far
1869   //                   ::= M # protected: virtual near
1870   //                   ::= N # protected: virtual far
1871   //                   ::= Q # public: near
1872   //                   ::= R # public: far
1873   //                   ::= S # public: static near
1874   //                   ::= T # public: static far
1875   //                   ::= U # public: virtual near
1876   //                   ::= V # public: virtual far
1877   // <global-function> ::= Y # global near
1878   //                   ::= Z # global far
1879   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1880     switch (MD->getAccess()) {
1881       case AS_none:
1882         llvm_unreachable("Unsupported access specifier");
1883       case AS_private:
1884         if (MD->isStatic())
1885           Out << 'C';
1886         else if (MD->isVirtual())
1887           Out << 'E';
1888         else
1889           Out << 'A';
1890         break;
1891       case AS_protected:
1892         if (MD->isStatic())
1893           Out << 'K';
1894         else if (MD->isVirtual())
1895           Out << 'M';
1896         else
1897           Out << 'I';
1898         break;
1899       case AS_public:
1900         if (MD->isStatic())
1901           Out << 'S';
1902         else if (MD->isVirtual())
1903           Out << 'U';
1904         else
1905           Out << 'Q';
1906     }
1907   } else {
1908     Out << 'Y';
1909   }
1910 }
1911 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1912   // <calling-convention> ::= A # __cdecl
1913   //                      ::= B # __export __cdecl
1914   //                      ::= C # __pascal
1915   //                      ::= D # __export __pascal
1916   //                      ::= E # __thiscall
1917   //                      ::= F # __export __thiscall
1918   //                      ::= G # __stdcall
1919   //                      ::= H # __export __stdcall
1920   //                      ::= I # __fastcall
1921   //                      ::= J # __export __fastcall
1922   //                      ::= Q # __vectorcall
1923   // The 'export' calling conventions are from a bygone era
1924   // (*cough*Win16*cough*) when functions were declared for export with
1925   // that keyword. (It didn't actually export them, it just made them so
1926   // that they could be in a DLL and somebody from another module could call
1927   // them.)
1928 
1929   switch (CC) {
1930     default:
1931       llvm_unreachable("Unsupported CC for mangling");
1932     case CC_X86_64Win64:
1933     case CC_X86_64SysV:
1934     case CC_C: Out << 'A'; break;
1935     case CC_X86Pascal: Out << 'C'; break;
1936     case CC_X86ThisCall: Out << 'E'; break;
1937     case CC_X86StdCall: Out << 'G'; break;
1938     case CC_X86FastCall: Out << 'I'; break;
1939     case CC_X86VectorCall: Out << 'Q'; break;
1940   }
1941 }
1942 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1943   mangleCallingConvention(T->getCallConv());
1944 }
1945 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1946                                                 const FunctionProtoType *FT) {
1947   // <throw-spec> ::= Z # throw(...) (default)
1948   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1949   //              ::= <type>+
1950   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1951   // all actually mangled as 'Z'. (They're ignored because their associated
1952   // functionality isn't implemented, and probably never will be.)
1953   Out << 'Z';
1954 }
1955 
1956 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1957                                          Qualifiers, SourceRange Range) {
1958   // Probably should be mangled as a template instantiation; need to see what
1959   // VC does first.
1960   DiagnosticsEngine &Diags = Context.getDiags();
1961   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1962     "cannot mangle this unresolved dependent type yet");
1963   Diags.Report(Range.getBegin(), DiagID)
1964     << Range;
1965 }
1966 
1967 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1968 // <union-type>  ::= T <name>
1969 // <struct-type> ::= U <name>
1970 // <class-type>  ::= V <name>
1971 // <enum-type>   ::= W4 <name>
1972 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
1973                                          SourceRange) {
1974   mangleType(cast<TagType>(T)->getDecl());
1975 }
1976 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
1977                                          SourceRange) {
1978   mangleType(cast<TagType>(T)->getDecl());
1979 }
1980 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1981   switch (TD->getTagKind()) {
1982     case TTK_Union:
1983       Out << 'T';
1984       break;
1985     case TTK_Struct:
1986     case TTK_Interface:
1987       Out << 'U';
1988       break;
1989     case TTK_Class:
1990       Out << 'V';
1991       break;
1992     case TTK_Enum:
1993       Out << "W4";
1994       break;
1995   }
1996   mangleName(TD);
1997 }
1998 
1999 // <type>       ::= <array-type>
2000 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2001 //                  [Y <dimension-count> <dimension>+]
2002 //                  <element-type> # as global, E is never required
2003 // It's supposed to be the other way around, but for some strange reason, it
2004 // isn't. Today this behavior is retained for the sole purpose of backwards
2005 // compatibility.
2006 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2007   // This isn't a recursive mangling, so now we have to do it all in this
2008   // one call.
2009   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2010   mangleType(T->getElementType(), SourceRange());
2011 }
2012 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2013                                          SourceRange) {
2014   llvm_unreachable("Should have been special cased");
2015 }
2016 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2017                                          SourceRange) {
2018   llvm_unreachable("Should have been special cased");
2019 }
2020 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2021                                          Qualifiers, SourceRange) {
2022   llvm_unreachable("Should have been special cased");
2023 }
2024 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2025                                          Qualifiers, SourceRange) {
2026   llvm_unreachable("Should have been special cased");
2027 }
2028 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2029   QualType ElementTy(T, 0);
2030   SmallVector<llvm::APInt, 3> Dimensions;
2031   for (;;) {
2032     if (ElementTy->isConstantArrayType()) {
2033       const ConstantArrayType *CAT =
2034           getASTContext().getAsConstantArrayType(ElementTy);
2035       Dimensions.push_back(CAT->getSize());
2036       ElementTy = CAT->getElementType();
2037     } else if (ElementTy->isIncompleteArrayType()) {
2038       const IncompleteArrayType *IAT =
2039           getASTContext().getAsIncompleteArrayType(ElementTy);
2040       Dimensions.push_back(llvm::APInt(32, 0));
2041       ElementTy = IAT->getElementType();
2042     } else if (ElementTy->isVariableArrayType()) {
2043       const VariableArrayType *VAT =
2044         getASTContext().getAsVariableArrayType(ElementTy);
2045       Dimensions.push_back(llvm::APInt(32, 0));
2046       ElementTy = VAT->getElementType();
2047     } else if (ElementTy->isDependentSizedArrayType()) {
2048       // The dependent expression has to be folded into a constant (TODO).
2049       const DependentSizedArrayType *DSAT =
2050         getASTContext().getAsDependentSizedArrayType(ElementTy);
2051       DiagnosticsEngine &Diags = Context.getDiags();
2052       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2053         "cannot mangle this dependent-length array yet");
2054       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2055         << DSAT->getBracketsRange();
2056       return;
2057     } else {
2058       break;
2059     }
2060   }
2061   Out << 'Y';
2062   // <dimension-count> ::= <number> # number of extra dimensions
2063   mangleNumber(Dimensions.size());
2064   for (const llvm::APInt &Dimension : Dimensions)
2065     mangleNumber(Dimension.getLimitedValue());
2066   mangleType(ElementTy, SourceRange(), QMM_Escape);
2067 }
2068 
2069 // <type>                   ::= <pointer-to-member-type>
2070 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2071 //                                                          <class name> <type>
2072 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2073                                          SourceRange Range) {
2074   QualType PointeeType = T->getPointeeType();
2075   manglePointerCVQualifiers(Quals);
2076   manglePointerExtQualifiers(Quals, PointeeType);
2077   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2078     Out << '8';
2079     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2080     mangleFunctionType(FPT, nullptr, true);
2081   } else {
2082     mangleQualifiers(PointeeType.getQualifiers(), true);
2083     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2084     mangleType(PointeeType, Range, QMM_Drop);
2085   }
2086 }
2087 
2088 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2089                                          Qualifiers, SourceRange Range) {
2090   DiagnosticsEngine &Diags = Context.getDiags();
2091   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2092     "cannot mangle this template type parameter type yet");
2093   Diags.Report(Range.getBegin(), DiagID)
2094     << Range;
2095 }
2096 
2097 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2098                                          Qualifiers, SourceRange Range) {
2099   DiagnosticsEngine &Diags = Context.getDiags();
2100   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2101     "cannot mangle this substituted parameter pack yet");
2102   Diags.Report(Range.getBegin(), DiagID)
2103     << Range;
2104 }
2105 
2106 // <type> ::= <pointer-type>
2107 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2108 //                       # the E is required for 64-bit non-static pointers
2109 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2110                                          SourceRange Range) {
2111   QualType PointeeType = T->getPointeeType();
2112   manglePointerCVQualifiers(Quals);
2113   manglePointerExtQualifiers(Quals, PointeeType);
2114   mangleType(PointeeType, Range);
2115 }
2116 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2117                                          Qualifiers Quals, SourceRange Range) {
2118   QualType PointeeType = T->getPointeeType();
2119   manglePointerCVQualifiers(Quals);
2120   manglePointerExtQualifiers(Quals, PointeeType);
2121   // Object pointers never have qualifiers.
2122   Out << 'A';
2123   mangleType(PointeeType, Range);
2124 }
2125 
2126 // <type> ::= <reference-type>
2127 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2128 //                 # the E is required for 64-bit non-static lvalue references
2129 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2130                                          Qualifiers Quals, SourceRange Range) {
2131   QualType PointeeType = T->getPointeeType();
2132   Out << (Quals.hasVolatile() ? 'B' : 'A');
2133   manglePointerExtQualifiers(Quals, PointeeType);
2134   mangleType(PointeeType, Range);
2135 }
2136 
2137 // <type> ::= <r-value-reference-type>
2138 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2139 //                 # the E is required for 64-bit non-static rvalue references
2140 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2141                                          Qualifiers Quals, SourceRange Range) {
2142   QualType PointeeType = T->getPointeeType();
2143   Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
2144   manglePointerExtQualifiers(Quals, PointeeType);
2145   mangleType(PointeeType, Range);
2146 }
2147 
2148 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2149                                          SourceRange Range) {
2150   DiagnosticsEngine &Diags = Context.getDiags();
2151   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2152     "cannot mangle this complex number type yet");
2153   Diags.Report(Range.getBegin(), DiagID)
2154     << Range;
2155 }
2156 
2157 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2158                                          SourceRange Range) {
2159   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2160   assert(ET && "vectors with non-builtin elements are unsupported");
2161   uint64_t Width = getASTContext().getTypeSize(T);
2162   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2163   // doesn't match the Intel types uses a custom mangling below.
2164   bool IsBuiltin = true;
2165   llvm::Triple::ArchType AT =
2166       getASTContext().getTargetInfo().getTriple().getArch();
2167   if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2168     if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2169       Out << "T__m64";
2170     } else if (Width >= 128) {
2171       if (ET->getKind() == BuiltinType::Float)
2172         Out << "T__m" << Width;
2173       else if (ET->getKind() == BuiltinType::LongLong)
2174         Out << "T__m" << Width << 'i';
2175       else if (ET->getKind() == BuiltinType::Double)
2176         Out << "U__m" << Width << 'd';
2177       else
2178         IsBuiltin = false;
2179     } else {
2180       IsBuiltin = false;
2181     }
2182   } else {
2183     IsBuiltin = false;
2184   }
2185 
2186   if (!IsBuiltin) {
2187     // The MS ABI doesn't have a special mangling for vector types, so we define
2188     // our own mangling to handle uses of __vector_size__ on user-specified
2189     // types, and for extensions like __v4sf.
2190     Out << "T__clang_vec" << T->getNumElements() << '_';
2191     mangleType(ET, Quals, Range);
2192   }
2193 
2194   Out << "@@";
2195 }
2196 
2197 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2198                                          Qualifiers Quals, SourceRange Range) {
2199   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2200 }
2201 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2202                                          Qualifiers, SourceRange Range) {
2203   DiagnosticsEngine &Diags = Context.getDiags();
2204   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2205     "cannot mangle this dependent-sized extended vector type yet");
2206   Diags.Report(Range.getBegin(), DiagID)
2207     << Range;
2208 }
2209 
2210 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2211                                          SourceRange) {
2212   // ObjC interfaces have structs underlying them.
2213   Out << 'U';
2214   mangleName(T->getDecl());
2215 }
2216 
2217 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2218                                          SourceRange Range) {
2219   // We don't allow overloading by different protocol qualification,
2220   // so mangling them isn't necessary.
2221   mangleType(T->getBaseType(), Range);
2222 }
2223 
2224 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2225                                          Qualifiers Quals, SourceRange Range) {
2226   QualType PointeeType = T->getPointeeType();
2227   manglePointerCVQualifiers(Quals);
2228   manglePointerExtQualifiers(Quals, PointeeType);
2229 
2230   Out << "_E";
2231 
2232   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2233 }
2234 
2235 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2236                                          Qualifiers, SourceRange) {
2237   llvm_unreachable("Cannot mangle injected class name type.");
2238 }
2239 
2240 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2241                                          Qualifiers, SourceRange Range) {
2242   DiagnosticsEngine &Diags = Context.getDiags();
2243   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2244     "cannot mangle this template specialization type yet");
2245   Diags.Report(Range.getBegin(), DiagID)
2246     << Range;
2247 }
2248 
2249 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2250                                          SourceRange Range) {
2251   DiagnosticsEngine &Diags = Context.getDiags();
2252   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2253     "cannot mangle this dependent name type yet");
2254   Diags.Report(Range.getBegin(), DiagID)
2255     << Range;
2256 }
2257 
2258 void MicrosoftCXXNameMangler::mangleType(
2259     const DependentTemplateSpecializationType *T, Qualifiers,
2260     SourceRange Range) {
2261   DiagnosticsEngine &Diags = Context.getDiags();
2262   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2263     "cannot mangle this dependent template specialization type yet");
2264   Diags.Report(Range.getBegin(), DiagID)
2265     << Range;
2266 }
2267 
2268 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2269                                          SourceRange Range) {
2270   DiagnosticsEngine &Diags = Context.getDiags();
2271   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2272     "cannot mangle this pack expansion yet");
2273   Diags.Report(Range.getBegin(), DiagID)
2274     << Range;
2275 }
2276 
2277 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2278                                          SourceRange Range) {
2279   DiagnosticsEngine &Diags = Context.getDiags();
2280   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2281     "cannot mangle this typeof(type) yet");
2282   Diags.Report(Range.getBegin(), DiagID)
2283     << Range;
2284 }
2285 
2286 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2287                                          SourceRange Range) {
2288   DiagnosticsEngine &Diags = Context.getDiags();
2289   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2290     "cannot mangle this typeof(expression) yet");
2291   Diags.Report(Range.getBegin(), DiagID)
2292     << Range;
2293 }
2294 
2295 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2296                                          SourceRange Range) {
2297   DiagnosticsEngine &Diags = Context.getDiags();
2298   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2299     "cannot mangle this decltype() yet");
2300   Diags.Report(Range.getBegin(), DiagID)
2301     << Range;
2302 }
2303 
2304 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2305                                          Qualifiers, SourceRange Range) {
2306   DiagnosticsEngine &Diags = Context.getDiags();
2307   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2308     "cannot mangle this unary transform type yet");
2309   Diags.Report(Range.getBegin(), DiagID)
2310     << Range;
2311 }
2312 
2313 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2314                                          SourceRange Range) {
2315   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2316 
2317   DiagnosticsEngine &Diags = Context.getDiags();
2318   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2319     "cannot mangle this 'auto' type yet");
2320   Diags.Report(Range.getBegin(), DiagID)
2321     << Range;
2322 }
2323 
2324 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2325                                          SourceRange Range) {
2326   DiagnosticsEngine &Diags = Context.getDiags();
2327   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2328     "cannot mangle this C11 atomic type yet");
2329   Diags.Report(Range.getBegin(), DiagID)
2330     << Range;
2331 }
2332 
2333 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2334                                                raw_ostream &Out) {
2335   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2336          "Invalid mangleName() call, argument is not a variable or function!");
2337   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2338          "Invalid mangleName() call on 'structor decl!");
2339 
2340   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2341                                  getASTContext().getSourceManager(),
2342                                  "Mangling declaration");
2343 
2344   MicrosoftCXXNameMangler Mangler(*this, Out);
2345   return Mangler.mangle(D);
2346 }
2347 
2348 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2349 //                       <virtual-adjustment>
2350 // <no-adjustment>      ::= A # private near
2351 //                      ::= B # private far
2352 //                      ::= I # protected near
2353 //                      ::= J # protected far
2354 //                      ::= Q # public near
2355 //                      ::= R # public far
2356 // <static-adjustment>  ::= G <static-offset> # private near
2357 //                      ::= H <static-offset> # private far
2358 //                      ::= O <static-offset> # protected near
2359 //                      ::= P <static-offset> # protected far
2360 //                      ::= W <static-offset> # public near
2361 //                      ::= X <static-offset> # public far
2362 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2363 //                      ::= $1 <virtual-shift> <static-offset> # private far
2364 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2365 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2366 //                      ::= $4 <virtual-shift> <static-offset> # public near
2367 //                      ::= $5 <virtual-shift> <static-offset> # public far
2368 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2369 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2370 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2371 //                          <offset-to-vtordisp>
2372 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2373                                       const ThisAdjustment &Adjustment,
2374                                       MicrosoftCXXNameMangler &Mangler,
2375                                       raw_ostream &Out) {
2376   if (!Adjustment.Virtual.isEmpty()) {
2377     Out << '$';
2378     char AccessSpec;
2379     switch (MD->getAccess()) {
2380     case AS_none:
2381       llvm_unreachable("Unsupported access specifier");
2382     case AS_private:
2383       AccessSpec = '0';
2384       break;
2385     case AS_protected:
2386       AccessSpec = '2';
2387       break;
2388     case AS_public:
2389       AccessSpec = '4';
2390     }
2391     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2392       Out << 'R' << AccessSpec;
2393       Mangler.mangleNumber(
2394           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2395       Mangler.mangleNumber(
2396           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2397       Mangler.mangleNumber(
2398           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2399       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2400     } else {
2401       Out << AccessSpec;
2402       Mangler.mangleNumber(
2403           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2404       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2405     }
2406   } else if (Adjustment.NonVirtual != 0) {
2407     switch (MD->getAccess()) {
2408     case AS_none:
2409       llvm_unreachable("Unsupported access specifier");
2410     case AS_private:
2411       Out << 'G';
2412       break;
2413     case AS_protected:
2414       Out << 'O';
2415       break;
2416     case AS_public:
2417       Out << 'W';
2418     }
2419     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2420   } else {
2421     switch (MD->getAccess()) {
2422     case AS_none:
2423       llvm_unreachable("Unsupported access specifier");
2424     case AS_private:
2425       Out << 'A';
2426       break;
2427     case AS_protected:
2428       Out << 'I';
2429       break;
2430     case AS_public:
2431       Out << 'Q';
2432     }
2433   }
2434 }
2435 
2436 void
2437 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2438                                                      raw_ostream &Out) {
2439   MicrosoftVTableContext *VTContext =
2440       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2441   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2442       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2443 
2444   MicrosoftCXXNameMangler Mangler(*this, Out);
2445   Mangler.getStream() << "\01?";
2446   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2447 }
2448 
2449 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2450                                              const ThunkInfo &Thunk,
2451                                              raw_ostream &Out) {
2452   MicrosoftCXXNameMangler Mangler(*this, Out);
2453   Out << "\01?";
2454   Mangler.mangleName(MD);
2455   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2456   if (!Thunk.Return.isEmpty())
2457     assert(Thunk.Method != nullptr &&
2458            "Thunk info should hold the overridee decl");
2459 
2460   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2461   Mangler.mangleFunctionType(
2462       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2463 }
2464 
2465 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2466     const CXXDestructorDecl *DD, CXXDtorType Type,
2467     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2468   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2469   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2470   // mangling manually until we support both deleting dtor types.
2471   assert(Type == Dtor_Deleting);
2472   MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2473   Out << "\01??_E";
2474   Mangler.mangleName(DD->getParent());
2475   mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2476   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2477 }
2478 
2479 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2480     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2481     raw_ostream &Out) {
2482   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2483   //                    <cvr-qualifiers> [<name>] @
2484   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2485   // is always '6' for vftables.
2486   MicrosoftCXXNameMangler Mangler(*this, Out);
2487   Mangler.getStream() << "\01??_7";
2488   Mangler.mangleName(Derived);
2489   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2490   for (const CXXRecordDecl *RD : BasePath)
2491     Mangler.mangleName(RD);
2492   Mangler.getStream() << '@';
2493 }
2494 
2495 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2496     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2497     raw_ostream &Out) {
2498   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2499   //                    <cvr-qualifiers> [<name>] @
2500   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2501   // is always '7' for vbtables.
2502   MicrosoftCXXNameMangler Mangler(*this, Out);
2503   Mangler.getStream() << "\01??_8";
2504   Mangler.mangleName(Derived);
2505   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2506   for (const CXXRecordDecl *RD : BasePath)
2507     Mangler.mangleName(RD);
2508   Mangler.getStream() << '@';
2509 }
2510 
2511 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2512   MicrosoftCXXNameMangler Mangler(*this, Out);
2513   Mangler.getStream() << "\01??_R0";
2514   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2515   Mangler.getStream() << "@8";
2516 }
2517 
2518 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2519                                                    raw_ostream &Out) {
2520   MicrosoftCXXNameMangler Mangler(*this, Out);
2521   Mangler.getStream() << '.';
2522   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2523 }
2524 
2525 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
2526                                                            uint32_t Flags,
2527                                                            raw_ostream &Out) {
2528   MicrosoftCXXNameMangler Mangler(*this, Out);
2529   Mangler.getStream() << "llvm.eh.handlertype.";
2530   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2531   Mangler.getStream() << '.' << Flags;
2532 }
2533 
2534 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2535     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2536   MicrosoftCXXNameMangler Mangler(*this, Out);
2537   Mangler.getStream() << "\01??_K";
2538   Mangler.mangleName(SrcRD);
2539   Mangler.getStream() << "$C";
2540   Mangler.mangleName(DstRD);
2541 }
2542 
2543 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2544                                                     bool IsConst,
2545                                                     bool IsVolatile,
2546                                                     uint32_t NumEntries,
2547                                                     raw_ostream &Out) {
2548   MicrosoftCXXNameMangler Mangler(*this, Out);
2549   Mangler.getStream() << "_TI";
2550   if (IsConst)
2551     Mangler.getStream() << 'C';
2552   if (IsVolatile)
2553     Mangler.getStream() << 'V';
2554   Mangler.getStream() << NumEntries;
2555   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2556 }
2557 
2558 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2559     QualType T, uint32_t NumEntries, raw_ostream &Out) {
2560   MicrosoftCXXNameMangler Mangler(*this, Out);
2561   Mangler.getStream() << "_CTA";
2562   Mangler.getStream() << NumEntries;
2563   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2564 }
2565 
2566 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2567     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2568     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2569     raw_ostream &Out) {
2570   MicrosoftCXXNameMangler Mangler(*this, Out);
2571   Mangler.getStream() << "_CT";
2572 
2573   llvm::SmallString<64> RTTIMangling;
2574   {
2575     llvm::raw_svector_ostream Stream(RTTIMangling);
2576     mangleCXXRTTI(T, Stream);
2577   }
2578   Mangler.getStream() << RTTIMangling.substr(1);
2579 
2580   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
2581   // in fact, superfluous but I'm not sure the change was made consciously.
2582   // TODO: Revisit this when VS2015 gets released.
2583   llvm::SmallString<64> CopyCtorMangling;
2584   if (CD) {
2585     llvm::raw_svector_ostream Stream(CopyCtorMangling);
2586     mangleCXXCtor(CD, CT, Stream);
2587   }
2588   Mangler.getStream() << CopyCtorMangling.substr(1);
2589 
2590   Mangler.getStream() << Size;
2591   if (VBPtrOffset == -1) {
2592     if (NVOffset) {
2593       Mangler.getStream() << NVOffset;
2594     }
2595   } else {
2596     Mangler.getStream() << NVOffset;
2597     Mangler.getStream() << VBPtrOffset;
2598     Mangler.getStream() << VBIndex;
2599   }
2600 }
2601 
2602 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2603     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2604     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2605   MicrosoftCXXNameMangler Mangler(*this, Out);
2606   Mangler.getStream() << "\01??_R1";
2607   Mangler.mangleNumber(NVOffset);
2608   Mangler.mangleNumber(VBPtrOffset);
2609   Mangler.mangleNumber(VBTableOffset);
2610   Mangler.mangleNumber(Flags);
2611   Mangler.mangleName(Derived);
2612   Mangler.getStream() << "8";
2613 }
2614 
2615 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2616     const CXXRecordDecl *Derived, raw_ostream &Out) {
2617   MicrosoftCXXNameMangler Mangler(*this, Out);
2618   Mangler.getStream() << "\01??_R2";
2619   Mangler.mangleName(Derived);
2620   Mangler.getStream() << "8";
2621 }
2622 
2623 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2624     const CXXRecordDecl *Derived, raw_ostream &Out) {
2625   MicrosoftCXXNameMangler Mangler(*this, Out);
2626   Mangler.getStream() << "\01??_R3";
2627   Mangler.mangleName(Derived);
2628   Mangler.getStream() << "8";
2629 }
2630 
2631 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2632     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2633     raw_ostream &Out) {
2634   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2635   //                    <cvr-qualifiers> [<name>] @
2636   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2637   // is always '6' for vftables.
2638   MicrosoftCXXNameMangler Mangler(*this, Out);
2639   Mangler.getStream() << "\01??_R4";
2640   Mangler.mangleName(Derived);
2641   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2642   for (const CXXRecordDecl *RD : BasePath)
2643     Mangler.mangleName(RD);
2644   Mangler.getStream() << '@';
2645 }
2646 
2647 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2648     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2649   MicrosoftCXXNameMangler Mangler(*this, Out);
2650   // The function body is in the same comdat as the function with the handler,
2651   // so the numbering here doesn't have to be the same across TUs.
2652   //
2653   // <mangled-name> ::= ?filt$ <filter-number> @0
2654   Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2655   Mangler.mangleName(EnclosingDecl);
2656 }
2657 
2658 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2659     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2660   MicrosoftCXXNameMangler Mangler(*this, Out);
2661   // The function body is in the same comdat as the function with the handler,
2662   // so the numbering here doesn't have to be the same across TUs.
2663   //
2664   // <mangled-name> ::= ?fin$ <filter-number> @0
2665   Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2666   Mangler.mangleName(EnclosingDecl);
2667 }
2668 
2669 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2670   // This is just a made up unique string for the purposes of tbaa.  undname
2671   // does *not* know how to demangle it.
2672   MicrosoftCXXNameMangler Mangler(*this, Out);
2673   Mangler.getStream() << '?';
2674   Mangler.mangleType(T, SourceRange());
2675 }
2676 
2677 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2678                                                CXXCtorType Type,
2679                                                raw_ostream &Out) {
2680   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2681   mangler.mangle(D);
2682 }
2683 
2684 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2685                                                CXXDtorType Type,
2686                                                raw_ostream &Out) {
2687   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2688   mangler.mangle(D);
2689 }
2690 
2691 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2692                                                           unsigned,
2693                                                           raw_ostream &) {
2694   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2695     "cannot mangle this reference temporary yet");
2696   getDiags().Report(VD->getLocation(), DiagID);
2697 }
2698 
2699 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2700     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2701   MicrosoftCXXNameMangler Mangler(*this, Out);
2702 
2703   Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2704   Mangler.mangleNestedName(VD);
2705 }
2706 
2707 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2708                                                            raw_ostream &Out) {
2709   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2710   //              ::= ?__J <postfix> @5 <scope-depth>
2711   //              ::= ?$S <guard-num> @ <postfix> @4IA
2712 
2713   // The first mangling is what MSVC uses to guard static locals in inline
2714   // functions.  It uses a different mangling in external functions to support
2715   // guarding more than 32 variables.  MSVC rejects inline functions with more
2716   // than 32 static locals.  We don't fully implement the second mangling
2717   // because those guards are not externally visible, and instead use LLVM's
2718   // default renaming when creating a new guard variable.
2719   MicrosoftCXXNameMangler Mangler(*this, Out);
2720 
2721   bool Visible = VD->isExternallyVisible();
2722   if (Visible) {
2723     Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2724   } else {
2725     Mangler.getStream() << "\01?$S1@";
2726   }
2727   unsigned ScopeDepth = 0;
2728   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2729     // If we do not have a discriminator and are emitting a guard variable for
2730     // use at global scope, then mangling the nested name will not be enough to
2731     // remove ambiguities.
2732     Mangler.mangle(VD, "");
2733   else
2734     Mangler.mangleNestedName(VD);
2735   Mangler.getStream() << (Visible ? "@5" : "@4IA");
2736   if (ScopeDepth)
2737     Mangler.mangleNumber(ScopeDepth);
2738 }
2739 
2740 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2741                                                     raw_ostream &Out,
2742                                                     char CharCode) {
2743   MicrosoftCXXNameMangler Mangler(*this, Out);
2744   Mangler.getStream() << "\01??__" << CharCode;
2745   Mangler.mangleName(D);
2746   if (D->isStaticDataMember()) {
2747     Mangler.mangleVariableEncoding(D);
2748     Mangler.getStream() << '@';
2749   }
2750   // This is the function class mangling.  These stubs are global, non-variadic,
2751   // cdecl functions that return void and take no args.
2752   Mangler.getStream() << "YAXXZ";
2753 }
2754 
2755 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2756                                                           raw_ostream &Out) {
2757   // <initializer-name> ::= ?__E <name> YAXXZ
2758   mangleInitFiniStub(D, Out, 'E');
2759 }
2760 
2761 void
2762 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2763                                                           raw_ostream &Out) {
2764   // <destructor-name> ::= ?__F <name> YAXXZ
2765   mangleInitFiniStub(D, Out, 'F');
2766 }
2767 
2768 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2769                                                      raw_ostream &Out) {
2770   // <char-type> ::= 0   # char
2771   //             ::= 1   # wchar_t
2772   //             ::= ??? # char16_t/char32_t will need a mangling too...
2773   //
2774   // <literal-length> ::= <non-negative integer>  # the length of the literal
2775   //
2776   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2777   //                                              # null-terminator
2778   //
2779   // <encoded-string> ::= <simple character>           # uninteresting character
2780   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2781   //                                                   # encode the byte for the
2782   //                                                   # character
2783   //                  ::= '?' [a-z]                    # \xe1 - \xfa
2784   //                  ::= '?' [A-Z]                    # \xc1 - \xda
2785   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
2786   //
2787   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2788   //               <encoded-string> '@'
2789   MicrosoftCXXNameMangler Mangler(*this, Out);
2790   Mangler.getStream() << "\01??_C@_";
2791 
2792   // <char-type>: The "kind" of string literal is encoded into the mangled name.
2793   if (SL->isWide())
2794     Mangler.getStream() << '1';
2795   else
2796     Mangler.getStream() << '0';
2797 
2798   // <literal-length>: The next part of the mangled name consists of the length
2799   // of the string.
2800   // The StringLiteral does not consider the NUL terminator byte(s) but the
2801   // mangling does.
2802   // N.B. The length is in terms of bytes, not characters.
2803   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2804 
2805   auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2806     unsigned CharByteWidth = SL->getCharByteWidth();
2807     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2808     unsigned OffsetInCodeUnit = Index % CharByteWidth;
2809     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2810   };
2811 
2812   auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2813     unsigned CharByteWidth = SL->getCharByteWidth();
2814     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2815     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2816     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2817   };
2818 
2819   // CRC all the bytes of the StringLiteral.
2820   llvm::JamCRC JC;
2821   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2822     JC.update(GetLittleEndianByte(I));
2823 
2824   // The NUL terminator byte(s) were not present earlier,
2825   // we need to manually process those bytes into the CRC.
2826   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2827        ++NullTerminator)
2828     JC.update('\x00');
2829 
2830   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2831   // scheme.
2832   Mangler.mangleNumber(JC.getCRC());
2833 
2834   // <encoded-string>: The mangled name also contains the first 32 _characters_
2835   // (including null-terminator bytes) of the StringLiteral.
2836   // Each character is encoded by splitting them into bytes and then encoding
2837   // the constituent bytes.
2838   auto MangleByte = [&Mangler](char Byte) {
2839     // There are five different manglings for characters:
2840     // - [a-zA-Z0-9_$]: A one-to-one mapping.
2841     // - ?[a-z]: The range from \xe1 to \xfa.
2842     // - ?[A-Z]: The range from \xc1 to \xda.
2843     // - ?[0-9]: The set of [,/\:. \n\t'-].
2844     // - ?$XX: A fallback which maps nibbles.
2845     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2846       Mangler.getStream() << Byte;
2847     } else if (isLetter(Byte & 0x7f)) {
2848       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2849     } else {
2850       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
2851                                    ' ', '\n', '\t', '\'', '-'};
2852       const char *Pos =
2853           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2854       if (Pos != std::end(SpecialChars)) {
2855         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2856       } else {
2857         Mangler.getStream() << "?$";
2858         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2859         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2860       }
2861     }
2862   };
2863 
2864   // Enforce our 32 character max.
2865   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2866   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2867        ++I)
2868     if (SL->isWide())
2869       MangleByte(GetBigEndianByte(I));
2870     else
2871       MangleByte(GetLittleEndianByte(I));
2872 
2873   // Encode the NUL terminator if there is room.
2874   if (NumCharsToMangle < 32)
2875     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2876          ++NullTerminator)
2877       MangleByte(0);
2878 
2879   Mangler.getStream() << '@';
2880 }
2881 
2882 MicrosoftMangleContext *
2883 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2884   return new MicrosoftMangleContextImpl(Context, Diags);
2885 }
2886