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