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