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