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