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