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/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/VTableBuilder.h"
26#include "clang/Basic/ABI.h"
27#include "clang/Basic/DiagnosticOptions.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/Support/MathExtras.h"
32
33using namespace clang;
34
35namespace {
36
37/// \brief Retrieve the declaration context that should be used when mangling
38/// the given declaration.
39static const DeclContext *getEffectiveDeclContext(const Decl *D) {
40  // The ABI assumes that lambda closure types that occur within
41  // default arguments live in the context of the function. However, due to
42  // the way in which Clang parses and creates function declarations, this is
43  // not the case: the lambda closure type ends up living in the context
44  // where the function itself resides, because the function declaration itself
45  // had not yet been created. Fix the context here.
46  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
47    if (RD->isLambda())
48      if (ParmVarDecl *ContextParam =
49              dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
50        return ContextParam->getDeclContext();
51  }
52
53  // Perform the same check for block literals.
54  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
55    if (ParmVarDecl *ContextParam =
56            dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
57      return ContextParam->getDeclContext();
58  }
59
60  const DeclContext *DC = D->getDeclContext();
61  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
62    return getEffectiveDeclContext(CD);
63
64  return DC;
65}
66
67static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
68  return getEffectiveDeclContext(cast<Decl>(DC));
69}
70
71static const FunctionDecl *getStructor(const FunctionDecl *fn) {
72  if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
73    return ftd->getTemplatedDecl();
74
75  return fn;
76}
77
78static bool isLambda(const NamedDecl *ND) {
79  const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
80  if (!Record)
81    return false;
82
83  return Record->isLambda();
84}
85
86/// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
87/// Microsoft Visual C++ ABI.
88class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
89  typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
90  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
91  llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
92  llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
93
94public:
95  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
96      : MicrosoftMangleContext(Context, Diags) {}
97  bool shouldMangleCXXName(const NamedDecl *D) override;
98  bool shouldMangleStringLiteral(const StringLiteral *SL) override;
99  void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
100  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
101                                raw_ostream &) override;
102  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
103                   raw_ostream &) override;
104  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
105                          const ThisAdjustment &ThisAdjustment,
106                          raw_ostream &) override;
107  void mangleCXXVFTable(const CXXRecordDecl *Derived,
108                        ArrayRef<const CXXRecordDecl *> BasePath,
109                        raw_ostream &Out) override;
110  void mangleCXXVBTable(const CXXRecordDecl *Derived,
111                        ArrayRef<const CXXRecordDecl *> BasePath,
112                        raw_ostream &Out) override;
113  void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
114  void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
115  void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
116                                        uint32_t NVOffset, int32_t VBPtrOffset,
117                                        uint32_t VBTableOffset, uint32_t Flags,
118                                        raw_ostream &Out) override;
119  void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
120                                   raw_ostream &Out) override;
121  void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
122                                             raw_ostream &Out) override;
123  void
124  mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
125                                     ArrayRef<const CXXRecordDecl *> BasePath,
126                                     raw_ostream &Out) override;
127  void mangleTypeName(QualType T, raw_ostream &) override;
128  void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
129                     raw_ostream &) override;
130  void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
131                     raw_ostream &) override;
132  void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
133                                raw_ostream &) override;
134  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
135  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
136  void mangleDynamicAtExitDestructor(const VarDecl *D,
137                                     raw_ostream &Out) override;
138  void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
139  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
140    // Lambda closure types are already numbered.
141    if (isLambda(ND))
142      return false;
143
144    const DeclContext *DC = getEffectiveDeclContext(ND);
145    if (!DC->isFunctionOrMethod())
146      return false;
147
148    // Use the canonical number for externally visible decls.
149    if (ND->isExternallyVisible()) {
150      disc = getASTContext().getManglingNumber(ND);
151      return true;
152    }
153
154    // Anonymous tags are already numbered.
155    if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
156      if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
157        return false;
158    }
159
160    // Make up a reasonable number for internal decls.
161    unsigned &discriminator = Uniquifier[ND];
162    if (!discriminator)
163      discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
164    disc = discriminator;
165    return true;
166  }
167
168  unsigned getLambdaId(const CXXRecordDecl *RD) {
169    assert(RD->isLambda() && "RD must be a lambda!");
170    assert(!RD->isExternallyVisible() && "RD must not be visible!");
171    assert(RD->getLambdaManglingNumber() == 0 &&
172           "RD must not have a mangling number!");
173    std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
174        Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
175    return Result.first->second;
176  }
177
178private:
179  void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
180};
181
182/// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
183/// Microsoft Visual C++ ABI.
184class MicrosoftCXXNameMangler {
185  MicrosoftMangleContextImpl &Context;
186  raw_ostream &Out;
187
188  /// The "structor" is the top-level declaration being mangled, if
189  /// that's not a template specialization; otherwise it's the pattern
190  /// for that specialization.
191  const NamedDecl *Structor;
192  unsigned StructorType;
193
194  typedef llvm::StringMap<unsigned> BackRefMap;
195  BackRefMap NameBackReferences;
196
197  typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
198  ArgBackRefMap TypeBackReferences;
199
200  ASTContext &getASTContext() const { return Context.getASTContext(); }
201
202  // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
203  // this check into mangleQualifiers().
204  const bool PointersAre64Bit;
205
206public:
207  enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
208
209  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
210      : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
211        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
212                         64) {}
213
214  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
215                          const CXXDestructorDecl *D, CXXDtorType Type)
216      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
217        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
218                         64) {}
219
220  raw_ostream &getStream() const { return Out; }
221
222  void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
223  void mangleName(const NamedDecl *ND);
224  void mangleFunctionEncoding(const FunctionDecl *FD);
225  void mangleVariableEncoding(const VarDecl *VD);
226  void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
227  void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
228                                   const CXXMethodDecl *MD);
229  void mangleVirtualMemPtrThunk(
230      const CXXMethodDecl *MD,
231      const MicrosoftVTableContext::MethodVFTableLocation &ML);
232  void mangleNumber(int64_t Number);
233  void mangleType(QualType T, SourceRange Range,
234                  QualifierMangleMode QMM = QMM_Mangle);
235  void mangleFunctionType(const FunctionType *T,
236                          const FunctionDecl *D = nullptr,
237                          bool ForceInstMethod = false);
238  void mangleNestedName(const NamedDecl *ND);
239
240private:
241  void mangleUnqualifiedName(const NamedDecl *ND) {
242    mangleUnqualifiedName(ND, ND->getDeclName());
243  }
244  void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
245  void mangleSourceName(StringRef Name);
246  void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
247  void mangleCXXDtorType(CXXDtorType T);
248  void mangleQualifiers(Qualifiers Quals, bool IsMember);
249  void mangleRefQualifier(RefQualifierKind RefQualifier);
250  void manglePointerCVQualifiers(Qualifiers Quals);
251  void manglePointerExtQualifiers(Qualifiers Quals, const Type *PointeeType);
252
253  void mangleUnscopedTemplateName(const TemplateDecl *ND);
254  void
255  mangleTemplateInstantiationName(const TemplateDecl *TD,
256                                  const TemplateArgumentList &TemplateArgs);
257  void mangleObjCMethodName(const ObjCMethodDecl *MD);
258
259  void mangleArgumentType(QualType T, SourceRange Range);
260
261  // Declare manglers for every type class.
262#define ABSTRACT_TYPE(CLASS, PARENT)
263#define NON_CANONICAL_TYPE(CLASS, PARENT)
264#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
265                                            SourceRange Range);
266#include "clang/AST/TypeNodes.def"
267#undef ABSTRACT_TYPE
268#undef NON_CANONICAL_TYPE
269#undef TYPE
270
271  void mangleType(const TagDecl *TD);
272  void mangleDecayedArrayType(const ArrayType *T);
273  void mangleArrayType(const ArrayType *T);
274  void mangleFunctionClass(const FunctionDecl *FD);
275  void mangleCallingConvention(const FunctionType *T);
276  void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
277  void mangleExpression(const Expr *E);
278  void mangleThrowSpecification(const FunctionProtoType *T);
279
280  void mangleTemplateArgs(const TemplateDecl *TD,
281                          const TemplateArgumentList &TemplateArgs);
282  void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA);
283};
284}
285
286bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
287  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
288    LanguageLinkage L = FD->getLanguageLinkage();
289    // Overloadable functions need mangling.
290    if (FD->hasAttr<OverloadableAttr>())
291      return true;
292
293    // The ABI expects that we would never mangle "typical" user-defined entry
294    // points regardless of visibility or freestanding-ness.
295    //
296    // N.B. This is distinct from asking about "main".  "main" has a lot of
297    // special rules associated with it in the standard while these
298    // user-defined entry points are outside of the purview of the standard.
299    // For example, there can be only one definition for "main" in a standards
300    // compliant program; however nothing forbids the existence of wmain and
301    // WinMain in the same translation unit.
302    if (FD->isMSVCRTEntryPoint())
303      return false;
304
305    // C++ functions and those whose names are not a simple identifier need
306    // mangling.
307    if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
308      return true;
309
310    // C functions are not mangled.
311    if (L == CLanguageLinkage)
312      return false;
313  }
314
315  // Otherwise, no mangling is done outside C++ mode.
316  if (!getASTContext().getLangOpts().CPlusPlus)
317    return false;
318
319  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
320    // C variables are not mangled.
321    if (VD->isExternC())
322      return false;
323
324    // Variables at global scope with non-internal linkage are not mangled.
325    const DeclContext *DC = getEffectiveDeclContext(D);
326    // Check for extern variable declared locally.
327    if (DC->isFunctionOrMethod() && D->hasLinkage())
328      while (!DC->isNamespace() && !DC->isTranslationUnit())
329        DC = getEffectiveParentContext(DC);
330
331    if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
332        !isa<VarTemplateSpecializationDecl>(D))
333      return false;
334  }
335
336  return true;
337}
338
339bool
340MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
341  return SL->isAscii() || SL->isWide();
342  // TODO: This needs to be updated when MSVC gains support for Unicode
343  // literals.
344}
345
346void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
347  // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
348  // Therefore it's really important that we don't decorate the
349  // name with leading underscores or leading/trailing at signs. So, by
350  // default, we emit an asm marker at the start so we get the name right.
351  // Callers can override this with a custom prefix.
352
353  // <mangled-name> ::= ? <name> <type-encoding>
354  Out << Prefix;
355  mangleName(D);
356  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
357    mangleFunctionEncoding(FD);
358  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
359    mangleVariableEncoding(VD);
360  else {
361    // TODO: Fields? Can MSVC even mangle them?
362    // Issue a diagnostic for now.
363    DiagnosticsEngine &Diags = Context.getDiags();
364    unsigned DiagID = Diags.getCustomDiagID(
365        DiagnosticsEngine::Error, "cannot mangle this declaration yet");
366    Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
367  }
368}
369
370void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
371  // <type-encoding> ::= <function-class> <function-type>
372
373  // Since MSVC operates on the type as written and not the canonical type, it
374  // actually matters which decl we have here.  MSVC appears to choose the
375  // first, since it is most likely to be the declaration in a header file.
376  FD = FD->getFirstDecl();
377
378  // We should never ever see a FunctionNoProtoType at this point.
379  // We don't even know how to mangle their types anyway :).
380  const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
381
382  // extern "C" functions can hold entities that must be mangled.
383  // As it stands, these functions still need to get expressed in the full
384  // external name.  They have their class and type omitted, replaced with '9'.
385  if (Context.shouldMangleDeclName(FD)) {
386    // First, the function class.
387    mangleFunctionClass(FD);
388
389    mangleFunctionType(FT, FD);
390  } else
391    Out << '9';
392}
393
394void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
395  // <type-encoding> ::= <storage-class> <variable-type>
396  // <storage-class> ::= 0  # private static member
397  //                 ::= 1  # protected static member
398  //                 ::= 2  # public static member
399  //                 ::= 3  # global
400  //                 ::= 4  # static local
401
402  // The first character in the encoding (after the name) is the storage class.
403  if (VD->isStaticDataMember()) {
404    // If it's a static member, it also encodes the access level.
405    switch (VD->getAccess()) {
406      default:
407      case AS_private: Out << '0'; break;
408      case AS_protected: Out << '1'; break;
409      case AS_public: Out << '2'; break;
410    }
411  }
412  else if (!VD->isStaticLocal())
413    Out << '3';
414  else
415    Out << '4';
416  // Now mangle the type.
417  // <variable-type> ::= <type> <cvr-qualifiers>
418  //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
419  // Pointers and references are odd. The type of 'int * const foo;' gets
420  // mangled as 'QAHA' instead of 'PAHB', for example.
421  SourceRange SR = VD->getSourceRange();
422  QualType Ty = VD->getType();
423  if (Ty->isPointerType() || Ty->isReferenceType() ||
424      Ty->isMemberPointerType()) {
425    mangleType(Ty, SR, QMM_Drop);
426    manglePointerExtQualifiers(
427        Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), nullptr);
428    if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
429      mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
430      // Member pointers are suffixed with a back reference to the member
431      // pointer's class name.
432      mangleName(MPT->getClass()->getAsCXXRecordDecl());
433    } else
434      mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
435  } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
436    // Global arrays are funny, too.
437    mangleDecayedArrayType(AT);
438    if (AT->getElementType()->isArrayType())
439      Out << 'A';
440    else
441      mangleQualifiers(Ty.getQualifiers(), false);
442  } else {
443    mangleType(Ty, SR, QMM_Drop);
444    mangleQualifiers(Ty.getLocalQualifiers(), false);
445  }
446}
447
448void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
449                                                      const ValueDecl *VD) {
450  // <member-data-pointer> ::= <integer-literal>
451  //                       ::= $F <number> <number>
452  //                       ::= $G <number> <number> <number>
453
454  int64_t FieldOffset;
455  int64_t VBTableOffset;
456  MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
457  if (VD) {
458    FieldOffset = getASTContext().getFieldOffset(VD);
459    assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
460           "cannot take address of bitfield");
461    FieldOffset /= getASTContext().getCharWidth();
462
463    VBTableOffset = 0;
464  } else {
465    FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
466
467    VBTableOffset = -1;
468  }
469
470  char Code = '\0';
471  switch (IM) {
472  case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
473  case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
474  case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
475  case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
476  }
477
478  Out << '$' << Code;
479
480  mangleNumber(FieldOffset);
481
482  // The C++ standard doesn't allow base-to-derived member pointer conversions
483  // in template parameter contexts, so the vbptr offset of data member pointers
484  // is always zero.
485  if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
486    mangleNumber(0);
487  if (MSInheritanceAttr::hasVBTableOffsetField(IM))
488    mangleNumber(VBTableOffset);
489}
490
491void
492MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
493                                                     const CXXMethodDecl *MD) {
494  // <member-function-pointer> ::= $1? <name>
495  //                           ::= $H? <name> <number>
496  //                           ::= $I? <name> <number> <number>
497  //                           ::= $J? <name> <number> <number> <number>
498
499  MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
500
501  char Code = '\0';
502  switch (IM) {
503  case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
504  case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
505  case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
506  case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
507  }
508
509  // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
510  // thunk.
511  uint64_t NVOffset = 0;
512  uint64_t VBTableOffset = 0;
513  uint64_t VBPtrOffset = 0;
514  if (MD) {
515    Out << '$' << Code << '?';
516    if (MD->isVirtual()) {
517      MicrosoftVTableContext *VTContext =
518          cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
519      const MicrosoftVTableContext::MethodVFTableLocation &ML =
520          VTContext->getMethodVFTableLocation(GlobalDecl(MD));
521      mangleVirtualMemPtrThunk(MD, ML);
522      NVOffset = ML.VFPtrOffset.getQuantity();
523      VBTableOffset = ML.VBTableIndex * 4;
524      if (ML.VBase) {
525        const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
526        VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
527      }
528    } else {
529      mangleName(MD);
530      mangleFunctionEncoding(MD);
531    }
532  } else {
533    // Null single inheritance member functions are encoded as a simple nullptr.
534    if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
535      Out << "$0A@";
536      return;
537    }
538    if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
539      VBTableOffset = -1;
540    Out << '$' << Code;
541  }
542
543  if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
544    mangleNumber(NVOffset);
545  if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
546    mangleNumber(VBPtrOffset);
547  if (MSInheritanceAttr::hasVBTableOffsetField(IM))
548    mangleNumber(VBTableOffset);
549}
550
551void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
552    const CXXMethodDecl *MD,
553    const MicrosoftVTableContext::MethodVFTableLocation &ML) {
554  // Get the vftable offset.
555  CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
556      getASTContext().getTargetInfo().getPointerWidth(0));
557  uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
558
559  Out << "?_9";
560  mangleName(MD->getParent());
561  Out << "$B";
562  mangleNumber(OffsetInVFTable);
563  Out << 'A';
564  Out << (PointersAre64Bit ? 'A' : 'E');
565}
566
567void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
568  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
569
570  // Always start with the unqualified name.
571  mangleUnqualifiedName(ND);
572
573  mangleNestedName(ND);
574
575  // Terminate the whole name with an '@'.
576  Out << '@';
577}
578
579void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
580  // <non-negative integer> ::= A@              # when Number == 0
581  //                        ::= <decimal digit> # when 1 <= Number <= 10
582  //                        ::= <hex digit>+ @  # when Number >= 10
583  //
584  // <number>               ::= [?] <non-negative integer>
585
586  uint64_t Value = static_cast<uint64_t>(Number);
587  if (Number < 0) {
588    Value = -Value;
589    Out << '?';
590  }
591
592  if (Value == 0)
593    Out << "A@";
594  else if (Value >= 1 && Value <= 10)
595    Out << (Value - 1);
596  else {
597    // Numbers that are not encoded as decimal digits are represented as nibbles
598    // in the range of ASCII characters 'A' to 'P'.
599    // The number 0x123450 would be encoded as 'BCDEFA'
600    char EncodedNumberBuffer[sizeof(uint64_t) * 2];
601    MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
602    MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
603    for (; Value != 0; Value >>= 4)
604      *I++ = 'A' + (Value & 0xf);
605    Out.write(I.base(), I - BufferRef.rbegin());
606    Out << '@';
607  }
608}
609
610static const TemplateDecl *
611isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
612  // Check if we have a function template.
613  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
614    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
615      TemplateArgs = FD->getTemplateSpecializationArgs();
616      return TD;
617    }
618  }
619
620  // Check if we have a class template.
621  if (const ClassTemplateSpecializationDecl *Spec =
622          dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
623    TemplateArgs = &Spec->getTemplateArgs();
624    return Spec->getSpecializedTemplate();
625  }
626
627  // Check if we have a variable template.
628  if (const VarTemplateSpecializationDecl *Spec =
629          dyn_cast<VarTemplateSpecializationDecl>(ND)) {
630    TemplateArgs = &Spec->getTemplateArgs();
631    return Spec->getSpecializedTemplate();
632  }
633
634  return nullptr;
635}
636
637void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
638                                                    DeclarationName Name) {
639  //  <unqualified-name> ::= <operator-name>
640  //                     ::= <ctor-dtor-name>
641  //                     ::= <source-name>
642  //                     ::= <template-name>
643
644  // Check if we have a template.
645  const TemplateArgumentList *TemplateArgs = nullptr;
646  if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
647    // Function templates aren't considered for name back referencing.  This
648    // makes sense since function templates aren't likely to occur multiple
649    // times in a symbol.
650    // FIXME: Test alias template mangling with MSVC 2013.
651    if (!isa<ClassTemplateDecl>(TD)) {
652      mangleTemplateInstantiationName(TD, *TemplateArgs);
653      Out << '@';
654      return;
655    }
656
657    // Here comes the tricky thing: if we need to mangle something like
658    //   void foo(A::X<Y>, B::X<Y>),
659    // the X<Y> part is aliased. However, if you need to mangle
660    //   void foo(A::X<A::Y>, A::X<B::Y>),
661    // the A::X<> part is not aliased.
662    // That said, from the mangler's perspective we have a structure like this:
663    //   namespace[s] -> type[ -> template-parameters]
664    // but from the Clang perspective we have
665    //   type [ -> template-parameters]
666    //      \-> namespace[s]
667    // What we do is we create a new mangler, mangle the same type (without
668    // a namespace suffix) to a string using the extra mangler and then use
669    // the mangled type name as a key to check the mangling of different types
670    // for aliasing.
671
672    llvm::SmallString<64> TemplateMangling;
673    llvm::raw_svector_ostream Stream(TemplateMangling);
674    MicrosoftCXXNameMangler Extra(Context, Stream);
675    Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
676    Stream.flush();
677
678    mangleSourceName(TemplateMangling);
679    return;
680  }
681
682  switch (Name.getNameKind()) {
683    case DeclarationName::Identifier: {
684      if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
685        mangleSourceName(II->getName());
686        break;
687      }
688
689      // Otherwise, an anonymous entity.  We must have a declaration.
690      assert(ND && "mangling empty name without declaration");
691
692      if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
693        if (NS->isAnonymousNamespace()) {
694          Out << "?A@";
695          break;
696        }
697      }
698
699      if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
700        // We must have an anonymous union or struct declaration.
701        const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
702        assert(RD && "expected variable decl to have a record type");
703        // Anonymous types with no tag or typedef get the name of their
704        // declarator mangled in.  If they have no declarator, number them with
705        // a $S prefix.
706        llvm::SmallString<64> Name("$S");
707        // Get a unique id for the anonymous struct.
708        Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
709        mangleSourceName(Name.str());
710        break;
711      }
712
713      // We must have an anonymous struct.
714      const TagDecl *TD = cast<TagDecl>(ND);
715      if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
716        assert(TD->getDeclContext() == D->getDeclContext() &&
717               "Typedef should not be in another decl context!");
718        assert(D->getDeclName().getAsIdentifierInfo() &&
719               "Typedef was not named!");
720        mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
721        break;
722      }
723
724      if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
725        if (Record->isLambda()) {
726          llvm::SmallString<10> Name("<lambda_");
727          unsigned LambdaId;
728          if (Record->getLambdaManglingNumber())
729            LambdaId = Record->getLambdaManglingNumber();
730          else
731            LambdaId = Context.getLambdaId(Record);
732
733          Name += llvm::utostr(LambdaId);
734          Name += ">";
735
736          mangleSourceName(Name);
737          break;
738        }
739      }
740
741      llvm::SmallString<64> Name("<unnamed-type-");
742      if (TD->hasDeclaratorForAnonDecl()) {
743        // Anonymous types with no tag or typedef get the name of their
744        // declarator mangled in if they have one.
745        Name += TD->getDeclaratorForAnonDecl()->getName();
746      } else {
747        // Otherwise, number the types using a $S prefix.
748        Name += "$S";
749        Name += llvm::utostr(Context.getAnonymousStructId(TD));
750      }
751      Name += ">";
752      mangleSourceName(Name.str());
753      break;
754    }
755
756    case DeclarationName::ObjCZeroArgSelector:
757    case DeclarationName::ObjCOneArgSelector:
758    case DeclarationName::ObjCMultiArgSelector:
759      llvm_unreachable("Can't mangle Objective-C selector names here!");
760
761    case DeclarationName::CXXConstructorName:
762      if (ND == Structor) {
763        assert(StructorType == Ctor_Complete &&
764               "Should never be asked to mangle a ctor other than complete");
765      }
766      Out << "?0";
767      break;
768
769    case DeclarationName::CXXDestructorName:
770      if (ND == Structor)
771        // If the named decl is the C++ destructor we're mangling,
772        // use the type we were given.
773        mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
774      else
775        // Otherwise, use the base destructor name. This is relevant if a
776        // class with a destructor is declared within a destructor.
777        mangleCXXDtorType(Dtor_Base);
778      break;
779
780    case DeclarationName::CXXConversionFunctionName:
781      // <operator-name> ::= ?B # (cast)
782      // The target type is encoded as the return type.
783      Out << "?B";
784      break;
785
786    case DeclarationName::CXXOperatorName:
787      mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
788      break;
789
790    case DeclarationName::CXXLiteralOperatorName: {
791      Out << "?__K";
792      mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
793      break;
794    }
795
796    case DeclarationName::CXXUsingDirective:
797      llvm_unreachable("Can't mangle a using directive name!");
798  }
799}
800
801void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
802  // <postfix> ::= <unqualified-name> [<postfix>]
803  //           ::= <substitution> [<postfix>]
804  if (isLambda(ND))
805    return;
806
807  const DeclContext *DC = ND->getDeclContext();
808
809  while (!DC->isTranslationUnit()) {
810    if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
811      unsigned Disc;
812      if (Context.getNextDiscriminator(ND, Disc)) {
813        Out << '?';
814        mangleNumber(Disc);
815        Out << '?';
816      }
817    }
818
819    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
820      DiagnosticsEngine &Diags = Context.getDiags();
821      unsigned DiagID =
822          Diags.getCustomDiagID(DiagnosticsEngine::Error,
823                                "cannot mangle a local inside this block yet");
824      Diags.Report(BD->getLocation(), DiagID);
825
826      // FIXME: This is completely, utterly, wrong; see ItaniumMangle
827      // for how this should be done.
828      Out << "__block_invoke" << Context.getBlockId(BD, false);
829      Out << '@';
830      continue;
831    } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
832      mangleObjCMethodName(Method);
833    } else if (isa<NamedDecl>(DC)) {
834      ND = cast<NamedDecl>(DC);
835      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
836        mangle(FD, "?");
837        break;
838      } else
839        mangleUnqualifiedName(ND);
840    }
841    DC = DC->getParent();
842  }
843}
844
845void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
846  // Microsoft uses the names on the case labels for these dtor variants.  Clang
847  // uses the Itanium terminology internally.  Everything in this ABI delegates
848  // towards the base dtor.
849  switch (T) {
850  // <operator-name> ::= ?1  # destructor
851  case Dtor_Base: Out << "?1"; return;
852  // <operator-name> ::= ?_D # vbase destructor
853  case Dtor_Complete: Out << "?_D"; return;
854  // <operator-name> ::= ?_G # scalar deleting destructor
855  case Dtor_Deleting: Out << "?_G"; return;
856  // <operator-name> ::= ?_E # vector deleting destructor
857  // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
858  // it.
859  }
860  llvm_unreachable("Unsupported dtor type?");
861}
862
863void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
864                                                 SourceLocation Loc) {
865  switch (OO) {
866  //                     ?0 # constructor
867  //                     ?1 # destructor
868  // <operator-name> ::= ?2 # new
869  case OO_New: Out << "?2"; break;
870  // <operator-name> ::= ?3 # delete
871  case OO_Delete: Out << "?3"; break;
872  // <operator-name> ::= ?4 # =
873  case OO_Equal: Out << "?4"; break;
874  // <operator-name> ::= ?5 # >>
875  case OO_GreaterGreater: Out << "?5"; break;
876  // <operator-name> ::= ?6 # <<
877  case OO_LessLess: Out << "?6"; break;
878  // <operator-name> ::= ?7 # !
879  case OO_Exclaim: Out << "?7"; break;
880  // <operator-name> ::= ?8 # ==
881  case OO_EqualEqual: Out << "?8"; break;
882  // <operator-name> ::= ?9 # !=
883  case OO_ExclaimEqual: Out << "?9"; break;
884  // <operator-name> ::= ?A # []
885  case OO_Subscript: Out << "?A"; break;
886  //                     ?B # conversion
887  // <operator-name> ::= ?C # ->
888  case OO_Arrow: Out << "?C"; break;
889  // <operator-name> ::= ?D # *
890  case OO_Star: Out << "?D"; break;
891  // <operator-name> ::= ?E # ++
892  case OO_PlusPlus: Out << "?E"; break;
893  // <operator-name> ::= ?F # --
894  case OO_MinusMinus: Out << "?F"; break;
895  // <operator-name> ::= ?G # -
896  case OO_Minus: Out << "?G"; break;
897  // <operator-name> ::= ?H # +
898  case OO_Plus: Out << "?H"; break;
899  // <operator-name> ::= ?I # &
900  case OO_Amp: Out << "?I"; break;
901  // <operator-name> ::= ?J # ->*
902  case OO_ArrowStar: Out << "?J"; break;
903  // <operator-name> ::= ?K # /
904  case OO_Slash: Out << "?K"; break;
905  // <operator-name> ::= ?L # %
906  case OO_Percent: Out << "?L"; break;
907  // <operator-name> ::= ?M # <
908  case OO_Less: Out << "?M"; break;
909  // <operator-name> ::= ?N # <=
910  case OO_LessEqual: Out << "?N"; break;
911  // <operator-name> ::= ?O # >
912  case OO_Greater: Out << "?O"; break;
913  // <operator-name> ::= ?P # >=
914  case OO_GreaterEqual: Out << "?P"; break;
915  // <operator-name> ::= ?Q # ,
916  case OO_Comma: Out << "?Q"; break;
917  // <operator-name> ::= ?R # ()
918  case OO_Call: Out << "?R"; break;
919  // <operator-name> ::= ?S # ~
920  case OO_Tilde: Out << "?S"; break;
921  // <operator-name> ::= ?T # ^
922  case OO_Caret: Out << "?T"; break;
923  // <operator-name> ::= ?U # |
924  case OO_Pipe: Out << "?U"; break;
925  // <operator-name> ::= ?V # &&
926  case OO_AmpAmp: Out << "?V"; break;
927  // <operator-name> ::= ?W # ||
928  case OO_PipePipe: Out << "?W"; break;
929  // <operator-name> ::= ?X # *=
930  case OO_StarEqual: Out << "?X"; break;
931  // <operator-name> ::= ?Y # +=
932  case OO_PlusEqual: Out << "?Y"; break;
933  // <operator-name> ::= ?Z # -=
934  case OO_MinusEqual: Out << "?Z"; break;
935  // <operator-name> ::= ?_0 # /=
936  case OO_SlashEqual: Out << "?_0"; break;
937  // <operator-name> ::= ?_1 # %=
938  case OO_PercentEqual: Out << "?_1"; break;
939  // <operator-name> ::= ?_2 # >>=
940  case OO_GreaterGreaterEqual: Out << "?_2"; break;
941  // <operator-name> ::= ?_3 # <<=
942  case OO_LessLessEqual: Out << "?_3"; break;
943  // <operator-name> ::= ?_4 # &=
944  case OO_AmpEqual: Out << "?_4"; break;
945  // <operator-name> ::= ?_5 # |=
946  case OO_PipeEqual: Out << "?_5"; break;
947  // <operator-name> ::= ?_6 # ^=
948  case OO_CaretEqual: Out << "?_6"; break;
949  //                     ?_7 # vftable
950  //                     ?_8 # vbtable
951  //                     ?_9 # vcall
952  //                     ?_A # typeof
953  //                     ?_B # local static guard
954  //                     ?_C # string
955  //                     ?_D # vbase destructor
956  //                     ?_E # vector deleting destructor
957  //                     ?_F # default constructor closure
958  //                     ?_G # scalar deleting destructor
959  //                     ?_H # vector constructor iterator
960  //                     ?_I # vector destructor iterator
961  //                     ?_J # vector vbase constructor iterator
962  //                     ?_K # virtual displacement map
963  //                     ?_L # eh vector constructor iterator
964  //                     ?_M # eh vector destructor iterator
965  //                     ?_N # eh vector vbase constructor iterator
966  //                     ?_O # copy constructor closure
967  //                     ?_P<name> # udt returning <name>
968  //                     ?_Q # <unknown>
969  //                     ?_R0 # RTTI Type Descriptor
970  //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
971  //                     ?_R2 # RTTI Base Class Array
972  //                     ?_R3 # RTTI Class Hierarchy Descriptor
973  //                     ?_R4 # RTTI Complete Object Locator
974  //                     ?_S # local vftable
975  //                     ?_T # local vftable constructor closure
976  // <operator-name> ::= ?_U # new[]
977  case OO_Array_New: Out << "?_U"; break;
978  // <operator-name> ::= ?_V # delete[]
979  case OO_Array_Delete: Out << "?_V"; break;
980
981  case OO_Conditional: {
982    DiagnosticsEngine &Diags = Context.getDiags();
983    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
984      "cannot mangle this conditional operator yet");
985    Diags.Report(Loc, DiagID);
986    break;
987  }
988
989  case OO_None:
990  case NUM_OVERLOADED_OPERATORS:
991    llvm_unreachable("Not an overloaded operator");
992  }
993}
994
995void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
996  // <source name> ::= <identifier> @
997  BackRefMap::iterator Found;
998  if (NameBackReferences.size() < 10) {
999    size_t Size = NameBackReferences.size();
1000    bool Inserted;
1001    std::tie(Found, Inserted) =
1002        NameBackReferences.insert(std::make_pair(Name, Size));
1003    if (Inserted)
1004      Found = NameBackReferences.end();
1005  } else {
1006    Found = NameBackReferences.find(Name);
1007  }
1008
1009  if (Found == NameBackReferences.end()) {
1010    Out << Name << '@';
1011  } else {
1012    Out << Found->second;
1013  }
1014}
1015
1016void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1017  Context.mangleObjCMethodName(MD, Out);
1018}
1019
1020void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1021    const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1022  // <template-name> ::= <unscoped-template-name> <template-args>
1023  //                 ::= <substitution>
1024  // Always start with the unqualified name.
1025
1026  // Templates have their own context for back references.
1027  ArgBackRefMap OuterArgsContext;
1028  BackRefMap OuterTemplateContext;
1029  NameBackReferences.swap(OuterTemplateContext);
1030  TypeBackReferences.swap(OuterArgsContext);
1031
1032  mangleUnscopedTemplateName(TD);
1033  mangleTemplateArgs(TD, TemplateArgs);
1034
1035  // Restore the previous back reference contexts.
1036  NameBackReferences.swap(OuterTemplateContext);
1037  TypeBackReferences.swap(OuterArgsContext);
1038}
1039
1040void
1041MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1042  // <unscoped-template-name> ::= ?$ <unqualified-name>
1043  Out << "?$";
1044  mangleUnqualifiedName(TD);
1045}
1046
1047void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1048                                                   bool IsBoolean) {
1049  // <integer-literal> ::= $0 <number>
1050  Out << "$0";
1051  // Make sure booleans are encoded as 0/1.
1052  if (IsBoolean && Value.getBoolValue())
1053    mangleNumber(1);
1054  else
1055    mangleNumber(Value.getSExtValue());
1056}
1057
1058void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1059  // See if this is a constant expression.
1060  llvm::APSInt Value;
1061  if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1062    mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1063    return;
1064  }
1065
1066  // Look through no-op casts like template parameter substitutions.
1067  E = E->IgnoreParenNoopCasts(Context.getASTContext());
1068
1069  const CXXUuidofExpr *UE = nullptr;
1070  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1071    if (UO->getOpcode() == UO_AddrOf)
1072      UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1073  } else
1074    UE = dyn_cast<CXXUuidofExpr>(E);
1075
1076  if (UE) {
1077    // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1078    // const __s_GUID _GUID_{lower case UUID with underscores}
1079    StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1080    std::string Name = "_GUID_" + Uuid.lower();
1081    std::replace(Name.begin(), Name.end(), '-', '_');
1082
1083    // If we had to peek through an address-of operator, treat this like we are
1084    // dealing with a pointer type.  Otherwise, treat it like a const reference.
1085    //
1086    // N.B. This matches up with the handling of TemplateArgument::Declaration
1087    // in mangleTemplateArg
1088    if (UE == E)
1089      Out << "$E?";
1090    else
1091      Out << "$1?";
1092    Out << Name << "@@3U__s_GUID@@B";
1093    return;
1094  }
1095
1096  // As bad as this diagnostic is, it's better than crashing.
1097  DiagnosticsEngine &Diags = Context.getDiags();
1098  unsigned DiagID = Diags.getCustomDiagID(
1099      DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1100  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1101                                        << E->getSourceRange();
1102}
1103
1104void MicrosoftCXXNameMangler::mangleTemplateArgs(
1105    const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1106  // <template-args> ::= <template-arg>+
1107  for (const TemplateArgument &TA : TemplateArgs.asArray())
1108    mangleTemplateArg(TD, TA);
1109}
1110
1111void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1112                                                const TemplateArgument &TA) {
1113  // <template-arg> ::= <type>
1114  //                ::= <integer-literal>
1115  //                ::= <member-data-pointer>
1116  //                ::= <member-function-pointer>
1117  //                ::= $E? <name> <type-encoding>
1118  //                ::= $1? <name> <type-encoding>
1119  //                ::= $0A@
1120  //                ::= <template-args>
1121
1122  switch (TA.getKind()) {
1123  case TemplateArgument::Null:
1124    llvm_unreachable("Can't mangle null template arguments!");
1125  case TemplateArgument::TemplateExpansion:
1126    llvm_unreachable("Can't mangle template expansion arguments!");
1127  case TemplateArgument::Type: {
1128    QualType T = TA.getAsType();
1129    mangleType(T, SourceRange(), QMM_Escape);
1130    break;
1131  }
1132  case TemplateArgument::Declaration: {
1133    const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1134    if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1135      mangleMemberDataPointer(
1136          cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1137          cast<ValueDecl>(ND));
1138    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1139      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1140      if (MD && MD->isInstance())
1141        mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1142      else
1143        mangle(FD, "$1?");
1144    } else {
1145      mangle(ND, TA.isDeclForReferenceParam() ? "$E?" : "$1?");
1146    }
1147    break;
1148  }
1149  case TemplateArgument::Integral:
1150    mangleIntegerLiteral(TA.getAsIntegral(),
1151                         TA.getIntegralType()->isBooleanType());
1152    break;
1153  case TemplateArgument::NullPtr: {
1154    QualType T = TA.getNullPtrType();
1155    if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1156      const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1157      if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
1158        mangleMemberFunctionPointer(RD, nullptr);
1159        return;
1160      }
1161      if (MPT->isMemberDataPointer()) {
1162        mangleMemberDataPointer(RD, nullptr);
1163        return;
1164      }
1165    }
1166    Out << "$0A@";
1167    break;
1168  }
1169  case TemplateArgument::Expression:
1170    mangleExpression(TA.getAsExpr());
1171    break;
1172  case TemplateArgument::Pack: {
1173    ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1174    if (TemplateArgs.empty()) {
1175      Out << "$S";
1176    } else {
1177      for (const TemplateArgument &PA : TemplateArgs)
1178        mangleTemplateArg(TD, PA);
1179    }
1180    break;
1181  }
1182  case TemplateArgument::Template:
1183    mangleType(cast<TagDecl>(
1184        TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl()));
1185    break;
1186  }
1187}
1188
1189void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1190                                               bool IsMember) {
1191  // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1192  // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1193  // 'I' means __restrict (32/64-bit).
1194  // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1195  // keyword!
1196  // <base-cvr-qualifiers> ::= A  # near
1197  //                       ::= B  # near const
1198  //                       ::= C  # near volatile
1199  //                       ::= D  # near const volatile
1200  //                       ::= E  # far (16-bit)
1201  //                       ::= F  # far const (16-bit)
1202  //                       ::= G  # far volatile (16-bit)
1203  //                       ::= H  # far const volatile (16-bit)
1204  //                       ::= I  # huge (16-bit)
1205  //                       ::= J  # huge const (16-bit)
1206  //                       ::= K  # huge volatile (16-bit)
1207  //                       ::= L  # huge const volatile (16-bit)
1208  //                       ::= M <basis> # based
1209  //                       ::= N <basis> # based const
1210  //                       ::= O <basis> # based volatile
1211  //                       ::= P <basis> # based const volatile
1212  //                       ::= Q  # near member
1213  //                       ::= R  # near const member
1214  //                       ::= S  # near volatile member
1215  //                       ::= T  # near const volatile member
1216  //                       ::= U  # far member (16-bit)
1217  //                       ::= V  # far const member (16-bit)
1218  //                       ::= W  # far volatile member (16-bit)
1219  //                       ::= X  # far const volatile member (16-bit)
1220  //                       ::= Y  # huge member (16-bit)
1221  //                       ::= Z  # huge const member (16-bit)
1222  //                       ::= 0  # huge volatile member (16-bit)
1223  //                       ::= 1  # huge const volatile member (16-bit)
1224  //                       ::= 2 <basis> # based member
1225  //                       ::= 3 <basis> # based const member
1226  //                       ::= 4 <basis> # based volatile member
1227  //                       ::= 5 <basis> # based const volatile member
1228  //                       ::= 6  # near function (pointers only)
1229  //                       ::= 7  # far function (pointers only)
1230  //                       ::= 8  # near method (pointers only)
1231  //                       ::= 9  # far method (pointers only)
1232  //                       ::= _A <basis> # based function (pointers only)
1233  //                       ::= _B <basis> # based function (far?) (pointers only)
1234  //                       ::= _C <basis> # based method (pointers only)
1235  //                       ::= _D <basis> # based method (far?) (pointers only)
1236  //                       ::= _E # block (Clang)
1237  // <basis> ::= 0 # __based(void)
1238  //         ::= 1 # __based(segment)?
1239  //         ::= 2 <name> # __based(name)
1240  //         ::= 3 # ?
1241  //         ::= 4 # ?
1242  //         ::= 5 # not really based
1243  bool HasConst = Quals.hasConst(),
1244       HasVolatile = Quals.hasVolatile();
1245
1246  if (!IsMember) {
1247    if (HasConst && HasVolatile) {
1248      Out << 'D';
1249    } else if (HasVolatile) {
1250      Out << 'C';
1251    } else if (HasConst) {
1252      Out << 'B';
1253    } else {
1254      Out << 'A';
1255    }
1256  } else {
1257    if (HasConst && HasVolatile) {
1258      Out << 'T';
1259    } else if (HasVolatile) {
1260      Out << 'S';
1261    } else if (HasConst) {
1262      Out << 'R';
1263    } else {
1264      Out << 'Q';
1265    }
1266  }
1267
1268  // FIXME: For now, just drop all extension qualifiers on the floor.
1269}
1270
1271void
1272MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1273  // <ref-qualifier> ::= G                # lvalue reference
1274  //                 ::= H                # rvalue-reference
1275  switch (RefQualifier) {
1276  case RQ_None:
1277    break;
1278
1279  case RQ_LValue:
1280    Out << 'G';
1281    break;
1282
1283  case RQ_RValue:
1284    Out << 'H';
1285    break;
1286  }
1287}
1288
1289void
1290MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1291                                                    const Type *PointeeType) {
1292  bool HasRestrict = Quals.hasRestrict();
1293  if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
1294    Out << 'E';
1295
1296  if (HasRestrict)
1297    Out << 'I';
1298}
1299
1300void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1301  // <pointer-cv-qualifiers> ::= P  # no qualifiers
1302  //                         ::= Q  # const
1303  //                         ::= R  # volatile
1304  //                         ::= S  # const volatile
1305  bool HasConst = Quals.hasConst(),
1306       HasVolatile = Quals.hasVolatile();
1307
1308  if (HasConst && HasVolatile) {
1309    Out << 'S';
1310  } else if (HasVolatile) {
1311    Out << 'R';
1312  } else if (HasConst) {
1313    Out << 'Q';
1314  } else {
1315    Out << 'P';
1316  }
1317}
1318
1319void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1320                                                 SourceRange Range) {
1321  // MSVC will backreference two canonically equivalent types that have slightly
1322  // different manglings when mangled alone.
1323
1324  // Decayed types do not match up with non-decayed versions of the same type.
1325  //
1326  // e.g.
1327  // void (*x)(void) will not form a backreference with void x(void)
1328  void *TypePtr;
1329  if (const DecayedType *DT = T->getAs<DecayedType>()) {
1330    TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
1331    // If the original parameter was textually written as an array,
1332    // instead treat the decayed parameter like it's const.
1333    //
1334    // e.g.
1335    // int [] -> int * const
1336    if (DT->getOriginalType()->isArrayType())
1337      T = T.withConst();
1338  } else
1339    TypePtr = T.getCanonicalType().getAsOpaquePtr();
1340
1341  ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1342
1343  if (Found == TypeBackReferences.end()) {
1344    size_t OutSizeBefore = Out.GetNumBytesInBuffer();
1345
1346    mangleType(T, Range, QMM_Drop);
1347
1348    // See if it's worth creating a back reference.
1349    // Only types longer than 1 character are considered
1350    // and only 10 back references slots are available:
1351    bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
1352    if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1353      size_t Size = TypeBackReferences.size();
1354      TypeBackReferences[TypePtr] = Size;
1355    }
1356  } else {
1357    Out << Found->second;
1358  }
1359}
1360
1361void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1362                                         QualifierMangleMode QMM) {
1363  // Don't use the canonical types.  MSVC includes things like 'const' on
1364  // pointer arguments to function pointers that canonicalization strips away.
1365  T = T.getDesugaredType(getASTContext());
1366  Qualifiers Quals = T.getLocalQualifiers();
1367  if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1368    // If there were any Quals, getAsArrayType() pushed them onto the array
1369    // element type.
1370    if (QMM == QMM_Mangle)
1371      Out << 'A';
1372    else if (QMM == QMM_Escape || QMM == QMM_Result)
1373      Out << "$$B";
1374    mangleArrayType(AT);
1375    return;
1376  }
1377
1378  bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1379                   T->isBlockPointerType();
1380
1381  switch (QMM) {
1382  case QMM_Drop:
1383    break;
1384  case QMM_Mangle:
1385    if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1386      Out << '6';
1387      mangleFunctionType(FT);
1388      return;
1389    }
1390    mangleQualifiers(Quals, false);
1391    break;
1392  case QMM_Escape:
1393    if (!IsPointer && Quals) {
1394      Out << "$$C";
1395      mangleQualifiers(Quals, false);
1396    }
1397    break;
1398  case QMM_Result:
1399    if ((!IsPointer && Quals) || isa<TagType>(T)) {
1400      Out << '?';
1401      mangleQualifiers(Quals, false);
1402    }
1403    break;
1404  }
1405
1406  // We have to mangle these now, while we still have enough information.
1407  if (IsPointer) {
1408    manglePointerCVQualifiers(Quals);
1409    manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
1410  }
1411  const Type *ty = T.getTypePtr();
1412
1413  switch (ty->getTypeClass()) {
1414#define ABSTRACT_TYPE(CLASS, PARENT)
1415#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1416  case Type::CLASS: \
1417    llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1418    return;
1419#define TYPE(CLASS, PARENT) \
1420  case Type::CLASS: \
1421    mangleType(cast<CLASS##Type>(ty), Range); \
1422    break;
1423#include "clang/AST/TypeNodes.def"
1424#undef ABSTRACT_TYPE
1425#undef NON_CANONICAL_TYPE
1426#undef TYPE
1427  }
1428}
1429
1430void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1431                                         SourceRange Range) {
1432  //  <type>         ::= <builtin-type>
1433  //  <builtin-type> ::= X  # void
1434  //                 ::= C  # signed char
1435  //                 ::= D  # char
1436  //                 ::= E  # unsigned char
1437  //                 ::= F  # short
1438  //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1439  //                 ::= H  # int
1440  //                 ::= I  # unsigned int
1441  //                 ::= J  # long
1442  //                 ::= K  # unsigned long
1443  //                     L  # <none>
1444  //                 ::= M  # float
1445  //                 ::= N  # double
1446  //                 ::= O  # long double (__float80 is mangled differently)
1447  //                 ::= _J # long long, __int64
1448  //                 ::= _K # unsigned long long, __int64
1449  //                 ::= _L # __int128
1450  //                 ::= _M # unsigned __int128
1451  //                 ::= _N # bool
1452  //                     _O # <array in parameter>
1453  //                 ::= _T # __float80 (Intel)
1454  //                 ::= _W # wchar_t
1455  //                 ::= _Z # __float80 (Digital Mars)
1456  switch (T->getKind()) {
1457  case BuiltinType::Void: Out << 'X'; break;
1458  case BuiltinType::SChar: Out << 'C'; break;
1459  case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1460  case BuiltinType::UChar: Out << 'E'; break;
1461  case BuiltinType::Short: Out << 'F'; break;
1462  case BuiltinType::UShort: Out << 'G'; break;
1463  case BuiltinType::Int: Out << 'H'; break;
1464  case BuiltinType::UInt: Out << 'I'; break;
1465  case BuiltinType::Long: Out << 'J'; break;
1466  case BuiltinType::ULong: Out << 'K'; break;
1467  case BuiltinType::Float: Out << 'M'; break;
1468  case BuiltinType::Double: Out << 'N'; break;
1469  // TODO: Determine size and mangle accordingly
1470  case BuiltinType::LongDouble: Out << 'O'; break;
1471  case BuiltinType::LongLong: Out << "_J"; break;
1472  case BuiltinType::ULongLong: Out << "_K"; break;
1473  case BuiltinType::Int128: Out << "_L"; break;
1474  case BuiltinType::UInt128: Out << "_M"; break;
1475  case BuiltinType::Bool: Out << "_N"; break;
1476  case BuiltinType::WChar_S:
1477  case BuiltinType::WChar_U: Out << "_W"; break;
1478
1479#define BUILTIN_TYPE(Id, SingletonId)
1480#define PLACEHOLDER_TYPE(Id, SingletonId) \
1481  case BuiltinType::Id:
1482#include "clang/AST/BuiltinTypes.def"
1483  case BuiltinType::Dependent:
1484    llvm_unreachable("placeholder types shouldn't get to name mangling");
1485
1486  case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1487  case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1488  case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1489
1490  case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1491  case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1492  case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1493  case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1494  case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1495  case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1496  case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1497  case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1498
1499  case BuiltinType::NullPtr: Out << "$$T"; break;
1500
1501  case BuiltinType::Char16:
1502  case BuiltinType::Char32:
1503  case BuiltinType::Half: {
1504    DiagnosticsEngine &Diags = Context.getDiags();
1505    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1506      "cannot mangle this built-in %0 type yet");
1507    Diags.Report(Range.getBegin(), DiagID)
1508      << T->getName(Context.getASTContext().getPrintingPolicy())
1509      << Range;
1510    break;
1511  }
1512  }
1513}
1514
1515// <type>          ::= <function-type>
1516void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1517                                         SourceRange) {
1518  // Structors only appear in decls, so at this point we know it's not a
1519  // structor type.
1520  // FIXME: This may not be lambda-friendly.
1521  Out << "$$A6";
1522  mangleFunctionType(T);
1523}
1524void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1525                                         SourceRange) {
1526  llvm_unreachable("Can't mangle K&R function prototypes");
1527}
1528
1529void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1530                                                 const FunctionDecl *D,
1531                                                 bool ForceInstMethod) {
1532  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1533  //                     <return-type> <argument-list> <throw-spec>
1534  const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1535
1536  SourceRange Range;
1537  if (D) Range = D->getSourceRange();
1538
1539  bool IsStructor = false, IsInstMethod = ForceInstMethod;
1540  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1541    if (MD->isInstance())
1542      IsInstMethod = true;
1543    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
1544      IsStructor = true;
1545  }
1546
1547  // If this is a C++ instance method, mangle the CVR qualifiers for the
1548  // this pointer.
1549  if (IsInstMethod) {
1550    Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1551    manglePointerExtQualifiers(Quals, nullptr);
1552    mangleRefQualifier(Proto->getRefQualifier());
1553    mangleQualifiers(Quals, false);
1554  }
1555
1556  mangleCallingConvention(T);
1557
1558  // <return-type> ::= <type>
1559  //               ::= @ # structors (they have no declared return type)
1560  if (IsStructor) {
1561    if (isa<CXXDestructorDecl>(D) && D == Structor &&
1562        StructorType == Dtor_Deleting) {
1563      // The scalar deleting destructor takes an extra int argument.
1564      // However, the FunctionType generated has 0 arguments.
1565      // FIXME: This is a temporary hack.
1566      // Maybe should fix the FunctionType creation instead?
1567      Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1568      return;
1569    }
1570    Out << '@';
1571  } else {
1572    QualType ResultType = Proto->getReturnType();
1573    if (const auto *AT =
1574            dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1575      Out << '?';
1576      mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1577      Out << '?';
1578      mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1579      Out << '@';
1580    } else {
1581      if (ResultType->isVoidType())
1582        ResultType = ResultType.getUnqualifiedType();
1583      mangleType(ResultType, Range, QMM_Result);
1584    }
1585  }
1586
1587  // <argument-list> ::= X # void
1588  //                 ::= <type>+ @
1589  //                 ::= <type>* Z # varargs
1590  if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1591    Out << 'X';
1592  } else {
1593    // Happens for function pointer type arguments for example.
1594    for (const QualType Arg : Proto->param_types())
1595      mangleArgumentType(Arg, Range);
1596    // <builtin-type>      ::= Z  # ellipsis
1597    if (Proto->isVariadic())
1598      Out << 'Z';
1599    else
1600      Out << '@';
1601  }
1602
1603  mangleThrowSpecification(Proto);
1604}
1605
1606void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1607  // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1608  //                                            # pointer. in 64-bit mode *all*
1609  //                                            # 'this' pointers are 64-bit.
1610  //                   ::= <global-function>
1611  // <member-function> ::= A # private: near
1612  //                   ::= B # private: far
1613  //                   ::= C # private: static near
1614  //                   ::= D # private: static far
1615  //                   ::= E # private: virtual near
1616  //                   ::= F # private: virtual far
1617  //                   ::= I # protected: near
1618  //                   ::= J # protected: far
1619  //                   ::= K # protected: static near
1620  //                   ::= L # protected: static far
1621  //                   ::= M # protected: virtual near
1622  //                   ::= N # protected: virtual far
1623  //                   ::= Q # public: near
1624  //                   ::= R # public: far
1625  //                   ::= S # public: static near
1626  //                   ::= T # public: static far
1627  //                   ::= U # public: virtual near
1628  //                   ::= V # public: virtual far
1629  // <global-function> ::= Y # global near
1630  //                   ::= Z # global far
1631  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1632    switch (MD->getAccess()) {
1633      case AS_none:
1634        llvm_unreachable("Unsupported access specifier");
1635      case AS_private:
1636        if (MD->isStatic())
1637          Out << 'C';
1638        else if (MD->isVirtual())
1639          Out << 'E';
1640        else
1641          Out << 'A';
1642        break;
1643      case AS_protected:
1644        if (MD->isStatic())
1645          Out << 'K';
1646        else if (MD->isVirtual())
1647          Out << 'M';
1648        else
1649          Out << 'I';
1650        break;
1651      case AS_public:
1652        if (MD->isStatic())
1653          Out << 'S';
1654        else if (MD->isVirtual())
1655          Out << 'U';
1656        else
1657          Out << 'Q';
1658    }
1659  } else
1660    Out << 'Y';
1661}
1662void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1663  // <calling-convention> ::= A # __cdecl
1664  //                      ::= B # __export __cdecl
1665  //                      ::= C # __pascal
1666  //                      ::= D # __export __pascal
1667  //                      ::= E # __thiscall
1668  //                      ::= F # __export __thiscall
1669  //                      ::= G # __stdcall
1670  //                      ::= H # __export __stdcall
1671  //                      ::= I # __fastcall
1672  //                      ::= J # __export __fastcall
1673  // The 'export' calling conventions are from a bygone era
1674  // (*cough*Win16*cough*) when functions were declared for export with
1675  // that keyword. (It didn't actually export them, it just made them so
1676  // that they could be in a DLL and somebody from another module could call
1677  // them.)
1678  CallingConv CC = T->getCallConv();
1679  switch (CC) {
1680    default:
1681      llvm_unreachable("Unsupported CC for mangling");
1682    case CC_X86_64Win64:
1683    case CC_X86_64SysV:
1684    case CC_C: Out << 'A'; break;
1685    case CC_X86Pascal: Out << 'C'; break;
1686    case CC_X86ThisCall: Out << 'E'; break;
1687    case CC_X86StdCall: Out << 'G'; break;
1688    case CC_X86FastCall: Out << 'I'; break;
1689  }
1690}
1691void MicrosoftCXXNameMangler::mangleThrowSpecification(
1692                                                const FunctionProtoType *FT) {
1693  // <throw-spec> ::= Z # throw(...) (default)
1694  //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1695  //              ::= <type>+
1696  // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1697  // all actually mangled as 'Z'. (They're ignored because their associated
1698  // functionality isn't implemented, and probably never will be.)
1699  Out << 'Z';
1700}
1701
1702void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1703                                         SourceRange Range) {
1704  // Probably should be mangled as a template instantiation; need to see what
1705  // VC does first.
1706  DiagnosticsEngine &Diags = Context.getDiags();
1707  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1708    "cannot mangle this unresolved dependent type yet");
1709  Diags.Report(Range.getBegin(), DiagID)
1710    << Range;
1711}
1712
1713// <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1714// <union-type>  ::= T <name>
1715// <struct-type> ::= U <name>
1716// <class-type>  ::= V <name>
1717// <enum-type>   ::= W4 <name>
1718void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1719  mangleType(cast<TagType>(T)->getDecl());
1720}
1721void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1722  mangleType(cast<TagType>(T)->getDecl());
1723}
1724void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1725  switch (TD->getTagKind()) {
1726    case TTK_Union:
1727      Out << 'T';
1728      break;
1729    case TTK_Struct:
1730    case TTK_Interface:
1731      Out << 'U';
1732      break;
1733    case TTK_Class:
1734      Out << 'V';
1735      break;
1736    case TTK_Enum:
1737      Out << "W4";
1738      break;
1739  }
1740  mangleName(TD);
1741}
1742
1743// <type>       ::= <array-type>
1744// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1745//                  [Y <dimension-count> <dimension>+]
1746//                  <element-type> # as global, E is never required
1747// It's supposed to be the other way around, but for some strange reason, it
1748// isn't. Today this behavior is retained for the sole purpose of backwards
1749// compatibility.
1750void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
1751  // This isn't a recursive mangling, so now we have to do it all in this
1752  // one call.
1753  manglePointerCVQualifiers(T->getElementType().getQualifiers());
1754  mangleType(T->getElementType(), SourceRange());
1755}
1756void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1757                                         SourceRange) {
1758  llvm_unreachable("Should have been special cased");
1759}
1760void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1761                                         SourceRange) {
1762  llvm_unreachable("Should have been special cased");
1763}
1764void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1765                                         SourceRange) {
1766  llvm_unreachable("Should have been special cased");
1767}
1768void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1769                                         SourceRange) {
1770  llvm_unreachable("Should have been special cased");
1771}
1772void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
1773  QualType ElementTy(T, 0);
1774  SmallVector<llvm::APInt, 3> Dimensions;
1775  for (;;) {
1776    if (const ConstantArrayType *CAT =
1777            getASTContext().getAsConstantArrayType(ElementTy)) {
1778      Dimensions.push_back(CAT->getSize());
1779      ElementTy = CAT->getElementType();
1780    } else if (ElementTy->isVariableArrayType()) {
1781      const VariableArrayType *VAT =
1782        getASTContext().getAsVariableArrayType(ElementTy);
1783      DiagnosticsEngine &Diags = Context.getDiags();
1784      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1785        "cannot mangle this variable-length array yet");
1786      Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1787        << VAT->getBracketsRange();
1788      return;
1789    } else if (ElementTy->isDependentSizedArrayType()) {
1790      // The dependent expression has to be folded into a constant (TODO).
1791      const DependentSizedArrayType *DSAT =
1792        getASTContext().getAsDependentSizedArrayType(ElementTy);
1793      DiagnosticsEngine &Diags = Context.getDiags();
1794      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1795        "cannot mangle this dependent-length array yet");
1796      Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1797        << DSAT->getBracketsRange();
1798      return;
1799    } else if (const IncompleteArrayType *IAT =
1800                   getASTContext().getAsIncompleteArrayType(ElementTy)) {
1801      Dimensions.push_back(llvm::APInt(32, 0));
1802      ElementTy = IAT->getElementType();
1803    }
1804    else break;
1805  }
1806  Out << 'Y';
1807  // <dimension-count> ::= <number> # number of extra dimensions
1808  mangleNumber(Dimensions.size());
1809  for (const llvm::APInt &Dimension : Dimensions)
1810    mangleNumber(Dimension.getLimitedValue());
1811  mangleType(ElementTy, SourceRange(), QMM_Escape);
1812}
1813
1814// <type>                   ::= <pointer-to-member-type>
1815// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1816//                                                          <class name> <type>
1817void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1818                                         SourceRange Range) {
1819  QualType PointeeType = T->getPointeeType();
1820  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1821    Out << '8';
1822    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1823    mangleFunctionType(FPT, nullptr, true);
1824  } else {
1825    mangleQualifiers(PointeeType.getQualifiers(), true);
1826    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1827    mangleType(PointeeType, Range, QMM_Drop);
1828  }
1829}
1830
1831void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1832                                         SourceRange Range) {
1833  DiagnosticsEngine &Diags = Context.getDiags();
1834  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1835    "cannot mangle this template type parameter type yet");
1836  Diags.Report(Range.getBegin(), DiagID)
1837    << Range;
1838}
1839
1840void MicrosoftCXXNameMangler::mangleType(
1841                                       const SubstTemplateTypeParmPackType *T,
1842                                       SourceRange Range) {
1843  DiagnosticsEngine &Diags = Context.getDiags();
1844  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1845    "cannot mangle this substituted parameter pack yet");
1846  Diags.Report(Range.getBegin(), DiagID)
1847    << Range;
1848}
1849
1850// <type> ::= <pointer-type>
1851// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1852//                       # the E is required for 64-bit non-static pointers
1853void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1854                                         SourceRange Range) {
1855  QualType PointeeTy = T->getPointeeType();
1856  mangleType(PointeeTy, Range);
1857}
1858void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1859                                         SourceRange Range) {
1860  // Object pointers never have qualifiers.
1861  Out << 'A';
1862  manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1863  mangleType(T->getPointeeType(), Range);
1864}
1865
1866// <type> ::= <reference-type>
1867// <reference-type> ::= A E? <cvr-qualifiers> <type>
1868//                 # the E is required for 64-bit non-static lvalue references
1869void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1870                                         SourceRange Range) {
1871  Out << 'A';
1872  manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1873  mangleType(T->getPointeeType(), Range);
1874}
1875
1876// <type> ::= <r-value-reference-type>
1877// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
1878//                 # the E is required for 64-bit non-static rvalue references
1879void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1880                                         SourceRange Range) {
1881  Out << "$$Q";
1882  manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1883  mangleType(T->getPointeeType(), Range);
1884}
1885
1886void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1887                                         SourceRange Range) {
1888  DiagnosticsEngine &Diags = Context.getDiags();
1889  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1890    "cannot mangle this complex number type yet");
1891  Diags.Report(Range.getBegin(), DiagID)
1892    << Range;
1893}
1894
1895void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1896                                         SourceRange Range) {
1897  const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
1898  assert(ET && "vectors with non-builtin elements are unsupported");
1899  uint64_t Width = getASTContext().getTypeSize(T);
1900  // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
1901  // doesn't match the Intel types uses a custom mangling below.
1902  bool IntelVector = true;
1903  if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
1904    Out << "T__m64";
1905  } else if (Width == 128 || Width == 256) {
1906    if (ET->getKind() == BuiltinType::Float)
1907      Out << "T__m" << Width;
1908    else if (ET->getKind() == BuiltinType::LongLong)
1909      Out << "T__m" << Width << 'i';
1910    else if (ET->getKind() == BuiltinType::Double)
1911      Out << "U__m" << Width << 'd';
1912    else
1913      IntelVector = false;
1914  } else {
1915    IntelVector = false;
1916  }
1917
1918  if (!IntelVector) {
1919    // The MS ABI doesn't have a special mangling for vector types, so we define
1920    // our own mangling to handle uses of __vector_size__ on user-specified
1921    // types, and for extensions like __v4sf.
1922    Out << "T__clang_vec" << T->getNumElements() << '_';
1923    mangleType(ET, Range);
1924  }
1925
1926  Out << "@@";
1927}
1928
1929void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1930                                         SourceRange Range) {
1931  DiagnosticsEngine &Diags = Context.getDiags();
1932  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1933    "cannot mangle this extended vector type yet");
1934  Diags.Report(Range.getBegin(), DiagID)
1935    << Range;
1936}
1937void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1938                                         SourceRange Range) {
1939  DiagnosticsEngine &Diags = Context.getDiags();
1940  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1941    "cannot mangle this dependent-sized extended vector type yet");
1942  Diags.Report(Range.getBegin(), DiagID)
1943    << Range;
1944}
1945
1946void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1947                                         SourceRange) {
1948  // ObjC interfaces have structs underlying them.
1949  Out << 'U';
1950  mangleName(T->getDecl());
1951}
1952
1953void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1954                                         SourceRange Range) {
1955  // We don't allow overloading by different protocol qualification,
1956  // so mangling them isn't necessary.
1957  mangleType(T->getBaseType(), Range);
1958}
1959
1960void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1961                                         SourceRange Range) {
1962  Out << "_E";
1963
1964  QualType pointee = T->getPointeeType();
1965  mangleFunctionType(pointee->castAs<FunctionProtoType>());
1966}
1967
1968void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
1969                                         SourceRange) {
1970  llvm_unreachable("Cannot mangle injected class name type.");
1971}
1972
1973void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1974                                         SourceRange Range) {
1975  DiagnosticsEngine &Diags = Context.getDiags();
1976  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1977    "cannot mangle this template specialization type yet");
1978  Diags.Report(Range.getBegin(), DiagID)
1979    << Range;
1980}
1981
1982void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1983                                         SourceRange Range) {
1984  DiagnosticsEngine &Diags = Context.getDiags();
1985  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1986    "cannot mangle this dependent name type yet");
1987  Diags.Report(Range.getBegin(), DiagID)
1988    << Range;
1989}
1990
1991void MicrosoftCXXNameMangler::mangleType(
1992                                 const DependentTemplateSpecializationType *T,
1993                                 SourceRange Range) {
1994  DiagnosticsEngine &Diags = Context.getDiags();
1995  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1996    "cannot mangle this dependent template specialization type yet");
1997  Diags.Report(Range.getBegin(), DiagID)
1998    << Range;
1999}
2000
2001void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
2002                                         SourceRange Range) {
2003  DiagnosticsEngine &Diags = Context.getDiags();
2004  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2005    "cannot mangle this pack expansion yet");
2006  Diags.Report(Range.getBegin(), DiagID)
2007    << Range;
2008}
2009
2010void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
2011                                         SourceRange Range) {
2012  DiagnosticsEngine &Diags = Context.getDiags();
2013  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2014    "cannot mangle this typeof(type) yet");
2015  Diags.Report(Range.getBegin(), DiagID)
2016    << Range;
2017}
2018
2019void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
2020                                         SourceRange Range) {
2021  DiagnosticsEngine &Diags = Context.getDiags();
2022  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2023    "cannot mangle this typeof(expression) yet");
2024  Diags.Report(Range.getBegin(), DiagID)
2025    << Range;
2026}
2027
2028void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
2029                                         SourceRange Range) {
2030  DiagnosticsEngine &Diags = Context.getDiags();
2031  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2032    "cannot mangle this decltype() yet");
2033  Diags.Report(Range.getBegin(), DiagID)
2034    << Range;
2035}
2036
2037void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2038                                         SourceRange Range) {
2039  DiagnosticsEngine &Diags = Context.getDiags();
2040  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2041    "cannot mangle this unary transform type yet");
2042  Diags.Report(Range.getBegin(), DiagID)
2043    << Range;
2044}
2045
2046void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
2047  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2048
2049  DiagnosticsEngine &Diags = Context.getDiags();
2050  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2051    "cannot mangle this 'auto' type yet");
2052  Diags.Report(Range.getBegin(), DiagID)
2053    << Range;
2054}
2055
2056void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
2057                                         SourceRange Range) {
2058  DiagnosticsEngine &Diags = Context.getDiags();
2059  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2060    "cannot mangle this C11 atomic type yet");
2061  Diags.Report(Range.getBegin(), DiagID)
2062    << Range;
2063}
2064
2065void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2066                                               raw_ostream &Out) {
2067  assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2068         "Invalid mangleName() call, argument is not a variable or function!");
2069  assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2070         "Invalid mangleName() call on 'structor decl!");
2071
2072  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2073                                 getASTContext().getSourceManager(),
2074                                 "Mangling declaration");
2075
2076  MicrosoftCXXNameMangler Mangler(*this, Out);
2077  return Mangler.mangle(D);
2078}
2079
2080// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2081//                       <virtual-adjustment>
2082// <no-adjustment>      ::= A # private near
2083//                      ::= B # private far
2084//                      ::= I # protected near
2085//                      ::= J # protected far
2086//                      ::= Q # public near
2087//                      ::= R # public far
2088// <static-adjustment>  ::= G <static-offset> # private near
2089//                      ::= H <static-offset> # private far
2090//                      ::= O <static-offset> # protected near
2091//                      ::= P <static-offset> # protected far
2092//                      ::= W <static-offset> # public near
2093//                      ::= X <static-offset> # public far
2094// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2095//                      ::= $1 <virtual-shift> <static-offset> # private far
2096//                      ::= $2 <virtual-shift> <static-offset> # protected near
2097//                      ::= $3 <virtual-shift> <static-offset> # protected far
2098//                      ::= $4 <virtual-shift> <static-offset> # public near
2099//                      ::= $5 <virtual-shift> <static-offset> # public far
2100// <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2101// <vtordisp-shift>     ::= <offset-to-vtordisp>
2102// <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2103//                          <offset-to-vtordisp>
2104static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2105                                      const ThisAdjustment &Adjustment,
2106                                      MicrosoftCXXNameMangler &Mangler,
2107                                      raw_ostream &Out) {
2108  if (!Adjustment.Virtual.isEmpty()) {
2109    Out << '$';
2110    char AccessSpec;
2111    switch (MD->getAccess()) {
2112    case AS_none:
2113      llvm_unreachable("Unsupported access specifier");
2114    case AS_private:
2115      AccessSpec = '0';
2116      break;
2117    case AS_protected:
2118      AccessSpec = '2';
2119      break;
2120    case AS_public:
2121      AccessSpec = '4';
2122    }
2123    if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2124      Out << 'R' << AccessSpec;
2125      Mangler.mangleNumber(
2126          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2127      Mangler.mangleNumber(
2128          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2129      Mangler.mangleNumber(
2130          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2131      Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2132    } else {
2133      Out << AccessSpec;
2134      Mangler.mangleNumber(
2135          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2136      Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2137    }
2138  } else if (Adjustment.NonVirtual != 0) {
2139    switch (MD->getAccess()) {
2140    case AS_none:
2141      llvm_unreachable("Unsupported access specifier");
2142    case AS_private:
2143      Out << 'G';
2144      break;
2145    case AS_protected:
2146      Out << 'O';
2147      break;
2148    case AS_public:
2149      Out << 'W';
2150    }
2151    Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2152  } else {
2153    switch (MD->getAccess()) {
2154    case AS_none:
2155      llvm_unreachable("Unsupported access specifier");
2156    case AS_private:
2157      Out << 'A';
2158      break;
2159    case AS_protected:
2160      Out << 'I';
2161      break;
2162    case AS_public:
2163      Out << 'Q';
2164    }
2165  }
2166}
2167
2168void
2169MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2170                                                     raw_ostream &Out) {
2171  MicrosoftVTableContext *VTContext =
2172      cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2173  const MicrosoftVTableContext::MethodVFTableLocation &ML =
2174      VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2175
2176  MicrosoftCXXNameMangler Mangler(*this, Out);
2177  Mangler.getStream() << "\01?";
2178  Mangler.mangleVirtualMemPtrThunk(MD, ML);
2179}
2180
2181void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2182                                             const ThunkInfo &Thunk,
2183                                             raw_ostream &Out) {
2184  MicrosoftCXXNameMangler Mangler(*this, Out);
2185  Out << "\01?";
2186  Mangler.mangleName(MD);
2187  mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2188  if (!Thunk.Return.isEmpty())
2189    assert(Thunk.Method != nullptr &&
2190           "Thunk info should hold the overridee decl");
2191
2192  const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2193  Mangler.mangleFunctionType(
2194      DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2195}
2196
2197void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2198    const CXXDestructorDecl *DD, CXXDtorType Type,
2199    const ThisAdjustment &Adjustment, raw_ostream &Out) {
2200  // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2201  // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2202  // mangling manually until we support both deleting dtor types.
2203  assert(Type == Dtor_Deleting);
2204  MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2205  Out << "\01??_E";
2206  Mangler.mangleName(DD->getParent());
2207  mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2208  Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2209}
2210
2211void MicrosoftMangleContextImpl::mangleCXXVFTable(
2212    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2213    raw_ostream &Out) {
2214  // <mangled-name> ::= ?_7 <class-name> <storage-class>
2215  //                    <cvr-qualifiers> [<name>] @
2216  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2217  // is always '6' for vftables.
2218  MicrosoftCXXNameMangler Mangler(*this, Out);
2219  Mangler.getStream() << "\01??_7";
2220  Mangler.mangleName(Derived);
2221  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2222  for (const CXXRecordDecl *RD : BasePath)
2223    Mangler.mangleName(RD);
2224  Mangler.getStream() << '@';
2225}
2226
2227void MicrosoftMangleContextImpl::mangleCXXVBTable(
2228    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2229    raw_ostream &Out) {
2230  // <mangled-name> ::= ?_8 <class-name> <storage-class>
2231  //                    <cvr-qualifiers> [<name>] @
2232  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2233  // is always '7' for vbtables.
2234  MicrosoftCXXNameMangler Mangler(*this, Out);
2235  Mangler.getStream() << "\01??_8";
2236  Mangler.mangleName(Derived);
2237  Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2238  for (const CXXRecordDecl *RD : BasePath)
2239    Mangler.mangleName(RD);
2240  Mangler.getStream() << '@';
2241}
2242
2243void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2244  MicrosoftCXXNameMangler Mangler(*this, Out);
2245  Mangler.getStream() << "\01??_R0";
2246  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2247  Mangler.getStream() << "@8";
2248}
2249
2250void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2251                                                   raw_ostream &Out) {
2252  MicrosoftCXXNameMangler Mangler(*this, Out);
2253  Mangler.getStream() << '.';
2254  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2255}
2256
2257void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2258    const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2259    uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2260  MicrosoftCXXNameMangler Mangler(*this, Out);
2261  Mangler.getStream() << "\01??_R1";
2262  Mangler.mangleNumber(NVOffset);
2263  Mangler.mangleNumber(VBPtrOffset);
2264  Mangler.mangleNumber(VBTableOffset);
2265  Mangler.mangleNumber(Flags);
2266  Mangler.mangleName(Derived);
2267  Mangler.getStream() << "8";
2268}
2269
2270void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2271    const CXXRecordDecl *Derived, raw_ostream &Out) {
2272  MicrosoftCXXNameMangler Mangler(*this, Out);
2273  Mangler.getStream() << "\01??_R2";
2274  Mangler.mangleName(Derived);
2275  Mangler.getStream() << "8";
2276}
2277
2278void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2279    const CXXRecordDecl *Derived, raw_ostream &Out) {
2280  MicrosoftCXXNameMangler Mangler(*this, Out);
2281  Mangler.getStream() << "\01??_R3";
2282  Mangler.mangleName(Derived);
2283  Mangler.getStream() << "8";
2284}
2285
2286void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2287    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2288    raw_ostream &Out) {
2289  // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2290  //                    <cvr-qualifiers> [<name>] @
2291  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2292  // is always '6' for vftables.
2293  MicrosoftCXXNameMangler Mangler(*this, Out);
2294  Mangler.getStream() << "\01??_R4";
2295  Mangler.mangleName(Derived);
2296  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2297  for (const CXXRecordDecl *RD : BasePath)
2298    Mangler.mangleName(RD);
2299  Mangler.getStream() << '@';
2300}
2301
2302void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2303  // This is just a made up unique string for the purposes of tbaa.  undname
2304  // does *not* know how to demangle it.
2305  MicrosoftCXXNameMangler Mangler(*this, Out);
2306  Mangler.getStream() << '?';
2307  Mangler.mangleType(T, SourceRange());
2308}
2309
2310void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2311                                               CXXCtorType Type,
2312                                               raw_ostream &Out) {
2313  MicrosoftCXXNameMangler mangler(*this, Out);
2314  mangler.mangle(D);
2315}
2316
2317void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2318                                               CXXDtorType Type,
2319                                               raw_ostream &Out) {
2320  MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2321  mangler.mangle(D);
2322}
2323
2324void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2325                                                          unsigned,
2326                                                          raw_ostream &) {
2327  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2328    "cannot mangle this reference temporary yet");
2329  getDiags().Report(VD->getLocation(), DiagID);
2330}
2331
2332void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2333                                                           raw_ostream &Out) {
2334  // TODO: This is not correct, especially with respect to MSVC2013.  MSVC2013
2335  // utilizes thread local variables to implement thread safe, re-entrant
2336  // initialization for statics.  They no longer differentiate between an
2337  // externally visible and non-externally visible static with respect to
2338  // mangling, they all get $TSS <number>.
2339  //
2340  // N.B. This means that they can get more than 32 static variable guards in a
2341  // scope.  It also means that they broke compatibility with their own ABI.
2342
2343  // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2344  //              ::= ?$S <guard-num> @ <postfix> @4IA
2345
2346  // The first mangling is what MSVC uses to guard static locals in inline
2347  // functions.  It uses a different mangling in external functions to support
2348  // guarding more than 32 variables.  MSVC rejects inline functions with more
2349  // than 32 static locals.  We don't fully implement the second mangling
2350  // because those guards are not externally visible, and instead use LLVM's
2351  // default renaming when creating a new guard variable.
2352  MicrosoftCXXNameMangler Mangler(*this, Out);
2353
2354  bool Visible = VD->isExternallyVisible();
2355  // <operator-name> ::= ?_B # local static guard
2356  Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
2357  unsigned ScopeDepth = 0;
2358  if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2359    // If we do not have a discriminator and are emitting a guard variable for
2360    // use at global scope, then mangling the nested name will not be enough to
2361    // remove ambiguities.
2362    Mangler.mangle(VD, "");
2363  else
2364    Mangler.mangleNestedName(VD);
2365  Mangler.getStream() << (Visible ? "@5" : "@4IA");
2366  if (ScopeDepth)
2367    Mangler.mangleNumber(ScopeDepth);
2368}
2369
2370void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2371                                                    raw_ostream &Out,
2372                                                    char CharCode) {
2373  MicrosoftCXXNameMangler Mangler(*this, Out);
2374  Mangler.getStream() << "\01??__" << CharCode;
2375  Mangler.mangleName(D);
2376  if (D->isStaticDataMember()) {
2377    Mangler.mangleVariableEncoding(D);
2378    Mangler.getStream() << '@';
2379  }
2380  // This is the function class mangling.  These stubs are global, non-variadic,
2381  // cdecl functions that return void and take no args.
2382  Mangler.getStream() << "YAXXZ";
2383}
2384
2385void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2386                                                          raw_ostream &Out) {
2387  // <initializer-name> ::= ?__E <name> YAXXZ
2388  mangleInitFiniStub(D, Out, 'E');
2389}
2390
2391void
2392MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2393                                                          raw_ostream &Out) {
2394  // <destructor-name> ::= ?__F <name> YAXXZ
2395  mangleInitFiniStub(D, Out, 'F');
2396}
2397
2398void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2399                                                     raw_ostream &Out) {
2400  // <char-type> ::= 0   # char
2401  //             ::= 1   # wchar_t
2402  //             ::= ??? # char16_t/char32_t will need a mangling too...
2403  //
2404  // <literal-length> ::= <non-negative integer>  # the length of the literal
2405  //
2406  // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2407  //                                              # null-terminator
2408  //
2409  // <encoded-string> ::= <simple character>           # uninteresting character
2410  //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2411  //                                                   # encode the byte for the
2412  //                                                   # character
2413  //                  ::= '?' [a-z]                    # \xe1 - \xfa
2414  //                  ::= '?' [A-Z]                    # \xc1 - \xda
2415  //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
2416  //
2417  // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2418  //               <encoded-string> '@'
2419  MicrosoftCXXNameMangler Mangler(*this, Out);
2420  Mangler.getStream() << "\01??_C@_";
2421
2422  // <char-type>: The "kind" of string literal is encoded into the mangled name.
2423  // TODO: This needs to be updated when MSVC gains support for unicode
2424  // literals.
2425  if (SL->isAscii())
2426    Mangler.getStream() << '0';
2427  else if (SL->isWide())
2428    Mangler.getStream() << '1';
2429  else
2430    llvm_unreachable("unexpected string literal kind!");
2431
2432  // <literal-length>: The next part of the mangled name consists of the length
2433  // of the string.
2434  // The StringLiteral does not consider the NUL terminator byte(s) but the
2435  // mangling does.
2436  // N.B. The length is in terms of bytes, not characters.
2437  Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2438
2439  // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2440  // properties of our CRC:
2441  //   Width  : 32
2442  //   Poly   : 04C11DB7
2443  //   Init   : FFFFFFFF
2444  //   RefIn  : True
2445  //   RefOut : True
2446  //   XorOut : 00000000
2447  //   Check  : 340BC6D9
2448  uint32_t CRC = 0xFFFFFFFFU;
2449
2450  auto UpdateCRC = [&CRC](char Byte) {
2451    for (unsigned i = 0; i < 8; ++i) {
2452      bool Bit = CRC & 0x80000000U;
2453      if (Byte & (1U << i))
2454        Bit = !Bit;
2455      CRC <<= 1;
2456      if (Bit)
2457        CRC ^= 0x04C11DB7U;
2458    }
2459  };
2460
2461  auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2462    unsigned CharByteWidth = SL->getCharByteWidth();
2463    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2464    unsigned OffsetInCodeUnit = Index % CharByteWidth;
2465    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2466  };
2467
2468  auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2469    unsigned CharByteWidth = SL->getCharByteWidth();
2470    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2471    unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2472    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2473  };
2474
2475  // CRC all the bytes of the StringLiteral.
2476  for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2477    UpdateCRC(GetLittleEndianByte(I));
2478
2479  // The NUL terminator byte(s) were not present earlier,
2480  // we need to manually process those bytes into the CRC.
2481  for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2482       ++NullTerminator)
2483    UpdateCRC('\x00');
2484
2485  // The literature refers to the process of reversing the bits in the final CRC
2486  // output as "reflection".
2487  CRC = llvm::reverseBits(CRC);
2488
2489  // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2490  // scheme.
2491  Mangler.mangleNumber(CRC);
2492
2493  // <encoded-string>: The mangled name also contains the first 32 _characters_
2494  // (including null-terminator bytes) of the StringLiteral.
2495  // Each character is encoded by splitting them into bytes and then encoding
2496  // the constituent bytes.
2497  auto MangleByte = [&Mangler](char Byte) {
2498    // There are five different manglings for characters:
2499    // - [a-zA-Z0-9_$]: A one-to-one mapping.
2500    // - ?[a-z]: The range from \xe1 to \xfa.
2501    // - ?[A-Z]: The range from \xc1 to \xda.
2502    // - ?[0-9]: The set of [,/\:. \n\t'-].
2503    // - ?$XX: A fallback which maps nibbles.
2504    if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2505      Mangler.getStream() << Byte;
2506    } else if (isLetter(Byte & 0x7f)) {
2507      Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2508    } else {
2509      switch (Byte) {
2510        case ',':
2511          Mangler.getStream() << "?0";
2512          break;
2513        case '/':
2514          Mangler.getStream() << "?1";
2515          break;
2516        case '\\':
2517          Mangler.getStream() << "?2";
2518          break;
2519        case ':':
2520          Mangler.getStream() << "?3";
2521          break;
2522        case '.':
2523          Mangler.getStream() << "?4";
2524          break;
2525        case ' ':
2526          Mangler.getStream() << "?5";
2527          break;
2528        case '\n':
2529          Mangler.getStream() << "?6";
2530          break;
2531        case '\t':
2532          Mangler.getStream() << "?7";
2533          break;
2534        case '\'':
2535          Mangler.getStream() << "?8";
2536          break;
2537        case '-':
2538          Mangler.getStream() << "?9";
2539          break;
2540        default:
2541          Mangler.getStream() << "?$";
2542          Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2543          Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2544          break;
2545      }
2546    }
2547  };
2548
2549  // Enforce our 32 character max.
2550  unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2551  for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2552       ++I)
2553    MangleByte(GetBigEndianByte(I));
2554
2555  // Encode the NUL terminator if there is room.
2556  if (NumCharsToMangle < 32)
2557    for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2558         ++NullTerminator)
2559      MangleByte(0);
2560
2561  Mangler.getStream() << '@';
2562}
2563
2564MicrosoftMangleContext *
2565MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2566  return new MicrosoftMangleContextImpl(Context, Diags);
2567}
2568