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