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