clang  9.0.0svn
MicrosoftMangle.cpp
Go to the documentation of this file.
1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Mangle.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclOpenMP.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/JamCRC.h"
31 #include "llvm/Support/xxhash.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/MathExtras.h"
34 
35 using namespace clang;
36 
37 namespace {
38 
39 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
40  raw_ostream &OS;
41  llvm::SmallString<64> Buffer;
42 
43  msvc_hashing_ostream(raw_ostream &OS)
44  : llvm::raw_svector_ostream(Buffer), OS(OS) {}
45  ~msvc_hashing_ostream() override {
46  StringRef MangledName = str();
47  bool StartsWithEscape = MangledName.startswith("\01");
48  if (StartsWithEscape)
49  MangledName = MangledName.drop_front(1);
50  if (MangledName.size() <= 4096) {
51  OS << str();
52  return;
53  }
54 
55  llvm::MD5 Hasher;
56  llvm::MD5::MD5Result Hash;
57  Hasher.update(MangledName);
58  Hasher.final(Hash);
59 
60  SmallString<32> HexString;
61  llvm::MD5::stringifyResult(Hash, HexString);
62 
63  if (StartsWithEscape)
64  OS << '\01';
65  OS << "??@" << HexString << '@';
66  }
67 };
68 
69 static const DeclContext *
70 getLambdaDefaultArgumentDeclContext(const Decl *D) {
71  if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
72  if (RD->isLambda())
73  if (const auto *Parm =
74  dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
75  return Parm->getDeclContext();
76  return nullptr;
77 }
78 
79 /// Retrieve the declaration context that should be used when mangling
80 /// the given declaration.
81 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
82  // The ABI assumes that lambda closure types that occur within
83  // default arguments live in the context of the function. However, due to
84  // the way in which Clang parses and creates function declarations, this is
85  // not the case: the lambda closure type ends up living in the context
86  // where the function itself resides, because the function declaration itself
87  // had not yet been created. Fix the context here.
88  if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
89  return LDADC;
90 
91  // Perform the same check for block literals.
92  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
93  if (ParmVarDecl *ContextParam =
94  dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
95  return ContextParam->getDeclContext();
96  }
97 
98  const DeclContext *DC = D->getDeclContext();
99  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
100  isa<OMPDeclareMapperDecl>(DC)) {
101  return getEffectiveDeclContext(cast<Decl>(DC));
102  }
103 
104  return DC->getRedeclContext();
105 }
106 
107 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
108  return getEffectiveDeclContext(cast<Decl>(DC));
109 }
110 
111 static const FunctionDecl *getStructor(const NamedDecl *ND) {
112  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
113  return FTD->getTemplatedDecl()->getCanonicalDecl();
114 
115  const auto *FD = cast<FunctionDecl>(ND);
116  if (const auto *FTD = FD->getPrimaryTemplate())
117  return FTD->getTemplatedDecl()->getCanonicalDecl();
118 
119  return FD->getCanonicalDecl();
120 }
121 
122 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
123 /// Microsoft Visual C++ ABI.
124 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
125  typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
126  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127  llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
128  llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
129  llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
130  llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
131  SmallString<16> AnonymousNamespaceHash;
132 
133 public:
134  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
135  bool shouldMangleCXXName(const NamedDecl *D) override;
136  bool shouldMangleStringLiteral(const StringLiteral *SL) override;
137  void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
138  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
139  const MethodVFTableLocation &ML,
140  raw_ostream &Out) override;
141  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
142  raw_ostream &) override;
143  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145  raw_ostream &) override;
146  void mangleCXXVFTable(const CXXRecordDecl *Derived,
148  raw_ostream &Out) override;
149  void mangleCXXVBTable(const CXXRecordDecl *Derived,
151  raw_ostream &Out) override;
152  void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
153  const CXXRecordDecl *DstRD,
154  raw_ostream &Out) override;
155  void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
156  bool IsUnaligned, uint32_t NumEntries,
157  raw_ostream &Out) override;
158  void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
159  raw_ostream &Out) override;
160  void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
161  CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
162  int32_t VBPtrOffset, uint32_t VBIndex,
163  raw_ostream &Out) override;
164  void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
165  void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
166  void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
167  uint32_t NVOffset, int32_t VBPtrOffset,
168  uint32_t VBTableOffset, uint32_t Flags,
169  raw_ostream &Out) override;
170  void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
171  raw_ostream &Out) override;
172  void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
173  raw_ostream &Out) override;
174  void
175  mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
177  raw_ostream &Out) override;
178  void mangleTypeName(QualType T, raw_ostream &) override;
179  void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
180  raw_ostream &) override;
181  void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
182  raw_ostream &) override;
183  void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
184  raw_ostream &) override;
185  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
186  void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
187  raw_ostream &Out) override;
188  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
189  void mangleDynamicAtExitDestructor(const VarDecl *D,
190  raw_ostream &Out) override;
191  void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
192  raw_ostream &Out) override;
193  void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
194  raw_ostream &Out) override;
195  void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
196  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
197  const DeclContext *DC = getEffectiveDeclContext(ND);
198  if (!DC->isFunctionOrMethod())
199  return false;
200 
201  // Lambda closure types are already numbered, give out a phony number so
202  // that they demangle nicely.
203  if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
204  if (RD->isLambda()) {
205  disc = 1;
206  return true;
207  }
208  }
209 
210  // Use the canonical number for externally visible decls.
211  if (ND->isExternallyVisible()) {
212  disc = getASTContext().getManglingNumber(ND);
213  return true;
214  }
215 
216  // Anonymous tags are already numbered.
217  if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
218  if (!Tag->hasNameForLinkage() &&
219  !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
220  !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
221  return false;
222  }
223 
224  // Make up a reasonable number for internal decls.
225  unsigned &discriminator = Uniquifier[ND];
226  if (!discriminator)
227  discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
228  disc = discriminator + 1;
229  return true;
230  }
231 
232  unsigned getLambdaId(const CXXRecordDecl *RD) {
233  assert(RD->isLambda() && "RD must be a lambda!");
234  assert(!RD->isExternallyVisible() && "RD must not be visible!");
235  assert(RD->getLambdaManglingNumber() == 0 &&
236  "RD must not have a mangling number!");
237  std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
238  Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
239  return Result.first->second;
240  }
241 
242  /// Return a character sequence that is (somewhat) unique to the TU suitable
243  /// for mangling anonymous namespaces.
244  StringRef getAnonymousNamespaceHash() const {
245  return AnonymousNamespaceHash;
246  }
247 
248 private:
249  void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
250 };
251 
252 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
253 /// Microsoft Visual C++ ABI.
254 class MicrosoftCXXNameMangler {
255  MicrosoftMangleContextImpl &Context;
256  raw_ostream &Out;
257 
258  /// The "structor" is the top-level declaration being mangled, if
259  /// that's not a template specialization; otherwise it's the pattern
260  /// for that specialization.
261  const NamedDecl *Structor;
262  unsigned StructorType;
263 
264  typedef llvm::SmallVector<std::string, 10> BackRefVec;
265  BackRefVec NameBackReferences;
266 
267  typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
268  ArgBackRefMap TypeBackReferences;
269 
270  typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet;
271  PassObjectSizeArgsSet PassObjectSizeArgs;
272 
273  ASTContext &getASTContext() const { return Context.getASTContext(); }
274 
275  // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
276  // this check into mangleQualifiers().
277  const bool PointersAre64Bit;
278 
279 public:
280  enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
281 
282  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
283  : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
284  PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
285  64) {}
286 
287  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
289  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
290  PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
291  64) {}
292 
293  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
295  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
296  PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
297  64) {}
298 
299  raw_ostream &getStream() const { return Out; }
300 
301  void mangle(const NamedDecl *D, StringRef Prefix = "?");
302  void mangleName(const NamedDecl *ND);
303  void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
304  void mangleVariableEncoding(const VarDecl *VD);
305  void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
306  void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
307  const CXXMethodDecl *MD);
308  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
309  const MethodVFTableLocation &ML);
310  void mangleNumber(int64_t Number);
311  void mangleTagTypeKind(TagTypeKind TK);
312  void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
313  ArrayRef<StringRef> NestedNames = None);
314  void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
315  void mangleType(QualType T, SourceRange Range,
316  QualifierMangleMode QMM = QMM_Mangle);
317  void mangleFunctionType(const FunctionType *T,
318  const FunctionDecl *D = nullptr,
319  bool ForceThisQuals = false,
320  bool MangleExceptionSpec = true);
321  void mangleNestedName(const NamedDecl *ND);
322 
323 private:
324  bool isStructorDecl(const NamedDecl *ND) const {
325  return ND == Structor || getStructor(ND) == Structor;
326  }
327 
328  void mangleUnqualifiedName(const NamedDecl *ND) {
329  mangleUnqualifiedName(ND, ND->getDeclName());
330  }
331  void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
332  void mangleSourceName(StringRef Name);
333  void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
334  void mangleCXXDtorType(CXXDtorType T);
335  void mangleQualifiers(Qualifiers Quals, bool IsMember);
336  void mangleRefQualifier(RefQualifierKind RefQualifier);
337  void manglePointerCVQualifiers(Qualifiers Quals);
338  void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
339 
340  void mangleUnscopedTemplateName(const TemplateDecl *ND);
341  void
342  mangleTemplateInstantiationName(const TemplateDecl *TD,
343  const TemplateArgumentList &TemplateArgs);
344  void mangleObjCMethodName(const ObjCMethodDecl *MD);
345 
346  void mangleArgumentType(QualType T, SourceRange Range);
347  void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
348 
349  bool isArtificialTagType(QualType T) const;
350 
351  // Declare manglers for every type class.
352 #define ABSTRACT_TYPE(CLASS, PARENT)
353 #define NON_CANONICAL_TYPE(CLASS, PARENT)
354 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
355  Qualifiers Quals, \
356  SourceRange Range);
357 #include "clang/AST/TypeNodes.def"
358 #undef ABSTRACT_TYPE
359 #undef NON_CANONICAL_TYPE
360 #undef TYPE
361 
362  void mangleType(const TagDecl *TD);
363  void mangleDecayedArrayType(const ArrayType *T);
364  void mangleArrayType(const ArrayType *T);
365  void mangleFunctionClass(const FunctionDecl *FD);
366  void mangleCallingConvention(CallingConv CC);
367  void mangleCallingConvention(const FunctionType *T);
368  void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
369  void mangleExpression(const Expr *E);
370  void mangleThrowSpecification(const FunctionProtoType *T);
371 
372  void mangleTemplateArgs(const TemplateDecl *TD,
373  const TemplateArgumentList &TemplateArgs);
374  void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
375  const NamedDecl *Parm);
376 
377  void mangleObjCProtocol(const ObjCProtocolDecl *PD);
378  void mangleObjCLifetime(const QualType T, Qualifiers Quals,
379  SourceRange Range);
380  void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
381  SourceRange Range);
382 };
383 }
384 
385 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
386  DiagnosticsEngine &Diags)
387  : MicrosoftMangleContext(Context, Diags) {
388  // To mangle anonymous namespaces, hash the path to the main source file. The
389  // path should be whatever (probably relative) path was passed on the command
390  // line. The goal is for the compiler to produce the same output regardless of
391  // working directory, so use the uncanonicalized relative path.
392  //
393  // It's important to make the mangled names unique because, when CodeView
394  // debug info is in use, the debugger uses mangled type names to distinguish
395  // between otherwise identically named types in anonymous namespaces.
396  //
397  // These symbols are always internal, so there is no need for the hash to
398  // match what MSVC produces. For the same reason, clang is free to change the
399  // hash at any time without breaking compatibility with old versions of clang.
400  // The generated names are intended to look similar to what MSVC generates,
401  // which are something like "?A0x01234567@".
402  SourceManager &SM = Context.getSourceManager();
403  if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
404  // Truncate the hash so we get 8 characters of hexadecimal.
405  uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
406  AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
407  } else {
408  // If we don't have a path to the main file, we'll just use 0.
409  AnonymousNamespaceHash = "0";
410  }
411 }
412 
413 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
414  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415  LanguageLinkage L = FD->getLanguageLinkage();
416  // Overloadable functions need mangling.
417  if (FD->hasAttr<OverloadableAttr>())
418  return true;
419 
420  // The ABI expects that we would never mangle "typical" user-defined entry
421  // points regardless of visibility or freestanding-ness.
422  //
423  // N.B. This is distinct from asking about "main". "main" has a lot of
424  // special rules associated with it in the standard while these
425  // user-defined entry points are outside of the purview of the standard.
426  // For example, there can be only one definition for "main" in a standards
427  // compliant program; however nothing forbids the existence of wmain and
428  // WinMain in the same translation unit.
429  if (FD->isMSVCRTEntryPoint())
430  return false;
431 
432  // C++ functions and those whose names are not a simple identifier need
433  // mangling.
434  if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
435  return true;
436 
437  // C functions are not mangled.
438  if (L == CLanguageLinkage)
439  return false;
440  }
441 
442  // Otherwise, no mangling is done outside C++ mode.
443  if (!getASTContext().getLangOpts().CPlusPlus)
444  return false;
445 
446  const VarDecl *VD = dyn_cast<VarDecl>(D);
447  if (VD && !isa<DecompositionDecl>(D)) {
448  // C variables are not mangled.
449  if (VD->isExternC())
450  return false;
451 
452  // Variables at global scope with non-internal linkage are not mangled.
453  const DeclContext *DC = getEffectiveDeclContext(D);
454  // Check for extern variable declared locally.
455  if (DC->isFunctionOrMethod() && D->hasLinkage())
456  while (!DC->isNamespace() && !DC->isTranslationUnit())
457  DC = getEffectiveParentContext(DC);
458 
459  if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
460  !isa<VarTemplateSpecializationDecl>(D) &&
461  D->getIdentifier() != nullptr)
462  return false;
463  }
464 
465  return true;
466 }
467 
468 bool
469 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
470  return true;
471 }
472 
473 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
474  // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
475  // Therefore it's really important that we don't decorate the
476  // name with leading underscores or leading/trailing at signs. So, by
477  // default, we emit an asm marker at the start so we get the name right.
478  // Callers can override this with a custom prefix.
479 
480  // <mangled-name> ::= ? <name> <type-encoding>
481  Out << Prefix;
482  mangleName(D);
483  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
484  mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
485  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
486  mangleVariableEncoding(VD);
487  else
488  llvm_unreachable("Tried to mangle unexpected NamedDecl!");
489 }
490 
491 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
492  bool ShouldMangle) {
493  // <type-encoding> ::= <function-class> <function-type>
494 
495  // Since MSVC operates on the type as written and not the canonical type, it
496  // actually matters which decl we have here. MSVC appears to choose the
497  // first, since it is most likely to be the declaration in a header file.
498  FD = FD->getFirstDecl();
499 
500  // We should never ever see a FunctionNoProtoType at this point.
501  // We don't even know how to mangle their types anyway :).
502  const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
503 
504  // extern "C" functions can hold entities that must be mangled.
505  // As it stands, these functions still need to get expressed in the full
506  // external name. They have their class and type omitted, replaced with '9'.
507  if (ShouldMangle) {
508  // We would like to mangle all extern "C" functions using this additional
509  // component but this would break compatibility with MSVC's behavior.
510  // Instead, do this when we know that compatibility isn't important (in
511  // other words, when it is an overloaded extern "C" function).
512  if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
513  Out << "$$J0";
514 
515  mangleFunctionClass(FD);
516 
517  mangleFunctionType(FT, FD, false, false);
518  } else {
519  Out << '9';
520  }
521 }
522 
523 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
524  // <type-encoding> ::= <storage-class> <variable-type>
525  // <storage-class> ::= 0 # private static member
526  // ::= 1 # protected static member
527  // ::= 2 # public static member
528  // ::= 3 # global
529  // ::= 4 # static local
530 
531  // The first character in the encoding (after the name) is the storage class.
532  if (VD->isStaticDataMember()) {
533  // If it's a static member, it also encodes the access level.
534  switch (VD->getAccess()) {
535  default:
536  case AS_private: Out << '0'; break;
537  case AS_protected: Out << '1'; break;
538  case AS_public: Out << '2'; break;
539  }
540  }
541  else if (!VD->isStaticLocal())
542  Out << '3';
543  else
544  Out << '4';
545  // Now mangle the type.
546  // <variable-type> ::= <type> <cvr-qualifiers>
547  // ::= <type> <pointee-cvr-qualifiers> # pointers, references
548  // Pointers and references are odd. The type of 'int * const foo;' gets
549  // mangled as 'QAHA' instead of 'PAHB', for example.
550  SourceRange SR = VD->getSourceRange();
551  QualType Ty = VD->getType();
552  if (Ty->isPointerType() || Ty->isReferenceType() ||
553  Ty->isMemberPointerType()) {
554  mangleType(Ty, SR, QMM_Drop);
555  manglePointerExtQualifiers(
556  Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
557  if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
558  mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
559  // Member pointers are suffixed with a back reference to the member
560  // pointer's class name.
561  mangleName(MPT->getClass()->getAsCXXRecordDecl());
562  } else
563  mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
564  } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
565  // Global arrays are funny, too.
566  mangleDecayedArrayType(AT);
567  if (AT->getElementType()->isArrayType())
568  Out << 'A';
569  else
570  mangleQualifiers(Ty.getQualifiers(), false);
571  } else {
572  mangleType(Ty, SR, QMM_Drop);
573  mangleQualifiers(Ty.getQualifiers(), false);
574  }
575 }
576 
577 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
578  const ValueDecl *VD) {
579  // <member-data-pointer> ::= <integer-literal>
580  // ::= $F <number> <number>
581  // ::= $G <number> <number> <number>
582 
583  int64_t FieldOffset;
584  int64_t VBTableOffset;
585  MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
586  if (VD) {
587  FieldOffset = getASTContext().getFieldOffset(VD);
588  assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
589  "cannot take address of bitfield");
590  FieldOffset /= getASTContext().getCharWidth();
591 
592  VBTableOffset = 0;
593 
594  if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
595  FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
596  } else {
597  FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
598 
599  VBTableOffset = -1;
600  }
601 
602  char Code = '\0';
603  switch (IM) {
604  case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
605  case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
606  case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
607  case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
608  }
609 
610  Out << '$' << Code;
611 
612  mangleNumber(FieldOffset);
613 
614  // The C++ standard doesn't allow base-to-derived member pointer conversions
615  // in template parameter contexts, so the vbptr offset of data member pointers
616  // is always zero.
617  if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
618  mangleNumber(0);
619  if (MSInheritanceAttr::hasVBTableOffsetField(IM))
620  mangleNumber(VBTableOffset);
621 }
622 
623 void
624 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
625  const CXXMethodDecl *MD) {
626  // <member-function-pointer> ::= $1? <name>
627  // ::= $H? <name> <number>
628  // ::= $I? <name> <number> <number>
629  // ::= $J? <name> <number> <number> <number>
630 
631  MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
632 
633  char Code = '\0';
634  switch (IM) {
635  case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
636  case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
637  case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
638  case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
639  }
640 
641  // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
642  // thunk.
643  uint64_t NVOffset = 0;
644  uint64_t VBTableOffset = 0;
645  uint64_t VBPtrOffset = 0;
646  if (MD) {
647  Out << '$' << Code << '?';
648  if (MD->isVirtual()) {
649  MicrosoftVTableContext *VTContext =
650  cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
652  VTContext->getMethodVFTableLocation(GlobalDecl(MD));
653  mangleVirtualMemPtrThunk(MD, ML);
654  NVOffset = ML.VFPtrOffset.getQuantity();
655  VBTableOffset = ML.VBTableIndex * 4;
656  if (ML.VBase) {
657  const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
658  VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
659  }
660  } else {
661  mangleName(MD);
662  mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
663  }
664 
665  if (VBTableOffset == 0 &&
666  IM == MSInheritanceAttr::Keyword_virtual_inheritance)
667  NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
668  } else {
669  // Null single inheritance member functions are encoded as a simple nullptr.
670  if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
671  Out << "$0A@";
672  return;
673  }
674  if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
675  VBTableOffset = -1;
676  Out << '$' << Code;
677  }
678 
679  if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
680  mangleNumber(static_cast<uint32_t>(NVOffset));
681  if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
682  mangleNumber(VBPtrOffset);
683  if (MSInheritanceAttr::hasVBTableOffsetField(IM))
684  mangleNumber(VBTableOffset);
685 }
686 
687 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
688  const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
689  // Get the vftable offset.
690  CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
691  getASTContext().getTargetInfo().getPointerWidth(0));
692  uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
693 
694  Out << "?_9";
695  mangleName(MD->getParent());
696  Out << "$B";
697  mangleNumber(OffsetInVFTable);
698  Out << 'A';
699  mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
700 }
701 
702 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
703  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
704 
705  // Always start with the unqualified name.
706  mangleUnqualifiedName(ND);
707 
708  mangleNestedName(ND);
709 
710  // Terminate the whole name with an '@'.
711  Out << '@';
712 }
713 
714 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
715  // <non-negative integer> ::= A@ # when Number == 0
716  // ::= <decimal digit> # when 1 <= Number <= 10
717  // ::= <hex digit>+ @ # when Number >= 10
718  //
719  // <number> ::= [?] <non-negative integer>
720 
721  uint64_t Value = static_cast<uint64_t>(Number);
722  if (Number < 0) {
723  Value = -Value;
724  Out << '?';
725  }
726 
727  if (Value == 0)
728  Out << "A@";
729  else if (Value >= 1 && Value <= 10)
730  Out << (Value - 1);
731  else {
732  // Numbers that are not encoded as decimal digits are represented as nibbles
733  // in the range of ASCII characters 'A' to 'P'.
734  // The number 0x123450 would be encoded as 'BCDEFA'
735  char EncodedNumberBuffer[sizeof(uint64_t) * 2];
736  MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
737  MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
738  for (; Value != 0; Value >>= 4)
739  *I++ = 'A' + (Value & 0xf);
740  Out.write(I.base(), I - BufferRef.rbegin());
741  Out << '@';
742  }
743 }
744 
745 static const TemplateDecl *
746 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
747  // Check if we have a function template.
748  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
749  if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
750  TemplateArgs = FD->getTemplateSpecializationArgs();
751  return TD;
752  }
753  }
754 
755  // Check if we have a class template.
756  if (const ClassTemplateSpecializationDecl *Spec =
757  dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
758  TemplateArgs = &Spec->getTemplateArgs();
759  return Spec->getSpecializedTemplate();
760  }
761 
762  // Check if we have a variable template.
763  if (const VarTemplateSpecializationDecl *Spec =
764  dyn_cast<VarTemplateSpecializationDecl>(ND)) {
765  TemplateArgs = &Spec->getTemplateArgs();
766  return Spec->getSpecializedTemplate();
767  }
768 
769  return nullptr;
770 }
771 
772 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
773  DeclarationName Name) {
774  // <unqualified-name> ::= <operator-name>
775  // ::= <ctor-dtor-name>
776  // ::= <source-name>
777  // ::= <template-name>
778 
779  // Check if we have a template.
780  const TemplateArgumentList *TemplateArgs = nullptr;
781  if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
782  // Function templates aren't considered for name back referencing. This
783  // makes sense since function templates aren't likely to occur multiple
784  // times in a symbol.
785  if (isa<FunctionTemplateDecl>(TD)) {
786  mangleTemplateInstantiationName(TD, *TemplateArgs);
787  Out << '@';
788  return;
789  }
790 
791  // Here comes the tricky thing: if we need to mangle something like
792  // void foo(A::X<Y>, B::X<Y>),
793  // the X<Y> part is aliased. However, if you need to mangle
794  // void foo(A::X<A::Y>, A::X<B::Y>),
795  // the A::X<> part is not aliased.
796  // That said, from the mangler's perspective we have a structure like this:
797  // namespace[s] -> type[ -> template-parameters]
798  // but from the Clang perspective we have
799  // type [ -> template-parameters]
800  // \-> namespace[s]
801  // What we do is we create a new mangler, mangle the same type (without
802  // a namespace suffix) to a string using the extra mangler and then use
803  // the mangled type name as a key to check the mangling of different types
804  // for aliasing.
805 
806  llvm::SmallString<64> TemplateMangling;
807  llvm::raw_svector_ostream Stream(TemplateMangling);
808  MicrosoftCXXNameMangler Extra(Context, Stream);
809  Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
810 
811  mangleSourceName(TemplateMangling);
812  return;
813  }
814 
815  switch (Name.getNameKind()) {
817  if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
818  mangleSourceName(II->getName());
819  break;
820  }
821 
822  // Otherwise, an anonymous entity. We must have a declaration.
823  assert(ND && "mangling empty name without declaration");
824 
825  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
826  if (NS->isAnonymousNamespace()) {
827  Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
828  break;
829  }
830  }
831 
832  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
833  // FIXME: Invented mangling for decomposition declarations:
834  // [X,Y,Z]
835  // where X,Y,Z are the names of the bindings.
836  llvm::SmallString<128> Name("[");
837  for (auto *BD : DD->bindings()) {
838  if (Name.size() > 1)
839  Name += ',';
840  Name += BD->getDeclName().getAsIdentifierInfo()->getName();
841  }
842  Name += ']';
843  mangleSourceName(Name);
844  break;
845  }
846 
847  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
848  // We must have an anonymous union or struct declaration.
849  const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
850  assert(RD && "expected variable decl to have a record type");
851  // Anonymous types with no tag or typedef get the name of their
852  // declarator mangled in. If they have no declarator, number them with
853  // a $S prefix.
854  llvm::SmallString<64> Name("$S");
855  // Get a unique id for the anonymous struct.
856  Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
857  mangleSourceName(Name.str());
858  break;
859  }
860 
861  // We must have an anonymous struct.
862  const TagDecl *TD = cast<TagDecl>(ND);
863  if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
864  assert(TD->getDeclContext() == D->getDeclContext() &&
865  "Typedef should not be in another decl context!");
866  assert(D->getDeclName().getAsIdentifierInfo() &&
867  "Typedef was not named!");
868  mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
869  break;
870  }
871 
872  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
873  if (Record->isLambda()) {
874  llvm::SmallString<10> Name("<lambda_");
875 
876  Decl *LambdaContextDecl = Record->getLambdaContextDecl();
877  unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
878  unsigned LambdaId;
879  const ParmVarDecl *Parm =
880  dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
881  const FunctionDecl *Func =
882  Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
883 
884  if (Func) {
885  unsigned DefaultArgNo =
886  Func->getNumParams() - Parm->getFunctionScopeIndex();
887  Name += llvm::utostr(DefaultArgNo);
888  Name += "_";
889  }
890 
891  if (LambdaManglingNumber)
892  LambdaId = LambdaManglingNumber;
893  else
894  LambdaId = Context.getLambdaId(Record);
895 
896  Name += llvm::utostr(LambdaId);
897  Name += ">";
898 
899  mangleSourceName(Name);
900 
901  // If the context of a closure type is an initializer for a class
902  // member (static or nonstatic), it is encoded in a qualified name.
903  if (LambdaManglingNumber && LambdaContextDecl) {
904  if ((isa<VarDecl>(LambdaContextDecl) ||
905  isa<FieldDecl>(LambdaContextDecl)) &&
906  LambdaContextDecl->getDeclContext()->isRecord()) {
907  mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
908  }
909  }
910  break;
911  }
912  }
913 
915  if (DeclaratorDecl *DD =
916  Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
917  // Anonymous types without a name for linkage purposes have their
918  // declarator mangled in if they have one.
919  Name += "<unnamed-type-";
920  Name += DD->getName();
921  } else if (TypedefNameDecl *TND =
922  Context.getASTContext().getTypedefNameForUnnamedTagDecl(
923  TD)) {
924  // Anonymous types without a name for linkage purposes have their
925  // associate typedef mangled in if they have one.
926  Name += "<unnamed-type-";
927  Name += TND->getName();
928  } else if (isa<EnumDecl>(TD) &&
929  cast<EnumDecl>(TD)->enumerator_begin() !=
930  cast<EnumDecl>(TD)->enumerator_end()) {
931  // Anonymous non-empty enums mangle in the first enumerator.
932  auto *ED = cast<EnumDecl>(TD);
933  Name += "<unnamed-enum-";
934  Name += ED->enumerator_begin()->getName();
935  } else {
936  // Otherwise, number the types using a $S prefix.
937  Name += "<unnamed-type-$S";
938  Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
939  }
940  Name += ">";
941  mangleSourceName(Name.str());
942  break;
943  }
944 
945  case DeclarationName::ObjCZeroArgSelector:
946  case DeclarationName::ObjCOneArgSelector:
947  case DeclarationName::ObjCMultiArgSelector: {
948  // This is reachable only when constructing an outlined SEH finally
949  // block. Nothing depends on this mangling and it's used only with
950  // functinos with internal linkage.
952  mangleSourceName(Name.str());
953  break;
954  }
955 
956  case DeclarationName::CXXConstructorName:
957  if (isStructorDecl(ND)) {
958  if (StructorType == Ctor_CopyingClosure) {
959  Out << "?_O";
960  return;
961  }
962  if (StructorType == Ctor_DefaultClosure) {
963  Out << "?_F";
964  return;
965  }
966  }
967  Out << "?0";
968  return;
969 
970  case DeclarationName::CXXDestructorName:
971  if (isStructorDecl(ND))
972  // If the named decl is the C++ destructor we're mangling,
973  // use the type we were given.
974  mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
975  else
976  // Otherwise, use the base destructor name. This is relevant if a
977  // class with a destructor is declared within a destructor.
978  mangleCXXDtorType(Dtor_Base);
979  break;
980 
981  case DeclarationName::CXXConversionFunctionName:
982  // <operator-name> ::= ?B # (cast)
983  // The target type is encoded as the return type.
984  Out << "?B";
985  break;
986 
987  case DeclarationName::CXXOperatorName:
988  mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
989  break;
990 
991  case DeclarationName::CXXLiteralOperatorName: {
992  Out << "?__K";
993  mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
994  break;
995  }
996 
997  case DeclarationName::CXXDeductionGuideName:
998  llvm_unreachable("Can't mangle a deduction guide name!");
999 
1000  case DeclarationName::CXXUsingDirective:
1001  llvm_unreachable("Can't mangle a using directive name!");
1002  }
1003 }
1004 
1005 // <postfix> ::= <unqualified-name> [<postfix>]
1006 // ::= <substitution> [<postfix>]
1007 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
1008  const DeclContext *DC = getEffectiveDeclContext(ND);
1009  while (!DC->isTranslationUnit()) {
1010  if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1011  unsigned Disc;
1012  if (Context.getNextDiscriminator(ND, Disc)) {
1013  Out << '?';
1014  mangleNumber(Disc);
1015  Out << '?';
1016  }
1017  }
1018 
1019  if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1020  auto Discriminate =
1021  [](StringRef Name, const unsigned Discriminator,
1022  const unsigned ParameterDiscriminator) -> std::string {
1023  std::string Buffer;
1024  llvm::raw_string_ostream Stream(Buffer);
1025  Stream << Name;
1026  if (Discriminator)
1027  Stream << '_' << Discriminator;
1028  if (ParameterDiscriminator)
1029  Stream << '_' << ParameterDiscriminator;
1030  return Stream.str();
1031  };
1032 
1033  unsigned Discriminator = BD->getBlockManglingNumber();
1034  if (!Discriminator)
1035  Discriminator = Context.getBlockId(BD, /*Local=*/false);
1036 
1037  // Mangle the parameter position as a discriminator to deal with unnamed
1038  // parameters. Rather than mangling the unqualified parameter name,
1039  // always use the position to give a uniform mangling.
1040  unsigned ParameterDiscriminator = 0;
1041  if (const auto *MC = BD->getBlockManglingContextDecl())
1042  if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1043  if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1044  ParameterDiscriminator =
1045  F->getNumParams() - P->getFunctionScopeIndex();
1046 
1047  DC = getEffectiveDeclContext(BD);
1048 
1049  Out << '?';
1050  mangleSourceName(Discriminate("_block_invoke", Discriminator,
1051  ParameterDiscriminator));
1052  // If we have a block mangling context, encode that now. This allows us
1053  // to discriminate between named static data initializers in the same
1054  // scope. This is handled differently from parameters, which use
1055  // positions to discriminate between multiple instances.
1056  if (const auto *MC = BD->getBlockManglingContextDecl())
1057  if (!isa<ParmVarDecl>(MC))
1058  if (const auto *ND = dyn_cast<NamedDecl>(MC))
1059  mangleUnqualifiedName(ND);
1060  // MS ABI and Itanium manglings are in inverted scopes. In the case of a
1061  // RecordDecl, mangle the entire scope hierarchy at this point rather than
1062  // just the unqualified name to get the ordering correct.
1063  if (const auto *RD = dyn_cast<RecordDecl>(DC))
1064  mangleName(RD);
1065  else
1066  Out << '@';
1067  // void __cdecl
1068  Out << "YAX";
1069  // struct __block_literal *
1070  Out << 'P';
1071  // __ptr64
1072  if (PointersAre64Bit)
1073  Out << 'E';
1074  Out << 'A';
1075  mangleArtificialTagType(TTK_Struct,
1076  Discriminate("__block_literal", Discriminator,
1077  ParameterDiscriminator));
1078  Out << "@Z";
1079 
1080  // If the effective context was a Record, we have fully mangled the
1081  // qualified name and do not need to continue.
1082  if (isa<RecordDecl>(DC))
1083  break;
1084  continue;
1085  } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1086  mangleObjCMethodName(Method);
1087  } else if (isa<NamedDecl>(DC)) {
1088  ND = cast<NamedDecl>(DC);
1089  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1090  mangle(FD, "?");
1091  break;
1092  } else {
1093  mangleUnqualifiedName(ND);
1094  // Lambdas in default arguments conceptually belong to the function the
1095  // parameter corresponds to.
1096  if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1097  DC = LDADC;
1098  continue;
1099  }
1100  }
1101  }
1102  DC = DC->getParent();
1103  }
1104 }
1105 
1106 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1107  // Microsoft uses the names on the case labels for these dtor variants. Clang
1108  // uses the Itanium terminology internally. Everything in this ABI delegates
1109  // towards the base dtor.
1110  switch (T) {
1111  // <operator-name> ::= ?1 # destructor
1112  case Dtor_Base: Out << "?1"; return;
1113  // <operator-name> ::= ?_D # vbase destructor
1114  case Dtor_Complete: Out << "?_D"; return;
1115  // <operator-name> ::= ?_G # scalar deleting destructor
1116  case Dtor_Deleting: Out << "?_G"; return;
1117  // <operator-name> ::= ?_E # vector deleting destructor
1118  // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
1119  // it.
1120  case Dtor_Comdat:
1121  llvm_unreachable("not expecting a COMDAT");
1122  }
1123  llvm_unreachable("Unsupported dtor type?");
1124 }
1125 
1126 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1127  SourceLocation Loc) {
1128  switch (OO) {
1129  // ?0 # constructor
1130  // ?1 # destructor
1131  // <operator-name> ::= ?2 # new
1132  case OO_New: Out << "?2"; break;
1133  // <operator-name> ::= ?3 # delete
1134  case OO_Delete: Out << "?3"; break;
1135  // <operator-name> ::= ?4 # =
1136  case OO_Equal: Out << "?4"; break;
1137  // <operator-name> ::= ?5 # >>
1138  case OO_GreaterGreater: Out << "?5"; break;
1139  // <operator-name> ::= ?6 # <<
1140  case OO_LessLess: Out << "?6"; break;
1141  // <operator-name> ::= ?7 # !
1142  case OO_Exclaim: Out << "?7"; break;
1143  // <operator-name> ::= ?8 # ==
1144  case OO_EqualEqual: Out << "?8"; break;
1145  // <operator-name> ::= ?9 # !=
1146  case OO_ExclaimEqual: Out << "?9"; break;
1147  // <operator-name> ::= ?A # []
1148  case OO_Subscript: Out << "?A"; break;
1149  // ?B # conversion
1150  // <operator-name> ::= ?C # ->
1151  case OO_Arrow: Out << "?C"; break;
1152  // <operator-name> ::= ?D # *
1153  case OO_Star: Out << "?D"; break;
1154  // <operator-name> ::= ?E # ++
1155  case OO_PlusPlus: Out << "?E"; break;
1156  // <operator-name> ::= ?F # --
1157  case OO_MinusMinus: Out << "?F"; break;
1158  // <operator-name> ::= ?G # -
1159  case OO_Minus: Out << "?G"; break;
1160  // <operator-name> ::= ?H # +
1161  case OO_Plus: Out << "?H"; break;
1162  // <operator-name> ::= ?I # &
1163  case OO_Amp: Out << "?I"; break;
1164  // <operator-name> ::= ?J # ->*
1165  case OO_ArrowStar: Out << "?J"; break;
1166  // <operator-name> ::= ?K # /
1167  case OO_Slash: Out << "?K"; break;
1168  // <operator-name> ::= ?L # %
1169  case OO_Percent: Out << "?L"; break;
1170  // <operator-name> ::= ?M # <
1171  case OO_Less: Out << "?M"; break;
1172  // <operator-name> ::= ?N # <=
1173  case OO_LessEqual: Out << "?N"; break;
1174  // <operator-name> ::= ?O # >
1175  case OO_Greater: Out << "?O"; break;
1176  // <operator-name> ::= ?P # >=
1177  case OO_GreaterEqual: Out << "?P"; break;
1178  // <operator-name> ::= ?Q # ,
1179  case OO_Comma: Out << "?Q"; break;
1180  // <operator-name> ::= ?R # ()
1181  case OO_Call: Out << "?R"; break;
1182  // <operator-name> ::= ?S # ~
1183  case OO_Tilde: Out << "?S"; break;
1184  // <operator-name> ::= ?T # ^
1185  case OO_Caret: Out << "?T"; break;
1186  // <operator-name> ::= ?U # |
1187  case OO_Pipe: Out << "?U"; break;
1188  // <operator-name> ::= ?V # &&
1189  case OO_AmpAmp: Out << "?V"; break;
1190  // <operator-name> ::= ?W # ||
1191  case OO_PipePipe: Out << "?W"; break;
1192  // <operator-name> ::= ?X # *=
1193  case OO_StarEqual: Out << "?X"; break;
1194  // <operator-name> ::= ?Y # +=
1195  case OO_PlusEqual: Out << "?Y"; break;
1196  // <operator-name> ::= ?Z # -=
1197  case OO_MinusEqual: Out << "?Z"; break;
1198  // <operator-name> ::= ?_0 # /=
1199  case OO_SlashEqual: Out << "?_0"; break;
1200  // <operator-name> ::= ?_1 # %=
1201  case OO_PercentEqual: Out << "?_1"; break;
1202  // <operator-name> ::= ?_2 # >>=
1203  case OO_GreaterGreaterEqual: Out << "?_2"; break;
1204  // <operator-name> ::= ?_3 # <<=
1205  case OO_LessLessEqual: Out << "?_3"; break;
1206  // <operator-name> ::= ?_4 # &=
1207  case OO_AmpEqual: Out << "?_4"; break;
1208  // <operator-name> ::= ?_5 # |=
1209  case OO_PipeEqual: Out << "?_5"; break;
1210  // <operator-name> ::= ?_6 # ^=
1211  case OO_CaretEqual: Out << "?_6"; break;
1212  // ?_7 # vftable
1213  // ?_8 # vbtable
1214  // ?_9 # vcall
1215  // ?_A # typeof
1216  // ?_B # local static guard
1217  // ?_C # string
1218  // ?_D # vbase destructor
1219  // ?_E # vector deleting destructor
1220  // ?_F # default constructor closure
1221  // ?_G # scalar deleting destructor
1222  // ?_H # vector constructor iterator
1223  // ?_I # vector destructor iterator
1224  // ?_J # vector vbase constructor iterator
1225  // ?_K # virtual displacement map
1226  // ?_L # eh vector constructor iterator
1227  // ?_M # eh vector destructor iterator
1228  // ?_N # eh vector vbase constructor iterator
1229  // ?_O # copy constructor closure
1230  // ?_P<name> # udt returning <name>
1231  // ?_Q # <unknown>
1232  // ?_R0 # RTTI Type Descriptor
1233  // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1234  // ?_R2 # RTTI Base Class Array
1235  // ?_R3 # RTTI Class Hierarchy Descriptor
1236  // ?_R4 # RTTI Complete Object Locator
1237  // ?_S # local vftable
1238  // ?_T # local vftable constructor closure
1239  // <operator-name> ::= ?_U # new[]
1240  case OO_Array_New: Out << "?_U"; break;
1241  // <operator-name> ::= ?_V # delete[]
1242  case OO_Array_Delete: Out << "?_V"; break;
1243  // <operator-name> ::= ?__L # co_await
1244  case OO_Coawait: Out << "?__L"; break;
1245 
1246  case OO_Spaceship: {
1247  // FIXME: Once MS picks a mangling, use it.
1248  DiagnosticsEngine &Diags = Context.getDiags();
1249  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1250  "cannot mangle this three-way comparison operator yet");
1251  Diags.Report(Loc, DiagID);
1252  break;
1253  }
1254 
1255  case OO_Conditional: {
1256  DiagnosticsEngine &Diags = Context.getDiags();
1257  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1258  "cannot mangle this conditional operator yet");
1259  Diags.Report(Loc, DiagID);
1260  break;
1261  }
1262 
1263  case OO_None:
1265  llvm_unreachable("Not an overloaded operator");
1266  }
1267 }
1268 
1269 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1270  // <source name> ::= <identifier> @
1271  BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
1272  if (Found == NameBackReferences.end()) {
1273  if (NameBackReferences.size() < 10)
1274  NameBackReferences.push_back(Name);
1275  Out << Name << '@';
1276  } else {
1277  Out << (Found - NameBackReferences.begin());
1278  }
1279 }
1280 
1281 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1282  Context.mangleObjCMethodName(MD, Out);
1283 }
1284 
1285 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1286  const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1287  // <template-name> ::= <unscoped-template-name> <template-args>
1288  // ::= <substitution>
1289  // Always start with the unqualified name.
1290 
1291  // Templates have their own context for back references.
1292  ArgBackRefMap OuterArgsContext;
1293  BackRefVec OuterTemplateContext;
1294  PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1295  NameBackReferences.swap(OuterTemplateContext);
1296  TypeBackReferences.swap(OuterArgsContext);
1297  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1298 
1299  mangleUnscopedTemplateName(TD);
1300  mangleTemplateArgs(TD, TemplateArgs);
1301 
1302  // Restore the previous back reference contexts.
1303  NameBackReferences.swap(OuterTemplateContext);
1304  TypeBackReferences.swap(OuterArgsContext);
1305  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1306 }
1307 
1308 void
1309 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1310  // <unscoped-template-name> ::= ?$ <unqualified-name>
1311  Out << "?$";
1312  mangleUnqualifiedName(TD);
1313 }
1314 
1315 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1316  bool IsBoolean) {
1317  // <integer-literal> ::= $0 <number>
1318  Out << "$0";
1319  // Make sure booleans are encoded as 0/1.
1320  if (IsBoolean && Value.getBoolValue())
1321  mangleNumber(1);
1322  else if (Value.isSigned())
1323  mangleNumber(Value.getSExtValue());
1324  else
1325  mangleNumber(Value.getZExtValue());
1326 }
1327 
1328 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1329  // See if this is a constant expression.
1330  llvm::APSInt Value;
1331  if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1332  mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1333  return;
1334  }
1335 
1336  // Look through no-op casts like template parameter substitutions.
1337  E = E->IgnoreParenNoopCasts(Context.getASTContext());
1338 
1339  const CXXUuidofExpr *UE = nullptr;
1340  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1341  if (UO->getOpcode() == UO_AddrOf)
1342  UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1343  } else
1344  UE = dyn_cast<CXXUuidofExpr>(E);
1345 
1346  if (UE) {
1347  // If we had to peek through an address-of operator, treat this like we are
1348  // dealing with a pointer type. Otherwise, treat it like a const reference.
1349  //
1350  // N.B. This matches up with the handling of TemplateArgument::Declaration
1351  // in mangleTemplateArg
1352  if (UE == E)
1353  Out << "$E?";
1354  else
1355  Out << "$1?";
1356 
1357  // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1358  // const __s_GUID _GUID_{lower case UUID with underscores}
1359  StringRef Uuid = UE->getUuidStr();
1360  std::string Name = "_GUID_" + Uuid.lower();
1361  std::replace(Name.begin(), Name.end(), '-', '_');
1362 
1363  mangleSourceName(Name);
1364  // Terminate the whole name with an '@'.
1365  Out << '@';
1366  // It's a global variable.
1367  Out << '3';
1368  // It's a struct called __s_GUID.
1369  mangleArtificialTagType(TTK_Struct, "__s_GUID");
1370  // It's const.
1371  Out << 'B';
1372  return;
1373  }
1374 
1375  // As bad as this diagnostic is, it's better than crashing.
1376  DiagnosticsEngine &Diags = Context.getDiags();
1377  unsigned DiagID = Diags.getCustomDiagID(
1378  DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1379  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1380  << E->getSourceRange();
1381 }
1382 
1383 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1384  const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1385  // <template-args> ::= <template-arg>+
1386  const TemplateParameterList *TPL = TD->getTemplateParameters();
1387  assert(TPL->size() == TemplateArgs.size() &&
1388  "size mismatch between args and parms!");
1389 
1390  for (size_t i = 0; i < TemplateArgs.size(); ++i) {
1391  const TemplateArgument &TA = TemplateArgs[i];
1392 
1393  // Separate consecutive packs by $$Z.
1394  if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
1395  TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
1396  Out << "$$Z";
1397 
1398  mangleTemplateArg(TD, TA, TPL->getParam(i));
1399  }
1400 }
1401 
1402 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1403  const TemplateArgument &TA,
1404  const NamedDecl *Parm) {
1405  // <template-arg> ::= <type>
1406  // ::= <integer-literal>
1407  // ::= <member-data-pointer>
1408  // ::= <member-function-pointer>
1409  // ::= $E? <name> <type-encoding>
1410  // ::= $1? <name> <type-encoding>
1411  // ::= $0A@
1412  // ::= <template-args>
1413 
1414  switch (TA.getKind()) {
1415  case TemplateArgument::Null:
1416  llvm_unreachable("Can't mangle null template arguments!");
1417  case TemplateArgument::TemplateExpansion:
1418  llvm_unreachable("Can't mangle template expansion arguments!");
1419  case TemplateArgument::Type: {
1420  QualType T = TA.getAsType();
1421  mangleType(T, SourceRange(), QMM_Escape);
1422  break;
1423  }
1424  case TemplateArgument::Declaration: {
1425  const NamedDecl *ND = TA.getAsDecl();
1426  if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1427  mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1428  ->getMostRecentNonInjectedDecl(),
1429  cast<ValueDecl>(ND));
1430  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1431  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1432  if (MD && MD->isInstance()) {
1433  mangleMemberFunctionPointer(
1435  } else {
1436  Out << "$1?";
1437  mangleName(FD);
1438  mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1439  }
1440  } else {
1441  mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1442  }
1443  break;
1444  }
1445  case TemplateArgument::Integral:
1446  mangleIntegerLiteral(TA.getAsIntegral(),
1447  TA.getIntegralType()->isBooleanType());
1448  break;
1449  case TemplateArgument::NullPtr: {
1450  QualType T = TA.getNullPtrType();
1451  if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1452  const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1453  if (MPT->isMemberFunctionPointerType() &&
1454  !isa<FunctionTemplateDecl>(TD)) {
1455  mangleMemberFunctionPointer(RD, nullptr);
1456  return;
1457  }
1458  if (MPT->isMemberDataPointer()) {
1459  if (!isa<FunctionTemplateDecl>(TD)) {
1460  mangleMemberDataPointer(RD, nullptr);
1461  return;
1462  }
1463  // nullptr data pointers are always represented with a single field
1464  // which is initialized with either 0 or -1. Why -1? Well, we need to
1465  // distinguish the case where the data member is at offset zero in the
1466  // record.
1467  // However, we are free to use 0 *if* we would use multiple fields for
1468  // non-nullptr member pointers.
1469  if (!RD->nullFieldOffsetIsZero()) {
1470  mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1471  return;
1472  }
1473  }
1474  }
1475  mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1476  break;
1477  }
1478  case TemplateArgument::Expression:
1479  mangleExpression(TA.getAsExpr());
1480  break;
1481  case TemplateArgument::Pack: {
1482  ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1483  if (TemplateArgs.empty()) {
1484  if (isa<TemplateTypeParmDecl>(Parm) ||
1485  isa<TemplateTemplateParmDecl>(Parm))
1486  // MSVC 2015 changed the mangling for empty expanded template packs,
1487  // use the old mangling for link compatibility for old versions.
1488  Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1489  LangOptions::MSVC2015)
1490  ? "$$V"
1491  : "$$$V");
1492  else if (isa<NonTypeTemplateParmDecl>(Parm))
1493  Out << "$S";
1494  else
1495  llvm_unreachable("unexpected template parameter decl!");
1496  } else {
1497  for (const TemplateArgument &PA : TemplateArgs)
1498  mangleTemplateArg(TD, PA, Parm);
1499  }
1500  break;
1501  }
1502  case TemplateArgument::Template: {
1503  const NamedDecl *ND =
1505  if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1506  mangleType(TD);
1507  } else if (isa<TypeAliasDecl>(ND)) {
1508  Out << "$$Y";
1509  mangleName(ND);
1510  } else {
1511  llvm_unreachable("unexpected template template NamedDecl!");
1512  }
1513  break;
1514  }
1515  }
1516 }
1517 
1518 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1519  llvm::SmallString<64> TemplateMangling;
1520  llvm::raw_svector_ostream Stream(TemplateMangling);
1521  MicrosoftCXXNameMangler Extra(Context, Stream);
1522 
1523  Stream << "?$";
1524  Extra.mangleSourceName("Protocol");
1525  Extra.mangleArtificialTagType(TTK_Struct, PD->getName());
1526 
1527  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1528 }
1529 
1530 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1531  Qualifiers Quals,
1532  SourceRange Range) {
1533  llvm::SmallString<64> TemplateMangling;
1534  llvm::raw_svector_ostream Stream(TemplateMangling);
1535  MicrosoftCXXNameMangler Extra(Context, Stream);
1536 
1537  Stream << "?$";
1538  switch (Quals.getObjCLifetime()) {
1539  case Qualifiers::OCL_None:
1540  case Qualifiers::OCL_ExplicitNone:
1541  break;
1542  case Qualifiers::OCL_Autoreleasing:
1543  Extra.mangleSourceName("Autoreleasing");
1544  break;
1545  case Qualifiers::OCL_Strong:
1546  Extra.mangleSourceName("Strong");
1547  break;
1548  case Qualifiers::OCL_Weak:
1549  Extra.mangleSourceName("Weak");
1550  break;
1551  }
1552  Extra.manglePointerCVQualifiers(Quals);
1553  Extra.manglePointerExtQualifiers(Quals, Type);
1554  Extra.mangleType(Type, Range);
1555 
1556  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1557 }
1558 
1559 void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
1560  Qualifiers Quals,
1561  SourceRange Range) {
1562  llvm::SmallString<64> TemplateMangling;
1563  llvm::raw_svector_ostream Stream(TemplateMangling);
1564  MicrosoftCXXNameMangler Extra(Context, Stream);
1565 
1566  Stream << "?$";
1567  Extra.mangleSourceName("KindOf");
1568  Extra.mangleType(QualType(T, 0)
1569  .stripObjCKindOfType(getASTContext())
1570  ->getAs<ObjCObjectType>(),
1571  Quals, Range);
1572 
1573  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1574 }
1575 
1576 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1577  bool IsMember) {
1578  // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1579  // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1580  // 'I' means __restrict (32/64-bit).
1581  // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1582  // keyword!
1583  // <base-cvr-qualifiers> ::= A # near
1584  // ::= B # near const
1585  // ::= C # near volatile
1586  // ::= D # near const volatile
1587  // ::= E # far (16-bit)
1588  // ::= F # far const (16-bit)
1589  // ::= G # far volatile (16-bit)
1590  // ::= H # far const volatile (16-bit)
1591  // ::= I # huge (16-bit)
1592  // ::= J # huge const (16-bit)
1593  // ::= K # huge volatile (16-bit)
1594  // ::= L # huge const volatile (16-bit)
1595  // ::= M <basis> # based
1596  // ::= N <basis> # based const
1597  // ::= O <basis> # based volatile
1598  // ::= P <basis> # based const volatile
1599  // ::= Q # near member
1600  // ::= R # near const member
1601  // ::= S # near volatile member
1602  // ::= T # near const volatile member
1603  // ::= U # far member (16-bit)
1604  // ::= V # far const member (16-bit)
1605  // ::= W # far volatile member (16-bit)
1606  // ::= X # far const volatile member (16-bit)
1607  // ::= Y # huge member (16-bit)
1608  // ::= Z # huge const member (16-bit)
1609  // ::= 0 # huge volatile member (16-bit)
1610  // ::= 1 # huge const volatile member (16-bit)
1611  // ::= 2 <basis> # based member
1612  // ::= 3 <basis> # based const member
1613  // ::= 4 <basis> # based volatile member
1614  // ::= 5 <basis> # based const volatile member
1615  // ::= 6 # near function (pointers only)
1616  // ::= 7 # far function (pointers only)
1617  // ::= 8 # near method (pointers only)
1618  // ::= 9 # far method (pointers only)
1619  // ::= _A <basis> # based function (pointers only)
1620  // ::= _B <basis> # based function (far?) (pointers only)
1621  // ::= _C <basis> # based method (pointers only)
1622  // ::= _D <basis> # based method (far?) (pointers only)
1623  // ::= _E # block (Clang)
1624  // <basis> ::= 0 # __based(void)
1625  // ::= 1 # __based(segment)?
1626  // ::= 2 <name> # __based(name)
1627  // ::= 3 # ?
1628  // ::= 4 # ?
1629  // ::= 5 # not really based
1630  bool HasConst = Quals.hasConst(),
1631  HasVolatile = Quals.hasVolatile();
1632 
1633  if (!IsMember) {
1634  if (HasConst && HasVolatile) {
1635  Out << 'D';
1636  } else if (HasVolatile) {
1637  Out << 'C';
1638  } else if (HasConst) {
1639  Out << 'B';
1640  } else {
1641  Out << 'A';
1642  }
1643  } else {
1644  if (HasConst && HasVolatile) {
1645  Out << 'T';
1646  } else if (HasVolatile) {
1647  Out << 'S';
1648  } else if (HasConst) {
1649  Out << 'R';
1650  } else {
1651  Out << 'Q';
1652  }
1653  }
1654 
1655  // FIXME: For now, just drop all extension qualifiers on the floor.
1656 }
1657 
1658 void
1659 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1660  // <ref-qualifier> ::= G # lvalue reference
1661  // ::= H # rvalue-reference
1662  switch (RefQualifier) {
1663  case RQ_None:
1664  break;
1665 
1666  case RQ_LValue:
1667  Out << 'G';
1668  break;
1669 
1670  case RQ_RValue:
1671  Out << 'H';
1672  break;
1673  }
1674 }
1675 
1676 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1677  QualType PointeeType) {
1678  if (PointersAre64Bit &&
1679  (PointeeType.isNull() || !PointeeType->isFunctionType()))
1680  Out << 'E';
1681 
1682  if (Quals.hasRestrict())
1683  Out << 'I';
1684 
1685  if (Quals.hasUnaligned() ||
1686  (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1687  Out << 'F';
1688 }
1689 
1690 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1691  // <pointer-cv-qualifiers> ::= P # no qualifiers
1692  // ::= Q # const
1693  // ::= R # volatile
1694  // ::= S # const volatile
1695  bool HasConst = Quals.hasConst(),
1696  HasVolatile = Quals.hasVolatile();
1697 
1698  if (HasConst && HasVolatile) {
1699  Out << 'S';
1700  } else if (HasVolatile) {
1701  Out << 'R';
1702  } else if (HasConst) {
1703  Out << 'Q';
1704  } else {
1705  Out << 'P';
1706  }
1707 }
1708 
1709 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1710  SourceRange Range) {
1711  // MSVC will backreference two canonically equivalent types that have slightly
1712  // different manglings when mangled alone.
1713 
1714  // Decayed types do not match up with non-decayed versions of the same type.
1715  //
1716  // e.g.
1717  // void (*x)(void) will not form a backreference with void x(void)
1718  void *TypePtr;
1719  if (const auto *DT = T->getAs<DecayedType>()) {
1720  QualType OriginalType = DT->getOriginalType();
1721  // All decayed ArrayTypes should be treated identically; as-if they were
1722  // a decayed IncompleteArrayType.
1723  if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1724  OriginalType = getASTContext().getIncompleteArrayType(
1725  AT->getElementType(), AT->getSizeModifier(),
1726  AT->getIndexTypeCVRQualifiers());
1727 
1728  TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1729  // If the original parameter was textually written as an array,
1730  // instead treat the decayed parameter like it's const.
1731  //
1732  // e.g.
1733  // int [] -> int * const
1734  if (OriginalType->isArrayType())
1735  T = T.withConst();
1736  } else {
1737  TypePtr = T.getCanonicalType().getAsOpaquePtr();
1738  }
1739 
1740  ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1741 
1742  if (Found == TypeBackReferences.end()) {
1743  size_t OutSizeBefore = Out.tell();
1744 
1745  mangleType(T, Range, QMM_Drop);
1746 
1747  // See if it's worth creating a back reference.
1748  // Only types longer than 1 character are considered
1749  // and only 10 back references slots are available:
1750  bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1751  if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1752  size_t Size = TypeBackReferences.size();
1753  TypeBackReferences[TypePtr] = Size;
1754  }
1755  } else {
1756  Out << Found->second;
1757  }
1758 }
1759 
1760 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1761  const PassObjectSizeAttr *POSA) {
1762  int Type = POSA->getType();
1763  bool Dynamic = POSA->isDynamic();
1764 
1765  auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first;
1766  auto *TypePtr = (const void *)&*Iter;
1767  ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1768 
1769  if (Found == TypeBackReferences.end()) {
1770  std::string Name =
1771  Dynamic ? "__pass_dynamic_object_size" : "__pass_object_size";
1772  mangleArtificialTagType(TTK_Enum, Name + llvm::utostr(Type), {"__clang"});
1773 
1774  if (TypeBackReferences.size() < 10) {
1775  size_t Size = TypeBackReferences.size();
1776  TypeBackReferences[TypePtr] = Size;
1777  }
1778  } else {
1779  Out << Found->second;
1780  }
1781 }
1782 
1783 void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
1784  Qualifiers Quals,
1785  SourceRange Range) {
1786  // Address space is mangled as an unqualified templated type in the __clang
1787  // namespace. The demangled version of this is:
1788  // In the case of a language specific address space:
1789  // __clang::struct _AS[language_addr_space]<Type>
1790  // where:
1791  // <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
1792  // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
1793  // "private"| "generic" ]
1794  // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1795  // Note that the above were chosen to match the Itanium mangling for this.
1796  //
1797  // In the case of a non-language specific address space:
1798  // __clang::struct _AS<TargetAS, Type>
1799  assert(Quals.hasAddressSpace() && "Not valid without address space");
1800  llvm::SmallString<32> ASMangling;
1801  llvm::raw_svector_ostream Stream(ASMangling);
1802  MicrosoftCXXNameMangler Extra(Context, Stream);
1803  Stream << "?$";
1804 
1805  LangAS AS = Quals.getAddressSpace();
1806  if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1807  unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1808  Extra.mangleSourceName("_AS");
1809  Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS),
1810  /*IsBoolean*/ false);
1811  } else {
1812  switch (AS) {
1813  default:
1814  llvm_unreachable("Not a language specific address space");
1815  case LangAS::opencl_global:
1816  Extra.mangleSourceName("_ASCLglobal");
1817  break;
1818  case LangAS::opencl_local:
1819  Extra.mangleSourceName("_ASCLlocal");
1820  break;
1821  case LangAS::opencl_constant:
1822  Extra.mangleSourceName("_ASCLconstant");
1823  break;
1824  case LangAS::opencl_private:
1825  Extra.mangleSourceName("_ASCLprivate");
1826  break;
1827  case LangAS::opencl_generic:
1828  Extra.mangleSourceName("_ASCLgeneric");
1829  break;
1830  case LangAS::cuda_device:
1831  Extra.mangleSourceName("_ASCUdevice");
1832  break;
1833  case LangAS::cuda_constant:
1834  Extra.mangleSourceName("_ASCUconstant");
1835  break;
1836  case LangAS::cuda_shared:
1837  Extra.mangleSourceName("_ASCUshared");
1838  break;
1839  }
1840  }
1841 
1842  Extra.mangleType(T, Range, QMM_Escape);
1843  mangleQualifiers(Qualifiers(), false);
1844  mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
1845 }
1846 
1847 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1848  QualifierMangleMode QMM) {
1849  // Don't use the canonical types. MSVC includes things like 'const' on
1850  // pointer arguments to function pointers that canonicalization strips away.
1851  T = T.getDesugaredType(getASTContext());
1852  Qualifiers Quals = T.getLocalQualifiers();
1853 
1854  if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1855  // If there were any Quals, getAsArrayType() pushed them onto the array
1856  // element type.
1857  if (QMM == QMM_Mangle)
1858  Out << 'A';
1859  else if (QMM == QMM_Escape || QMM == QMM_Result)
1860  Out << "$$B";
1861  mangleArrayType(AT);
1862  return;
1863  }
1864 
1865  bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1866  T->isReferenceType() || T->isBlockPointerType();
1867 
1868  switch (QMM) {
1869  case QMM_Drop:
1870  if (Quals.hasObjCLifetime())
1871  Quals = Quals.withoutObjCLifetime();
1872  break;
1873  case QMM_Mangle:
1874  if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1875  Out << '6';
1876  mangleFunctionType(FT);
1877  return;
1878  }
1879  mangleQualifiers(Quals, false);
1880  break;
1881  case QMM_Escape:
1882  if (!IsPointer && Quals) {
1883  Out << "$$C";
1884  mangleQualifiers(Quals, false);
1885  }
1886  break;
1887  case QMM_Result:
1888  // Presence of __unaligned qualifier shouldn't affect mangling here.
1889  Quals.removeUnaligned();
1890  if (Quals.hasObjCLifetime())
1891  Quals = Quals.withoutObjCLifetime();
1892  if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1893  Out << '?';
1894  mangleQualifiers(Quals, false);
1895  }
1896  break;
1897  }
1898 
1899  const Type *ty = T.getTypePtr();
1900 
1901  switch (ty->getTypeClass()) {
1902 #define ABSTRACT_TYPE(CLASS, PARENT)
1903 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1904  case Type::CLASS: \
1905  llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1906  return;
1907 #define TYPE(CLASS, PARENT) \
1908  case Type::CLASS: \
1909  mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1910  break;
1911 #include "clang/AST/TypeNodes.def"
1912 #undef ABSTRACT_TYPE
1913 #undef NON_CANONICAL_TYPE
1914 #undef TYPE
1915  }
1916 }
1917 
1918 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1919  SourceRange Range) {
1920  // <type> ::= <builtin-type>
1921  // <builtin-type> ::= X # void
1922  // ::= C # signed char
1923  // ::= D # char
1924  // ::= E # unsigned char
1925  // ::= F # short
1926  // ::= G # unsigned short (or wchar_t if it's not a builtin)
1927  // ::= H # int
1928  // ::= I # unsigned int
1929  // ::= J # long
1930  // ::= K # unsigned long
1931  // L # <none>
1932  // ::= M # float
1933  // ::= N # double
1934  // ::= O # long double (__float80 is mangled differently)
1935  // ::= _J # long long, __int64
1936  // ::= _K # unsigned long long, __int64
1937  // ::= _L # __int128
1938  // ::= _M # unsigned __int128
1939  // ::= _N # bool
1940  // _O # <array in parameter>
1941  // ::= _Q # char8_t
1942  // ::= _S # char16_t
1943  // ::= _T # __float80 (Intel)
1944  // ::= _U # char32_t
1945  // ::= _W # wchar_t
1946  // ::= _Z # __float80 (Digital Mars)
1947  switch (T->getKind()) {
1948  case BuiltinType::Void:
1949  Out << 'X';
1950  break;
1951  case BuiltinType::SChar:
1952  Out << 'C';
1953  break;
1954  case BuiltinType::Char_U:
1955  case BuiltinType::Char_S:
1956  Out << 'D';
1957  break;
1958  case BuiltinType::UChar:
1959  Out << 'E';
1960  break;
1961  case BuiltinType::Short:
1962  Out << 'F';
1963  break;
1964  case BuiltinType::UShort:
1965  Out << 'G';
1966  break;
1967  case BuiltinType::Int:
1968  Out << 'H';
1969  break;
1970  case BuiltinType::UInt:
1971  Out << 'I';
1972  break;
1973  case BuiltinType::Long:
1974  Out << 'J';
1975  break;
1976  case BuiltinType::ULong:
1977  Out << 'K';
1978  break;
1979  case BuiltinType::Float:
1980  Out << 'M';
1981  break;
1982  case BuiltinType::Double:
1983  Out << 'N';
1984  break;
1985  // TODO: Determine size and mangle accordingly
1986  case BuiltinType::LongDouble:
1987  Out << 'O';
1988  break;
1989  case BuiltinType::LongLong:
1990  Out << "_J";
1991  break;
1992  case BuiltinType::ULongLong:
1993  Out << "_K";
1994  break;
1995  case BuiltinType::Int128:
1996  Out << "_L";
1997  break;
1998  case BuiltinType::UInt128:
1999  Out << "_M";
2000  break;
2001  case BuiltinType::Bool:
2002  Out << "_N";
2003  break;
2004  case BuiltinType::Char8:
2005  Out << "_Q";
2006  break;
2007  case BuiltinType::Char16:
2008  Out << "_S";
2009  break;
2010  case BuiltinType::Char32:
2011  Out << "_U";
2012  break;
2013  case BuiltinType::WChar_S:
2014  case BuiltinType::WChar_U:
2015  Out << "_W";
2016  break;
2017 
2018 #define BUILTIN_TYPE(Id, SingletonId)
2019 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2020  case BuiltinType::Id:
2021 #include "clang/AST/BuiltinTypes.def"
2022  case BuiltinType::Dependent:
2023  llvm_unreachable("placeholder types shouldn't get to name mangling");
2024 
2025  case BuiltinType::ObjCId:
2026  mangleArtificialTagType(TTK_Struct, "objc_object");
2027  break;
2028  case BuiltinType::ObjCClass:
2029  mangleArtificialTagType(TTK_Struct, "objc_class");
2030  break;
2031  case BuiltinType::ObjCSel:
2032  mangleArtificialTagType(TTK_Struct, "objc_selector");
2033  break;
2034 
2035 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2036  case BuiltinType::Id: \
2037  Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2038  break;
2039 #include "clang/Basic/OpenCLImageTypes.def"
2040  case BuiltinType::OCLSampler:
2041  Out << "PA";
2042  mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2043  break;
2044  case BuiltinType::OCLEvent:
2045  Out << "PA";
2046  mangleArtificialTagType(TTK_Struct, "ocl_event");
2047  break;
2048  case BuiltinType::OCLClkEvent:
2049  Out << "PA";
2050  mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2051  break;
2052  case BuiltinType::OCLQueue:
2053  Out << "PA";
2054  mangleArtificialTagType(TTK_Struct, "ocl_queue");
2055  break;
2056  case BuiltinType::OCLReserveID:
2057  Out << "PA";
2058  mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2059  break;
2060 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2061  case BuiltinType::Id: \
2062  mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2063  break;
2064 #include "clang/Basic/OpenCLExtensionTypes.def"
2065 
2066  case BuiltinType::NullPtr:
2067  Out << "$$T";
2068  break;
2069 
2070  case BuiltinType::Float16:
2071  mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2072  break;
2073 
2074  case BuiltinType::Half:
2075  mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2076  break;
2077 
2078  case BuiltinType::ShortAccum:
2079  case BuiltinType::Accum:
2080  case BuiltinType::LongAccum:
2081  case BuiltinType::UShortAccum:
2082  case BuiltinType::UAccum:
2083  case BuiltinType::ULongAccum:
2084  case BuiltinType::ShortFract:
2085  case BuiltinType::Fract:
2086  case BuiltinType::LongFract:
2087  case BuiltinType::UShortFract:
2088  case BuiltinType::UFract:
2089  case BuiltinType::ULongFract:
2090  case BuiltinType::SatShortAccum:
2091  case BuiltinType::SatAccum:
2092  case BuiltinType::SatLongAccum:
2093  case BuiltinType::SatUShortAccum:
2094  case BuiltinType::SatUAccum:
2095  case BuiltinType::SatULongAccum:
2096  case BuiltinType::SatShortFract:
2097  case BuiltinType::SatFract:
2098  case BuiltinType::SatLongFract:
2099  case BuiltinType::SatUShortFract:
2100  case BuiltinType::SatUFract:
2101  case BuiltinType::SatULongFract:
2102  case BuiltinType::Float128: {
2103  DiagnosticsEngine &Diags = Context.getDiags();
2104  unsigned DiagID = Diags.getCustomDiagID(
2105  DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2106  Diags.Report(Range.getBegin(), DiagID)
2107  << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2108  break;
2109  }
2110  }
2111 }
2112 
2113 // <type> ::= <function-type>
2114 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2115  SourceRange) {
2116  // Structors only appear in decls, so at this point we know it's not a
2117  // structor type.
2118  // FIXME: This may not be lambda-friendly.
2119  if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) {
2120  Out << "$$A8@@";
2121  mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2122  } else {
2123  Out << "$$A6";
2124  mangleFunctionType(T);
2125  }
2126 }
2127 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2129  Out << "$$A6";
2130  mangleFunctionType(T);
2131 }
2132 
2133 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2134  const FunctionDecl *D,
2135  bool ForceThisQuals,
2136  bool MangleExceptionSpec) {
2137  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2138  // <return-type> <argument-list> <throw-spec>
2139  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2140 
2141  SourceRange Range;
2142  if (D) Range = D->getSourceRange();
2143 
2144  bool IsInLambda = false;
2145  bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2146  CallingConv CC = T->getCallConv();
2147  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2148  if (MD->getParent()->isLambda())
2149  IsInLambda = true;
2150  if (MD->isInstance())
2151  HasThisQuals = true;
2152  if (isa<CXXDestructorDecl>(MD)) {
2153  IsStructor = true;
2154  } else if (isa<CXXConstructorDecl>(MD)) {
2155  IsStructor = true;
2156  IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2157  StructorType == Ctor_DefaultClosure) &&
2158  isStructorDecl(MD);
2159  if (IsCtorClosure)
2160  CC = getASTContext().getDefaultCallingConvention(
2161  /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2162  }
2163  }
2164 
2165  // If this is a C++ instance method, mangle the CVR qualifiers for the
2166  // this pointer.
2167  if (HasThisQuals) {
2168  Qualifiers Quals = Proto->getMethodQuals();
2169  manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2170  mangleRefQualifier(Proto->getRefQualifier());
2171  mangleQualifiers(Quals, /*IsMember=*/false);
2172  }
2173 
2174  mangleCallingConvention(CC);
2175 
2176  // <return-type> ::= <type>
2177  // ::= @ # structors (they have no declared return type)
2178  if (IsStructor) {
2179  if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2180  // The scalar deleting destructor takes an extra int argument which is not
2181  // reflected in the AST.
2182  if (StructorType == Dtor_Deleting) {
2183  Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2184  return;
2185  }
2186  // The vbase destructor returns void which is not reflected in the AST.
2187  if (StructorType == Dtor_Complete) {
2188  Out << "XXZ";
2189  return;
2190  }
2191  }
2192  if (IsCtorClosure) {
2193  // Default constructor closure and copy constructor closure both return
2194  // void.
2195  Out << 'X';
2196 
2197  if (StructorType == Ctor_DefaultClosure) {
2198  // Default constructor closure always has no arguments.
2199  Out << 'X';
2200  } else if (StructorType == Ctor_CopyingClosure) {
2201  // Copy constructor closure always takes an unqualified reference.
2202  mangleArgumentType(getASTContext().getLValueReferenceType(
2203  Proto->getParamType(0)
2205  ->getPointeeType(),
2206  /*SpelledAsLValue=*/true),
2207  Range);
2208  Out << '@';
2209  } else {
2210  llvm_unreachable("unexpected constructor closure!");
2211  }
2212  Out << 'Z';
2213  return;
2214  }
2215  Out << '@';
2216  } else {
2217  QualType ResultType = T->getReturnType();
2218  if (const auto *AT =
2219  dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2220  Out << '?';
2221  mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2222  Out << '?';
2223  assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2224  "shouldn't need to mangle __auto_type!");
2225  mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2226  Out << '@';
2227  } else if (IsInLambda) {
2228  Out << '@';
2229  } else {
2230  if (ResultType->isVoidType())
2231  ResultType = ResultType.getUnqualifiedType();
2232  mangleType(ResultType, Range, QMM_Result);
2233  }
2234  }
2235 
2236  // <argument-list> ::= X # void
2237  // ::= <type>+ @
2238  // ::= <type>* Z # varargs
2239  if (!Proto) {
2240  // Function types without prototypes can arise when mangling a function type
2241  // within an overloadable function in C. We mangle these as the absence of
2242  // any parameter types (not even an empty parameter list).
2243  Out << '@';
2244  } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2245  Out << 'X';
2246  } else {
2247  // Happens for function pointer type arguments for example.
2248  for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2249  mangleArgumentType(Proto->getParamType(I), Range);
2250  // Mangle each pass_object_size parameter as if it's a parameter of enum
2251  // type passed directly after the parameter with the pass_object_size
2252  // attribute. The aforementioned enum's name is __pass_object_size, and we
2253  // pretend it resides in a top-level namespace called __clang.
2254  //
2255  // FIXME: Is there a defined extension notation for the MS ABI, or is it
2256  // necessary to just cross our fingers and hope this type+namespace
2257  // combination doesn't conflict with anything?
2258  if (D)
2259  if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2260  manglePassObjectSizeArg(P);
2261  }
2262  // <builtin-type> ::= Z # ellipsis
2263  if (Proto->isVariadic())
2264  Out << 'Z';
2265  else
2266  Out << '@';
2267  }
2268 
2269  if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2270  getASTContext().getLangOpts().isCompatibleWithMSVC(
2271  LangOptions::MSVC2017_5))
2272  mangleThrowSpecification(Proto);
2273  else
2274  Out << 'Z';
2275 }
2276 
2277 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2278  // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
2279  // # pointer. in 64-bit mode *all*
2280  // # 'this' pointers are 64-bit.
2281  // ::= <global-function>
2282  // <member-function> ::= A # private: near
2283  // ::= B # private: far
2284  // ::= C # private: static near
2285  // ::= D # private: static far
2286  // ::= E # private: virtual near
2287  // ::= F # private: virtual far
2288  // ::= I # protected: near
2289  // ::= J # protected: far
2290  // ::= K # protected: static near
2291  // ::= L # protected: static far
2292  // ::= M # protected: virtual near
2293  // ::= N # protected: virtual far
2294  // ::= Q # public: near
2295  // ::= R # public: far
2296  // ::= S # public: static near
2297  // ::= T # public: static far
2298  // ::= U # public: virtual near
2299  // ::= V # public: virtual far
2300  // <global-function> ::= Y # global near
2301  // ::= Z # global far
2302  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2303  bool IsVirtual = MD->isVirtual();
2304  // When mangling vbase destructor variants, ignore whether or not the
2305  // underlying destructor was defined to be virtual.
2306  if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2307  StructorType == Dtor_Complete) {
2308  IsVirtual = false;
2309  }
2310  switch (MD->getAccess()) {
2311  case AS_none:
2312  llvm_unreachable("Unsupported access specifier");
2313  case AS_private:
2314  if (MD->isStatic())
2315  Out << 'C';
2316  else if (IsVirtual)
2317  Out << 'E';
2318  else
2319  Out << 'A';
2320  break;
2321  case AS_protected:
2322  if (MD->isStatic())
2323  Out << 'K';
2324  else if (IsVirtual)
2325  Out << 'M';
2326  else
2327  Out << 'I';
2328  break;
2329  case AS_public:
2330  if (MD->isStatic())
2331  Out << 'S';
2332  else if (IsVirtual)
2333  Out << 'U';
2334  else
2335  Out << 'Q';
2336  }
2337  } else {
2338  Out << 'Y';
2339  }
2340 }
2341 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2342  // <calling-convention> ::= A # __cdecl
2343  // ::= B # __export __cdecl
2344  // ::= C # __pascal
2345  // ::= D # __export __pascal
2346  // ::= E # __thiscall
2347  // ::= F # __export __thiscall
2348  // ::= G # __stdcall
2349  // ::= H # __export __stdcall
2350  // ::= I # __fastcall
2351  // ::= J # __export __fastcall
2352  // ::= Q # __vectorcall
2353  // ::= w # __regcall
2354  // The 'export' calling conventions are from a bygone era
2355  // (*cough*Win16*cough*) when functions were declared for export with
2356  // that keyword. (It didn't actually export them, it just made them so
2357  // that they could be in a DLL and somebody from another module could call
2358  // them.)
2359 
2360  switch (CC) {
2361  default:
2362  llvm_unreachable("Unsupported CC for mangling");
2363  case CC_Win64:
2364  case CC_X86_64SysV:
2365  case CC_C: Out << 'A'; break;
2366  case CC_X86Pascal: Out << 'C'; break;
2367  case CC_X86ThisCall: Out << 'E'; break;
2368  case CC_X86StdCall: Out << 'G'; break;
2369  case CC_X86FastCall: Out << 'I'; break;
2370  case CC_X86VectorCall: Out << 'Q'; break;
2371  case CC_Swift: Out << 'S'; break;
2372  case CC_PreserveMost: Out << 'U'; break;
2373  case CC_X86RegCall: Out << 'w'; break;
2374  }
2375 }
2376 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2377  mangleCallingConvention(T->getCallConv());
2378 }
2379 
2380 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2381  const FunctionProtoType *FT) {
2382  // <throw-spec> ::= Z # (default)
2383  // ::= _E # noexcept
2384  if (FT->canThrow())
2385  Out << 'Z';
2386  else
2387  Out << "_E";
2388 }
2389 
2390 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2391  Qualifiers, SourceRange Range) {
2392  // Probably should be mangled as a template instantiation; need to see what
2393  // VC does first.
2394  DiagnosticsEngine &Diags = Context.getDiags();
2395  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2396  "cannot mangle this unresolved dependent type yet");
2397  Diags.Report(Range.getBegin(), DiagID)
2398  << Range;
2399 }
2400 
2401 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2402 // <union-type> ::= T <name>
2403 // <struct-type> ::= U <name>
2404 // <class-type> ::= V <name>
2405 // <enum-type> ::= W4 <name>
2406 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2407  switch (TTK) {
2408  case TTK_Union:
2409  Out << 'T';
2410  break;
2411  case TTK_Struct:
2412  case TTK_Interface:
2413  Out << 'U';
2414  break;
2415  case TTK_Class:
2416  Out << 'V';
2417  break;
2418  case TTK_Enum:
2419  Out << "W4";
2420  break;
2421  }
2422 }
2423 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2424  SourceRange) {
2425  mangleType(cast<TagType>(T)->getDecl());
2426 }
2427 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2428  SourceRange) {
2429  mangleType(cast<TagType>(T)->getDecl());
2430 }
2431 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2432  mangleTagTypeKind(TD->getTagKind());
2433  mangleName(TD);
2434 }
2435 
2436 // If you add a call to this, consider updating isArtificialTagType() too.
2437 void MicrosoftCXXNameMangler::mangleArtificialTagType(
2438  TagTypeKind TK, StringRef UnqualifiedName,
2439  ArrayRef<StringRef> NestedNames) {
2440  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2441  mangleTagTypeKind(TK);
2442 
2443  // Always start with the unqualified name.
2444  mangleSourceName(UnqualifiedName);
2445 
2446  for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2447  mangleSourceName(*I);
2448 
2449  // Terminate the whole name with an '@'.
2450  Out << '@';
2451 }
2452 
2453 // <type> ::= <array-type>
2454 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2455 // [Y <dimension-count> <dimension>+]
2456 // <element-type> # as global, E is never required
2457 // It's supposed to be the other way around, but for some strange reason, it
2458 // isn't. Today this behavior is retained for the sole purpose of backwards
2459 // compatibility.
2460 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2461  // This isn't a recursive mangling, so now we have to do it all in this
2462  // one call.
2463  manglePointerCVQualifiers(T->getElementType().getQualifiers());
2464  mangleType(T->getElementType(), SourceRange());
2465 }
2466 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2467  SourceRange) {
2468  llvm_unreachable("Should have been special cased");
2469 }
2470 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2471  SourceRange) {
2472  llvm_unreachable("Should have been special cased");
2473 }
2474 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2476  llvm_unreachable("Should have been special cased");
2477 }
2478 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2480  llvm_unreachable("Should have been special cased");
2481 }
2482 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2483  QualType ElementTy(T, 0);
2484  SmallVector<llvm::APInt, 3> Dimensions;
2485  for (;;) {
2486  if (ElementTy->isConstantArrayType()) {
2487  const ConstantArrayType *CAT =
2488  getASTContext().getAsConstantArrayType(ElementTy);
2489  Dimensions.push_back(CAT->getSize());
2490  ElementTy = CAT->getElementType();
2491  } else if (ElementTy->isIncompleteArrayType()) {
2492  const IncompleteArrayType *IAT =
2493  getASTContext().getAsIncompleteArrayType(ElementTy);
2494  Dimensions.push_back(llvm::APInt(32, 0));
2495  ElementTy = IAT->getElementType();
2496  } else if (ElementTy->isVariableArrayType()) {
2497  const VariableArrayType *VAT =
2498  getASTContext().getAsVariableArrayType(ElementTy);
2499  Dimensions.push_back(llvm::APInt(32, 0));
2500  ElementTy = VAT->getElementType();
2501  } else if (ElementTy->isDependentSizedArrayType()) {
2502  // The dependent expression has to be folded into a constant (TODO).
2503  const DependentSizedArrayType *DSAT =
2504  getASTContext().getAsDependentSizedArrayType(ElementTy);
2505  DiagnosticsEngine &Diags = Context.getDiags();
2506  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2507  "cannot mangle this dependent-length array yet");
2508  Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2509  << DSAT->getBracketsRange();
2510  return;
2511  } else {
2512  break;
2513  }
2514  }
2515  Out << 'Y';
2516  // <dimension-count> ::= <number> # number of extra dimensions
2517  mangleNumber(Dimensions.size());
2518  for (const llvm::APInt &Dimension : Dimensions)
2519  mangleNumber(Dimension.getLimitedValue());
2520  mangleType(ElementTy, SourceRange(), QMM_Escape);
2521 }
2522 
2523 // <type> ::= <pointer-to-member-type>
2524 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2525 // <class name> <type>
2526 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2527  Qualifiers Quals, SourceRange Range) {
2528  QualType PointeeType = T->getPointeeType();
2529  manglePointerCVQualifiers(Quals);
2530  manglePointerExtQualifiers(Quals, PointeeType);
2531  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2532  Out << '8';
2533  mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2534  mangleFunctionType(FPT, nullptr, true);
2535  } else {
2536  mangleQualifiers(PointeeType.getQualifiers(), true);
2537  mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2538  mangleType(PointeeType, Range, QMM_Drop);
2539  }
2540 }
2541 
2542 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2543  Qualifiers, SourceRange Range) {
2544  DiagnosticsEngine &Diags = Context.getDiags();
2545  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2546  "cannot mangle this template type parameter type yet");
2547  Diags.Report(Range.getBegin(), DiagID)
2548  << Range;
2549 }
2550 
2551 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2552  Qualifiers, SourceRange Range) {
2553  DiagnosticsEngine &Diags = Context.getDiags();
2554  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2555  "cannot mangle this substituted parameter pack yet");
2556  Diags.Report(Range.getBegin(), DiagID)
2557  << Range;
2558 }
2559 
2560 // <type> ::= <pointer-type>
2561 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2562 // # the E is required for 64-bit non-static pointers
2563 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2564  SourceRange Range) {
2565  QualType PointeeType = T->getPointeeType();
2566  manglePointerCVQualifiers(Quals);
2567  manglePointerExtQualifiers(Quals, PointeeType);
2568 
2569  if (PointeeType.getQualifiers().hasAddressSpace())
2570  mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2571  else
2572  mangleType(PointeeType, Range);
2573 }
2574 
2575 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2576  Qualifiers Quals, SourceRange Range) {
2577  QualType PointeeType = T->getPointeeType();
2578  switch (Quals.getObjCLifetime()) {
2579  case Qualifiers::OCL_None:
2580  case Qualifiers::OCL_ExplicitNone:
2581  break;
2582  case Qualifiers::OCL_Autoreleasing:
2583  case Qualifiers::OCL_Strong:
2584  case Qualifiers::OCL_Weak:
2585  return mangleObjCLifetime(PointeeType, Quals, Range);
2586  }
2587  manglePointerCVQualifiers(Quals);
2588  manglePointerExtQualifiers(Quals, PointeeType);
2589  mangleType(PointeeType, Range);
2590 }
2591 
2592 // <type> ::= <reference-type>
2593 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2594 // # the E is required for 64-bit non-static lvalue references
2595 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2596  Qualifiers Quals, SourceRange Range) {
2597  QualType PointeeType = T->getPointeeType();
2598  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2599  Out << 'A';
2600  manglePointerExtQualifiers(Quals, PointeeType);
2601  mangleType(PointeeType, Range);
2602 }
2603 
2604 // <type> ::= <r-value-reference-type>
2605 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2606 // # the E is required for 64-bit non-static rvalue references
2607 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2608  Qualifiers Quals, SourceRange Range) {
2609  QualType PointeeType = T->getPointeeType();
2610  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2611  Out << "$$Q";
2612  manglePointerExtQualifiers(Quals, PointeeType);
2613  mangleType(PointeeType, Range);
2614 }
2615 
2616 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2617  SourceRange Range) {
2618  QualType ElementType = T->getElementType();
2619 
2620  llvm::SmallString<64> TemplateMangling;
2621  llvm::raw_svector_ostream Stream(TemplateMangling);
2622  MicrosoftCXXNameMangler Extra(Context, Stream);
2623  Stream << "?$";
2624  Extra.mangleSourceName("_Complex");
2625  Extra.mangleType(ElementType, Range, QMM_Escape);
2626 
2627  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2628 }
2629 
2630 // Returns true for types that mangleArtificialTagType() gets called for with
2631 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2632 // mangling matters.
2633 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2634 // support.)
2635 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2636  const Type *ty = T.getTypePtr();
2637  switch (ty->getTypeClass()) {
2638  default:
2639  return false;
2640 
2641  case Type::Vector: {
2642  // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2643  // but since mangleType(VectorType*) always calls mangleArtificialTagType()
2644  // just always return true (the other vector types are clang-only).
2645  return true;
2646  }
2647  }
2648 }
2649 
2650 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2651  SourceRange Range) {
2652  const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2653  assert(ET && "vectors with non-builtin elements are unsupported");
2654  uint64_t Width = getASTContext().getTypeSize(T);
2655  // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2656  // doesn't match the Intel types uses a custom mangling below.
2657  size_t OutSizeBefore = Out.tell();
2658  if (!isa<ExtVectorType>(T)) {
2659  llvm::Triple::ArchType AT =
2660  getASTContext().getTargetInfo().getTriple().getArch();
2661  if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2662  if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2663  mangleArtificialTagType(TTK_Union, "__m64");
2664  } else if (Width >= 128) {
2665  if (ET->getKind() == BuiltinType::Float)
2666  mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
2667  else if (ET->getKind() == BuiltinType::LongLong)
2668  mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2669  else if (ET->getKind() == BuiltinType::Double)
2670  mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2671  }
2672  }
2673  }
2674 
2675  bool IsBuiltin = Out.tell() != OutSizeBefore;
2676  if (!IsBuiltin) {
2677  // The MS ABI doesn't have a special mangling for vector types, so we define
2678  // our own mangling to handle uses of __vector_size__ on user-specified
2679  // types, and for extensions like __v4sf.
2680 
2681  llvm::SmallString<64> TemplateMangling;
2682  llvm::raw_svector_ostream Stream(TemplateMangling);
2683  MicrosoftCXXNameMangler Extra(Context, Stream);
2684  Stream << "?$";
2685  Extra.mangleSourceName("__vector");
2686  Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2687  Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2688  /*IsBoolean=*/false);
2689 
2690  mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
2691  }
2692 }
2693 
2694 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2695  Qualifiers Quals, SourceRange Range) {
2696  mangleType(static_cast<const VectorType *>(T), Quals, Range);
2697 }
2698 
2699 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2700  Qualifiers, SourceRange Range) {
2701  DiagnosticsEngine &Diags = Context.getDiags();
2702  unsigned DiagID = Diags.getCustomDiagID(
2704  "cannot mangle this dependent-sized vector type yet");
2705  Diags.Report(Range.getBegin(), DiagID) << Range;
2706 }
2707 
2708 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2709  Qualifiers, SourceRange Range) {
2710  DiagnosticsEngine &Diags = Context.getDiags();
2711  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2712  "cannot mangle this dependent-sized extended vector type yet");
2713  Diags.Report(Range.getBegin(), DiagID)
2714  << Range;
2715 }
2716 
2717 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2718  Qualifiers, SourceRange Range) {
2719  DiagnosticsEngine &Diags = Context.getDiags();
2720  unsigned DiagID = Diags.getCustomDiagID(
2722  "cannot mangle this dependent address space type yet");
2723  Diags.Report(Range.getBegin(), DiagID) << Range;
2724 }
2725 
2726 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2727  SourceRange) {
2728  // ObjC interfaces have structs underlying them.
2729  mangleTagTypeKind(TTK_Struct);
2730  mangleName(T->getDecl());
2731 }
2732 
2733 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
2734  Qualifiers Quals, SourceRange Range) {
2735  if (T->isKindOfType())
2736  return mangleObjCKindOfType(T, Quals, Range);
2737 
2738  if (T->qual_empty() && !T->isSpecialized())
2739  return mangleType(T->getBaseType(), Range, QMM_Drop);
2740 
2741  ArgBackRefMap OuterArgsContext;
2742  BackRefVec OuterTemplateContext;
2743 
2744  TypeBackReferences.swap(OuterArgsContext);
2745  NameBackReferences.swap(OuterTemplateContext);
2746 
2747  mangleTagTypeKind(TTK_Struct);
2748 
2749  Out << "?$";
2750  if (T->isObjCId())
2751  mangleSourceName("objc_object");
2752  else if (T->isObjCClass())
2753  mangleSourceName("objc_class");
2754  else
2755  mangleSourceName(T->getInterface()->getName());
2756 
2757  for (const auto &Q : T->quals())
2758  mangleObjCProtocol(Q);
2759 
2760  if (T->isSpecialized())
2761  for (const auto &TA : T->getTypeArgs())
2762  mangleType(TA, Range, QMM_Drop);
2763 
2764  Out << '@';
2765 
2766  Out << '@';
2767 
2768  TypeBackReferences.swap(OuterArgsContext);
2769  NameBackReferences.swap(OuterTemplateContext);
2770 }
2771 
2772 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2773  Qualifiers Quals, SourceRange Range) {
2774  QualType PointeeType = T->getPointeeType();
2775  manglePointerCVQualifiers(Quals);
2776  manglePointerExtQualifiers(Quals, PointeeType);
2777 
2778  Out << "_E";
2779 
2780  mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2781 }
2782 
2783 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2785  llvm_unreachable("Cannot mangle injected class name type.");
2786 }
2787 
2788 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2789  Qualifiers, SourceRange Range) {
2790  DiagnosticsEngine &Diags = Context.getDiags();
2791  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2792  "cannot mangle this template specialization type yet");
2793  Diags.Report(Range.getBegin(), DiagID)
2794  << Range;
2795 }
2796 
2797 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2798  SourceRange Range) {
2799  DiagnosticsEngine &Diags = Context.getDiags();
2800  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2801  "cannot mangle this dependent name type yet");
2802  Diags.Report(Range.getBegin(), DiagID)
2803  << Range;
2804 }
2805 
2806 void MicrosoftCXXNameMangler::mangleType(
2808  SourceRange Range) {
2809  DiagnosticsEngine &Diags = Context.getDiags();
2810  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2811  "cannot mangle this dependent template specialization type yet");
2812  Diags.Report(Range.getBegin(), DiagID)
2813  << Range;
2814 }
2815 
2816 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2817  SourceRange Range) {
2818  DiagnosticsEngine &Diags = Context.getDiags();
2819  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2820  "cannot mangle this pack expansion yet");
2821  Diags.Report(Range.getBegin(), DiagID)
2822  << Range;
2823 }
2824 
2825 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2826  SourceRange Range) {
2827  DiagnosticsEngine &Diags = Context.getDiags();
2828  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2829  "cannot mangle this typeof(type) yet");
2830  Diags.Report(Range.getBegin(), DiagID)
2831  << Range;
2832 }
2833 
2834 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2835  SourceRange Range) {
2836  DiagnosticsEngine &Diags = Context.getDiags();
2837  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2838  "cannot mangle this typeof(expression) yet");
2839  Diags.Report(Range.getBegin(), DiagID)
2840  << Range;
2841 }
2842 
2843 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2844  SourceRange Range) {
2845  DiagnosticsEngine &Diags = Context.getDiags();
2846  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2847  "cannot mangle this decltype() yet");
2848  Diags.Report(Range.getBegin(), DiagID)
2849  << Range;
2850 }
2851 
2852 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2853  Qualifiers, SourceRange Range) {
2854  DiagnosticsEngine &Diags = Context.getDiags();
2855  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2856  "cannot mangle this unary transform type yet");
2857  Diags.Report(Range.getBegin(), DiagID)
2858  << Range;
2859 }
2860 
2861 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2862  SourceRange Range) {
2863  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2864 
2865  DiagnosticsEngine &Diags = Context.getDiags();
2866  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2867  "cannot mangle this 'auto' type yet");
2868  Diags.Report(Range.getBegin(), DiagID)
2869  << Range;
2870 }
2871 
2872 void MicrosoftCXXNameMangler::mangleType(
2874  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2875 
2876  DiagnosticsEngine &Diags = Context.getDiags();
2877  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2878  "cannot mangle this deduced class template specialization type yet");
2879  Diags.Report(Range.getBegin(), DiagID)
2880  << Range;
2881 }
2882 
2883 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2884  SourceRange Range) {
2885  QualType ValueType = T->getValueType();
2886 
2887  llvm::SmallString<64> TemplateMangling;
2888  llvm::raw_svector_ostream Stream(TemplateMangling);
2889  MicrosoftCXXNameMangler Extra(Context, Stream);
2890  Stream << "?$";
2891  Extra.mangleSourceName("_Atomic");
2892  Extra.mangleType(ValueType, Range, QMM_Escape);
2893 
2894  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2895 }
2896 
2897 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2898  SourceRange Range) {
2899  DiagnosticsEngine &Diags = Context.getDiags();
2900  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2901  "cannot mangle this OpenCL pipe type yet");
2902  Diags.Report(Range.getBegin(), DiagID)
2903  << Range;
2904 }
2905 
2906 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2907  raw_ostream &Out) {
2908  assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2909  "Invalid mangleName() call, argument is not a variable or function!");
2910  assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2911  "Invalid mangleName() call on 'structor decl!");
2912 
2913  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2914  getASTContext().getSourceManager(),
2915  "Mangling declaration");
2916 
2917  msvc_hashing_ostream MHO(Out);
2918  MicrosoftCXXNameMangler Mangler(*this, MHO);
2919  return Mangler.mangle(D);
2920 }
2921 
2922 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2923 // <virtual-adjustment>
2924 // <no-adjustment> ::= A # private near
2925 // ::= B # private far
2926 // ::= I # protected near
2927 // ::= J # protected far
2928 // ::= Q # public near
2929 // ::= R # public far
2930 // <static-adjustment> ::= G <static-offset> # private near
2931 // ::= H <static-offset> # private far
2932 // ::= O <static-offset> # protected near
2933 // ::= P <static-offset> # protected far
2934 // ::= W <static-offset> # public near
2935 // ::= X <static-offset> # public far
2936 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2937 // ::= $1 <virtual-shift> <static-offset> # private far
2938 // ::= $2 <virtual-shift> <static-offset> # protected near
2939 // ::= $3 <virtual-shift> <static-offset> # protected far
2940 // ::= $4 <virtual-shift> <static-offset> # public near
2941 // ::= $5 <virtual-shift> <static-offset> # public far
2942 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2943 // <vtordisp-shift> ::= <offset-to-vtordisp>
2944 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2945 // <offset-to-vtordisp>
2947  const ThisAdjustment &Adjustment,
2948  MicrosoftCXXNameMangler &Mangler,
2949  raw_ostream &Out) {
2950  if (!Adjustment.Virtual.isEmpty()) {
2951  Out << '$';
2952  char AccessSpec;
2953  switch (AS) {
2954  case AS_none:
2955  llvm_unreachable("Unsupported access specifier");
2956  case AS_private:
2957  AccessSpec = '0';
2958  break;
2959  case AS_protected:
2960  AccessSpec = '2';
2961  break;
2962  case AS_public:
2963  AccessSpec = '4';
2964  }
2965  if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2966  Out << 'R' << AccessSpec;
2967  Mangler.mangleNumber(
2968  static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2969  Mangler.mangleNumber(
2970  static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2971  Mangler.mangleNumber(
2972  static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2973  Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2974  } else {
2975  Out << AccessSpec;
2976  Mangler.mangleNumber(
2977  static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2978  Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2979  }
2980  } else if (Adjustment.NonVirtual != 0) {
2981  switch (AS) {
2982  case AS_none:
2983  llvm_unreachable("Unsupported access specifier");
2984  case AS_private:
2985  Out << 'G';
2986  break;
2987  case AS_protected:
2988  Out << 'O';
2989  break;
2990  case AS_public:
2991  Out << 'W';
2992  }
2993  Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2994  } else {
2995  switch (AS) {
2996  case AS_none:
2997  llvm_unreachable("Unsupported access specifier");
2998  case AS_private:
2999  Out << 'A';
3000  break;
3001  case AS_protected:
3002  Out << 'I';
3003  break;
3004  case AS_public:
3005  Out << 'Q';
3006  }
3007  }
3008 }
3009 
3010 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3011  const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3012  raw_ostream &Out) {
3013  msvc_hashing_ostream MHO(Out);
3014  MicrosoftCXXNameMangler Mangler(*this, MHO);
3015  Mangler.getStream() << '?';
3016  Mangler.mangleVirtualMemPtrThunk(MD, ML);
3017 }
3018 
3019 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3020  const ThunkInfo &Thunk,
3021  raw_ostream &Out) {
3022  msvc_hashing_ostream MHO(Out);
3023  MicrosoftCXXNameMangler Mangler(*this, MHO);
3024  Mangler.getStream() << '?';
3025  Mangler.mangleName(MD);
3026 
3027  // Usually the thunk uses the access specifier of the new method, but if this
3028  // is a covariant return thunk, then MSVC always uses the public access
3029  // specifier, and we do the same.
3030  AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3031  mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3032 
3033  if (!Thunk.Return.isEmpty())
3034  assert(Thunk.Method != nullptr &&
3035  "Thunk info should hold the overridee decl");
3036 
3037  const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3038  Mangler.mangleFunctionType(
3039  DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3040 }
3041 
3042 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3043  const CXXDestructorDecl *DD, CXXDtorType Type,
3044  const ThisAdjustment &Adjustment, raw_ostream &Out) {
3045  // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3046  // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3047  // mangling manually until we support both deleting dtor types.
3048  assert(Type == Dtor_Deleting);
3049  msvc_hashing_ostream MHO(Out);
3050  MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3051  Mangler.getStream() << "??_E";
3052  Mangler.mangleName(DD->getParent());
3053  mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3054  Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3055 }
3056 
3057 void MicrosoftMangleContextImpl::mangleCXXVFTable(
3058  const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3059  raw_ostream &Out) {
3060  // <mangled-name> ::= ?_7 <class-name> <storage-class>
3061  // <cvr-qualifiers> [<name>] @
3062  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3063  // is always '6' for vftables.
3064  msvc_hashing_ostream MHO(Out);
3065  MicrosoftCXXNameMangler Mangler(*this, MHO);
3066  if (Derived->hasAttr<DLLImportAttr>())
3067  Mangler.getStream() << "??_S";
3068  else
3069  Mangler.getStream() << "??_7";
3070  Mangler.mangleName(Derived);
3071  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3072  for (const CXXRecordDecl *RD : BasePath)
3073  Mangler.mangleName(RD);
3074  Mangler.getStream() << '@';
3075 }
3076 
3077 void MicrosoftMangleContextImpl::mangleCXXVBTable(
3078  const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3079  raw_ostream &Out) {
3080  // <mangled-name> ::= ?_8 <class-name> <storage-class>
3081  // <cvr-qualifiers> [<name>] @
3082  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3083  // is always '7' for vbtables.
3084  msvc_hashing_ostream MHO(Out);
3085  MicrosoftCXXNameMangler Mangler(*this, MHO);
3086  Mangler.getStream() << "??_8";
3087  Mangler.mangleName(Derived);
3088  Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
3089  for (const CXXRecordDecl *RD : BasePath)
3090  Mangler.mangleName(RD);
3091  Mangler.getStream() << '@';
3092 }
3093 
3094 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3095  msvc_hashing_ostream MHO(Out);
3096  MicrosoftCXXNameMangler Mangler(*this, MHO);
3097  Mangler.getStream() << "??_R0";
3098  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3099  Mangler.getStream() << "@8";
3100 }
3101 
3102 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3103  raw_ostream &Out) {
3104  MicrosoftCXXNameMangler Mangler(*this, Out);
3105  Mangler.getStream() << '.';
3106  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3107 }
3108 
3109 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3110  const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3111  msvc_hashing_ostream MHO(Out);
3112  MicrosoftCXXNameMangler Mangler(*this, MHO);
3113  Mangler.getStream() << "??_K";
3114  Mangler.mangleName(SrcRD);
3115  Mangler.getStream() << "$C";
3116  Mangler.mangleName(DstRD);
3117 }
3118 
3119 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3120  bool IsVolatile,
3121  bool IsUnaligned,
3122  uint32_t NumEntries,
3123  raw_ostream &Out) {
3124  msvc_hashing_ostream MHO(Out);
3125  MicrosoftCXXNameMangler Mangler(*this, MHO);
3126  Mangler.getStream() << "_TI";
3127  if (IsConst)
3128  Mangler.getStream() << 'C';
3129  if (IsVolatile)
3130  Mangler.getStream() << 'V';
3131  if (IsUnaligned)
3132  Mangler.getStream() << 'U';
3133  Mangler.getStream() << NumEntries;
3134  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3135 }
3136 
3137 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3138  QualType T, uint32_t NumEntries, raw_ostream &Out) {
3139  msvc_hashing_ostream MHO(Out);
3140  MicrosoftCXXNameMangler Mangler(*this, MHO);
3141  Mangler.getStream() << "_CTA";
3142  Mangler.getStream() << NumEntries;
3143  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3144 }
3145 
3146 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3147  QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3148  uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3149  raw_ostream &Out) {
3150  MicrosoftCXXNameMangler Mangler(*this, Out);
3151  Mangler.getStream() << "_CT";
3152 
3153  llvm::SmallString<64> RTTIMangling;
3154  {
3155  llvm::raw_svector_ostream Stream(RTTIMangling);
3156  msvc_hashing_ostream MHO(Stream);
3157  mangleCXXRTTI(T, MHO);
3158  }
3159  Mangler.getStream() << RTTIMangling;
3160 
3161  // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
3162  // in fact, superfluous but I'm not sure the change was made consciously.
3163  llvm::SmallString<64> CopyCtorMangling;
3164  if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
3165  LangOptions::MSVC2015) &&
3166  CD) {
3167  llvm::raw_svector_ostream Stream(CopyCtorMangling);
3168  msvc_hashing_ostream MHO(Stream);
3169  mangleCXXCtor(CD, CT, MHO);
3170  }
3171  Mangler.getStream() << CopyCtorMangling;
3172 
3173  Mangler.getStream() << Size;
3174  if (VBPtrOffset == -1) {
3175  if (NVOffset) {
3176  Mangler.getStream() << NVOffset;
3177  }
3178  } else {
3179  Mangler.getStream() << NVOffset;
3180  Mangler.getStream() << VBPtrOffset;
3181  Mangler.getStream() << VBIndex;
3182  }
3183 }
3184 
3185 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3186  const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3187  uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3188  msvc_hashing_ostream MHO(Out);
3189  MicrosoftCXXNameMangler Mangler(*this, MHO);
3190  Mangler.getStream() << "??_R1";
3191  Mangler.mangleNumber(NVOffset);
3192  Mangler.mangleNumber(VBPtrOffset);
3193  Mangler.mangleNumber(VBTableOffset);
3194  Mangler.mangleNumber(Flags);
3195  Mangler.mangleName(Derived);
3196  Mangler.getStream() << "8";
3197 }
3198 
3199 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3200  const CXXRecordDecl *Derived, raw_ostream &Out) {
3201  msvc_hashing_ostream MHO(Out);
3202  MicrosoftCXXNameMangler Mangler(*this, MHO);
3203  Mangler.getStream() << "??_R2";
3204  Mangler.mangleName(Derived);
3205  Mangler.getStream() << "8";
3206 }
3207 
3208 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3209  const CXXRecordDecl *Derived, raw_ostream &Out) {
3210  msvc_hashing_ostream MHO(Out);
3211  MicrosoftCXXNameMangler Mangler(*this, MHO);
3212  Mangler.getStream() << "??_R3";
3213  Mangler.mangleName(Derived);
3214  Mangler.getStream() << "8";
3215 }
3216 
3217 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3218  const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3219  raw_ostream &Out) {
3220  // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3221  // <cvr-qualifiers> [<name>] @
3222  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3223  // is always '6' for vftables.
3224  llvm::SmallString<64> VFTableMangling;
3225  llvm::raw_svector_ostream Stream(VFTableMangling);
3226  mangleCXXVFTable(Derived, BasePath, Stream);
3227 
3228  if (VFTableMangling.startswith("??@")) {
3229  assert(VFTableMangling.endswith("@"));
3230  Out << VFTableMangling << "??_R4@";
3231  return;
3232  }
3233 
3234  assert(VFTableMangling.startswith("??_7") ||
3235  VFTableMangling.startswith("??_S"));
3236 
3237  Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3238 }
3239 
3240 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3241  const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3242  msvc_hashing_ostream MHO(Out);
3243  MicrosoftCXXNameMangler Mangler(*this, MHO);
3244  // The function body is in the same comdat as the function with the handler,
3245  // so the numbering here doesn't have to be the same across TUs.
3246  //
3247  // <mangled-name> ::= ?filt$ <filter-number> @0
3248  Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3249  Mangler.mangleName(EnclosingDecl);
3250 }
3251 
3252 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3253  const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3254  msvc_hashing_ostream MHO(Out);
3255  MicrosoftCXXNameMangler Mangler(*this, MHO);
3256  // The function body is in the same comdat as the function with the handler,
3257  // so the numbering here doesn't have to be the same across TUs.
3258  //
3259  // <mangled-name> ::= ?fin$ <filter-number> @0
3260  Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3261  Mangler.mangleName(EnclosingDecl);
3262 }
3263 
3264 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3265  // This is just a made up unique string for the purposes of tbaa. undname
3266  // does *not* know how to demangle it.
3267  MicrosoftCXXNameMangler Mangler(*this, Out);
3268  Mangler.getStream() << '?';
3269  Mangler.mangleType(T, SourceRange());
3270 }
3271 
3272 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3273  CXXCtorType Type,
3274  raw_ostream &Out) {
3275  msvc_hashing_ostream MHO(Out);
3276  MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3277  mangler.mangle(D);
3278 }
3279 
3280 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3281  CXXDtorType Type,
3282  raw_ostream &Out) {
3283  msvc_hashing_ostream MHO(Out);
3284  MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3285  mangler.mangle(D);
3286 }
3287 
3288 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3289  const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3290  msvc_hashing_ostream MHO(Out);
3291  MicrosoftCXXNameMangler Mangler(*this, MHO);
3292 
3293  Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3294  Mangler.mangle(VD, "");
3295 }
3296 
3297 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3298  const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3299  msvc_hashing_ostream MHO(Out);
3300  MicrosoftCXXNameMangler Mangler(*this, MHO);
3301 
3302  Mangler.getStream() << "?$TSS" << GuardNum << '@';
3303  Mangler.mangleNestedName(VD);
3304  Mangler.getStream() << "@4HA";
3305 }
3306 
3307 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3308  raw_ostream &Out) {
3309  // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3310  // ::= ?__J <postfix> @5 <scope-depth>
3311  // ::= ?$S <guard-num> @ <postfix> @4IA
3312 
3313  // The first mangling is what MSVC uses to guard static locals in inline
3314  // functions. It uses a different mangling in external functions to support
3315  // guarding more than 32 variables. MSVC rejects inline functions with more
3316  // than 32 static locals. We don't fully implement the second mangling
3317  // because those guards are not externally visible, and instead use LLVM's
3318  // default renaming when creating a new guard variable.
3319  msvc_hashing_ostream MHO(Out);
3320  MicrosoftCXXNameMangler Mangler(*this, MHO);
3321 
3322  bool Visible = VD->isExternallyVisible();
3323  if (Visible) {
3324  Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3325  } else {
3326  Mangler.getStream() << "?$S1@";
3327  }
3328  unsigned ScopeDepth = 0;
3329  if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3330  // If we do not have a discriminator and are emitting a guard variable for
3331  // use at global scope, then mangling the nested name will not be enough to
3332  // remove ambiguities.
3333  Mangler.mangle(VD, "");
3334  else
3335  Mangler.mangleNestedName(VD);
3336  Mangler.getStream() << (Visible ? "@5" : "@4IA");
3337  if (ScopeDepth)
3338  Mangler.mangleNumber(ScopeDepth);
3339 }
3340 
3341 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3342  char CharCode,
3343  raw_ostream &Out) {
3344  msvc_hashing_ostream MHO(Out);
3345  MicrosoftCXXNameMangler Mangler(*this, MHO);
3346  Mangler.getStream() << "??__" << CharCode;
3347  if (D->isStaticDataMember()) {
3348  Mangler.getStream() << '?';
3349  Mangler.mangleName(D);
3350  Mangler.mangleVariableEncoding(D);
3351  Mangler.getStream() << "@@";
3352  } else {
3353  Mangler.mangleName(D);
3354  }
3355  // This is the function class mangling. These stubs are global, non-variadic,
3356  // cdecl functions that return void and take no args.
3357  Mangler.getStream() << "YAXXZ";
3358 }
3359 
3360 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3361  raw_ostream &Out) {
3362  // <initializer-name> ::= ?__E <name> YAXXZ
3363  mangleInitFiniStub(D, 'E', Out);
3364 }
3365 
3366 void
3367 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3368  raw_ostream &Out) {
3369  // <destructor-name> ::= ?__F <name> YAXXZ
3370  mangleInitFiniStub(D, 'F', Out);
3371 }
3372 
3373 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3374  raw_ostream &Out) {
3375  // <char-type> ::= 0 # char, char16_t, char32_t
3376  // # (little endian char data in mangling)
3377  // ::= 1 # wchar_t (big endian char data in mangling)
3378  //
3379  // <literal-length> ::= <non-negative integer> # the length of the literal
3380  //
3381  // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
3382  // # trailing null bytes
3383  //
3384  // <encoded-string> ::= <simple character> # uninteresting character
3385  // ::= '?$' <hex digit> <hex digit> # these two nibbles
3386  // # encode the byte for the
3387  // # character
3388  // ::= '?' [a-z] # \xe1 - \xfa
3389  // ::= '?' [A-Z] # \xc1 - \xda
3390  // ::= '?' [0-9] # [,/\:. \n\t'-]
3391  //
3392  // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3393  // <encoded-string> '@'
3394  MicrosoftCXXNameMangler Mangler(*this, Out);
3395  Mangler.getStream() << "??_C@_";
3396 
3397  // The actual string length might be different from that of the string literal
3398  // in cases like:
3399  // char foo[3] = "foobar";
3400  // char bar[42] = "foobar";
3401  // Where it is truncated or zero-padded to fit the array. This is the length
3402  // used for mangling, and any trailing null-bytes also need to be mangled.
3403  unsigned StringLength = getASTContext()
3404  .getAsConstantArrayType(SL->getType())
3405  ->getSize()
3406  .getZExtValue();
3407  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3408 
3409  // <char-type>: The "kind" of string literal is encoded into the mangled name.
3410  if (SL->isWide())
3411  Mangler.getStream() << '1';
3412  else
3413  Mangler.getStream() << '0';
3414 
3415  // <literal-length>: The next part of the mangled name consists of the length
3416  // of the string in bytes.
3417  Mangler.mangleNumber(StringByteLength);
3418 
3419  auto GetLittleEndianByte = [&SL](unsigned Index) {
3420  unsigned CharByteWidth = SL->getCharByteWidth();
3421  if (Index / CharByteWidth >= SL->getLength())
3422  return static_cast<char>(0);
3423  uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3424  unsigned OffsetInCodeUnit = Index % CharByteWidth;
3425  return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3426  };
3427 
3428  auto GetBigEndianByte = [&SL](unsigned Index) {
3429  unsigned CharByteWidth = SL->getCharByteWidth();
3430  if (Index / CharByteWidth >= SL->getLength())
3431  return static_cast<char>(0);
3432  uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3433  unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3434  return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3435  };
3436 
3437  // CRC all the bytes of the StringLiteral.
3438  llvm::JamCRC JC;
3439  for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3440  JC.update(GetLittleEndianByte(I));
3441 
3442  // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3443  // scheme.
3444  Mangler.mangleNumber(JC.getCRC());
3445 
3446  // <encoded-string>: The mangled name also contains the first 32 bytes
3447  // (including null-terminator bytes) of the encoded StringLiteral.
3448  // Each character is encoded by splitting them into bytes and then encoding
3449  // the constituent bytes.
3450  auto MangleByte = [&Mangler](char Byte) {
3451  // There are five different manglings for characters:
3452  // - [a-zA-Z0-9_$]: A one-to-one mapping.
3453  // - ?[a-z]: The range from \xe1 to \xfa.
3454  // - ?[A-Z]: The range from \xc1 to \xda.
3455  // - ?[0-9]: The set of [,/\:. \n\t'-].
3456  // - ?$XX: A fallback which maps nibbles.
3457  if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3458  Mangler.getStream() << Byte;
3459  } else if (isLetter(Byte & 0x7f)) {
3460  Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3461  } else {
3462  const char SpecialChars[] = {',', '/', '\\', ':', '.',
3463  ' ', '\n', '\t', '\'', '-'};
3464  const char *Pos = llvm::find(SpecialChars, Byte);
3465  if (Pos != std::end(SpecialChars)) {
3466  Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3467  } else {
3468  Mangler.getStream() << "?$";
3469  Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3470  Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3471  }
3472  }
3473  };
3474 
3475  // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3476  unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3477  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3478  for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3479  if (SL->isWide())
3480  MangleByte(GetBigEndianByte(I));
3481  else
3482  MangleByte(GetLittleEndianByte(I));
3483  }
3484 
3485  Mangler.getStream() << '@';
3486 }
3487 
3490  return new MicrosoftMangleContextImpl(Context, Diags);
3491 }
Defines the clang::ASTContext interface.
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it&#39;s either not been deduced or was deduce...
Definition: Type.h:4747
Represents a function declaration or definition.
Definition: Decl.h:1737
StringRef Identifier
Definition: Format.cpp:1714
void removeUnaligned()
Definition: Type.h:297
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:2734
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2549
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:4035
QualType getPointeeType() const
Definition: Type.h:2562
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:4133
A (possibly-)qualified type.
Definition: Type.h:639
bool isBlockPointerType() const
Definition: Type.h:6316
bool isArrayType() const
Definition: Type.h:6357
bool isMemberPointerType() const
Definition: Type.h:6339
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:280
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2915
static void mangleThunkThisAdjustment(AccessSpecifier AS, const ThisAdjustment &Adjustment, MicrosoftCXXNameMangler &Mangler, raw_ostream &Out)
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:365
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:939
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:29
Kind getKind() const
Definition: Type.h:2430
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3367
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:5224
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:269
bool isEmpty() const
Definition: ABI.h:86
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4014
bool isVirtual() const
Definition: DeclCXX.h:2093
Defines the C++ template declaration subclasses.
StringRef P
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:452
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4761
The base class of the type hierarchy.
Definition: Type.h:1414
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: ABI.h:110
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1296
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2824
Represent a C++ namespace.
Definition: Decl.h:514
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:132
QualType withConst() const
Definition: Type.h:811
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:97
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5995
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2491
Default closure variant of a ctor.
Definition: ABI.h:29
MSInheritanceAttr::Spelling getMSInheritanceModel() const
Returns the inheritance model used for this record.
QualType getElementType() const
Definition: Type.h:2859
Represents a variable declaration or definition.
Definition: Decl.h:812
unsigned getNumParams() const
Definition: Type.h:3900
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6768
The "union" keyword.
Definition: Type.h:5051
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
Represents a C++17 deduced template specialization type.
Definition: Type.h:4797
A this pointer adjustment.
Definition: ABI.h:107
The "__interface" keyword.
Definition: Type.h:5048
Represents a variable template specialization, which refers to a variable template with a given set o...
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
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:190
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:67
Represents a parameter to a function.
Definition: Decl.h:1549
Defines the clang::Expr interface and subclasses for C++ expressions.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:314
The collection of all-type qualifiers we support.
Definition: Type.h:137
bool isVariableArrayType() const
Definition: Type.h:6369
PipeType - OpenCL20.
Definition: Type.h:6014
bool isDependentSizedArrayType() const
Definition: Type.h:6373
const char * getStmtClassName() const
Definition: Stmt.cpp:74
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
int32_t VBOffsetOffset
The offset (in bytes) of the vbase offset in the vbtable.
Definition: ABI.h:131
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:370
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
Represents a class type in Objective C.
Definition: Type.h:5550
QualType getPointeeType() const
Definition: Type.h:2666
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
LLVM_READONLY bool isLetter(unsigned char c)
Return true if this character is an ASCII letter: [a-zA-Z].
Definition: CharInfo.h:111
NameKind getNameKind() const
Determine what kind of name this is.
bool isNamespace() const
Definition: DeclBase.h:1845
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1602
bool isReferenceType() const
Definition: Type.h:6320
bool addressSpaceMapManglingFor(LangAS AS) const
Definition: ASTContext.h:2533
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4671
The this pointer adjustment as well as an optional return adjustment for a thunk. ...
Definition: ABI.h:178
unsigned getCharByteWidth() const
Definition: Expr.h:1712
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6103
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2750
unsigned getLength() const
Definition: Expr.h:1711
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1370
TagKind getTagKind() const
Definition: Decl.h:3242
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:664
bool hasAddressSpace() const
Definition: Type.h:352
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:274
Deleting dtor.
Definition: ABI.h:34
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:148
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:4188
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:653
LangAS getAddressSpace() const
Definition: Type.h:353
const Type * getClass() const
Definition: Type.h:2802
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1195
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6084
Enums/classes describing ABI related information about constructors, destructors and thunks...
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2063
bool isInstance() const
Definition: DeclCXX.h:2076
void * getAsOpaquePtr() const
Definition: Type.h:684
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5785
bool hasConst() const
Definition: Type.h:254
Expr * getSizeExpr() const
Definition: Type.h:3060
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3140
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:753
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3472
Represents a K&R-style &#39;int foo()&#39; function, which has no information available about its arguments...
Definition: Type.h:3662
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2027
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:1911
bool hasAttr() const
Definition: DeclBase.h:534
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:5613
return Out str()
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1635
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3699
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:688
qual_range quals() const
Definition: Type.h:5450
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:178
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3038
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:431
CXXDtorType
C++ destructor types.
Definition: ABI.h:33
QualType getElementType() const
Definition: Type.h:2502
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3857
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:108
QualType getPointeeType() const
Definition: Type.h:2706
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6831
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2713
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3492
ObjCLifetime getObjCLifetime() const
Definition: Type.h:327
DeclContext * getDeclContext()
Definition: DeclBase.h:430
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1697
TLSKind getTLSKind() const
Definition: Decl.cpp:1949
Represents the type decltype(expr) (C++11).
Definition: Type.h:4258
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:2189
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn&#39;t...
Base object dtor.
Definition: ABI.h:36
QualType getType() const
Definition: Expr.h:130
bool isFunctionOrMethod() const
Definition: DeclBase.h:1813
bool isWide() const
Definition: Expr.h:1719
A unary type transform, which is a type constructed from another.
Definition: Type.h:4301
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1761
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1934
Represents a GCC generic vector type.
Definition: Type.h:3180
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2732
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:305
static const TemplateDecl * isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs)
The result type of a method or function.
bool isObjCClass() const
Definition: Type.h:5619
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:704
bool nullFieldOffsetIsZero() const
In the Microsoft C++ ABI, use zero for the field offset of a null data member pointer if we can guara...
Definition: DeclCXX.h:1946
The COMDAT used for dtors.
Definition: ABI.h:37
const SourceManager & SM
Definition: Format.cpp:1568
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:235
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:34
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
The "struct" keyword.
Definition: Type.h:5045
QualType getCanonicalType() const
Definition: Type.h:6123
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:646
Encodes a location in the source.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5763
QualType getReturnType() const
Definition: Type.h:3625
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4408
Represents typeof(type), a GCC extension.
Definition: Type.h:4231
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5750
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3063
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have...
Definition: Linkage.h:64
QualType getElementType() const
Definition: Type.h:3215
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3257
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2048
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
No ref-qualifier was provided.
Definition: Type.h:1367
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2284
This file defines OpenMP nodes for declarative directives.
Qualifiers getMethodQuals() const
Definition: Type.h:4027
bool hasRestrict() const
Definition: Type.h:264
Qualifiers withoutObjCLifetime() const
Definition: Type.h:315
bool isAnyPointerType() const
Definition: Type.h:6312
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition: Type.h:1365
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:777
TypeClass getTypeClass() const
Definition: Type.h:1820
Complete object dtor.
Definition: ABI.h:35
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:300
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1971
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1373
SourceRange getBracketsRange() const
Definition: Type.h:3066
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2634
CXXCtorType
C++ constructor types.
Definition: ABI.h:24
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:214
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4990
Represents a pack expansion of types.
Definition: Type.h:5367
StringRef getName() const
Return the actual identifier string.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2915
Represents a template argument.
Definition: TemplateBase.h:50
Optional< types::ID > Type
TagTypeKind
The kind of a tag type.
Definition: Type.h:5043
bool isObjCId() const
Definition: Type.h:5615
Dataflow Directional Tag Classes.
ThisAdjustment This
The this pointer adjustment.
Definition: ABI.h:180
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1266
uint64_t Index
Method&#39;s index in the vftable.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
bool isRecord() const
Definition: DeclBase.h:1840
AccessSpecifier getAccess() const
Definition: DeclBase.h:465
A decomposition declaration.
Definition: DeclCXX.h:3850
FileID getMainFileID() const
Returns the FileID of the main source file.
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
The name of a declaration.
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2173
bool isBooleanType() const
Definition: Type.h:6677
LLVM_READONLY bool isIdentifierBody(unsigned char c, bool AllowDollar=false)
Returns true if this is a body character of a C identifier, which is [a-zA-Z0-9_].
Definition: CharInfo.h:58
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:682
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2768
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
bool hasObjCLifetime() const
Definition: Type.h:326
union clang::ThisAdjustment::VirtualAdjustment Virtual
Represents a pointer to an Objective C object.
Definition: Type.h:5806
Pointer to a block type.
Definition: Type.h:2651
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isIncompleteArrayType() const
Definition: Type.h:6365
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4382
Complex values, per C99 6.2.5p11.
Definition: Type.h:2489
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:3061
T * getAttr() const
Definition: DeclBase.h:530
const llvm::APInt & getSize() const
Definition: Type.h:2902
bool isFunctionType() const
Definition: Type.h:6304
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1059
ExtVectorType - Extended vector type.
Definition: Type.h:3299
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1748
ReturnAdjustment Return
The return adjustment.
Definition: ABI.h:183
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
The "class" keyword.
Definition: Type.h:5054
bool isConstantArrayType() const
Definition: Type.h:6361
SourceManager & getSourceManager()
Definition: ASTContext.h:661
A template argument list.
Definition: DeclTemplate.h:209
StringRef getUuidStr() const
Definition: ExprCXX.h:973
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
QualType getParamType(unsigned i) const
Definition: Type.h:3902
CallingConv getCallConv() const
Definition: Type.h:3635
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6164
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3273
bool hasUnaligned() const
Definition: Type.h:293
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:5276
bool isVoidType() const
Definition: Type.h:6560
Represents a C array with an unspecified size.
Definition: Type.h:2938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6111
int32_t VtordispOffset
The offset of the vtordisp (in bytes), relative to the ECX.
Definition: ABI.h:124
The "enum" keyword.
Definition: Type.h:5057
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2403
bool qual_empty() const
Definition: Type.h:5454
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:251
Copying closure variant of a ctor.
Definition: ABI.h:28
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1599
Defines the clang::TargetInfo interface.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3654
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
bool hasVolatile() const
Definition: Type.h:259
unsigned getNumElements() const
Definition: Type.h:3216
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:256
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
Represents an extended address space qualifier where the input address space value is dependent...
Definition: Type.h:3098
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4853
bool isPointerType() const
Definition: Type.h:6308
__DEVICE__ int min(int __a, int __b)
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1134
IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it...
QualType getType() const
Definition: Decl.h:647
A trivial tuple used to represent a source range.
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2996
This represents a decl that may have a name.
Definition: Decl.h:248
bool isTranslationUnit() const
Definition: DeclBase.h:1836
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2983
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:916
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:280
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2517
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parenthese and casts which do not change the value (including ptr->int casts of the sam...
Definition: Expr.cpp:2750
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3072
SourceLocation getBegin() const
int32_t VBPtrOffset
The offset of the vbptr of the derived class (in bytes), relative to the ECX after vtordisp adjustmen...
Definition: ABI.h:128
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2884
This class handles loading and caching of source files into memory.
struct clang::ThisAdjustment::VirtualAdjustment::@134 Microsoft
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1733
SourceLocation getLocation() const
Definition: DeclBase.h:421
QualType getPointeeType() const
Definition: Type.h:2788
bool isExternallyVisible() const
Definition: Decl.h:379
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1173
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5822