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