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