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