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