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