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