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