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