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