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/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/Basic/ABI.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include <map>
26 
27 using namespace clang;
28 
29 namespace {
30 
31 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
32   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
33     return ftd->getTemplatedDecl();
34 
35   return fn;
36 }
37 
38 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
39 /// Microsoft Visual C++ ABI.
40 class MicrosoftCXXNameMangler {
41   MangleContext &Context;
42   raw_ostream &Out;
43 
44   /// The "structor" is the top-level declaration being mangled, if
45   /// that's not a template specialization; otherwise it's the pattern
46   /// for that specialization.
47   const NamedDecl *Structor;
48   unsigned StructorType;
49 
50   // FIXME: audit the performance of BackRefMap as it might do way too many
51   // copying of strings.
52   typedef std::map<std::string, unsigned> BackRefMap;
53   BackRefMap NameBackReferences;
54   bool UseNameBackReferences;
55 
56   typedef llvm::DenseMap<void*, unsigned> ArgBackRefMap;
57   ArgBackRefMap TypeBackReferences;
58 
59   ASTContext &getASTContext() const { return Context.getASTContext(); }
60 
61 public:
62   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
63     : Context(C), Out(Out_),
64       Structor(0), StructorType(-1),
65       UseNameBackReferences(true) { }
66 
67   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_,
68                           const CXXDestructorDecl *D, CXXDtorType Type)
69     : Context(C), Out(Out_),
70       Structor(getStructor(D)), StructorType(Type),
71       UseNameBackReferences(true) { }
72 
73   raw_ostream &getStream() const { return Out; }
74 
75   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
76   void mangleName(const NamedDecl *ND);
77   void mangleFunctionEncoding(const FunctionDecl *FD);
78   void mangleVariableEncoding(const VarDecl *VD);
79   void mangleNumber(int64_t Number);
80   void mangleNumber(const llvm::APSInt &Value);
81   void mangleType(QualType T, SourceRange Range, bool MangleQualifiers = true);
82 
83 private:
84   void disableBackReferences() { UseNameBackReferences = false; }
85   void mangleUnqualifiedName(const NamedDecl *ND) {
86     mangleUnqualifiedName(ND, ND->getDeclName());
87   }
88   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
89   void mangleSourceName(const IdentifierInfo *II);
90   void manglePostfix(const DeclContext *DC, bool NoFunction=false);
91   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
92   void mangleCXXDtorType(CXXDtorType T);
93   void mangleQualifiers(Qualifiers Quals, bool IsMember);
94   void manglePointerQualifiers(Qualifiers Quals);
95 
96   void mangleUnscopedTemplateName(const TemplateDecl *ND);
97   void mangleTemplateInstantiationName(const TemplateDecl *TD,
98                                       const TemplateArgumentList &TemplateArgs);
99   void mangleObjCMethodName(const ObjCMethodDecl *MD);
100   void mangleLocalName(const FunctionDecl *FD);
101 
102   void mangleArgumentType(QualType T, SourceRange Range);
103 
104   // Declare manglers for every type class.
105 #define ABSTRACT_TYPE(CLASS, PARENT)
106 #define NON_CANONICAL_TYPE(CLASS, PARENT)
107 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
108                                             SourceRange Range);
109 #include "clang/AST/TypeNodes.def"
110 #undef ABSTRACT_TYPE
111 #undef NON_CANONICAL_TYPE
112 #undef TYPE
113 
114   void mangleType(const TagType*);
115   void mangleType(const FunctionType *T, const FunctionDecl *D,
116                   bool IsStructor, bool IsInstMethod);
117   void mangleType(const ArrayType *T, bool IsGlobal);
118   void mangleExtraDimensions(QualType T);
119   void mangleFunctionClass(const FunctionDecl *FD);
120   void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
121   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
122   void mangleExpression(const Expr *E);
123   void mangleThrowSpecification(const FunctionProtoType *T);
124 
125   void mangleTemplateArgs(const TemplateDecl *TD,
126                           const TemplateArgumentList &TemplateArgs);
127 
128 };
129 
130 /// MicrosoftMangleContext - Overrides the default MangleContext for the
131 /// Microsoft Visual C++ ABI.
132 class MicrosoftMangleContext : public MangleContext {
133 public:
134   MicrosoftMangleContext(ASTContext &Context,
135                    DiagnosticsEngine &Diags) : MangleContext(Context, Diags) { }
136   virtual bool shouldMangleDeclName(const NamedDecl *D);
137   virtual void mangleName(const NamedDecl *D, raw_ostream &Out);
138   virtual void mangleThunk(const CXXMethodDecl *MD,
139                            const ThunkInfo &Thunk,
140                            raw_ostream &);
141   virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
142                                   const ThisAdjustment &ThisAdjustment,
143                                   raw_ostream &);
144   virtual void mangleCXXVTable(const CXXRecordDecl *RD,
145                                raw_ostream &);
146   virtual void mangleCXXVTT(const CXXRecordDecl *RD,
147                             raw_ostream &);
148   virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
149                                    const CXXRecordDecl *Type,
150                                    raw_ostream &);
151   virtual void mangleCXXRTTI(QualType T, raw_ostream &);
152   virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
153   virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
154                              raw_ostream &);
155   virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
156                              raw_ostream &);
157   virtual void mangleReferenceTemporary(const clang::VarDecl *,
158                                         raw_ostream &);
159 };
160 
161 }
162 
163 static bool isInCLinkageSpecification(const Decl *D) {
164   D = D->getCanonicalDecl();
165   for (const DeclContext *DC = D->getDeclContext();
166        !DC->isTranslationUnit(); DC = DC->getParent()) {
167     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
168       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
169   }
170 
171   return false;
172 }
173 
174 bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
175   // In C, functions with no attributes never need to be mangled. Fastpath them.
176   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
177     return false;
178 
179   // Any decl can be declared with __asm("foo") on it, and this takes precedence
180   // over all other naming in the .o file.
181   if (D->hasAttr<AsmLabelAttr>())
182     return true;
183 
184   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
185   // (always) as does passing a C++ member function and a function
186   // whose name is not a simple identifier.
187   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
188   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
189              !FD->getDeclName().isIdentifier()))
190     return true;
191 
192   // Otherwise, no mangling is done outside C++ mode.
193   if (!getASTContext().getLangOpts().CPlusPlus)
194     return false;
195 
196   // Variables at global scope with internal linkage are not mangled.
197   if (!FD) {
198     const DeclContext *DC = D->getDeclContext();
199     if (DC->isTranslationUnit() && D->getLinkage() == InternalLinkage)
200       return false;
201   }
202 
203   // C functions and "main" are not mangled.
204   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
205     return false;
206 
207   return true;
208 }
209 
210 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
211                                      StringRef Prefix) {
212   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
213   // Therefore it's really important that we don't decorate the
214   // name with leading underscores or leading/trailing at signs. So, by
215   // default, we emit an asm marker at the start so we get the name right.
216   // Callers can override this with a custom prefix.
217 
218   // Any decl can be declared with __asm("foo") on it, and this takes precedence
219   // over all other naming in the .o file.
220   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
221     // If we have an asm name, then we use it as the mangling.
222     Out << '\01' << ALA->getLabel();
223     return;
224   }
225 
226   // <mangled-name> ::= ? <name> <type-encoding>
227   Out << Prefix;
228   mangleName(D);
229   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
230     mangleFunctionEncoding(FD);
231   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
232     mangleVariableEncoding(VD);
233   else {
234     // TODO: Fields? Can MSVC even mangle them?
235     // Issue a diagnostic for now.
236     DiagnosticsEngine &Diags = Context.getDiags();
237     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
238       "cannot mangle this declaration yet");
239     Diags.Report(D->getLocation(), DiagID)
240       << D->getSourceRange();
241   }
242 }
243 
244 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
245   // <type-encoding> ::= <function-class> <function-type>
246 
247   // Don't mangle in the type if this isn't a decl we should typically mangle.
248   if (!Context.shouldMangleDeclName(FD))
249     return;
250 
251   // We should never ever see a FunctionNoProtoType at this point.
252   // We don't even know how to mangle their types anyway :).
253   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
254 
255   bool InStructor = false, InInstMethod = false;
256   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
257   if (MD) {
258     if (MD->isInstance())
259       InInstMethod = true;
260     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
261       InStructor = true;
262   }
263 
264   // First, the function class.
265   mangleFunctionClass(FD);
266 
267   mangleType(FT, FD, InStructor, InInstMethod);
268 }
269 
270 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
271   // <type-encoding> ::= <storage-class> <variable-type>
272   // <storage-class> ::= 0  # private static member
273   //                 ::= 1  # protected static member
274   //                 ::= 2  # public static member
275   //                 ::= 3  # global
276   //                 ::= 4  # static local
277 
278   // The first character in the encoding (after the name) is the storage class.
279   if (VD->isStaticDataMember()) {
280     // If it's a static member, it also encodes the access level.
281     switch (VD->getAccess()) {
282       default:
283       case AS_private: Out << '0'; break;
284       case AS_protected: Out << '1'; break;
285       case AS_public: Out << '2'; break;
286     }
287   }
288   else if (!VD->isStaticLocal())
289     Out << '3';
290   else
291     Out << '4';
292   // Now mangle the type.
293   // <variable-type> ::= <type> <cvr-qualifiers>
294   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
295   // Pointers and references are odd. The type of 'int * const foo;' gets
296   // mangled as 'QAHA' instead of 'PAHB', for example.
297   TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
298   QualType Ty = TL.getType();
299   if (Ty->isPointerType() || Ty->isReferenceType()) {
300     mangleType(Ty, TL.getSourceRange());
301     mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
302   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
303     // Global arrays are funny, too.
304     mangleType(AT, true);
305     mangleQualifiers(Ty.getQualifiers(), false);
306   } else {
307     mangleType(Ty.getLocalUnqualifiedType(), TL.getSourceRange());
308     mangleQualifiers(Ty.getLocalQualifiers(), false);
309   }
310 }
311 
312 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
313   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
314   const DeclContext *DC = ND->getDeclContext();
315 
316   // Always start with the unqualified name.
317   mangleUnqualifiedName(ND);
318 
319   // If this is an extern variable declared locally, the relevant DeclContext
320   // is that of the containing namespace, or the translation unit.
321   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
322     while (!DC->isNamespace() && !DC->isTranslationUnit())
323       DC = DC->getParent();
324 
325   manglePostfix(DC);
326 
327   // Terminate the whole name with an '@'.
328   Out << '@';
329 }
330 
331 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
332   llvm::APSInt APSNumber(/*BitWidth=*/64, /*isUnsigned=*/false);
333   APSNumber = Number;
334   mangleNumber(APSNumber);
335 }
336 
337 void MicrosoftCXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
338   // <number> ::= [?] <decimal digit> # 1 <= Number <= 10
339   //          ::= [?] <hex digit>+ @ # 0 or > 9; A = 0, B = 1, etc...
340   //          ::= [?] @ # 0 (alternate mangling, not emitted by VC)
341   if (Value.isSigned() && Value.isNegative()) {
342     Out << '?';
343     mangleNumber(llvm::APSInt(Value.abs()));
344     return;
345   }
346   llvm::APSInt Temp(Value);
347   // There's a special shorter mangling for 0, but Microsoft
348   // chose not to use it. Instead, 0 gets mangled as "A@". Oh well...
349   if (Value.uge(1) && Value.ule(10)) {
350     --Temp;
351     Temp.print(Out, false);
352   } else {
353     // We have to build up the encoding in reverse order, so it will come
354     // out right when we write it out.
355     char Encoding[64];
356     char *EndPtr = Encoding+sizeof(Encoding);
357     char *CurPtr = EndPtr;
358     llvm::APSInt NibbleMask(Value.getBitWidth(), Value.isUnsigned());
359     NibbleMask = 0xf;
360     do {
361       *--CurPtr = 'A' + Temp.And(NibbleMask).getLimitedValue(0xf);
362       Temp = Temp.lshr(4);
363     } while (Temp != 0);
364     Out.write(CurPtr, EndPtr-CurPtr);
365     Out << '@';
366   }
367 }
368 
369 static const TemplateDecl *
370 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
371   // Check if we have a function template.
372   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
373     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
374       TemplateArgs = FD->getTemplateSpecializationArgs();
375       return TD;
376     }
377   }
378 
379   // Check if we have a class template.
380   if (const ClassTemplateSpecializationDecl *Spec =
381         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
382     TemplateArgs = &Spec->getTemplateArgs();
383     return Spec->getSpecializedTemplate();
384   }
385 
386   return 0;
387 }
388 
389 void
390 MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
391                                                DeclarationName Name) {
392   //  <unqualified-name> ::= <operator-name>
393   //                     ::= <ctor-dtor-name>
394   //                     ::= <source-name>
395   //                     ::= <template-name>
396 
397   // Check if we have a template.
398   const TemplateArgumentList *TemplateArgs = 0;
399   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
400     // We have a template.
401     // Here comes the tricky thing: if we need to mangle something like
402     //   void foo(A::X<Y>, B::X<Y>),
403     // the X<Y> part is aliased. However, if you need to mangle
404     //   void foo(A::X<A::Y>, A::X<B::Y>),
405     // the A::X<> part is not aliased.
406     // That said, from the mangler's perspective we have a structure like this:
407     //   namespace[s] -> type[ -> template-parameters]
408     // but from the Clang perspective we have
409     //   type [ -> template-parameters]
410     //      \-> namespace[s]
411     // What we do is we create a new mangler, mangle the same type (without
412     // a namespace suffix) using the extra mangler with back references
413     // disabled (to avoid infinite recursion) and then use the mangled type
414     // name as a key to check the mangling of different types for aliasing.
415 
416     std::string BackReferenceKey;
417     BackRefMap::iterator Found;
418     if (UseNameBackReferences) {
419       llvm::raw_string_ostream Stream(BackReferenceKey);
420       MicrosoftCXXNameMangler Extra(Context, Stream);
421       Extra.disableBackReferences();
422       Extra.mangleUnqualifiedName(ND, Name);
423       Stream.flush();
424 
425       Found = NameBackReferences.find(BackReferenceKey);
426     }
427     if (!UseNameBackReferences || Found == NameBackReferences.end()) {
428       mangleTemplateInstantiationName(TD, *TemplateArgs);
429       if (UseNameBackReferences && NameBackReferences.size() < 10) {
430         size_t Size = NameBackReferences.size();
431         NameBackReferences[BackReferenceKey] = Size;
432       }
433     } else {
434       Out << Found->second;
435     }
436     return;
437   }
438 
439   switch (Name.getNameKind()) {
440     case DeclarationName::Identifier: {
441       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
442         mangleSourceName(II);
443         break;
444       }
445 
446       // Otherwise, an anonymous entity.  We must have a declaration.
447       assert(ND && "mangling empty name without declaration");
448 
449       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
450         if (NS->isAnonymousNamespace()) {
451           Out << "?A@";
452           break;
453         }
454       }
455 
456       // We must have an anonymous struct.
457       const TagDecl *TD = cast<TagDecl>(ND);
458       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
459         assert(TD->getDeclContext() == D->getDeclContext() &&
460                "Typedef should not be in another decl context!");
461         assert(D->getDeclName().getAsIdentifierInfo() &&
462                "Typedef was not named!");
463         mangleSourceName(D->getDeclName().getAsIdentifierInfo());
464         break;
465       }
466 
467       // When VC encounters an anonymous type with no tag and no typedef,
468       // it literally emits '<unnamed-tag>'.
469       Out << "<unnamed-tag>";
470       break;
471     }
472 
473     case DeclarationName::ObjCZeroArgSelector:
474     case DeclarationName::ObjCOneArgSelector:
475     case DeclarationName::ObjCMultiArgSelector:
476       llvm_unreachable("Can't mangle Objective-C selector names here!");
477 
478     case DeclarationName::CXXConstructorName:
479       if (ND == Structor) {
480         assert(StructorType == Ctor_Complete &&
481                "Should never be asked to mangle a ctor other than complete");
482       }
483       Out << "?0";
484       break;
485 
486     case DeclarationName::CXXDestructorName:
487       if (ND == Structor)
488         // If the named decl is the C++ destructor we're mangling,
489         // use the type we were given.
490         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
491       else
492         // Otherwise, use the complete destructor name. This is relevant if a
493         // class with a destructor is declared within a destructor.
494         mangleCXXDtorType(Dtor_Complete);
495       break;
496 
497     case DeclarationName::CXXConversionFunctionName:
498       // <operator-name> ::= ?B # (cast)
499       // The target type is encoded as the return type.
500       Out << "?B";
501       break;
502 
503     case DeclarationName::CXXOperatorName:
504       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
505       break;
506 
507     case DeclarationName::CXXLiteralOperatorName: {
508       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
509       DiagnosticsEngine Diags = Context.getDiags();
510       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
511         "cannot mangle this literal operator yet");
512       Diags.Report(ND->getLocation(), DiagID);
513       break;
514     }
515 
516     case DeclarationName::CXXUsingDirective:
517       llvm_unreachable("Can't mangle a using directive name!");
518   }
519 }
520 
521 void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
522                                             bool NoFunction) {
523   // <postfix> ::= <unqualified-name> [<postfix>]
524   //           ::= <substitution> [<postfix>]
525 
526   if (!DC) return;
527 
528   while (isa<LinkageSpecDecl>(DC))
529     DC = DC->getParent();
530 
531   if (DC->isTranslationUnit())
532     return;
533 
534   if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
535     Context.mangleBlock(BD, Out);
536     Out << '@';
537     return manglePostfix(DC->getParent(), NoFunction);
538   }
539 
540   if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
541     return;
542   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
543     mangleObjCMethodName(Method);
544   else if (const FunctionDecl *Func = dyn_cast<FunctionDecl>(DC))
545     mangleLocalName(Func);
546   else {
547     mangleUnqualifiedName(cast<NamedDecl>(DC));
548     manglePostfix(DC->getParent(), NoFunction);
549   }
550 }
551 
552 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
553   switch (T) {
554   case Dtor_Deleting:
555     Out << "?_G";
556     return;
557   case Dtor_Base:
558     // FIXME: We should be asked to mangle base dtors.
559     // However, fixing this would require larger changes to the CodeGenModule.
560     // Please put llvm_unreachable here when CGM is changed.
561     // For now, just mangle a base dtor the same way as a complete dtor...
562   case Dtor_Complete:
563     Out << "?1";
564     return;
565   }
566   llvm_unreachable("Unsupported dtor type?");
567 }
568 
569 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
570                                                  SourceLocation Loc) {
571   switch (OO) {
572   //                     ?0 # constructor
573   //                     ?1 # destructor
574   // <operator-name> ::= ?2 # new
575   case OO_New: Out << "?2"; break;
576   // <operator-name> ::= ?3 # delete
577   case OO_Delete: Out << "?3"; break;
578   // <operator-name> ::= ?4 # =
579   case OO_Equal: Out << "?4"; break;
580   // <operator-name> ::= ?5 # >>
581   case OO_GreaterGreater: Out << "?5"; break;
582   // <operator-name> ::= ?6 # <<
583   case OO_LessLess: Out << "?6"; break;
584   // <operator-name> ::= ?7 # !
585   case OO_Exclaim: Out << "?7"; break;
586   // <operator-name> ::= ?8 # ==
587   case OO_EqualEqual: Out << "?8"; break;
588   // <operator-name> ::= ?9 # !=
589   case OO_ExclaimEqual: Out << "?9"; break;
590   // <operator-name> ::= ?A # []
591   case OO_Subscript: Out << "?A"; break;
592   //                     ?B # conversion
593   // <operator-name> ::= ?C # ->
594   case OO_Arrow: Out << "?C"; break;
595   // <operator-name> ::= ?D # *
596   case OO_Star: Out << "?D"; break;
597   // <operator-name> ::= ?E # ++
598   case OO_PlusPlus: Out << "?E"; break;
599   // <operator-name> ::= ?F # --
600   case OO_MinusMinus: Out << "?F"; break;
601   // <operator-name> ::= ?G # -
602   case OO_Minus: Out << "?G"; break;
603   // <operator-name> ::= ?H # +
604   case OO_Plus: Out << "?H"; break;
605   // <operator-name> ::= ?I # &
606   case OO_Amp: Out << "?I"; break;
607   // <operator-name> ::= ?J # ->*
608   case OO_ArrowStar: Out << "?J"; break;
609   // <operator-name> ::= ?K # /
610   case OO_Slash: Out << "?K"; break;
611   // <operator-name> ::= ?L # %
612   case OO_Percent: Out << "?L"; break;
613   // <operator-name> ::= ?M # <
614   case OO_Less: Out << "?M"; break;
615   // <operator-name> ::= ?N # <=
616   case OO_LessEqual: Out << "?N"; break;
617   // <operator-name> ::= ?O # >
618   case OO_Greater: Out << "?O"; break;
619   // <operator-name> ::= ?P # >=
620   case OO_GreaterEqual: Out << "?P"; break;
621   // <operator-name> ::= ?Q # ,
622   case OO_Comma: Out << "?Q"; break;
623   // <operator-name> ::= ?R # ()
624   case OO_Call: Out << "?R"; break;
625   // <operator-name> ::= ?S # ~
626   case OO_Tilde: Out << "?S"; break;
627   // <operator-name> ::= ?T # ^
628   case OO_Caret: Out << "?T"; break;
629   // <operator-name> ::= ?U # |
630   case OO_Pipe: Out << "?U"; break;
631   // <operator-name> ::= ?V # &&
632   case OO_AmpAmp: Out << "?V"; break;
633   // <operator-name> ::= ?W # ||
634   case OO_PipePipe: Out << "?W"; break;
635   // <operator-name> ::= ?X # *=
636   case OO_StarEqual: Out << "?X"; break;
637   // <operator-name> ::= ?Y # +=
638   case OO_PlusEqual: Out << "?Y"; break;
639   // <operator-name> ::= ?Z # -=
640   case OO_MinusEqual: Out << "?Z"; break;
641   // <operator-name> ::= ?_0 # /=
642   case OO_SlashEqual: Out << "?_0"; break;
643   // <operator-name> ::= ?_1 # %=
644   case OO_PercentEqual: Out << "?_1"; break;
645   // <operator-name> ::= ?_2 # >>=
646   case OO_GreaterGreaterEqual: Out << "?_2"; break;
647   // <operator-name> ::= ?_3 # <<=
648   case OO_LessLessEqual: Out << "?_3"; break;
649   // <operator-name> ::= ?_4 # &=
650   case OO_AmpEqual: Out << "?_4"; break;
651   // <operator-name> ::= ?_5 # |=
652   case OO_PipeEqual: Out << "?_5"; break;
653   // <operator-name> ::= ?_6 # ^=
654   case OO_CaretEqual: Out << "?_6"; break;
655   //                     ?_7 # vftable
656   //                     ?_8 # vbtable
657   //                     ?_9 # vcall
658   //                     ?_A # typeof
659   //                     ?_B # local static guard
660   //                     ?_C # string
661   //                     ?_D # vbase destructor
662   //                     ?_E # vector deleting destructor
663   //                     ?_F # default constructor closure
664   //                     ?_G # scalar deleting destructor
665   //                     ?_H # vector constructor iterator
666   //                     ?_I # vector destructor iterator
667   //                     ?_J # vector vbase constructor iterator
668   //                     ?_K # virtual displacement map
669   //                     ?_L # eh vector constructor iterator
670   //                     ?_M # eh vector destructor iterator
671   //                     ?_N # eh vector vbase constructor iterator
672   //                     ?_O # copy constructor closure
673   //                     ?_P<name> # udt returning <name>
674   //                     ?_Q # <unknown>
675   //                     ?_R0 # RTTI Type Descriptor
676   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
677   //                     ?_R2 # RTTI Base Class Array
678   //                     ?_R3 # RTTI Class Hierarchy Descriptor
679   //                     ?_R4 # RTTI Complete Object Locator
680   //                     ?_S # local vftable
681   //                     ?_T # local vftable constructor closure
682   // <operator-name> ::= ?_U # new[]
683   case OO_Array_New: Out << "?_U"; break;
684   // <operator-name> ::= ?_V # delete[]
685   case OO_Array_Delete: Out << "?_V"; break;
686 
687   case OO_Conditional: {
688     DiagnosticsEngine &Diags = Context.getDiags();
689     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
690       "cannot mangle this conditional operator yet");
691     Diags.Report(Loc, DiagID);
692     break;
693   }
694 
695   case OO_None:
696   case NUM_OVERLOADED_OPERATORS:
697     llvm_unreachable("Not an overloaded operator");
698   }
699 }
700 
701 void MicrosoftCXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
702   // <source name> ::= <identifier> @
703   std::string key = II->getNameStart();
704   BackRefMap::iterator Found;
705   if (UseNameBackReferences)
706     Found = NameBackReferences.find(key);
707   if (!UseNameBackReferences || Found == NameBackReferences.end()) {
708     Out << II->getName() << '@';
709     if (UseNameBackReferences && NameBackReferences.size() < 10) {
710       size_t Size = NameBackReferences.size();
711       NameBackReferences[key] = Size;
712     }
713   } else {
714     Out << Found->second;
715   }
716 }
717 
718 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
719   Context.mangleObjCMethodName(MD, Out);
720 }
721 
722 // Find out how many function decls live above this one and return an integer
723 // suitable for use as the number in a numbered anonymous scope.
724 // TODO: Memoize.
725 static unsigned getLocalNestingLevel(const FunctionDecl *FD) {
726   const DeclContext *DC = FD->getParent();
727   int level = 1;
728 
729   while (DC && !DC->isTranslationUnit()) {
730     if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) level++;
731     DC = DC->getParent();
732   }
733 
734   return 2*level;
735 }
736 
737 void MicrosoftCXXNameMangler::mangleLocalName(const FunctionDecl *FD) {
738   // <nested-name> ::= <numbered-anonymous-scope> ? <mangled-name>
739   // <numbered-anonymous-scope> ::= ? <number>
740   // Even though the name is rendered in reverse order (e.g.
741   // A::B::C is rendered as C@B@A), VC numbers the scopes from outermost to
742   // innermost. So a method bar in class C local to function foo gets mangled
743   // as something like:
744   // ?bar@C@?1??foo@@YAXXZ@QAEXXZ
745   // This is more apparent when you have a type nested inside a method of a
746   // type nested inside a function. A method baz in class D local to method
747   // bar of class C local to function foo gets mangled as:
748   // ?baz@D@?3??bar@C@?1??foo@@YAXXZ@QAEXXZ@QAEXXZ
749   // This scheme is general enough to support GCC-style nested
750   // functions. You could have a method baz of class C inside a function bar
751   // inside a function foo, like so:
752   // ?baz@C@?3??bar@?1??foo@@YAXXZ@YAXXZ@QAEXXZ
753   int NestLevel = getLocalNestingLevel(FD);
754   Out << '?';
755   mangleNumber(NestLevel);
756   Out << '?';
757   mangle(FD, "?");
758 }
759 
760 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
761                                                          const TemplateDecl *TD,
762                      const TemplateArgumentList &TemplateArgs) {
763   // <template-name> ::= <unscoped-template-name> <template-args>
764   //                 ::= <substitution>
765   // Always start with the unqualified name.
766 
767   // Templates have their own context for back references.
768   ArgBackRefMap OuterArgsContext;
769   BackRefMap OuterTemplateContext;
770   NameBackReferences.swap(OuterTemplateContext);
771   TypeBackReferences.swap(OuterArgsContext);
772 
773   mangleUnscopedTemplateName(TD);
774   mangleTemplateArgs(TD, TemplateArgs);
775 
776   // Restore the previous back reference contexts.
777   NameBackReferences.swap(OuterTemplateContext);
778   TypeBackReferences.swap(OuterArgsContext);
779 }
780 
781 void
782 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
783   // <unscoped-template-name> ::= ?$ <unqualified-name>
784   Out << "?$";
785   mangleUnqualifiedName(TD);
786 }
787 
788 void
789 MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
790                                               bool IsBoolean) {
791   // <integer-literal> ::= $0 <number>
792   Out << "$0";
793   // Make sure booleans are encoded as 0/1.
794   if (IsBoolean && Value.getBoolValue())
795     mangleNumber(1);
796   else
797     mangleNumber(Value);
798 }
799 
800 void
801 MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
802   // See if this is a constant expression.
803   llvm::APSInt Value;
804   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
805     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
806     return;
807   }
808 
809   // As bad as this diagnostic is, it's better than crashing.
810   DiagnosticsEngine &Diags = Context.getDiags();
811   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
812                                    "cannot yet mangle expression type %0");
813   Diags.Report(E->getExprLoc(), DiagID)
814     << E->getStmtClassName() << E->getSourceRange();
815 }
816 
817 void
818 MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateDecl *TD,
819                                      const TemplateArgumentList &TemplateArgs) {
820   // <template-args> ::= {<type> | <integer-literal>}+ @
821   unsigned NumTemplateArgs = TemplateArgs.size();
822   for (unsigned i = 0; i < NumTemplateArgs; ++i) {
823     const TemplateArgument &TA = TemplateArgs[i];
824     switch (TA.getKind()) {
825     case TemplateArgument::Null:
826       llvm_unreachable("Can't mangle null template arguments!");
827     case TemplateArgument::Type:
828       mangleType(TA.getAsType(), SourceRange());
829       break;
830     case TemplateArgument::Declaration:
831       mangle(cast<NamedDecl>(TA.getAsDecl()), "$1?");
832       break;
833     case TemplateArgument::Integral:
834       mangleIntegerLiteral(TA.getAsIntegral(),
835                            TA.getIntegralType()->isBooleanType());
836       break;
837     case TemplateArgument::Expression:
838       mangleExpression(TA.getAsExpr());
839       break;
840     case TemplateArgument::Template:
841     case TemplateArgument::TemplateExpansion:
842     case TemplateArgument::NullPtr:
843     case TemplateArgument::Pack: {
844       // Issue a diagnostic.
845       DiagnosticsEngine &Diags = Context.getDiags();
846       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
847         "cannot mangle template argument %0 of kind %select{ERROR|ERROR|"
848         "pointer/reference|nullptr|integral|template|template pack expansion|"
849         "ERROR|parameter pack}1 yet");
850       Diags.Report(TD->getLocation(), DiagID)
851         << i + 1
852         << TA.getKind()
853         << TD->getSourceRange();
854     }
855     }
856   }
857   Out << '@';
858 }
859 
860 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
861                                                bool IsMember) {
862   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
863   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
864   // 'I' means __restrict (32/64-bit).
865   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
866   // keyword!
867   // <base-cvr-qualifiers> ::= A  # near
868   //                       ::= B  # near const
869   //                       ::= C  # near volatile
870   //                       ::= D  # near const volatile
871   //                       ::= E  # far (16-bit)
872   //                       ::= F  # far const (16-bit)
873   //                       ::= G  # far volatile (16-bit)
874   //                       ::= H  # far const volatile (16-bit)
875   //                       ::= I  # huge (16-bit)
876   //                       ::= J  # huge const (16-bit)
877   //                       ::= K  # huge volatile (16-bit)
878   //                       ::= L  # huge const volatile (16-bit)
879   //                       ::= M <basis> # based
880   //                       ::= N <basis> # based const
881   //                       ::= O <basis> # based volatile
882   //                       ::= P <basis> # based const volatile
883   //                       ::= Q  # near member
884   //                       ::= R  # near const member
885   //                       ::= S  # near volatile member
886   //                       ::= T  # near const volatile member
887   //                       ::= U  # far member (16-bit)
888   //                       ::= V  # far const member (16-bit)
889   //                       ::= W  # far volatile member (16-bit)
890   //                       ::= X  # far const volatile member (16-bit)
891   //                       ::= Y  # huge member (16-bit)
892   //                       ::= Z  # huge const member (16-bit)
893   //                       ::= 0  # huge volatile member (16-bit)
894   //                       ::= 1  # huge const volatile member (16-bit)
895   //                       ::= 2 <basis> # based member
896   //                       ::= 3 <basis> # based const member
897   //                       ::= 4 <basis> # based volatile member
898   //                       ::= 5 <basis> # based const volatile member
899   //                       ::= 6  # near function (pointers only)
900   //                       ::= 7  # far function (pointers only)
901   //                       ::= 8  # near method (pointers only)
902   //                       ::= 9  # far method (pointers only)
903   //                       ::= _A <basis> # based function (pointers only)
904   //                       ::= _B <basis> # based function (far?) (pointers only)
905   //                       ::= _C <basis> # based method (pointers only)
906   //                       ::= _D <basis> # based method (far?) (pointers only)
907   //                       ::= _E # block (Clang)
908   // <basis> ::= 0 # __based(void)
909   //         ::= 1 # __based(segment)?
910   //         ::= 2 <name> # __based(name)
911   //         ::= 3 # ?
912   //         ::= 4 # ?
913   //         ::= 5 # not really based
914   bool HasConst = Quals.hasConst(),
915        HasVolatile = Quals.hasVolatile();
916   if (!IsMember) {
917     if (HasConst && HasVolatile) {
918       Out << 'D';
919     } else if (HasVolatile) {
920       Out << 'C';
921     } else if (HasConst) {
922       Out << 'B';
923     } else {
924       Out << 'A';
925     }
926   } else {
927     if (HasConst && HasVolatile) {
928       Out << 'T';
929     } else if (HasVolatile) {
930       Out << 'S';
931     } else if (HasConst) {
932       Out << 'R';
933     } else {
934       Out << 'Q';
935     }
936   }
937 
938   // FIXME: For now, just drop all extension qualifiers on the floor.
939 }
940 
941 void MicrosoftCXXNameMangler::manglePointerQualifiers(Qualifiers Quals) {
942   // <pointer-cvr-qualifiers> ::= P  # no qualifiers
943   //                          ::= Q  # const
944   //                          ::= R  # volatile
945   //                          ::= S  # const volatile
946   bool HasConst = Quals.hasConst(),
947        HasVolatile = Quals.hasVolatile();
948   if (HasConst && HasVolatile) {
949     Out << 'S';
950   } else if (HasVolatile) {
951     Out << 'R';
952   } else if (HasConst) {
953     Out << 'Q';
954   } else {
955     Out << 'P';
956   }
957 }
958 
959 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
960                                                  SourceRange Range) {
961   void *TypePtr = getASTContext().getCanonicalType(T).getAsOpaquePtr();
962   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
963 
964   if (Found == TypeBackReferences.end()) {
965     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
966 
967     mangleType(T, Range, false);
968 
969     // See if it's worth creating a back reference.
970     // Only types longer than 1 character are considered
971     // and only 10 back references slots are available:
972     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
973     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
974       size_t Size = TypeBackReferences.size();
975       TypeBackReferences[TypePtr] = Size;
976     }
977   } else {
978     Out << Found->second;
979   }
980 }
981 
982 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
983                                          bool MangleQualifiers) {
984   // Only operate on the canonical type!
985   T = getASTContext().getCanonicalType(T);
986 
987   Qualifiers Quals = T.getLocalQualifiers();
988   // We have to mangle these now, while we still have enough information.
989   if (T->isAnyPointerType() || T->isMemberPointerType() ||
990       T->isBlockPointerType()) {
991     manglePointerQualifiers(Quals);
992   } else if (Quals && MangleQualifiers) {
993     mangleQualifiers(Quals, false);
994   }
995 
996   SplitQualType split = T.split();
997   const Type *ty = split.Ty;
998 
999   // If we're mangling a qualified array type, push the qualifiers to
1000   // the element type.
1001   if (split.Quals && isa<ArrayType>(T)) {
1002     ty = Context.getASTContext().getAsArrayType(T);
1003   }
1004 
1005   switch (ty->getTypeClass()) {
1006 #define ABSTRACT_TYPE(CLASS, PARENT)
1007 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1008   case Type::CLASS: \
1009     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1010     return;
1011 #define TYPE(CLASS, PARENT) \
1012   case Type::CLASS: \
1013     mangleType(cast<CLASS##Type>(ty), Range); \
1014     break;
1015 #include "clang/AST/TypeNodes.def"
1016 #undef ABSTRACT_TYPE
1017 #undef NON_CANONICAL_TYPE
1018 #undef TYPE
1019   }
1020 }
1021 
1022 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1023                                          SourceRange Range) {
1024   //  <type>         ::= <builtin-type>
1025   //  <builtin-type> ::= X  # void
1026   //                 ::= C  # signed char
1027   //                 ::= D  # char
1028   //                 ::= E  # unsigned char
1029   //                 ::= F  # short
1030   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1031   //                 ::= H  # int
1032   //                 ::= I  # unsigned int
1033   //                 ::= J  # long
1034   //                 ::= K  # unsigned long
1035   //                     L  # <none>
1036   //                 ::= M  # float
1037   //                 ::= N  # double
1038   //                 ::= O  # long double (__float80 is mangled differently)
1039   //                 ::= _J # long long, __int64
1040   //                 ::= _K # unsigned long long, __int64
1041   //                 ::= _L # __int128
1042   //                 ::= _M # unsigned __int128
1043   //                 ::= _N # bool
1044   //                     _O # <array in parameter>
1045   //                 ::= _T # __float80 (Intel)
1046   //                 ::= _W # wchar_t
1047   //                 ::= _Z # __float80 (Digital Mars)
1048   switch (T->getKind()) {
1049   case BuiltinType::Void: Out << 'X'; break;
1050   case BuiltinType::SChar: Out << 'C'; break;
1051   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1052   case BuiltinType::UChar: Out << 'E'; break;
1053   case BuiltinType::Short: Out << 'F'; break;
1054   case BuiltinType::UShort: Out << 'G'; break;
1055   case BuiltinType::Int: Out << 'H'; break;
1056   case BuiltinType::UInt: Out << 'I'; break;
1057   case BuiltinType::Long: Out << 'J'; break;
1058   case BuiltinType::ULong: Out << 'K'; break;
1059   case BuiltinType::Float: Out << 'M'; break;
1060   case BuiltinType::Double: Out << 'N'; break;
1061   // TODO: Determine size and mangle accordingly
1062   case BuiltinType::LongDouble: Out << 'O'; break;
1063   case BuiltinType::LongLong: Out << "_J"; break;
1064   case BuiltinType::ULongLong: Out << "_K"; break;
1065   case BuiltinType::Int128: Out << "_L"; break;
1066   case BuiltinType::UInt128: Out << "_M"; break;
1067   case BuiltinType::Bool: Out << "_N"; break;
1068   case BuiltinType::WChar_S:
1069   case BuiltinType::WChar_U: Out << "_W"; break;
1070 
1071 #define BUILTIN_TYPE(Id, SingletonId)
1072 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1073   case BuiltinType::Id:
1074 #include "clang/AST/BuiltinTypes.def"
1075   case BuiltinType::Dependent:
1076     llvm_unreachable("placeholder types shouldn't get to name mangling");
1077 
1078   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1079   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1080   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1081 
1082   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1083   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1084   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1085   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1086   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1087   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1088   case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1089   case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1090 
1091   case BuiltinType::NullPtr: Out << "$$T"; break;
1092 
1093   case BuiltinType::Char16:
1094   case BuiltinType::Char32:
1095   case BuiltinType::Half: {
1096     DiagnosticsEngine &Diags = Context.getDiags();
1097     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1098       "cannot mangle this built-in %0 type yet");
1099     Diags.Report(Range.getBegin(), DiagID)
1100       << T->getName(Context.getASTContext().getPrintingPolicy())
1101       << Range;
1102     break;
1103   }
1104   }
1105 }
1106 
1107 // <type>          ::= <function-type>
1108 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1109                                          SourceRange) {
1110   // Structors only appear in decls, so at this point we know it's not a
1111   // structor type.
1112   // FIXME: This may not be lambda-friendly.
1113   Out << "$$A6";
1114   mangleType(T, NULL, false, false);
1115 }
1116 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1117                                          SourceRange) {
1118   llvm_unreachable("Can't mangle K&R function prototypes");
1119 }
1120 
1121 void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
1122                                          const FunctionDecl *D,
1123                                          bool IsStructor,
1124                                          bool IsInstMethod) {
1125   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1126   //                     <return-type> <argument-list> <throw-spec>
1127   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1128 
1129   // If this is a C++ instance method, mangle the CVR qualifiers for the
1130   // this pointer.
1131   if (IsInstMethod)
1132     mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
1133 
1134   mangleCallingConvention(T, IsInstMethod);
1135 
1136   // <return-type> ::= <type>
1137   //               ::= @ # structors (they have no declared return type)
1138   if (IsStructor) {
1139     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1140         StructorType == Dtor_Deleting) {
1141       // The scalar deleting destructor takes an extra int argument.
1142       // However, the FunctionType generated has 0 arguments.
1143       // FIXME: This is a temporary hack.
1144       // Maybe should fix the FunctionType creation instead?
1145       Out << "PAXI@Z";
1146       return;
1147     }
1148     Out << '@';
1149   } else {
1150     QualType Result = Proto->getResultType();
1151     const Type* RT = Result.getTypePtr();
1152     if (!RT->isAnyPointerType() && !RT->isReferenceType()) {
1153       if (Result.hasQualifiers() || !RT->isBuiltinType())
1154         Out << '?';
1155       if (!RT->isBuiltinType() && !Result.hasQualifiers()) {
1156         // Lack of qualifiers for user types is mangled as 'A'.
1157         Out << 'A';
1158       }
1159     }
1160 
1161     // FIXME: Get the source range for the result type. Or, better yet,
1162     // implement the unimplemented stuff so we don't need accurate source
1163     // location info anymore :).
1164     mangleType(Result, SourceRange());
1165   }
1166 
1167   // <argument-list> ::= X # void
1168   //                 ::= <type>+ @
1169   //                 ::= <type>* Z # varargs
1170   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1171     Out << 'X';
1172   } else {
1173     if (D) {
1174       // If we got a decl, use the type-as-written to make sure arrays
1175       // get mangled right.  Note that we can't rely on the TSI
1176       // existing if (for example) the parameter was synthesized.
1177       for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
1178              ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
1179         TypeSourceInfo *TSI = (*Parm)->getTypeSourceInfo();
1180         QualType Type = TSI ? TSI->getType() : (*Parm)->getType();
1181         mangleArgumentType(Type, (*Parm)->getSourceRange());
1182       }
1183     } else {
1184       // Happens for function pointer type arguments for example.
1185       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1186            ArgEnd = Proto->arg_type_end();
1187            Arg != ArgEnd; ++Arg)
1188         mangleArgumentType(*Arg, SourceRange());
1189     }
1190     // <builtin-type>      ::= Z  # ellipsis
1191     if (Proto->isVariadic())
1192       Out << 'Z';
1193     else
1194       Out << '@';
1195   }
1196 
1197   mangleThrowSpecification(Proto);
1198 }
1199 
1200 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1201   // <function-class> ::= A # private: near
1202   //                  ::= B # private: far
1203   //                  ::= C # private: static near
1204   //                  ::= D # private: static far
1205   //                  ::= E # private: virtual near
1206   //                  ::= F # private: virtual far
1207   //                  ::= G # private: thunk near
1208   //                  ::= H # private: thunk far
1209   //                  ::= I # protected: near
1210   //                  ::= J # protected: far
1211   //                  ::= K # protected: static near
1212   //                  ::= L # protected: static far
1213   //                  ::= M # protected: virtual near
1214   //                  ::= N # protected: virtual far
1215   //                  ::= O # protected: thunk near
1216   //                  ::= P # protected: thunk far
1217   //                  ::= Q # public: near
1218   //                  ::= R # public: far
1219   //                  ::= S # public: static near
1220   //                  ::= T # public: static far
1221   //                  ::= U # public: virtual near
1222   //                  ::= V # public: virtual far
1223   //                  ::= W # public: thunk near
1224   //                  ::= X # public: thunk far
1225   //                  ::= Y # global near
1226   //                  ::= Z # global far
1227   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1228     switch (MD->getAccess()) {
1229       default:
1230       case AS_private:
1231         if (MD->isStatic())
1232           Out << 'C';
1233         else if (MD->isVirtual())
1234           Out << 'E';
1235         else
1236           Out << 'A';
1237         break;
1238       case AS_protected:
1239         if (MD->isStatic())
1240           Out << 'K';
1241         else if (MD->isVirtual())
1242           Out << 'M';
1243         else
1244           Out << 'I';
1245         break;
1246       case AS_public:
1247         if (MD->isStatic())
1248           Out << 'S';
1249         else if (MD->isVirtual())
1250           Out << 'U';
1251         else
1252           Out << 'Q';
1253     }
1254   } else
1255     Out << 'Y';
1256 }
1257 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
1258                                                       bool IsInstMethod) {
1259   // <calling-convention> ::= A # __cdecl
1260   //                      ::= B # __export __cdecl
1261   //                      ::= C # __pascal
1262   //                      ::= D # __export __pascal
1263   //                      ::= E # __thiscall
1264   //                      ::= F # __export __thiscall
1265   //                      ::= G # __stdcall
1266   //                      ::= H # __export __stdcall
1267   //                      ::= I # __fastcall
1268   //                      ::= J # __export __fastcall
1269   // The 'export' calling conventions are from a bygone era
1270   // (*cough*Win16*cough*) when functions were declared for export with
1271   // that keyword. (It didn't actually export them, it just made them so
1272   // that they could be in a DLL and somebody from another module could call
1273   // them.)
1274   CallingConv CC = T->getCallConv();
1275   if (CC == CC_Default) {
1276     if (IsInstMethod) {
1277       const FunctionProtoType *FPT =
1278         T->getCanonicalTypeUnqualified().castAs<FunctionProtoType>();
1279       bool isVariadic = FPT->isVariadic();
1280       CC = getASTContext().getDefaultCXXMethodCallConv(isVariadic);
1281     } else {
1282       CC = CC_C;
1283     }
1284   }
1285   switch (CC) {
1286     default:
1287       llvm_unreachable("Unsupported CC for mangling");
1288     case CC_Default:
1289     case CC_C: Out << 'A'; break;
1290     case CC_X86Pascal: Out << 'C'; break;
1291     case CC_X86ThisCall: Out << 'E'; break;
1292     case CC_X86StdCall: Out << 'G'; break;
1293     case CC_X86FastCall: Out << 'I'; break;
1294   }
1295 }
1296 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1297                                                 const FunctionProtoType *FT) {
1298   // <throw-spec> ::= Z # throw(...) (default)
1299   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1300   //              ::= <type>+
1301   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1302   // all actually mangled as 'Z'. (They're ignored because their associated
1303   // functionality isn't implemented, and probably never will be.)
1304   Out << 'Z';
1305 }
1306 
1307 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1308                                          SourceRange Range) {
1309   // Probably should be mangled as a template instantiation; need to see what
1310   // VC does first.
1311   DiagnosticsEngine &Diags = Context.getDiags();
1312   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1313     "cannot mangle this unresolved dependent type yet");
1314   Diags.Report(Range.getBegin(), DiagID)
1315     << Range;
1316 }
1317 
1318 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1319 // <union-type>  ::= T <name>
1320 // <struct-type> ::= U <name>
1321 // <class-type>  ::= V <name>
1322 // <enum-type>   ::= W <size> <name>
1323 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1324   mangleType(cast<TagType>(T));
1325 }
1326 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1327   mangleType(cast<TagType>(T));
1328 }
1329 void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
1330   switch (T->getDecl()->getTagKind()) {
1331     case TTK_Union:
1332       Out << 'T';
1333       break;
1334     case TTK_Struct:
1335     case TTK_Interface:
1336       Out << 'U';
1337       break;
1338     case TTK_Class:
1339       Out << 'V';
1340       break;
1341     case TTK_Enum:
1342       Out << 'W';
1343       Out << getASTContext().getTypeSizeInChars(
1344                 cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
1345       break;
1346   }
1347   mangleName(T->getDecl());
1348 }
1349 
1350 // <type>       ::= <array-type>
1351 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1352 //                  [Y <dimension-count> <dimension>+]
1353 //                  <element-type> # as global
1354 //              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1355 //                  <element-type> # as param
1356 // It's supposed to be the other way around, but for some strange reason, it
1357 // isn't. Today this behavior is retained for the sole purpose of backwards
1358 // compatibility.
1359 void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
1360   // This isn't a recursive mangling, so now we have to do it all in this
1361   // one call.
1362   if (IsGlobal) {
1363     manglePointerQualifiers(T->getElementType().getQualifiers());
1364   } else {
1365     Out << 'Q';
1366   }
1367   mangleExtraDimensions(T->getElementType());
1368 }
1369 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1370                                          SourceRange) {
1371   mangleType(cast<ArrayType>(T), false);
1372 }
1373 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1374                                          SourceRange) {
1375   mangleType(cast<ArrayType>(T), false);
1376 }
1377 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1378                                          SourceRange) {
1379   mangleType(cast<ArrayType>(T), false);
1380 }
1381 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1382                                          SourceRange) {
1383   mangleType(cast<ArrayType>(T), false);
1384 }
1385 void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
1386   SmallVector<llvm::APInt, 3> Dimensions;
1387   for (;;) {
1388     if (const ConstantArrayType *CAT =
1389           getASTContext().getAsConstantArrayType(ElementTy)) {
1390       Dimensions.push_back(CAT->getSize());
1391       ElementTy = CAT->getElementType();
1392     } else if (ElementTy->isVariableArrayType()) {
1393       const VariableArrayType *VAT =
1394         getASTContext().getAsVariableArrayType(ElementTy);
1395       DiagnosticsEngine &Diags = Context.getDiags();
1396       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1397         "cannot mangle this variable-length array yet");
1398       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1399         << VAT->getBracketsRange();
1400       return;
1401     } else if (ElementTy->isDependentSizedArrayType()) {
1402       // The dependent expression has to be folded into a constant (TODO).
1403       const DependentSizedArrayType *DSAT =
1404         getASTContext().getAsDependentSizedArrayType(ElementTy);
1405       DiagnosticsEngine &Diags = Context.getDiags();
1406       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1407         "cannot mangle this dependent-length array yet");
1408       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1409         << DSAT->getBracketsRange();
1410       return;
1411     } else if (ElementTy->isIncompleteArrayType()) continue;
1412     else break;
1413   }
1414   mangleQualifiers(ElementTy.getQualifiers(), false);
1415   // If there are any additional dimensions, mangle them now.
1416   if (Dimensions.size() > 0) {
1417     Out << 'Y';
1418     // <dimension-count> ::= <number> # number of extra dimensions
1419     mangleNumber(Dimensions.size());
1420     for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
1421       mangleNumber(Dimensions[Dim].getLimitedValue());
1422     }
1423   }
1424   mangleType(ElementTy.getLocalUnqualifiedType(), SourceRange());
1425 }
1426 
1427 // <type>                   ::= <pointer-to-member-type>
1428 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1429 //                                                          <class name> <type>
1430 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1431                                          SourceRange Range) {
1432   QualType PointeeType = T->getPointeeType();
1433   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1434     Out << '8';
1435     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1436     mangleType(FPT, NULL, false, true);
1437   } else {
1438     mangleQualifiers(PointeeType.getQualifiers(), true);
1439     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1440     mangleType(PointeeType.getLocalUnqualifiedType(), Range);
1441   }
1442 }
1443 
1444 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1445                                          SourceRange Range) {
1446   DiagnosticsEngine &Diags = Context.getDiags();
1447   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1448     "cannot mangle this template type parameter type yet");
1449   Diags.Report(Range.getBegin(), DiagID)
1450     << Range;
1451 }
1452 
1453 void MicrosoftCXXNameMangler::mangleType(
1454                                        const SubstTemplateTypeParmPackType *T,
1455                                        SourceRange Range) {
1456   DiagnosticsEngine &Diags = Context.getDiags();
1457   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1458     "cannot mangle this substituted parameter pack yet");
1459   Diags.Report(Range.getBegin(), DiagID)
1460     << Range;
1461 }
1462 
1463 // <type> ::= <pointer-type>
1464 // <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1465 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1466                                          SourceRange Range) {
1467   QualType PointeeTy = T->getPointeeType();
1468   if (PointeeTy->isArrayType()) {
1469     // Pointers to arrays are mangled like arrays.
1470     mangleExtraDimensions(PointeeTy);
1471   } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
1472     // Function pointers are special.
1473     Out << '6';
1474     mangleType(FT, NULL, false, false);
1475   } else {
1476     mangleQualifiers(PointeeTy.getQualifiers(), false);
1477     mangleType(PointeeTy, Range, false);
1478   }
1479 }
1480 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1481                                          SourceRange Range) {
1482   // Object pointers never have qualifiers.
1483   Out << 'A';
1484   mangleType(T->getPointeeType(), Range);
1485 }
1486 
1487 // <type> ::= <reference-type>
1488 // <reference-type> ::= A <cvr-qualifiers> <type>
1489 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1490                                          SourceRange Range) {
1491   Out << 'A';
1492   QualType PointeeTy = T->getPointeeType();
1493   if (!PointeeTy.hasQualifiers())
1494     // Lack of qualifiers is mangled as 'A'.
1495     Out << 'A';
1496   mangleType(PointeeTy, Range);
1497 }
1498 
1499 // <type> ::= <r-value-reference-type>
1500 // <r-value-reference-type> ::= $$Q <cvr-qualifiers> <type>
1501 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1502                                          SourceRange Range) {
1503   Out << "$$Q";
1504   QualType PointeeTy = T->getPointeeType();
1505   if (!PointeeTy.hasQualifiers())
1506     // Lack of qualifiers is mangled as 'A'.
1507     Out << 'A';
1508   mangleType(PointeeTy, Range);
1509 }
1510 
1511 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1512                                          SourceRange Range) {
1513   DiagnosticsEngine &Diags = Context.getDiags();
1514   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1515     "cannot mangle this complex number type yet");
1516   Diags.Report(Range.getBegin(), DiagID)
1517     << Range;
1518 }
1519 
1520 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1521                                          SourceRange Range) {
1522   DiagnosticsEngine &Diags = Context.getDiags();
1523   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1524     "cannot mangle this vector type yet");
1525   Diags.Report(Range.getBegin(), DiagID)
1526     << Range;
1527 }
1528 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1529                                          SourceRange Range) {
1530   DiagnosticsEngine &Diags = Context.getDiags();
1531   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1532     "cannot mangle this extended vector type yet");
1533   Diags.Report(Range.getBegin(), DiagID)
1534     << Range;
1535 }
1536 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1537                                          SourceRange Range) {
1538   DiagnosticsEngine &Diags = Context.getDiags();
1539   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1540     "cannot mangle this dependent-sized extended vector type yet");
1541   Diags.Report(Range.getBegin(), DiagID)
1542     << Range;
1543 }
1544 
1545 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1546                                          SourceRange) {
1547   // ObjC interfaces have structs underlying them.
1548   Out << 'U';
1549   mangleName(T->getDecl());
1550 }
1551 
1552 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1553                                          SourceRange Range) {
1554   // We don't allow overloading by different protocol qualification,
1555   // so mangling them isn't necessary.
1556   mangleType(T->getBaseType(), Range);
1557 }
1558 
1559 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1560                                          SourceRange Range) {
1561   Out << "_E";
1562 
1563   QualType pointee = T->getPointeeType();
1564   mangleType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
1565 }
1566 
1567 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T,
1568                                          SourceRange Range) {
1569   DiagnosticsEngine &Diags = Context.getDiags();
1570   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1571     "cannot mangle this injected class name type yet");
1572   Diags.Report(Range.getBegin(), DiagID)
1573     << Range;
1574 }
1575 
1576 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1577                                          SourceRange Range) {
1578   DiagnosticsEngine &Diags = Context.getDiags();
1579   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1580     "cannot mangle this template specialization type yet");
1581   Diags.Report(Range.getBegin(), DiagID)
1582     << Range;
1583 }
1584 
1585 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1586                                          SourceRange Range) {
1587   DiagnosticsEngine &Diags = Context.getDiags();
1588   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1589     "cannot mangle this dependent name type yet");
1590   Diags.Report(Range.getBegin(), DiagID)
1591     << Range;
1592 }
1593 
1594 void MicrosoftCXXNameMangler::mangleType(
1595                                  const DependentTemplateSpecializationType *T,
1596                                  SourceRange Range) {
1597   DiagnosticsEngine &Diags = Context.getDiags();
1598   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1599     "cannot mangle this dependent template specialization type yet");
1600   Diags.Report(Range.getBegin(), DiagID)
1601     << Range;
1602 }
1603 
1604 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1605                                          SourceRange Range) {
1606   DiagnosticsEngine &Diags = Context.getDiags();
1607   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1608     "cannot mangle this pack expansion yet");
1609   Diags.Report(Range.getBegin(), DiagID)
1610     << Range;
1611 }
1612 
1613 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1614                                          SourceRange Range) {
1615   DiagnosticsEngine &Diags = Context.getDiags();
1616   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1617     "cannot mangle this typeof(type) yet");
1618   Diags.Report(Range.getBegin(), DiagID)
1619     << Range;
1620 }
1621 
1622 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1623                                          SourceRange Range) {
1624   DiagnosticsEngine &Diags = Context.getDiags();
1625   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1626     "cannot mangle this typeof(expression) yet");
1627   Diags.Report(Range.getBegin(), DiagID)
1628     << Range;
1629 }
1630 
1631 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1632                                          SourceRange Range) {
1633   DiagnosticsEngine &Diags = Context.getDiags();
1634   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1635     "cannot mangle this decltype() yet");
1636   Diags.Report(Range.getBegin(), DiagID)
1637     << Range;
1638 }
1639 
1640 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
1641                                          SourceRange Range) {
1642   DiagnosticsEngine &Diags = Context.getDiags();
1643   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1644     "cannot mangle this unary transform type yet");
1645   Diags.Report(Range.getBegin(), DiagID)
1646     << Range;
1647 }
1648 
1649 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
1650   DiagnosticsEngine &Diags = Context.getDiags();
1651   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1652     "cannot mangle this 'auto' type yet");
1653   Diags.Report(Range.getBegin(), DiagID)
1654     << Range;
1655 }
1656 
1657 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
1658                                          SourceRange Range) {
1659   DiagnosticsEngine &Diags = Context.getDiags();
1660   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1661     "cannot mangle this C11 atomic type yet");
1662   Diags.Report(Range.getBegin(), DiagID)
1663     << Range;
1664 }
1665 
1666 void MicrosoftMangleContext::mangleName(const NamedDecl *D,
1667                                         raw_ostream &Out) {
1668   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1669          "Invalid mangleName() call, argument is not a variable or function!");
1670   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1671          "Invalid mangleName() call on 'structor decl!");
1672 
1673   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
1674                                  getASTContext().getSourceManager(),
1675                                  "Mangling declaration");
1676 
1677   MicrosoftCXXNameMangler Mangler(*this, Out);
1678   return Mangler.mangle(D);
1679 }
1680 void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
1681                                          const ThunkInfo &Thunk,
1682                                          raw_ostream &) {
1683   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1684     "cannot mangle thunk for this method yet");
1685   getDiags().Report(MD->getLocation(), DiagID);
1686 }
1687 void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
1688                                                 CXXDtorType Type,
1689                                                 const ThisAdjustment &,
1690                                                 raw_ostream &) {
1691   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1692     "cannot mangle thunk for this destructor yet");
1693   getDiags().Report(DD->getLocation(), DiagID);
1694 }
1695 void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
1696                                              raw_ostream &Out) {
1697   // <mangled-name> ::= ? <operator-name> <class-name> <storage-class>
1698   //                      <cvr-qualifiers> [<name>] @
1699   // <operator-name> ::= _7 # vftable
1700   //                 ::= _8 # vbtable
1701   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
1702   // is always '6' for vftables and '7' for vbtables. (The difference is
1703   // beyond me.)
1704   // TODO: vbtables.
1705   MicrosoftCXXNameMangler Mangler(*this, Out);
1706   Mangler.getStream() << "\01??_7";
1707   Mangler.mangleName(RD);
1708   Mangler.getStream() << "6B";
1709   // TODO: If the class has more than one vtable, mangle in the class it came
1710   // from.
1711   Mangler.getStream() << '@';
1712 }
1713 void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
1714                                           raw_ostream &) {
1715   llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
1716 }
1717 void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
1718                                                  int64_t Offset,
1719                                                  const CXXRecordDecl *Type,
1720                                                  raw_ostream &) {
1721   llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
1722 }
1723 void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
1724                                            raw_ostream &) {
1725   // FIXME: Give a location...
1726   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1727     "cannot mangle RTTI descriptors for type %0 yet");
1728   getDiags().Report(DiagID)
1729     << T.getBaseTypeIdentifier();
1730 }
1731 void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
1732                                                raw_ostream &) {
1733   // FIXME: Give a location...
1734   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1735     "cannot mangle the name of type %0 into RTTI descriptors yet");
1736   getDiags().Report(DiagID)
1737     << T.getBaseTypeIdentifier();
1738 }
1739 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
1740                                            CXXCtorType Type,
1741                                            raw_ostream & Out) {
1742   MicrosoftCXXNameMangler mangler(*this, Out);
1743   mangler.mangle(D);
1744 }
1745 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
1746                                            CXXDtorType Type,
1747                                            raw_ostream & Out) {
1748   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
1749   mangler.mangle(D);
1750 }
1751 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *VD,
1752                                                       raw_ostream &) {
1753   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1754     "cannot mangle this reference temporary yet");
1755   getDiags().Report(VD->getLocation(), DiagID);
1756 }
1757 
1758 MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
1759                                                    DiagnosticsEngine &Diags) {
1760   return new MicrosoftMangleContext(Context, Diags);
1761 }
1762