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/CharUnits.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/Basic/ABI.h"
23 
24 using namespace clang;
25 
26 namespace {
27 
28 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
29 /// Microsoft Visual C++ ABI.
30 class MicrosoftCXXNameMangler {
31   MangleContext &Context;
32   raw_ostream &Out;
33 
34   ASTContext &getASTContext() const { return Context.getASTContext(); }
35 
36 public:
37   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
38   : Context(C), Out(Out_) { }
39 
40   void mangle(const NamedDecl *D, StringRef Prefix = "?");
41   void mangleName(const NamedDecl *ND);
42   void mangleFunctionEncoding(const FunctionDecl *FD);
43   void mangleVariableEncoding(const VarDecl *VD);
44   void mangleNumber(int64_t Number);
45   void mangleNumber(const llvm::APSInt &Value);
46   void mangleType(QualType T);
47 
48 private:
49   void mangleUnqualifiedName(const NamedDecl *ND) {
50     mangleUnqualifiedName(ND, ND->getDeclName());
51   }
52   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
53   void mangleSourceName(const IdentifierInfo *II);
54   void manglePostfix(const DeclContext *DC, bool NoFunction=false);
55   void mangleOperatorName(OverloadedOperatorKind OO);
56   void mangleQualifiers(Qualifiers Quals, bool IsMember);
57 
58   void mangleUnscopedTemplateName(const TemplateDecl *ND);
59   void mangleTemplateInstantiationName(const TemplateDecl *TD,
60                                        const TemplateArgument *TemplateArgs,
61                                        unsigned NumTemplateArgs,
62                                        SourceLocation InstantiationLoc);
63   void mangleObjCMethodName(const ObjCMethodDecl *MD);
64 
65   // Declare manglers for every type class.
66 #define ABSTRACT_TYPE(CLASS, PARENT)
67 #define NON_CANONICAL_TYPE(CLASS, PARENT)
68 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
69 #include "clang/AST/TypeNodes.def"
70 
71   void mangleType(const TagType*);
72   void mangleType(const FunctionType *T, const FunctionDecl *D,
73                   bool IsStructor, bool IsInstMethod);
74   void mangleType(const ArrayType *T, bool IsGlobal);
75   void mangleExtraDimensions(QualType T);
76   void mangleFunctionClass(const FunctionDecl *FD);
77   void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
78   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Number);
79   void mangleThrowSpecification(const FunctionProtoType *T);
80 
81   void mangleTemplateArgs(const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs,
82                           SourceLocation InstantiationLoc);
83 
84 };
85 
86 /// MicrosoftMangleContext - Overrides the default MangleContext for the
87 /// Microsoft Visual C++ ABI.
88 class MicrosoftMangleContext : public MangleContext {
89 public:
90   MicrosoftMangleContext(ASTContext &Context,
91                    DiagnosticsEngine &Diags) : MangleContext(Context, Diags) { }
92   virtual bool shouldMangleDeclName(const NamedDecl *D);
93   virtual void mangleName(const NamedDecl *D, raw_ostream &Out);
94   virtual void mangleThunk(const CXXMethodDecl *MD,
95                            const ThunkInfo &Thunk,
96                            raw_ostream &);
97   virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
98                                   const ThisAdjustment &ThisAdjustment,
99                                   raw_ostream &);
100   virtual void mangleCXXVTable(const CXXRecordDecl *RD,
101                                raw_ostream &);
102   virtual void mangleCXXVTT(const CXXRecordDecl *RD,
103                             raw_ostream &);
104   virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
105                                    const CXXRecordDecl *Type,
106                                    raw_ostream &);
107   virtual void mangleCXXRTTI(QualType T, raw_ostream &);
108   virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
109   virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
110                              raw_ostream &);
111   virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
112                              raw_ostream &);
113   virtual void mangleReferenceTemporary(const clang::VarDecl *,
114                                         raw_ostream &);
115 };
116 
117 }
118 
119 static bool isInCLinkageSpecification(const Decl *D) {
120   D = D->getCanonicalDecl();
121   for (const DeclContext *DC = D->getDeclContext();
122        !DC->isTranslationUnit(); DC = DC->getParent()) {
123     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
124       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
125   }
126 
127   return false;
128 }
129 
130 bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
131   // In C, functions with no attributes never need to be mangled. Fastpath them.
132   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
133     return false;
134 
135   // Any decl can be declared with __asm("foo") on it, and this takes precedence
136   // over all other naming in the .o file.
137   if (D->hasAttr<AsmLabelAttr>())
138     return true;
139 
140   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
141   // (always) as does passing a C++ member function and a function
142   // whose name is not a simple identifier.
143   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
144   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
145              !FD->getDeclName().isIdentifier()))
146     return true;
147 
148   // Otherwise, no mangling is done outside C++ mode.
149   if (!getASTContext().getLangOpts().CPlusPlus)
150     return false;
151 
152   // Variables at global scope with internal linkage are not mangled.
153   if (!FD) {
154     const DeclContext *DC = D->getDeclContext();
155     if (DC->isTranslationUnit() && D->getLinkage() == InternalLinkage)
156       return false;
157   }
158 
159   // C functions and "main" are not mangled.
160   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
161     return false;
162 
163   return true;
164 }
165 
166 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
167                                      StringRef Prefix) {
168   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
169   // Therefore it's really important that we don't decorate the
170   // name with leading underscores or leading/trailing at signs. So, emit a
171   // asm marker at the start so we get the name right.
172   Out << '\01';  // LLVM IR Marker for __asm("foo")
173 
174   // Any decl can be declared with __asm("foo") on it, and this takes precedence
175   // over all other naming in the .o file.
176   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
177     // If we have an asm name, then we use it as the mangling.
178     Out << ALA->getLabel();
179     return;
180   }
181 
182   // <mangled-name> ::= ? <name> <type-encoding>
183   Out << Prefix;
184   mangleName(D);
185   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
186     mangleFunctionEncoding(FD);
187   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
188     mangleVariableEncoding(VD);
189   // TODO: Fields? Can MSVC even mangle them?
190 }
191 
192 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
193   // <type-encoding> ::= <function-class> <function-type>
194 
195   // Don't mangle in the type if this isn't a decl we should typically mangle.
196   if (!Context.shouldMangleDeclName(FD))
197     return;
198 
199   // We should never ever see a FunctionNoProtoType at this point.
200   // We don't even know how to mangle their types anyway :).
201   const FunctionProtoType *FT = cast<FunctionProtoType>(FD->getType());
202 
203   bool InStructor = false, InInstMethod = false;
204   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
205   if (MD) {
206     if (MD->isInstance())
207       InInstMethod = true;
208     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
209       InStructor = true;
210   }
211 
212   // First, the function class.
213   mangleFunctionClass(FD);
214 
215   mangleType(FT, FD, InStructor, InInstMethod);
216 }
217 
218 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
219   // <type-encoding> ::= <storage-class> <variable-type>
220   // <storage-class> ::= 0  # private static member
221   //                 ::= 1  # protected static member
222   //                 ::= 2  # public static member
223   //                 ::= 3  # global
224   //                 ::= 4  # static local
225 
226   // The first character in the encoding (after the name) is the storage class.
227   if (VD->isStaticDataMember()) {
228     // If it's a static member, it also encodes the access level.
229     switch (VD->getAccess()) {
230       default:
231       case AS_private: Out << '0'; break;
232       case AS_protected: Out << '1'; break;
233       case AS_public: Out << '2'; break;
234     }
235   }
236   else if (!VD->isStaticLocal())
237     Out << '3';
238   else
239     Out << '4';
240   // Now mangle the type.
241   // <variable-type> ::= <type> <cvr-qualifiers>
242   //                 ::= <type> A # pointers, references, arrays
243   // Pointers and references are odd. The type of 'int * const foo;' gets
244   // mangled as 'QAHA' instead of 'PAHB', for example.
245   QualType Ty = VD->getType();
246   if (Ty->isPointerType() || Ty->isReferenceType()) {
247     mangleType(Ty);
248     Out << 'A';
249   } else if (Ty->isArrayType()) {
250     // Global arrays are funny, too.
251     mangleType(cast<ArrayType>(Ty.getTypePtr()), true);
252     Out << 'A';
253   } else {
254     mangleType(Ty.getLocalUnqualifiedType());
255     mangleQualifiers(Ty.getLocalQualifiers(), false);
256   }
257 }
258 
259 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
260   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
261   const DeclContext *DC = ND->getDeclContext();
262 
263   // Always start with the unqualified name.
264   mangleUnqualifiedName(ND);
265 
266   // If this is an extern variable declared locally, the relevant DeclContext
267   // is that of the containing namespace, or the translation unit.
268   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
269     while (!DC->isNamespace() && !DC->isTranslationUnit())
270       DC = DC->getParent();
271 
272   manglePostfix(DC);
273 
274   // Terminate the whole name with an '@'.
275   Out << '@';
276 }
277 
278 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
279   // <number> ::= [?] <decimal digit> # 1 <= Number <= 10
280   //          ::= [?] <hex digit>+ @ # 0 or > 9; A = 0, B = 1, etc...
281   //          ::= [?] @ # 0 (alternate mangling, not emitted by VC)
282   if (Number < 0) {
283     Out << '?';
284     Number = -Number;
285   }
286   // Oddly enough, there's a special shorter mangling for 0, but Microsoft chose not
287   // to use it. Instead, 0 gets mangled as "A@". Oh well...
288   if (Number >= 1 && Number <= 10)
289     Out << Number-1;
290   else {
291     // We have to build up the encoding in reverse order, so it will come
292     // out right when we write it out.
293     char Encoding[16];
294     char *EndPtr = Encoding+sizeof(Encoding);
295     char *CurPtr = EndPtr;
296     do {
297       *--CurPtr = 'A' + (Number % 16);
298       Number /= 16;
299     } while (Number);
300     Out.write(CurPtr, EndPtr-CurPtr);
301     Out << '@';
302   }
303 }
304 
305 void MicrosoftCXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
306   if (Value.isSigned() && Value.isNegative()) {
307     Out << '?';
308     mangleNumber(llvm::APSInt(Value.abs()));
309     return;
310   }
311   if (Value.uge(1) && Value.ule(10))
312     (Value-llvm::APSInt(llvm::APInt(Value.getBitWidth(), 1, Value.isSigned()),
313                         Value.isUnsigned())).print(Out, false);
314   else {
315     // We have to build up the encoding in reverse order, so it will come
316     // out right when we write it out.
317     char Encoding[64];
318     char *EndPtr = Encoding+sizeof(Encoding);
319     char *CurPtr = EndPtr;
320     llvm::APSInt NibbleMask(Value.getBitWidth(), Value.isUnsigned());
321     NibbleMask = 0xf;
322     for (int i = 0, e = Value.getActiveBits() / 4; i != e; ++i) {
323       *--CurPtr = 'A' + Value.And(NibbleMask).lshr(i*4).getLimitedValue(0xf);
324       NibbleMask = NibbleMask.shl(4);
325     };
326     Out.write(CurPtr, EndPtr-CurPtr);
327     Out << '@';
328   }
329 }
330 
331 static const TemplateDecl *
332 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
333   // Check if we have a function template.
334   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
335     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
336       TemplateArgs = FD->getTemplateSpecializationArgs();
337       return TD;
338     }
339   }
340 
341   // Check if we have a class template.
342   if (const ClassTemplateSpecializationDecl *Spec =
343       dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
344     TemplateArgs = &Spec->getTemplateArgs();
345     return Spec->getSpecializedTemplate();
346   }
347 
348   return 0;
349 }
350 
351 void
352 MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
353                                                DeclarationName Name) {
354   //  <unqualified-name> ::= <operator-name>
355   //                     ::= <ctor-dtor-name>
356   //                     ::= <source-name>
357   //                     ::= <template-name>
358   const TemplateArgumentList *TemplateArgs;
359   // Check if we have a template.
360   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
361     mangleTemplateInstantiationName(TD, TemplateArgs->data(), TemplateArgs->size(),
362                                     ND->getLocation());
363     return;
364   }
365 
366   switch (Name.getNameKind()) {
367     case DeclarationName::Identifier: {
368       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
369         mangleSourceName(II);
370         break;
371       }
372 
373       // Otherwise, an anonymous entity.  We must have a declaration.
374       assert(ND && "mangling empty name without declaration");
375 
376       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
377         if (NS->isAnonymousNamespace()) {
378           Out << "?A";
379           break;
380         }
381       }
382 
383       // We must have an anonymous struct.
384       const TagDecl *TD = cast<TagDecl>(ND);
385       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
386         assert(TD->getDeclContext() == D->getDeclContext() &&
387                "Typedef should not be in another decl context!");
388         assert(D->getDeclName().getAsIdentifierInfo() &&
389                "Typedef was not named!");
390         mangleSourceName(D->getDeclName().getAsIdentifierInfo());
391         break;
392       }
393 
394       // When VC encounters an anonymous type with no tag and no typedef,
395       // it literally emits '<unnamed-tag>'.
396       Out << "<unnamed-tag>";
397       break;
398     }
399 
400     case DeclarationName::ObjCZeroArgSelector:
401     case DeclarationName::ObjCOneArgSelector:
402     case DeclarationName::ObjCMultiArgSelector:
403       llvm_unreachable("Can't mangle Objective-C selector names here!");
404 
405     case DeclarationName::CXXConstructorName:
406       Out << "?0";
407       break;
408 
409     case DeclarationName::CXXDestructorName:
410       Out << "?1";
411       break;
412 
413     case DeclarationName::CXXConversionFunctionName:
414       // <operator-name> ::= ?B # (cast)
415       // The target type is encoded as the return type.
416       Out << "?B";
417       break;
418 
419     case DeclarationName::CXXOperatorName:
420       mangleOperatorName(Name.getCXXOverloadedOperator());
421       break;
422 
423     case DeclarationName::CXXLiteralOperatorName:
424       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
425       llvm_unreachable("Don't know how to mangle literal operators yet!");
426 
427     case DeclarationName::CXXUsingDirective:
428       llvm_unreachable("Can't mangle a using directive name!");
429   }
430 }
431 
432 void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
433                                             bool NoFunction) {
434   // <postfix> ::= <unqualified-name> [<postfix>]
435   //           ::= <template-param>
436   //           ::= <substitution> [<postfix>]
437 
438   if (!DC) return;
439 
440   while (isa<LinkageSpecDecl>(DC))
441     DC = DC->getParent();
442 
443   if (DC->isTranslationUnit())
444     return;
445 
446   if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
447     Context.mangleBlock(BD, Out);
448     Out << '@';
449     return manglePostfix(DC->getParent(), NoFunction);
450   }
451 
452   if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
453     return;
454   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
455     mangleObjCMethodName(Method);
456   else {
457     mangleUnqualifiedName(cast<NamedDecl>(DC));
458     manglePostfix(DC->getParent(), NoFunction);
459   }
460 }
461 
462 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO) {
463   switch (OO) {
464   //                     ?0 # constructor
465   //                     ?1 # destructor
466   // <operator-name> ::= ?2 # new
467   case OO_New: Out << "?2"; break;
468   // <operator-name> ::= ?3 # delete
469   case OO_Delete: Out << "?3"; break;
470   // <operator-name> ::= ?4 # =
471   case OO_Equal: Out << "?4"; break;
472   // <operator-name> ::= ?5 # >>
473   case OO_GreaterGreater: Out << "?5"; break;
474   // <operator-name> ::= ?6 # <<
475   case OO_LessLess: Out << "?6"; break;
476   // <operator-name> ::= ?7 # !
477   case OO_Exclaim: Out << "?7"; break;
478   // <operator-name> ::= ?8 # ==
479   case OO_EqualEqual: Out << "?8"; break;
480   // <operator-name> ::= ?9 # !=
481   case OO_ExclaimEqual: Out << "?9"; break;
482   // <operator-name> ::= ?A # []
483   case OO_Subscript: Out << "?A"; break;
484   //                     ?B # conversion
485   // <operator-name> ::= ?C # ->
486   case OO_Arrow: Out << "?C"; break;
487   // <operator-name> ::= ?D # *
488   case OO_Star: Out << "?D"; break;
489   // <operator-name> ::= ?E # ++
490   case OO_PlusPlus: Out << "?E"; break;
491   // <operator-name> ::= ?F # --
492   case OO_MinusMinus: Out << "?F"; break;
493   // <operator-name> ::= ?G # -
494   case OO_Minus: Out << "?G"; break;
495   // <operator-name> ::= ?H # +
496   case OO_Plus: Out << "?H"; break;
497   // <operator-name> ::= ?I # &
498   case OO_Amp: Out << "?I"; break;
499   // <operator-name> ::= ?J # ->*
500   case OO_ArrowStar: Out << "?J"; break;
501   // <operator-name> ::= ?K # /
502   case OO_Slash: Out << "?K"; break;
503   // <operator-name> ::= ?L # %
504   case OO_Percent: Out << "?L"; break;
505   // <operator-name> ::= ?M # <
506   case OO_Less: Out << "?M"; break;
507   // <operator-name> ::= ?N # <=
508   case OO_LessEqual: Out << "?N"; break;
509   // <operator-name> ::= ?O # >
510   case OO_Greater: Out << "?O"; break;
511   // <operator-name> ::= ?P # >=
512   case OO_GreaterEqual: Out << "?P"; break;
513   // <operator-name> ::= ?Q # ,
514   case OO_Comma: Out << "?Q"; break;
515   // <operator-name> ::= ?R # ()
516   case OO_Call: Out << "?R"; break;
517   // <operator-name> ::= ?S # ~
518   case OO_Tilde: Out << "?S"; break;
519   // <operator-name> ::= ?T # ^
520   case OO_Caret: Out << "?T"; break;
521   // <operator-name> ::= ?U # |
522   case OO_Pipe: Out << "?U"; break;
523   // <operator-name> ::= ?V # &&
524   case OO_AmpAmp: Out << "?V"; break;
525   // <operator-name> ::= ?W # ||
526   case OO_PipePipe: Out << "?W"; break;
527   // <operator-name> ::= ?X # *=
528   case OO_StarEqual: Out << "?X"; break;
529   // <operator-name> ::= ?Y # +=
530   case OO_PlusEqual: Out << "?Y"; break;
531   // <operator-name> ::= ?Z # -=
532   case OO_MinusEqual: Out << "?Z"; break;
533   // <operator-name> ::= ?_0 # /=
534   case OO_SlashEqual: Out << "?_0"; break;
535   // <operator-name> ::= ?_1 # %=
536   case OO_PercentEqual: Out << "?_1"; break;
537   // <operator-name> ::= ?_2 # >>=
538   case OO_GreaterGreaterEqual: Out << "?_2"; break;
539   // <operator-name> ::= ?_3 # <<=
540   case OO_LessLessEqual: Out << "?_3"; break;
541   // <operator-name> ::= ?_4 # &=
542   case OO_AmpEqual: Out << "?_4"; break;
543   // <operator-name> ::= ?_5 # |=
544   case OO_PipeEqual: Out << "?_5"; break;
545   // <operator-name> ::= ?_6 # ^=
546   case OO_CaretEqual: Out << "?_6"; break;
547   //                     ?_7 # vftable
548   //                     ?_8 # vbtable
549   //                     ?_9 # vcall
550   //                     ?_A # typeof
551   //                     ?_B # local static guard
552   //                     ?_C # string
553   //                     ?_D # vbase destructor
554   //                     ?_E # vector deleting destructor
555   //                     ?_F # default constructor closure
556   //                     ?_G # scalar deleting destructor
557   //                     ?_H # vector constructor iterator
558   //                     ?_I # vector destructor iterator
559   //                     ?_J # vector vbase constructor iterator
560   //                     ?_K # virtual displacement map
561   //                     ?_L # eh vector constructor iterator
562   //                     ?_M # eh vector destructor iterator
563   //                     ?_N # eh vector vbase constructor iterator
564   //                     ?_O # copy constructor closure
565   //                     ?_P<name> # udt returning <name>
566   //                     ?_Q # <unknown>
567   //                     ?_R0 # RTTI Type Descriptor
568   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
569   //                     ?_R2 # RTTI Base Class Array
570   //                     ?_R3 # RTTI Class Hierarchy Descriptor
571   //                     ?_R4 # RTTI Complete Object Locator
572   //                     ?_S # local vftable
573   //                     ?_T # local vftable constructor closure
574   // <operator-name> ::= ?_U # new[]
575   case OO_Array_New: Out << "?_U"; break;
576   // <operator-name> ::= ?_V # delete[]
577   case OO_Array_Delete: Out << "?_V"; break;
578 
579   case OO_Conditional:
580     llvm_unreachable("Don't know how to mangle ?:");
581 
582   case OO_None:
583   case NUM_OVERLOADED_OPERATORS:
584     llvm_unreachable("Not an overloaded operator");
585   }
586 }
587 
588 void MicrosoftCXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
589   // <source name> ::= <identifier> @
590   Out << II->getName() << '@';
591 }
592 
593 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(const TemplateDecl *TD,
594                                                      const TemplateArgument *TemplateArgs,
595                                                               unsigned NumTemplateArgs,
596                                                         SourceLocation InstantiationLoc) {
597   // <template-name> ::= <unscoped-template-name> <template-args>
598   //                 ::= <substitution>
599   // Always start with the unqualified name.
600   mangleUnscopedTemplateName(TD);
601   mangleTemplateArgs(TemplateArgs, NumTemplateArgs, InstantiationLoc);
602 }
603 
604 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
605   Context.mangleObjCMethodName(MD, Out);
606 }
607 
608 void
609 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
610   // <unscoped-template-name> ::= ?$ <unqualified-name>
611   Out << "?$";
612   mangleUnqualifiedName(TD);
613 }
614 
615 void
616 MicrosoftCXXNameMangler::mangleIntegerLiteral(QualType T, const llvm::APSInt &Value) {
617   // <integer-literal> ::= $0 <number>
618   Out << "$0";
619   // Make sure booleans are encoded as 0/1.
620   if (T->isBooleanType())
621     Out << (Value.getBoolValue() ? "0" : "A@");
622   else
623     mangleNumber(Value);
624 }
625 
626 void
627 MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
628                                             unsigned NumTemplateArgs,
629                                             SourceLocation InstantiationLoc) {
630   // <template-args> ::= {<type> | <integer-literal>}+ @
631   for (unsigned int i = 0; i < NumTemplateArgs; ++i) {
632     const TemplateArgument &TA = TemplateArgs[i];
633     switch (TA.getKind()) {
634   	case TemplateArgument::Null:
635   		llvm_unreachable("Can't mangle null template arguments!");
636     case TemplateArgument::Type:
637       mangleType(TA.getAsType());
638       break;
639     case TemplateArgument::Integral:
640       mangleIntegerLiteral(TA.getIntegralType(), *TA.getAsIntegral());
641       break;
642     default: {
643     	// Issue a diagnostic.
644     	DiagnosticsEngine &Diags = Context.getDiags();
645     	unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
646     		"cannot yet mangle this %select{null|type|pointer/reference|integral|template|"
647     		"template pack expansion|expression|parameter pack}0 template argument");
648     	Diags.Report(InstantiationLoc, DiagID)
649     		<< TA.getKind();
650     }
651     }
652   }
653   Out << '@';
654 }
655 
656 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
657                                                bool IsMember) {
658   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
659   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
660   // 'I' means __restrict (32/64-bit).
661   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
662   // keyword!
663   // <base-cvr-qualifiers> ::= A  # near
664   //                       ::= B  # near const
665   //                       ::= C  # near volatile
666   //                       ::= D  # near const volatile
667   //                       ::= E  # far (16-bit)
668   //                       ::= F  # far const (16-bit)
669   //                       ::= G  # far volatile (16-bit)
670   //                       ::= H  # far const volatile (16-bit)
671   //                       ::= I  # huge (16-bit)
672   //                       ::= J  # huge const (16-bit)
673   //                       ::= K  # huge volatile (16-bit)
674   //                       ::= L  # huge const volatile (16-bit)
675   //                       ::= M <basis> # based
676   //                       ::= N <basis> # based const
677   //                       ::= O <basis> # based volatile
678   //                       ::= P <basis> # based const volatile
679   //                       ::= Q  # near member
680   //                       ::= R  # near const member
681   //                       ::= S  # near volatile member
682   //                       ::= T  # near const volatile member
683   //                       ::= U  # far member (16-bit)
684   //                       ::= V  # far const member (16-bit)
685   //                       ::= W  # far volatile member (16-bit)
686   //                       ::= X  # far const volatile member (16-bit)
687   //                       ::= Y  # huge member (16-bit)
688   //                       ::= Z  # huge const member (16-bit)
689   //                       ::= 0  # huge volatile member (16-bit)
690   //                       ::= 1  # huge const volatile member (16-bit)
691   //                       ::= 2 <basis> # based member
692   //                       ::= 3 <basis> # based const member
693   //                       ::= 4 <basis> # based volatile member
694   //                       ::= 5 <basis> # based const volatile member
695   //                       ::= 6  # near function (pointers only)
696   //                       ::= 7  # far function (pointers only)
697   //                       ::= 8  # near method (pointers only)
698   //                       ::= 9  # far method (pointers only)
699   //                       ::= _A <basis> # based function (pointers only)
700   //                       ::= _B <basis> # based function (far?) (pointers only)
701   //                       ::= _C <basis> # based method (pointers only)
702   //                       ::= _D <basis> # based method (far?) (pointers only)
703   //                       ::= _E # block (Clang)
704   // <basis> ::= 0 # __based(void)
705   //         ::= 1 # __based(segment)?
706   //         ::= 2 <name> # __based(name)
707   //         ::= 3 # ?
708   //         ::= 4 # ?
709   //         ::= 5 # not really based
710   if (!IsMember) {
711     if (!Quals.hasVolatile()) {
712       if (!Quals.hasConst())
713         Out << 'A';
714       else
715         Out << 'B';
716     } else {
717       if (!Quals.hasConst())
718         Out << 'C';
719       else
720         Out << 'D';
721     }
722   } else {
723     if (!Quals.hasVolatile()) {
724       if (!Quals.hasConst())
725         Out << 'Q';
726       else
727         Out << 'R';
728     } else {
729       if (!Quals.hasConst())
730         Out << 'S';
731       else
732         Out << 'T';
733     }
734   }
735 
736   // FIXME: For now, just drop all extension qualifiers on the floor.
737 }
738 
739 void MicrosoftCXXNameMangler::mangleType(QualType T) {
740   // Only operate on the canonical type!
741   T = getASTContext().getCanonicalType(T);
742 
743   Qualifiers Quals = T.getLocalQualifiers();
744   if (Quals) {
745     // We have to mangle these now, while we still have enough information.
746     // <pointer-cvr-qualifiers> ::= P  # pointer
747     //                          ::= Q  # const pointer
748     //                          ::= R  # volatile pointer
749     //                          ::= S  # const volatile pointer
750     if (T->isAnyPointerType() || T->isMemberPointerType() ||
751         T->isBlockPointerType()) {
752       if (!Quals.hasVolatile())
753         Out << 'Q';
754       else {
755         if (!Quals.hasConst())
756           Out << 'R';
757         else
758           Out << 'S';
759       }
760     } else
761       // Just emit qualifiers like normal.
762       // NB: When we mangle a pointer/reference type, and the pointee
763       // type has no qualifiers, the lack of qualifier gets mangled
764       // in there.
765       mangleQualifiers(Quals, false);
766   } else if (T->isAnyPointerType() || T->isMemberPointerType() ||
767              T->isBlockPointerType()) {
768     Out << 'P';
769   }
770   switch (T->getTypeClass()) {
771 #define ABSTRACT_TYPE(CLASS, PARENT)
772 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
773 case Type::CLASS: \
774 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
775 return;
776 #define TYPE(CLASS, PARENT) \
777 case Type::CLASS: \
778 mangleType(static_cast<const CLASS##Type*>(T.getTypePtr())); \
779 break;
780 #include "clang/AST/TypeNodes.def"
781   }
782 }
783 
784 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T) {
785   //  <type>         ::= <builtin-type>
786   //  <builtin-type> ::= X  # void
787   //                 ::= C  # signed char
788   //                 ::= D  # char
789   //                 ::= E  # unsigned char
790   //                 ::= F  # short
791   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
792   //                 ::= H  # int
793   //                 ::= I  # unsigned int
794   //                 ::= J  # long
795   //                 ::= K  # unsigned long
796   //                     L  # <none>
797   //                 ::= M  # float
798   //                 ::= N  # double
799   //                 ::= O  # long double (__float80 is mangled differently)
800   //                 ::= _J # long long, __int64
801   //                 ::= _K # unsigned long long, __int64
802   //                 ::= _L # __int128
803   //                 ::= _M # unsigned __int128
804   //                 ::= _N # bool
805   //                     _O # <array in parameter>
806   //                 ::= _T # __float80 (Intel)
807   //                 ::= _W # wchar_t
808   //                 ::= _Z # __float80 (Digital Mars)
809   switch (T->getKind()) {
810   case BuiltinType::Void: Out << 'X'; break;
811   case BuiltinType::SChar: Out << 'C'; break;
812   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
813   case BuiltinType::UChar: Out << 'E'; break;
814   case BuiltinType::Short: Out << 'F'; break;
815   case BuiltinType::UShort: Out << 'G'; break;
816   case BuiltinType::Int: Out << 'H'; break;
817   case BuiltinType::UInt: Out << 'I'; break;
818   case BuiltinType::Long: Out << 'J'; break;
819   case BuiltinType::ULong: Out << 'K'; break;
820   case BuiltinType::Float: Out << 'M'; break;
821   case BuiltinType::Double: Out << 'N'; break;
822   // TODO: Determine size and mangle accordingly
823   case BuiltinType::LongDouble: Out << 'O'; break;
824   case BuiltinType::LongLong: Out << "_J"; break;
825   case BuiltinType::ULongLong: Out << "_K"; break;
826   case BuiltinType::Int128: Out << "_L"; break;
827   case BuiltinType::UInt128: Out << "_M"; break;
828   case BuiltinType::Bool: Out << "_N"; break;
829   case BuiltinType::WChar_S:
830   case BuiltinType::WChar_U: Out << "_W"; break;
831 
832 #define BUILTIN_TYPE(Id, SingletonId)
833 #define PLACEHOLDER_TYPE(Id, SingletonId) \
834   case BuiltinType::Id:
835 #include "clang/AST/BuiltinTypes.def"
836   case BuiltinType::Dependent:
837     llvm_unreachable("placeholder types shouldn't get to name mangling");
838 
839   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
840   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
841   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
842 
843   case BuiltinType::Char16:
844   case BuiltinType::Char32:
845   case BuiltinType::Half:
846   case BuiltinType::NullPtr:
847     assert(0 && "Don't know how to mangle this type yet");
848   }
849 }
850 
851 // <type>          ::= <function-type>
852 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T) {
853   // Structors only appear in decls, so at this point we know it's not a
854   // structor type.
855   // I'll probably have mangleType(MemberPointerType) call the mangleType()
856   // method directly.
857   mangleType(T, NULL, false, false);
858 }
859 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T) {
860   llvm_unreachable("Can't mangle K&R function prototypes");
861 }
862 
863 void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
864                                          const FunctionDecl *D,
865                                          bool IsStructor,
866                                          bool IsInstMethod) {
867   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
868   //                     <return-type> <argument-list> <throw-spec>
869   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
870 
871   // If this is a C++ instance method, mangle the CVR qualifiers for the
872   // this pointer.
873   if (IsInstMethod)
874     mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
875 
876   mangleCallingConvention(T, IsInstMethod);
877 
878   // <return-type> ::= <type>
879   //               ::= @ # structors (they have no declared return type)
880   if (IsStructor)
881     Out << '@';
882   else
883     mangleType(Proto->getResultType());
884 
885   // <argument-list> ::= X # void
886   //                 ::= <type>+ @
887   //                 ::= <type>* Z # varargs
888   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
889     Out << 'X';
890   } else {
891     if (D) {
892       // If we got a decl, use the type-as-written to make sure arrays
893       // get mangled right.  Note that we can't rely on the TSI
894       // existing if (for example) the parameter was synthesized.
895       for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
896              ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
897         if (TypeSourceInfo *typeAsWritten = (*Parm)->getTypeSourceInfo())
898           mangleType(typeAsWritten->getType());
899         else
900           mangleType((*Parm)->getType());
901       }
902     } else {
903       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
904            ArgEnd = Proto->arg_type_end();
905            Arg != ArgEnd; ++Arg)
906         mangleType(*Arg);
907     }
908     // <builtin-type>      ::= Z  # ellipsis
909     if (Proto->isVariadic())
910       Out << 'Z';
911     else
912       Out << '@';
913   }
914 
915   mangleThrowSpecification(Proto);
916 }
917 
918 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
919   // <function-class> ::= A # private: near
920   //                  ::= B # private: far
921   //                  ::= C # private: static near
922   //                  ::= D # private: static far
923   //                  ::= E # private: virtual near
924   //                  ::= F # private: virtual far
925   //                  ::= G # private: thunk near
926   //                  ::= H # private: thunk far
927   //                  ::= I # protected: near
928   //                  ::= J # protected: far
929   //                  ::= K # protected: static near
930   //                  ::= L # protected: static far
931   //                  ::= M # protected: virtual near
932   //                  ::= N # protected: virtual far
933   //                  ::= O # protected: thunk near
934   //                  ::= P # protected: thunk far
935   //                  ::= Q # public: near
936   //                  ::= R # public: far
937   //                  ::= S # public: static near
938   //                  ::= T # public: static far
939   //                  ::= U # public: virtual near
940   //                  ::= V # public: virtual far
941   //                  ::= W # public: thunk near
942   //                  ::= X # public: thunk far
943   //                  ::= Y # global near
944   //                  ::= Z # global far
945   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
946     switch (MD->getAccess()) {
947       default:
948       case AS_private:
949         if (MD->isStatic())
950           Out << 'C';
951         else if (MD->isVirtual())
952           Out << 'E';
953         else
954           Out << 'A';
955         break;
956       case AS_protected:
957         if (MD->isStatic())
958           Out << 'K';
959         else if (MD->isVirtual())
960           Out << 'M';
961         else
962           Out << 'I';
963         break;
964       case AS_public:
965         if (MD->isStatic())
966           Out << 'S';
967         else if (MD->isVirtual())
968           Out << 'U';
969         else
970           Out << 'Q';
971     }
972   } else
973     Out << 'Y';
974 }
975 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
976                                                       bool IsInstMethod) {
977   // <calling-convention> ::= A # __cdecl
978   //                      ::= B # __export __cdecl
979   //                      ::= C # __pascal
980   //                      ::= D # __export __pascal
981   //                      ::= E # __thiscall
982   //                      ::= F # __export __thiscall
983   //                      ::= G # __stdcall
984   //                      ::= H # __export __stdcall
985   //                      ::= I # __fastcall
986   //                      ::= J # __export __fastcall
987   // The 'export' calling conventions are from a bygone era
988   // (*cough*Win16*cough*) when functions were declared for export with
989   // that keyword. (It didn't actually export them, it just made them so
990   // that they could be in a DLL and somebody from another module could call
991   // them.)
992   CallingConv CC = T->getCallConv();
993   if (CC == CC_Default)
994     CC = IsInstMethod ? getASTContext().getDefaultMethodCallConv() : CC_C;
995   switch (CC) {
996     default:
997       llvm_unreachable("Unsupported CC for mangling");
998     case CC_Default:
999     case CC_C: Out << 'A'; break;
1000     case CC_X86Pascal: Out << 'C'; break;
1001     case CC_X86ThisCall: Out << 'E'; break;
1002     case CC_X86StdCall: Out << 'G'; break;
1003     case CC_X86FastCall: Out << 'I'; break;
1004   }
1005 }
1006 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1007                                                 const FunctionProtoType *FT) {
1008   // <throw-spec> ::= Z # throw(...) (default)
1009   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1010   //              ::= <type>+
1011   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1012   // all actually mangled as 'Z'. (They're ignored because their associated
1013   // functionality isn't implemented, and probably never will be.)
1014   Out << 'Z';
1015 }
1016 
1017 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1018   llvm_unreachable("Don't know how to mangle UnresolvedUsingTypes yet!");
1019 }
1020 
1021 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1022 // <union-type>  ::= T <name>
1023 // <struct-type> ::= U <name>
1024 // <class-type>  ::= V <name>
1025 // <enum-type>   ::= W <size> <name>
1026 void MicrosoftCXXNameMangler::mangleType(const EnumType *T) {
1027   mangleType(static_cast<const TagType*>(T));
1028 }
1029 void MicrosoftCXXNameMangler::mangleType(const RecordType *T) {
1030   mangleType(static_cast<const TagType*>(T));
1031 }
1032 void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
1033   switch (T->getDecl()->getTagKind()) {
1034     case TTK_Union:
1035       Out << 'T';
1036       break;
1037     case TTK_Struct:
1038       Out << 'U';
1039       break;
1040     case TTK_Class:
1041       Out << 'V';
1042       break;
1043     case TTK_Enum:
1044       Out << 'W';
1045       Out << getASTContext().getTypeSizeInChars(
1046                 cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
1047       break;
1048   }
1049   mangleName(T->getDecl());
1050 }
1051 
1052 // <type>       ::= <array-type>
1053 // <array-type> ::= P <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1054 //                                                  <element-type> # as global
1055 //              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1056 //                                                  <element-type> # as param
1057 // It's supposed to be the other way around, but for some strange reason, it
1058 // isn't. Today this behavior is retained for the sole purpose of backwards
1059 // compatibility.
1060 void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
1061   // This isn't a recursive mangling, so now we have to do it all in this
1062   // one call.
1063   if (IsGlobal)
1064     Out << 'P';
1065   else
1066     Out << 'Q';
1067   mangleExtraDimensions(T->getElementType());
1068 }
1069 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T) {
1070   mangleType(static_cast<const ArrayType *>(T), false);
1071 }
1072 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T) {
1073   mangleType(static_cast<const ArrayType *>(T), false);
1074 }
1075 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1076   mangleType(static_cast<const ArrayType *>(T), false);
1077 }
1078 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T) {
1079   mangleType(static_cast<const ArrayType *>(T), false);
1080 }
1081 void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
1082   SmallVector<llvm::APInt, 3> Dimensions;
1083   for (;;) {
1084     if (ElementTy->isConstantArrayType()) {
1085       const ConstantArrayType *CAT =
1086       static_cast<const ConstantArrayType *>(ElementTy.getTypePtr());
1087       Dimensions.push_back(CAT->getSize());
1088       ElementTy = CAT->getElementType();
1089     } else if (ElementTy->isVariableArrayType()) {
1090       llvm_unreachable("Don't know how to mangle VLAs!");
1091     } else if (ElementTy->isDependentSizedArrayType()) {
1092       // The dependent expression has to be folded into a constant (TODO).
1093       llvm_unreachable("Don't know how to mangle dependent-sized arrays!");
1094     } else if (ElementTy->isIncompleteArrayType()) continue;
1095     else break;
1096   }
1097   mangleQualifiers(ElementTy.getQualifiers(), false);
1098   // If there are any additional dimensions, mangle them now.
1099   if (Dimensions.size() > 0) {
1100     Out << 'Y';
1101     // <dimension-count> ::= <number> # number of extra dimensions
1102     mangleNumber(Dimensions.size());
1103     for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
1104       mangleNumber(Dimensions[Dim].getLimitedValue());
1105     }
1106   }
1107   mangleType(ElementTy.getLocalUnqualifiedType());
1108 }
1109 
1110 // <type>                   ::= <pointer-to-member-type>
1111 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1112 //                                                          <class name> <type>
1113 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T) {
1114   QualType PointeeType = T->getPointeeType();
1115   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
1116     Out << '8';
1117     mangleName(cast<RecordType>(T->getClass())->getDecl());
1118     mangleType(FPT, NULL, false, true);
1119   } else {
1120     mangleQualifiers(PointeeType.getQualifiers(), true);
1121     mangleName(cast<RecordType>(T->getClass())->getDecl());
1122     mangleType(PointeeType.getLocalUnqualifiedType());
1123   }
1124 }
1125 
1126 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T) {
1127   llvm_unreachable("Don't know how to mangle TemplateTypeParmTypes yet!");
1128 }
1129 
1130 void MicrosoftCXXNameMangler::mangleType(
1131                                        const SubstTemplateTypeParmPackType *T) {
1132   llvm_unreachable(
1133          "Don't know how to mangle SubstTemplateTypeParmPackTypes yet!");
1134 }
1135 
1136 // <type> ::= <pointer-type>
1137 // <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1138 void MicrosoftCXXNameMangler::mangleType(const PointerType *T) {
1139   QualType PointeeTy = T->getPointeeType();
1140   if (PointeeTy->isArrayType()) {
1141     // Pointers to arrays are mangled like arrays.
1142     mangleExtraDimensions(T->getPointeeType());
1143   } else if (PointeeTy->isFunctionType()) {
1144     // Function pointers are special.
1145     Out << '6';
1146     mangleType(static_cast<const FunctionType *>(PointeeTy.getTypePtr()),
1147                NULL, false, false);
1148   } else {
1149     if (!PointeeTy.hasQualifiers())
1150       // Lack of qualifiers is mangled as 'A'.
1151       Out << 'A';
1152     mangleType(PointeeTy);
1153   }
1154 }
1155 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
1156   // Object pointers never have qualifiers.
1157   Out << 'A';
1158   mangleType(T->getPointeeType());
1159 }
1160 
1161 // <type> ::= <reference-type>
1162 // <reference-type> ::= A <cvr-qualifiers> <type>
1163 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T) {
1164   Out << 'A';
1165   QualType PointeeTy = T->getPointeeType();
1166   if (!PointeeTy.hasQualifiers())
1167     // Lack of qualifiers is mangled as 'A'.
1168     Out << 'A';
1169   mangleType(PointeeTy);
1170 }
1171 
1172 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T) {
1173   llvm_unreachable("Don't know how to mangle RValueReferenceTypes yet!");
1174 }
1175 
1176 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T) {
1177   llvm_unreachable("Don't know how to mangle ComplexTypes yet!");
1178 }
1179 
1180 void MicrosoftCXXNameMangler::mangleType(const VectorType *T) {
1181   llvm_unreachable("Don't know how to mangle VectorTypes yet!");
1182 }
1183 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T) {
1184   llvm_unreachable("Don't know how to mangle ExtVectorTypes yet!");
1185 }
1186 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
1187   llvm_unreachable(
1188                   "Don't know how to mangle DependentSizedExtVectorTypes yet!");
1189 }
1190 
1191 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T) {
1192   // ObjC interfaces have structs underlying them.
1193   Out << 'U';
1194   mangleName(T->getDecl());
1195 }
1196 
1197 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T) {
1198   // We don't allow overloading by different protocol qualification,
1199   // so mangling them isn't necessary.
1200   mangleType(T->getBaseType());
1201 }
1202 
1203 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T) {
1204   Out << "_E";
1205   mangleType(T->getPointeeType());
1206 }
1207 
1208 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T) {
1209   llvm_unreachable("Don't know how to mangle InjectedClassNameTypes yet!");
1210 }
1211 
1212 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T) {
1213   llvm_unreachable("Don't know how to mangle TemplateSpecializationTypes yet!");
1214 }
1215 
1216 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T) {
1217   llvm_unreachable("Don't know how to mangle DependentNameTypes yet!");
1218 }
1219 
1220 void MicrosoftCXXNameMangler::mangleType(
1221                                  const DependentTemplateSpecializationType *T) {
1222   llvm_unreachable(
1223          "Don't know how to mangle DependentTemplateSpecializationTypes yet!");
1224 }
1225 
1226 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T) {
1227   llvm_unreachable("Don't know how to mangle PackExpansionTypes yet!");
1228 }
1229 
1230 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T) {
1231   llvm_unreachable("Don't know how to mangle TypeOfTypes yet!");
1232 }
1233 
1234 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T) {
1235   llvm_unreachable("Don't know how to mangle TypeOfExprTypes yet!");
1236 }
1237 
1238 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T) {
1239   llvm_unreachable("Don't know how to mangle DecltypeTypes yet!");
1240 }
1241 
1242 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T) {
1243   llvm_unreachable("Don't know how to mangle UnaryTransformationTypes yet!");
1244 }
1245 
1246 void MicrosoftCXXNameMangler::mangleType(const AutoType *T) {
1247   llvm_unreachable("Don't know how to mangle AutoTypes yet!");
1248 }
1249 
1250 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T) {
1251   llvm_unreachable("Don't know how to mangle AtomicTypes yet!");
1252 }
1253 
1254 void MicrosoftMangleContext::mangleName(const NamedDecl *D,
1255                                         raw_ostream &Out) {
1256   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1257          "Invalid mangleName() call, argument is not a variable or function!");
1258   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1259          "Invalid mangleName() call on 'structor decl!");
1260 
1261   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
1262                                  getASTContext().getSourceManager(),
1263                                  "Mangling declaration");
1264 
1265   MicrosoftCXXNameMangler Mangler(*this, Out);
1266   return Mangler.mangle(D);
1267 }
1268 void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
1269                                          const ThunkInfo &Thunk,
1270                                          raw_ostream &) {
1271   llvm_unreachable("Can't yet mangle thunks!");
1272 }
1273 void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
1274                                                 CXXDtorType Type,
1275                                                 const ThisAdjustment &,
1276                                                 raw_ostream &) {
1277   llvm_unreachable("Can't yet mangle destructor thunks!");
1278 }
1279 void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
1280                                              raw_ostream &) {
1281   llvm_unreachable("Can't yet mangle virtual tables!");
1282 }
1283 void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
1284                                           raw_ostream &) {
1285   llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
1286 }
1287 void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
1288                                                  int64_t Offset,
1289                                                  const CXXRecordDecl *Type,
1290                                                  raw_ostream &) {
1291   llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
1292 }
1293 void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
1294                                            raw_ostream &) {
1295   llvm_unreachable("Can't yet mangle RTTI!");
1296 }
1297 void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
1298                                                raw_ostream &) {
1299   llvm_unreachable("Can't yet mangle RTTI names!");
1300 }
1301 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
1302                                            CXXCtorType Type,
1303                                            raw_ostream & Out) {
1304   MicrosoftCXXNameMangler mangler(*this, Out);
1305   mangler.mangle(D);
1306 }
1307 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
1308                                            CXXDtorType Type,
1309                                            raw_ostream & Out) {
1310   MicrosoftCXXNameMangler mangler(*this, Out);
1311   mangler.mangle(D);
1312 }
1313 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *,
1314                                                       raw_ostream &) {
1315   llvm_unreachable("Can't yet mangle reference temporaries!");
1316 }
1317 
1318 MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
1319                                                    DiagnosticsEngine &Diags) {
1320   return new MicrosoftMangleContext(Context, Diags);
1321 }
1322