1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Mangle.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.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"
26 #include "clang/AST/VTableBuilder.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/JamCRC.h"
32 #include "llvm/Support/xxhash.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
36 using namespace clang;
40 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
42 llvm::SmallString<64> Buffer;
44 msvc_hashing_ostream(raw_ostream &OS)
45 : llvm::raw_svector_ostream(Buffer), OS(OS) {}
46 ~msvc_hashing_ostream() override {
47 StringRef MangledName = str();
48 bool StartsWithEscape = MangledName.startswith("\01");
50 MangledName = MangledName.drop_front(1);
51 if (MangledName.size() <= 4096) {
57 llvm::MD5::MD5Result Hash;
58 Hasher.update(MangledName);
61 SmallString<32> HexString;
62 llvm::MD5::stringifyResult(Hash, HexString);
66 OS << "??@" << HexString << '@';
70 static const DeclContext *
71 getLambdaDefaultArgumentDeclContext(const Decl *D) {
72 if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
74 if (const auto *Parm =
75 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
76 return Parm->getDeclContext();
80 /// Retrieve the declaration context that should be used when mangling
81 /// the given declaration.
82 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
83 // The ABI assumes that lambda closure types that occur within
84 // default arguments live in the context of the function. However, due to
85 // the way in which Clang parses and creates function declarations, this is
86 // not the case: the lambda closure type ends up living in the context
87 // where the function itself resides, because the function declaration itself
88 // had not yet been created. Fix the context here.
89 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
92 // Perform the same check for block literals.
93 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
94 if (ParmVarDecl *ContextParam =
95 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
96 return ContextParam->getDeclContext();
99 const DeclContext *DC = D->getDeclContext();
100 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
101 return getEffectiveDeclContext(cast<Decl>(DC));
104 return DC->getRedeclContext();
107 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
108 return getEffectiveDeclContext(cast<Decl>(DC));
111 static const FunctionDecl *getStructor(const NamedDecl *ND) {
112 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
113 return FTD->getTemplatedDecl()->getCanonicalDecl();
115 const auto *FD = cast<FunctionDecl>(ND);
116 if (const auto *FTD = FD->getPrimaryTemplate())
117 return FTD->getTemplatedDecl()->getCanonicalDecl();
119 return FD->getCanonicalDecl();
122 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
123 /// Microsoft Visual C++ ABI.
124 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
125 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
128 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
129 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
130 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
131 SmallString<16> AnonymousNamespaceHash;
134 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
135 bool shouldMangleCXXName(const NamedDecl *D) override;
136 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
137 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
138 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
139 const MethodVFTableLocation &ML,
140 raw_ostream &Out) override;
141 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
142 raw_ostream &) override;
143 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
144 const ThisAdjustment &ThisAdjustment,
145 raw_ostream &) override;
146 void mangleCXXVFTable(const CXXRecordDecl *Derived,
147 ArrayRef<const CXXRecordDecl *> BasePath,
148 raw_ostream &Out) override;
149 void mangleCXXVBTable(const CXXRecordDecl *Derived,
150 ArrayRef<const CXXRecordDecl *> BasePath,
151 raw_ostream &Out) override;
152 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
153 const CXXRecordDecl *DstRD,
154 raw_ostream &Out) override;
155 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
156 bool IsUnaligned, uint32_t NumEntries,
157 raw_ostream &Out) override;
158 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
159 raw_ostream &Out) override;
160 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
161 CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
162 int32_t VBPtrOffset, uint32_t VBIndex,
163 raw_ostream &Out) override;
164 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
165 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
166 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
167 uint32_t NVOffset, int32_t VBPtrOffset,
168 uint32_t VBTableOffset, uint32_t Flags,
169 raw_ostream &Out) override;
170 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
171 raw_ostream &Out) override;
172 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
173 raw_ostream &Out) override;
175 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
176 ArrayRef<const CXXRecordDecl *> BasePath,
177 raw_ostream &Out) override;
178 void mangleTypeName(QualType T, raw_ostream &) override;
179 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
180 raw_ostream &) override;
181 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
182 raw_ostream &) override;
183 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
184 raw_ostream &) override;
185 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
186 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
187 raw_ostream &Out) override;
188 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
189 void mangleDynamicAtExitDestructor(const VarDecl *D,
190 raw_ostream &Out) override;
191 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
192 raw_ostream &Out) override;
193 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
194 raw_ostream &Out) override;
195 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
196 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
197 const DeclContext *DC = getEffectiveDeclContext(ND);
198 if (!DC->isFunctionOrMethod())
201 // Lambda closure types are already numbered, give out a phony number so
202 // that they demangle nicely.
203 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
204 if (RD->isLambda()) {
210 // Use the canonical number for externally visible decls.
211 if (ND->isExternallyVisible()) {
212 disc = getASTContext().getManglingNumber(ND);
216 // Anonymous tags are already numbered.
217 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
218 if (!Tag->hasNameForLinkage() &&
219 !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
220 !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
224 // Make up a reasonable number for internal decls.
225 unsigned &discriminator = Uniquifier[ND];
227 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
228 disc = discriminator + 1;
232 unsigned getLambdaId(const CXXRecordDecl *RD) {
233 assert(RD->isLambda() && "RD must be a lambda!");
234 assert(!RD->isExternallyVisible() && "RD must not be visible!");
235 assert(RD->getLambdaManglingNumber() == 0 &&
236 "RD must not have a mangling number!");
237 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
238 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
239 return Result.first->second;
242 /// Return a character sequence that is (somewhat) unique to the TU suitable
243 /// for mangling anonymous namespaces.
244 StringRef getAnonymousNamespaceHash() const {
245 return AnonymousNamespaceHash;
249 void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
252 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
253 /// Microsoft Visual C++ ABI.
254 class MicrosoftCXXNameMangler {
255 MicrosoftMangleContextImpl &Context;
258 /// The "structor" is the top-level declaration being mangled, if
259 /// that's not a template specialization; otherwise it's the pattern
260 /// for that specialization.
261 const NamedDecl *Structor;
262 unsigned StructorType;
264 typedef llvm::SmallVector<std::string, 10> BackRefVec;
265 BackRefVec NameBackReferences;
267 typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
268 ArgBackRefMap TypeBackReferences;
270 typedef std::set<int> PassObjectSizeArgsSet;
271 PassObjectSizeArgsSet PassObjectSizeArgs;
273 ASTContext &getASTContext() const { return Context.getASTContext(); }
275 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
276 // this check into mangleQualifiers().
277 const bool PointersAre64Bit;
280 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
282 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
283 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
284 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
287 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
288 const CXXConstructorDecl *D, CXXCtorType Type)
289 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
290 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
293 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
294 const CXXDestructorDecl *D, CXXDtorType Type)
295 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
296 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
299 raw_ostream &getStream() const { return Out; }
301 void mangle(const NamedDecl *D, StringRef Prefix = "?");
302 void mangleName(const NamedDecl *ND);
303 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
304 void mangleVariableEncoding(const VarDecl *VD);
305 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
306 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
307 const CXXMethodDecl *MD);
308 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
309 const MethodVFTableLocation &ML);
310 void mangleNumber(int64_t Number);
311 void mangleTagTypeKind(TagTypeKind TK);
312 void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName,
313 ArrayRef<StringRef> NestedNames = None);
314 void mangleType(QualType T, SourceRange Range,
315 QualifierMangleMode QMM = QMM_Mangle);
316 void mangleFunctionType(const FunctionType *T,
317 const FunctionDecl *D = nullptr,
318 bool ForceThisQuals = false);
319 void mangleNestedName(const NamedDecl *ND);
322 bool isStructorDecl(const NamedDecl *ND) const {
323 return ND == Structor || getStructor(ND) == Structor;
326 void mangleUnqualifiedName(const NamedDecl *ND) {
327 mangleUnqualifiedName(ND, ND->getDeclName());
329 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
330 void mangleSourceName(StringRef Name);
331 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
332 void mangleCXXDtorType(CXXDtorType T);
333 void mangleQualifiers(Qualifiers Quals, bool IsMember);
334 void mangleRefQualifier(RefQualifierKind RefQualifier);
335 void manglePointerCVQualifiers(Qualifiers Quals);
336 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
338 void mangleUnscopedTemplateName(const TemplateDecl *ND);
340 mangleTemplateInstantiationName(const TemplateDecl *TD,
341 const TemplateArgumentList &TemplateArgs);
342 void mangleObjCMethodName(const ObjCMethodDecl *MD);
344 void mangleArgumentType(QualType T, SourceRange Range);
345 void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
347 bool isArtificialTagType(QualType T) const;
349 // Declare manglers for every type class.
350 #define ABSTRACT_TYPE(CLASS, PARENT)
351 #define NON_CANONICAL_TYPE(CLASS, PARENT)
352 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
355 #include "clang/AST/TypeNodes.def"
357 #undef NON_CANONICAL_TYPE
360 void mangleType(const TagDecl *TD);
361 void mangleDecayedArrayType(const ArrayType *T);
362 void mangleArrayType(const ArrayType *T);
363 void mangleFunctionClass(const FunctionDecl *FD);
364 void mangleCallingConvention(CallingConv CC);
365 void mangleCallingConvention(const FunctionType *T);
366 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
367 void mangleExpression(const Expr *E);
368 void mangleThrowSpecification(const FunctionProtoType *T);
370 void mangleTemplateArgs(const TemplateDecl *TD,
371 const TemplateArgumentList &TemplateArgs);
372 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
373 const NamedDecl *Parm);
375 void mangleObjCProtocol(const ObjCProtocolDecl *PD);
376 void mangleObjCLifetime(const QualType T, Qualifiers Quals,
381 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
382 DiagnosticsEngine &Diags)
383 : MicrosoftMangleContext(Context, Diags) {
384 // To mangle anonymous namespaces, hash the path to the main source file. The
385 // path should be whatever (probably relative) path was passed on the command
386 // line. The goal is for the compiler to produce the same output regardless of
387 // working directory, so use the uncanonicalized relative path.
389 // It's important to make the mangled names unique because, when CodeView
390 // debug info is in use, the debugger uses mangled type names to distinguish
391 // between otherwise identically named types in anonymous namespaces.
393 // These symbols are always internal, so there is no need for the hash to
394 // match what MSVC produces. For the same reason, clang is free to change the
395 // hash at any time without breaking compatibility with old versions of clang.
396 // The generated names are intended to look similar to what MSVC generates,
397 // which are something like "?A0x01234567@".
398 SourceManager &SM = Context.getSourceManager();
399 if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
400 // Truncate the hash so we get 8 characters of hexadecimal.
401 uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
402 AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
404 // If we don't have a path to the main file, we'll just use 0.
405 AnonymousNamespaceHash = "0";
409 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
410 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
411 LanguageLinkage L = FD->getLanguageLinkage();
412 // Overloadable functions need mangling.
413 if (FD->hasAttr<OverloadableAttr>())
416 // The ABI expects that we would never mangle "typical" user-defined entry
417 // points regardless of visibility or freestanding-ness.
419 // N.B. This is distinct from asking about "main". "main" has a lot of
420 // special rules associated with it in the standard while these
421 // user-defined entry points are outside of the purview of the standard.
422 // For example, there can be only one definition for "main" in a standards
423 // compliant program; however nothing forbids the existence of wmain and
424 // WinMain in the same translation unit.
425 if (FD->isMSVCRTEntryPoint())
428 // C++ functions and those whose names are not a simple identifier need
430 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
433 // C functions are not mangled.
434 if (L == CLanguageLinkage)
438 // Otherwise, no mangling is done outside C++ mode.
439 if (!getASTContext().getLangOpts().CPlusPlus)
442 const VarDecl *VD = dyn_cast<VarDecl>(D);
443 if (VD && !isa<DecompositionDecl>(D)) {
444 // C variables are not mangled.
448 // Variables at global scope with non-internal linkage are not mangled.
449 const DeclContext *DC = getEffectiveDeclContext(D);
450 // Check for extern variable declared locally.
451 if (DC->isFunctionOrMethod() && D->hasLinkage())
452 while (!DC->isNamespace() && !DC->isTranslationUnit())
453 DC = getEffectiveParentContext(DC);
455 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
456 !isa<VarTemplateSpecializationDecl>(D) &&
457 D->getIdentifier() != nullptr)
465 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
469 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
470 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
471 // Therefore it's really important that we don't decorate the
472 // name with leading underscores or leading/trailing at signs. So, by
473 // default, we emit an asm marker at the start so we get the name right.
474 // Callers can override this with a custom prefix.
476 // <mangled-name> ::= ? <name> <type-encoding>
479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
480 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
481 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
482 mangleVariableEncoding(VD);
483 else if (!isa<ObjCInterfaceDecl>(D))
484 llvm_unreachable("Tried to mangle unexpected NamedDecl!");
487 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
489 // <type-encoding> ::= <function-class> <function-type>
491 // Since MSVC operates on the type as written and not the canonical type, it
492 // actually matters which decl we have here. MSVC appears to choose the
493 // first, since it is most likely to be the declaration in a header file.
494 FD = FD->getFirstDecl();
496 // We should never ever see a FunctionNoProtoType at this point.
497 // We don't even know how to mangle their types anyway :).
498 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
500 // extern "C" functions can hold entities that must be mangled.
501 // As it stands, these functions still need to get expressed in the full
502 // external name. They have their class and type omitted, replaced with '9'.
504 // We would like to mangle all extern "C" functions using this additional
505 // component but this would break compatibility with MSVC's behavior.
506 // Instead, do this when we know that compatibility isn't important (in
507 // other words, when it is an overloaded extern "C" function).
508 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
511 mangleFunctionClass(FD);
513 mangleFunctionType(FT, FD);
519 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
520 // <type-encoding> ::= <storage-class> <variable-type>
521 // <storage-class> ::= 0 # private static member
522 // ::= 1 # protected static member
523 // ::= 2 # public static member
525 // ::= 4 # static local
527 // The first character in the encoding (after the name) is the storage class.
528 if (VD->isStaticDataMember()) {
529 // If it's a static member, it also encodes the access level.
530 switch (VD->getAccess()) {
532 case AS_private: Out << '0'; break;
533 case AS_protected: Out << '1'; break;
534 case AS_public: Out << '2'; break;
537 else if (!VD->isStaticLocal())
541 // Now mangle the type.
542 // <variable-type> ::= <type> <cvr-qualifiers>
543 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
544 // Pointers and references are odd. The type of 'int * const foo;' gets
545 // mangled as 'QAHA' instead of 'PAHB', for example.
546 SourceRange SR = VD->getSourceRange();
547 QualType Ty = VD->getType();
548 if (Ty->isPointerType() || Ty->isReferenceType() ||
549 Ty->isMemberPointerType()) {
550 mangleType(Ty, SR, QMM_Drop);
551 manglePointerExtQualifiers(
552 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
553 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
554 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
555 // Member pointers are suffixed with a back reference to the member
556 // pointer's class name.
557 mangleName(MPT->getClass()->getAsCXXRecordDecl());
559 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
560 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
561 // Global arrays are funny, too.
562 mangleDecayedArrayType(AT);
563 if (AT->getElementType()->isArrayType())
566 mangleQualifiers(Ty.getQualifiers(), false);
568 mangleType(Ty, SR, QMM_Drop);
569 mangleQualifiers(Ty.getQualifiers(), false);
573 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
574 const ValueDecl *VD) {
575 // <member-data-pointer> ::= <integer-literal>
576 // ::= $F <number> <number>
577 // ::= $G <number> <number> <number>
580 int64_t VBTableOffset;
581 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
583 FieldOffset = getASTContext().getFieldOffset(VD);
584 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
585 "cannot take address of bitfield");
586 FieldOffset /= getASTContext().getCharWidth();
590 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
591 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
593 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
600 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
601 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
602 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
603 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
608 mangleNumber(FieldOffset);
610 // The C++ standard doesn't allow base-to-derived member pointer conversions
611 // in template parameter contexts, so the vbptr offset of data member pointers
613 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
615 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
616 mangleNumber(VBTableOffset);
620 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
621 const CXXMethodDecl *MD) {
622 // <member-function-pointer> ::= $1? <name>
623 // ::= $H? <name> <number>
624 // ::= $I? <name> <number> <number>
625 // ::= $J? <name> <number> <number> <number>
627 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
631 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
632 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
633 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
634 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
637 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
639 uint64_t NVOffset = 0;
640 uint64_t VBTableOffset = 0;
641 uint64_t VBPtrOffset = 0;
643 Out << '$' << Code << '?';
644 if (MD->isVirtual()) {
645 MicrosoftVTableContext *VTContext =
646 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
647 MethodVFTableLocation ML =
648 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
649 mangleVirtualMemPtrThunk(MD, ML);
650 NVOffset = ML.VFPtrOffset.getQuantity();
651 VBTableOffset = ML.VBTableIndex * 4;
653 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
654 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
658 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
661 if (VBTableOffset == 0 &&
662 IM == MSInheritanceAttr::Keyword_virtual_inheritance)
663 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
665 // Null single inheritance member functions are encoded as a simple nullptr.
666 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
670 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
675 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
676 mangleNumber(static_cast<uint32_t>(NVOffset));
677 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
678 mangleNumber(VBPtrOffset);
679 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
680 mangleNumber(VBTableOffset);
683 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
684 const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
685 // Get the vftable offset.
686 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
687 getASTContext().getTargetInfo().getPointerWidth(0));
688 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
691 mangleName(MD->getParent());
693 mangleNumber(OffsetInVFTable);
695 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
698 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
699 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
701 // Always start with the unqualified name.
702 mangleUnqualifiedName(ND);
704 mangleNestedName(ND);
706 // Terminate the whole name with an '@'.
710 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
711 // <non-negative integer> ::= A@ # when Number == 0
712 // ::= <decimal digit> # when 1 <= Number <= 10
713 // ::= <hex digit>+ @ # when Number >= 10
715 // <number> ::= [?] <non-negative integer>
717 uint64_t Value = static_cast<uint64_t>(Number);
725 else if (Value >= 1 && Value <= 10)
728 // Numbers that are not encoded as decimal digits are represented as nibbles
729 // in the range of ASCII characters 'A' to 'P'.
730 // The number 0x123450 would be encoded as 'BCDEFA'
731 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
732 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
733 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
734 for (; Value != 0; Value >>= 4)
735 *I++ = 'A' + (Value & 0xf);
736 Out.write(I.base(), I - BufferRef.rbegin());
741 static const TemplateDecl *
742 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
743 // Check if we have a function template.
744 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
745 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
746 TemplateArgs = FD->getTemplateSpecializationArgs();
751 // Check if we have a class template.
752 if (const ClassTemplateSpecializationDecl *Spec =
753 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
754 TemplateArgs = &Spec->getTemplateArgs();
755 return Spec->getSpecializedTemplate();
758 // Check if we have a variable template.
759 if (const VarTemplateSpecializationDecl *Spec =
760 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
761 TemplateArgs = &Spec->getTemplateArgs();
762 return Spec->getSpecializedTemplate();
768 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
769 DeclarationName Name) {
770 // <unqualified-name> ::= <operator-name>
771 // ::= <ctor-dtor-name>
773 // ::= <template-name>
775 // Check if we have a template.
776 const TemplateArgumentList *TemplateArgs = nullptr;
777 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
778 // Function templates aren't considered for name back referencing. This
779 // makes sense since function templates aren't likely to occur multiple
780 // times in a symbol.
781 if (isa<FunctionTemplateDecl>(TD)) {
782 mangleTemplateInstantiationName(TD, *TemplateArgs);
787 // Here comes the tricky thing: if we need to mangle something like
788 // void foo(A::X<Y>, B::X<Y>),
789 // the X<Y> part is aliased. However, if you need to mangle
790 // void foo(A::X<A::Y>, A::X<B::Y>),
791 // the A::X<> part is not aliased.
792 // That said, from the mangler's perspective we have a structure like this:
793 // namespace[s] -> type[ -> template-parameters]
794 // but from the Clang perspective we have
795 // type [ -> template-parameters]
797 // What we do is we create a new mangler, mangle the same type (without
798 // a namespace suffix) to a string using the extra mangler and then use
799 // the mangled type name as a key to check the mangling of different types
802 llvm::SmallString<64> TemplateMangling;
803 llvm::raw_svector_ostream Stream(TemplateMangling);
804 MicrosoftCXXNameMangler Extra(Context, Stream);
805 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
807 mangleSourceName(TemplateMangling);
811 switch (Name.getNameKind()) {
812 case DeclarationName::Identifier: {
813 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
814 mangleSourceName(II->getName());
818 // Otherwise, an anonymous entity. We must have a declaration.
819 assert(ND && "mangling empty name without declaration");
821 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
822 if (NS->isAnonymousNamespace()) {
823 Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
828 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
829 // FIXME: Invented mangling for decomposition declarations:
831 // where X,Y,Z are the names of the bindings.
832 llvm::SmallString<128> Name("[");
833 for (auto *BD : DD->bindings()) {
836 Name += BD->getDeclName().getAsIdentifierInfo()->getName();
839 mangleSourceName(Name);
843 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
844 // We must have an anonymous union or struct declaration.
845 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
846 assert(RD && "expected variable decl to have a record type");
847 // Anonymous types with no tag or typedef get the name of their
848 // declarator mangled in. If they have no declarator, number them with
850 llvm::SmallString<64> Name("$S");
851 // Get a unique id for the anonymous struct.
852 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
853 mangleSourceName(Name.str());
857 // We must have an anonymous struct.
858 const TagDecl *TD = cast<TagDecl>(ND);
859 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
860 assert(TD->getDeclContext() == D->getDeclContext() &&
861 "Typedef should not be in another decl context!");
862 assert(D->getDeclName().getAsIdentifierInfo() &&
863 "Typedef was not named!");
864 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
868 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
869 if (Record->isLambda()) {
870 llvm::SmallString<10> Name("<lambda_");
872 Decl *LambdaContextDecl = Record->getLambdaContextDecl();
873 unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
875 const ParmVarDecl *Parm =
876 dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
877 const FunctionDecl *Func =
878 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
881 unsigned DefaultArgNo =
882 Func->getNumParams() - Parm->getFunctionScopeIndex();
883 Name += llvm::utostr(DefaultArgNo);
887 if (LambdaManglingNumber)
888 LambdaId = LambdaManglingNumber;
890 LambdaId = Context.getLambdaId(Record);
892 Name += llvm::utostr(LambdaId);
895 mangleSourceName(Name);
897 // If the context of a closure type is an initializer for a class
898 // member (static or nonstatic), it is encoded in a qualified name.
899 if (LambdaManglingNumber && LambdaContextDecl) {
900 if ((isa<VarDecl>(LambdaContextDecl) ||
901 isa<FieldDecl>(LambdaContextDecl)) &&
902 LambdaContextDecl->getDeclContext()->isRecord()) {
903 mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
910 llvm::SmallString<64> Name;
911 if (DeclaratorDecl *DD =
912 Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
913 // Anonymous types without a name for linkage purposes have their
914 // declarator mangled in if they have one.
915 Name += "<unnamed-type-";
916 Name += DD->getName();
917 } else if (TypedefNameDecl *TND =
918 Context.getASTContext().getTypedefNameForUnnamedTagDecl(
920 // Anonymous types without a name for linkage purposes have their
921 // associate typedef mangled in if they have one.
922 Name += "<unnamed-type-";
923 Name += TND->getName();
924 } else if (isa<EnumDecl>(TD) &&
925 cast<EnumDecl>(TD)->enumerator_begin() !=
926 cast<EnumDecl>(TD)->enumerator_end()) {
927 // Anonymous non-empty enums mangle in the first enumerator.
928 auto *ED = cast<EnumDecl>(TD);
929 Name += "<unnamed-enum-";
930 Name += ED->enumerator_begin()->getName();
932 // Otherwise, number the types using a $S prefix.
933 Name += "<unnamed-type-$S";
934 Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
937 mangleSourceName(Name.str());
941 case DeclarationName::ObjCZeroArgSelector:
942 case DeclarationName::ObjCOneArgSelector:
943 case DeclarationName::ObjCMultiArgSelector: {
944 // This is reachable only when constructing an outlined SEH finally
945 // block. Nothing depends on this mangling and it's used only with
946 // functinos with internal linkage.
947 llvm::SmallString<64> Name;
948 mangleSourceName(Name.str());
952 case DeclarationName::CXXConstructorName:
953 if (isStructorDecl(ND)) {
954 if (StructorType == Ctor_CopyingClosure) {
958 if (StructorType == Ctor_DefaultClosure) {
966 case DeclarationName::CXXDestructorName:
967 if (isStructorDecl(ND))
968 // If the named decl is the C++ destructor we're mangling,
969 // use the type we were given.
970 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
972 // Otherwise, use the base destructor name. This is relevant if a
973 // class with a destructor is declared within a destructor.
974 mangleCXXDtorType(Dtor_Base);
977 case DeclarationName::CXXConversionFunctionName:
978 // <operator-name> ::= ?B # (cast)
979 // The target type is encoded as the return type.
983 case DeclarationName::CXXOperatorName:
984 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
987 case DeclarationName::CXXLiteralOperatorName: {
989 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
993 case DeclarationName::CXXDeductionGuideName:
994 llvm_unreachable("Can't mangle a deduction guide name!");
996 case DeclarationName::CXXUsingDirective:
997 llvm_unreachable("Can't mangle a using directive name!");
1001 // <postfix> ::= <unqualified-name> [<postfix>]
1002 // ::= <substitution> [<postfix>]
1003 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
1004 const DeclContext *DC = getEffectiveDeclContext(ND);
1005 while (!DC->isTranslationUnit()) {
1006 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1008 if (Context.getNextDiscriminator(ND, Disc)) {
1015 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1017 [](StringRef Name, const unsigned Discriminator,
1018 const unsigned ParameterDiscriminator) -> std::string {
1020 llvm::raw_string_ostream Stream(Buffer);
1023 Stream << '_' << Discriminator;
1024 if (ParameterDiscriminator)
1025 Stream << '_' << ParameterDiscriminator;
1026 return Stream.str();
1029 unsigned Discriminator = BD->getBlockManglingNumber();
1031 Discriminator = Context.getBlockId(BD, /*Local=*/false);
1033 // Mangle the parameter position as a discriminator to deal with unnamed
1034 // parameters. Rather than mangling the unqualified parameter name,
1035 // always use the position to give a uniform mangling.
1036 unsigned ParameterDiscriminator = 0;
1037 if (const auto *MC = BD->getBlockManglingContextDecl())
1038 if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1039 if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1040 ParameterDiscriminator =
1041 F->getNumParams() - P->getFunctionScopeIndex();
1043 DC = getEffectiveDeclContext(BD);
1046 mangleSourceName(Discriminate("_block_invoke", Discriminator,
1047 ParameterDiscriminator));
1048 // If we have a block mangling context, encode that now. This allows us
1049 // to discriminate between named static data initializers in the same
1050 // scope. This is handled differently from parameters, which use
1051 // positions to discriminate between multiple instances.
1052 if (const auto *MC = BD->getBlockManglingContextDecl())
1053 if (!isa<ParmVarDecl>(MC))
1054 if (const auto *ND = dyn_cast<NamedDecl>(MC))
1055 mangleUnqualifiedName(ND);
1056 // MS ABI and Itanium manglings are in inverted scopes. In the case of a
1057 // RecordDecl, mangle the entire scope hierarchy at this point rather than
1058 // just the unqualified name to get the ordering correct.
1059 if (const auto *RD = dyn_cast<RecordDecl>(DC))
1065 // struct __block_literal *
1068 if (PointersAre64Bit)
1071 mangleArtificalTagType(TTK_Struct,
1072 Discriminate("__block_literal", Discriminator,
1073 ParameterDiscriminator));
1076 // If the effective context was a Record, we have fully mangled the
1077 // qualified name and do not need to continue.
1078 if (isa<RecordDecl>(DC))
1081 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1082 mangleObjCMethodName(Method);
1083 } else if (isa<NamedDecl>(DC)) {
1084 ND = cast<NamedDecl>(DC);
1085 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1089 mangleUnqualifiedName(ND);
1090 // Lambdas in default arguments conceptually belong to the function the
1091 // parameter corresponds to.
1092 if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1098 DC = DC->getParent();
1102 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1103 // Microsoft uses the names on the case labels for these dtor variants. Clang
1104 // uses the Itanium terminology internally. Everything in this ABI delegates
1105 // towards the base dtor.
1107 // <operator-name> ::= ?1 # destructor
1108 case Dtor_Base: Out << "?1"; return;
1109 // <operator-name> ::= ?_D # vbase destructor
1110 case Dtor_Complete: Out << "?_D"; return;
1111 // <operator-name> ::= ?_G # scalar deleting destructor
1112 case Dtor_Deleting: Out << "?_G"; return;
1113 // <operator-name> ::= ?_E # vector deleting destructor
1114 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
1117 llvm_unreachable("not expecting a COMDAT");
1119 llvm_unreachable("Unsupported dtor type?");
1122 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1123 SourceLocation Loc) {
1127 // <operator-name> ::= ?2 # new
1128 case OO_New: Out << "?2"; break;
1129 // <operator-name> ::= ?3 # delete
1130 case OO_Delete: Out << "?3"; break;
1131 // <operator-name> ::= ?4 # =
1132 case OO_Equal: Out << "?4"; break;
1133 // <operator-name> ::= ?5 # >>
1134 case OO_GreaterGreater: Out << "?5"; break;
1135 // <operator-name> ::= ?6 # <<
1136 case OO_LessLess: Out << "?6"; break;
1137 // <operator-name> ::= ?7 # !
1138 case OO_Exclaim: Out << "?7"; break;
1139 // <operator-name> ::= ?8 # ==
1140 case OO_EqualEqual: Out << "?8"; break;
1141 // <operator-name> ::= ?9 # !=
1142 case OO_ExclaimEqual: Out << "?9"; break;
1143 // <operator-name> ::= ?A # []
1144 case OO_Subscript: Out << "?A"; break;
1146 // <operator-name> ::= ?C # ->
1147 case OO_Arrow: Out << "?C"; break;
1148 // <operator-name> ::= ?D # *
1149 case OO_Star: Out << "?D"; break;
1150 // <operator-name> ::= ?E # ++
1151 case OO_PlusPlus: Out << "?E"; break;
1152 // <operator-name> ::= ?F # --
1153 case OO_MinusMinus: Out << "?F"; break;
1154 // <operator-name> ::= ?G # -
1155 case OO_Minus: Out << "?G"; break;
1156 // <operator-name> ::= ?H # +
1157 case OO_Plus: Out << "?H"; break;
1158 // <operator-name> ::= ?I # &
1159 case OO_Amp: Out << "?I"; break;
1160 // <operator-name> ::= ?J # ->*
1161 case OO_ArrowStar: Out << "?J"; break;
1162 // <operator-name> ::= ?K # /
1163 case OO_Slash: Out << "?K"; break;
1164 // <operator-name> ::= ?L # %
1165 case OO_Percent: Out << "?L"; break;
1166 // <operator-name> ::= ?M # <
1167 case OO_Less: Out << "?M"; break;
1168 // <operator-name> ::= ?N # <=
1169 case OO_LessEqual: Out << "?N"; break;
1170 // <operator-name> ::= ?O # >
1171 case OO_Greater: Out << "?O"; break;
1172 // <operator-name> ::= ?P # >=
1173 case OO_GreaterEqual: Out << "?P"; break;
1174 // <operator-name> ::= ?Q # ,
1175 case OO_Comma: Out << "?Q"; break;
1176 // <operator-name> ::= ?R # ()
1177 case OO_Call: Out << "?R"; break;
1178 // <operator-name> ::= ?S # ~
1179 case OO_Tilde: Out << "?S"; break;
1180 // <operator-name> ::= ?T # ^
1181 case OO_Caret: Out << "?T"; break;
1182 // <operator-name> ::= ?U # |
1183 case OO_Pipe: Out << "?U"; break;
1184 // <operator-name> ::= ?V # &&
1185 case OO_AmpAmp: Out << "?V"; break;
1186 // <operator-name> ::= ?W # ||
1187 case OO_PipePipe: Out << "?W"; break;
1188 // <operator-name> ::= ?X # *=
1189 case OO_StarEqual: Out << "?X"; break;
1190 // <operator-name> ::= ?Y # +=
1191 case OO_PlusEqual: Out << "?Y"; break;
1192 // <operator-name> ::= ?Z # -=
1193 case OO_MinusEqual: Out << "?Z"; break;
1194 // <operator-name> ::= ?_0 # /=
1195 case OO_SlashEqual: Out << "?_0"; break;
1196 // <operator-name> ::= ?_1 # %=
1197 case OO_PercentEqual: Out << "?_1"; break;
1198 // <operator-name> ::= ?_2 # >>=
1199 case OO_GreaterGreaterEqual: Out << "?_2"; break;
1200 // <operator-name> ::= ?_3 # <<=
1201 case OO_LessLessEqual: Out << "?_3"; break;
1202 // <operator-name> ::= ?_4 # &=
1203 case OO_AmpEqual: Out << "?_4"; break;
1204 // <operator-name> ::= ?_5 # |=
1205 case OO_PipeEqual: Out << "?_5"; break;
1206 // <operator-name> ::= ?_6 # ^=
1207 case OO_CaretEqual: Out << "?_6"; break;
1212 // ?_B # local static guard
1214 // ?_D # vbase destructor
1215 // ?_E # vector deleting destructor
1216 // ?_F # default constructor closure
1217 // ?_G # scalar deleting destructor
1218 // ?_H # vector constructor iterator
1219 // ?_I # vector destructor iterator
1220 // ?_J # vector vbase constructor iterator
1221 // ?_K # virtual displacement map
1222 // ?_L # eh vector constructor iterator
1223 // ?_M # eh vector destructor iterator
1224 // ?_N # eh vector vbase constructor iterator
1225 // ?_O # copy constructor closure
1226 // ?_P<name> # udt returning <name>
1228 // ?_R0 # RTTI Type Descriptor
1229 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1230 // ?_R2 # RTTI Base Class Array
1231 // ?_R3 # RTTI Class Hierarchy Descriptor
1232 // ?_R4 # RTTI Complete Object Locator
1233 // ?_S # local vftable
1234 // ?_T # local vftable constructor closure
1235 // <operator-name> ::= ?_U # new[]
1236 case OO_Array_New: Out << "?_U"; break;
1237 // <operator-name> ::= ?_V # delete[]
1238 case OO_Array_Delete: Out << "?_V"; break;
1239 // <operator-name> ::= ?__L # co_await
1240 case OO_Coawait: Out << "?__L"; break;
1242 case OO_Spaceship: {
1243 // FIXME: Once MS picks a mangling, use it.
1244 DiagnosticsEngine &Diags = Context.getDiags();
1245 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1246 "cannot mangle this three-way comparison operator yet");
1247 Diags.Report(Loc, DiagID);
1251 case OO_Conditional: {
1252 DiagnosticsEngine &Diags = Context.getDiags();
1253 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1254 "cannot mangle this conditional operator yet");
1255 Diags.Report(Loc, DiagID);
1260 case NUM_OVERLOADED_OPERATORS:
1261 llvm_unreachable("Not an overloaded operator");
1265 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1266 // <source name> ::= <identifier> @
1267 BackRefVec::iterator Found =
1268 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1269 if (Found == NameBackReferences.end()) {
1270 if (NameBackReferences.size() < 10)
1271 NameBackReferences.push_back(Name);
1274 Out << (Found - NameBackReferences.begin());
1278 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1279 Context.mangleObjCMethodName(MD, Out);
1282 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1283 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1284 // <template-name> ::= <unscoped-template-name> <template-args>
1285 // ::= <substitution>
1286 // Always start with the unqualified name.
1288 // Templates have their own context for back references.
1289 ArgBackRefMap OuterArgsContext;
1290 BackRefVec OuterTemplateContext;
1291 PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1292 NameBackReferences.swap(OuterTemplateContext);
1293 TypeBackReferences.swap(OuterArgsContext);
1294 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1296 mangleUnscopedTemplateName(TD);
1297 mangleTemplateArgs(TD, TemplateArgs);
1299 // Restore the previous back reference contexts.
1300 NameBackReferences.swap(OuterTemplateContext);
1301 TypeBackReferences.swap(OuterArgsContext);
1302 PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1306 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1307 // <unscoped-template-name> ::= ?$ <unqualified-name>
1309 mangleUnqualifiedName(TD);
1312 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1314 // <integer-literal> ::= $0 <number>
1316 // Make sure booleans are encoded as 0/1.
1317 if (IsBoolean && Value.getBoolValue())
1319 else if (Value.isSigned())
1320 mangleNumber(Value.getSExtValue());
1322 mangleNumber(Value.getZExtValue());
1325 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1326 // See if this is a constant expression.
1328 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1329 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1333 // Look through no-op casts like template parameter substitutions.
1334 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1336 const CXXUuidofExpr *UE = nullptr;
1337 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1338 if (UO->getOpcode() == UO_AddrOf)
1339 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1341 UE = dyn_cast<CXXUuidofExpr>(E);
1344 // If we had to peek through an address-of operator, treat this like we are
1345 // dealing with a pointer type. Otherwise, treat it like a const reference.
1347 // N.B. This matches up with the handling of TemplateArgument::Declaration
1348 // in mangleTemplateArg
1354 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1355 // const __s_GUID _GUID_{lower case UUID with underscores}
1356 StringRef Uuid = UE->getUuidStr();
1357 std::string Name = "_GUID_" + Uuid.lower();
1358 std::replace(Name.begin(), Name.end(), '-', '_');
1360 mangleSourceName(Name);
1361 // Terminate the whole name with an '@'.
1363 // It's a global variable.
1365 // It's a struct called __s_GUID.
1366 mangleArtificalTagType(TTK_Struct, "__s_GUID");
1372 // As bad as this diagnostic is, it's better than crashing.
1373 DiagnosticsEngine &Diags = Context.getDiags();
1374 unsigned DiagID = Diags.getCustomDiagID(
1375 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1376 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1377 << E->getSourceRange();
1380 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1381 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1382 // <template-args> ::= <template-arg>+
1383 const TemplateParameterList *TPL = TD->getTemplateParameters();
1384 assert(TPL->size() == TemplateArgs.size() &&
1385 "size mismatch between args and parms!");
1388 for (const TemplateArgument &TA : TemplateArgs.asArray())
1389 mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1392 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1393 const TemplateArgument &TA,
1394 const NamedDecl *Parm) {
1395 // <template-arg> ::= <type>
1396 // ::= <integer-literal>
1397 // ::= <member-data-pointer>
1398 // ::= <member-function-pointer>
1399 // ::= $E? <name> <type-encoding>
1400 // ::= $1? <name> <type-encoding>
1402 // ::= <template-args>
1404 switch (TA.getKind()) {
1405 case TemplateArgument::Null:
1406 llvm_unreachable("Can't mangle null template arguments!");
1407 case TemplateArgument::TemplateExpansion:
1408 llvm_unreachable("Can't mangle template expansion arguments!");
1409 case TemplateArgument::Type: {
1410 QualType T = TA.getAsType();
1411 mangleType(T, SourceRange(), QMM_Escape);
1414 case TemplateArgument::Declaration: {
1415 const NamedDecl *ND = TA.getAsDecl();
1416 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1417 mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1418 ->getMostRecentNonInjectedDecl(),
1419 cast<ValueDecl>(ND));
1420 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1421 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1422 if (MD && MD->isInstance()) {
1423 mangleMemberFunctionPointer(
1424 MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1428 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1431 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1435 case TemplateArgument::Integral:
1436 mangleIntegerLiteral(TA.getAsIntegral(),
1437 TA.getIntegralType()->isBooleanType());
1439 case TemplateArgument::NullPtr: {
1440 QualType T = TA.getNullPtrType();
1441 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1442 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1443 if (MPT->isMemberFunctionPointerType() &&
1444 !isa<FunctionTemplateDecl>(TD)) {
1445 mangleMemberFunctionPointer(RD, nullptr);
1448 if (MPT->isMemberDataPointer()) {
1449 if (!isa<FunctionTemplateDecl>(TD)) {
1450 mangleMemberDataPointer(RD, nullptr);
1453 // nullptr data pointers are always represented with a single field
1454 // which is initialized with either 0 or -1. Why -1? Well, we need to
1455 // distinguish the case where the data member is at offset zero in the
1457 // However, we are free to use 0 *if* we would use multiple fields for
1458 // non-nullptr member pointers.
1459 if (!RD->nullFieldOffsetIsZero()) {
1460 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1465 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1468 case TemplateArgument::Expression:
1469 mangleExpression(TA.getAsExpr());
1471 case TemplateArgument::Pack: {
1472 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1473 if (TemplateArgs.empty()) {
1474 if (isa<TemplateTypeParmDecl>(Parm) ||
1475 isa<TemplateTemplateParmDecl>(Parm))
1476 // MSVC 2015 changed the mangling for empty expanded template packs,
1477 // use the old mangling for link compatibility for old versions.
1478 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1479 LangOptions::MSVC2015)
1482 else if (isa<NonTypeTemplateParmDecl>(Parm))
1485 llvm_unreachable("unexpected template parameter decl!");
1487 for (const TemplateArgument &PA : TemplateArgs)
1488 mangleTemplateArg(TD, PA, Parm);
1492 case TemplateArgument::Template: {
1493 const NamedDecl *ND =
1494 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1495 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1497 } else if (isa<TypeAliasDecl>(ND)) {
1501 llvm_unreachable("unexpected template template NamedDecl!");
1508 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1509 llvm::SmallString<64> TemplateMangling;
1510 llvm::raw_svector_ostream Stream(TemplateMangling);
1511 MicrosoftCXXNameMangler Extra(Context, Stream);
1514 Extra.mangleSourceName("Protocol");
1515 Extra.mangleArtificalTagType(TTK_Struct, PD->getName());
1517 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1520 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1522 SourceRange Range) {
1523 llvm::SmallString<64> TemplateMangling;
1524 llvm::raw_svector_ostream Stream(TemplateMangling);
1525 MicrosoftCXXNameMangler Extra(Context, Stream);
1528 switch (Quals.getObjCLifetime()) {
1529 case Qualifiers::OCL_None:
1530 case Qualifiers::OCL_ExplicitNone:
1532 case Qualifiers::OCL_Autoreleasing:
1533 Extra.mangleSourceName("Autoreleasing");
1535 case Qualifiers::OCL_Strong:
1536 Extra.mangleSourceName("Strong");
1538 case Qualifiers::OCL_Weak:
1539 Extra.mangleSourceName("Weak");
1542 Extra.manglePointerCVQualifiers(Quals);
1543 Extra.manglePointerExtQualifiers(Quals, Type);
1544 Extra.mangleType(Type, Range);
1546 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1549 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1551 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1552 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1553 // 'I' means __restrict (32/64-bit).
1554 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1556 // <base-cvr-qualifiers> ::= A # near
1557 // ::= B # near const
1558 // ::= C # near volatile
1559 // ::= D # near const volatile
1560 // ::= E # far (16-bit)
1561 // ::= F # far const (16-bit)
1562 // ::= G # far volatile (16-bit)
1563 // ::= H # far const volatile (16-bit)
1564 // ::= I # huge (16-bit)
1565 // ::= J # huge const (16-bit)
1566 // ::= K # huge volatile (16-bit)
1567 // ::= L # huge const volatile (16-bit)
1568 // ::= M <basis> # based
1569 // ::= N <basis> # based const
1570 // ::= O <basis> # based volatile
1571 // ::= P <basis> # based const volatile
1572 // ::= Q # near member
1573 // ::= R # near const member
1574 // ::= S # near volatile member
1575 // ::= T # near const volatile member
1576 // ::= U # far member (16-bit)
1577 // ::= V # far const member (16-bit)
1578 // ::= W # far volatile member (16-bit)
1579 // ::= X # far const volatile member (16-bit)
1580 // ::= Y # huge member (16-bit)
1581 // ::= Z # huge const member (16-bit)
1582 // ::= 0 # huge volatile member (16-bit)
1583 // ::= 1 # huge const volatile member (16-bit)
1584 // ::= 2 <basis> # based member
1585 // ::= 3 <basis> # based const member
1586 // ::= 4 <basis> # based volatile member
1587 // ::= 5 <basis> # based const volatile member
1588 // ::= 6 # near function (pointers only)
1589 // ::= 7 # far function (pointers only)
1590 // ::= 8 # near method (pointers only)
1591 // ::= 9 # far method (pointers only)
1592 // ::= _A <basis> # based function (pointers only)
1593 // ::= _B <basis> # based function (far?) (pointers only)
1594 // ::= _C <basis> # based method (pointers only)
1595 // ::= _D <basis> # based method (far?) (pointers only)
1596 // ::= _E # block (Clang)
1597 // <basis> ::= 0 # __based(void)
1598 // ::= 1 # __based(segment)?
1599 // ::= 2 <name> # __based(name)
1602 // ::= 5 # not really based
1603 bool HasConst = Quals.hasConst(),
1604 HasVolatile = Quals.hasVolatile();
1607 if (HasConst && HasVolatile) {
1609 } else if (HasVolatile) {
1611 } else if (HasConst) {
1617 if (HasConst && HasVolatile) {
1619 } else if (HasVolatile) {
1621 } else if (HasConst) {
1628 // FIXME: For now, just drop all extension qualifiers on the floor.
1632 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1633 // <ref-qualifier> ::= G # lvalue reference
1634 // ::= H # rvalue-reference
1635 switch (RefQualifier) {
1649 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1650 QualType PointeeType) {
1651 if (PointersAre64Bit &&
1652 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1655 if (Quals.hasRestrict())
1658 if (Quals.hasUnaligned() ||
1659 (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1663 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1664 // <pointer-cv-qualifiers> ::= P # no qualifiers
1667 // ::= S # const volatile
1668 bool HasConst = Quals.hasConst(),
1669 HasVolatile = Quals.hasVolatile();
1671 if (HasConst && HasVolatile) {
1673 } else if (HasVolatile) {
1675 } else if (HasConst) {
1682 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1683 SourceRange Range) {
1684 // MSVC will backreference two canonically equivalent types that have slightly
1685 // different manglings when mangled alone.
1687 // Decayed types do not match up with non-decayed versions of the same type.
1690 // void (*x)(void) will not form a backreference with void x(void)
1692 if (const auto *DT = T->getAs<DecayedType>()) {
1693 QualType OriginalType = DT->getOriginalType();
1694 // All decayed ArrayTypes should be treated identically; as-if they were
1695 // a decayed IncompleteArrayType.
1696 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1697 OriginalType = getASTContext().getIncompleteArrayType(
1698 AT->getElementType(), AT->getSizeModifier(),
1699 AT->getIndexTypeCVRQualifiers());
1701 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1702 // If the original parameter was textually written as an array,
1703 // instead treat the decayed parameter like it's const.
1706 // int [] -> int * const
1707 if (OriginalType->isArrayType())
1710 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1713 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1715 if (Found == TypeBackReferences.end()) {
1716 size_t OutSizeBefore = Out.tell();
1718 mangleType(T, Range, QMM_Drop);
1720 // See if it's worth creating a back reference.
1721 // Only types longer than 1 character are considered
1722 // and only 10 back references slots are available:
1723 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1724 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1725 size_t Size = TypeBackReferences.size();
1726 TypeBackReferences[TypePtr] = Size;
1729 Out << Found->second;
1733 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1734 const PassObjectSizeAttr *POSA) {
1735 int Type = POSA->getType();
1737 auto Iter = PassObjectSizeArgs.insert(Type).first;
1738 auto *TypePtr = (const void *)&*Iter;
1739 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1741 if (Found == TypeBackReferences.end()) {
1742 mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1745 if (TypeBackReferences.size() < 10) {
1746 size_t Size = TypeBackReferences.size();
1747 TypeBackReferences[TypePtr] = Size;
1750 Out << Found->second;
1754 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1755 QualifierMangleMode QMM) {
1756 // Don't use the canonical types. MSVC includes things like 'const' on
1757 // pointer arguments to function pointers that canonicalization strips away.
1758 T = T.getDesugaredType(getASTContext());
1759 Qualifiers Quals = T.getLocalQualifiers();
1760 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1761 // If there were any Quals, getAsArrayType() pushed them onto the array
1763 if (QMM == QMM_Mangle)
1765 else if (QMM == QMM_Escape || QMM == QMM_Result)
1767 mangleArrayType(AT);
1771 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1772 T->isReferenceType() || T->isBlockPointerType();
1776 if (Quals.hasObjCLifetime())
1777 Quals = Quals.withoutObjCLifetime();
1780 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1782 mangleFunctionType(FT);
1785 mangleQualifiers(Quals, false);
1788 if (!IsPointer && Quals) {
1790 mangleQualifiers(Quals, false);
1794 // Presence of __unaligned qualifier shouldn't affect mangling here.
1795 Quals.removeUnaligned();
1796 if (Quals.hasObjCLifetime())
1797 Quals = Quals.withoutObjCLifetime();
1798 if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1800 mangleQualifiers(Quals, false);
1805 const Type *ty = T.getTypePtr();
1807 switch (ty->getTypeClass()) {
1808 #define ABSTRACT_TYPE(CLASS, PARENT)
1809 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1811 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1813 #define TYPE(CLASS, PARENT) \
1815 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1817 #include "clang/AST/TypeNodes.def"
1818 #undef ABSTRACT_TYPE
1819 #undef NON_CANONICAL_TYPE
1824 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1825 SourceRange Range) {
1826 // <type> ::= <builtin-type>
1827 // <builtin-type> ::= X # void
1828 // ::= C # signed char
1830 // ::= E # unsigned char
1832 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1834 // ::= I # unsigned int
1836 // ::= K # unsigned long
1840 // ::= O # long double (__float80 is mangled differently)
1841 // ::= _J # long long, __int64
1842 // ::= _K # unsigned long long, __int64
1843 // ::= _L # __int128
1844 // ::= _M # unsigned __int128
1846 // _O # <array in parameter>
1847 // ::= _T # __float80 (Intel)
1848 // ::= _S # char16_t
1849 // ::= _U # char32_t
1851 // ::= _Z # __float80 (Digital Mars)
1852 switch (T->getKind()) {
1853 case BuiltinType::Void:
1856 case BuiltinType::SChar:
1859 case BuiltinType::Char_U:
1860 case BuiltinType::Char_S:
1863 case BuiltinType::UChar:
1866 case BuiltinType::Short:
1869 case BuiltinType::UShort:
1872 case BuiltinType::Int:
1875 case BuiltinType::UInt:
1878 case BuiltinType::Long:
1881 case BuiltinType::ULong:
1884 case BuiltinType::Float:
1887 case BuiltinType::Double:
1890 // TODO: Determine size and mangle accordingly
1891 case BuiltinType::LongDouble:
1894 case BuiltinType::LongLong:
1897 case BuiltinType::ULongLong:
1900 case BuiltinType::Int128:
1903 case BuiltinType::UInt128:
1906 case BuiltinType::Bool:
1909 case BuiltinType::Char16:
1912 case BuiltinType::Char32:
1915 case BuiltinType::WChar_S:
1916 case BuiltinType::WChar_U:
1920 #define BUILTIN_TYPE(Id, SingletonId)
1921 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1922 case BuiltinType::Id:
1923 #include "clang/AST/BuiltinTypes.def"
1924 case BuiltinType::Dependent:
1925 llvm_unreachable("placeholder types shouldn't get to name mangling");
1927 case BuiltinType::ObjCId:
1928 mangleArtificalTagType(TTK_Struct, ".objc_object");
1930 case BuiltinType::ObjCClass:
1931 mangleArtificalTagType(TTK_Struct, ".objc_class");
1933 case BuiltinType::ObjCSel:
1934 mangleArtificalTagType(TTK_Struct, ".objc_selector");
1937 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1938 case BuiltinType::Id: \
1939 Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
1941 #include "clang/Basic/OpenCLImageTypes.def"
1942 case BuiltinType::OCLSampler:
1944 mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1946 case BuiltinType::OCLEvent:
1948 mangleArtificalTagType(TTK_Struct, "ocl_event");
1950 case BuiltinType::OCLClkEvent:
1952 mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1954 case BuiltinType::OCLQueue:
1956 mangleArtificalTagType(TTK_Struct, "ocl_queue");
1958 case BuiltinType::OCLReserveID:
1960 mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1963 case BuiltinType::NullPtr:
1967 case BuiltinType::Float16:
1968 mangleArtificalTagType(TTK_Struct, "_Float16", {"__clang"});
1971 case BuiltinType::Half:
1972 mangleArtificalTagType(TTK_Struct, "_Half", {"__clang"});
1975 case BuiltinType::ShortAccum:
1976 case BuiltinType::Accum:
1977 case BuiltinType::LongAccum:
1978 case BuiltinType::UShortAccum:
1979 case BuiltinType::UAccum:
1980 case BuiltinType::ULongAccum:
1981 case BuiltinType::ShortFract:
1982 case BuiltinType::Fract:
1983 case BuiltinType::LongFract:
1984 case BuiltinType::UShortFract:
1985 case BuiltinType::UFract:
1986 case BuiltinType::ULongFract:
1987 case BuiltinType::SatShortAccum:
1988 case BuiltinType::SatAccum:
1989 case BuiltinType::SatLongAccum:
1990 case BuiltinType::SatUShortAccum:
1991 case BuiltinType::SatUAccum:
1992 case BuiltinType::SatULongAccum:
1993 case BuiltinType::SatShortFract:
1994 case BuiltinType::SatFract:
1995 case BuiltinType::SatLongFract:
1996 case BuiltinType::SatUShortFract:
1997 case BuiltinType::SatUFract:
1998 case BuiltinType::SatULongFract:
1999 case BuiltinType::Char8:
2000 case BuiltinType::Float128: {
2001 DiagnosticsEngine &Diags = Context.getDiags();
2002 unsigned DiagID = Diags.getCustomDiagID(
2003 DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2004 Diags.Report(Range.getBegin(), DiagID)
2005 << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2011 // <type> ::= <function-type>
2012 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2014 // Structors only appear in decls, so at this point we know it's not a
2016 // FIXME: This may not be lambda-friendly.
2017 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
2019 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2022 mangleFunctionType(T);
2025 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2026 Qualifiers, SourceRange) {
2028 mangleFunctionType(T);
2031 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2032 const FunctionDecl *D,
2033 bool ForceThisQuals) {
2034 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2035 // <return-type> <argument-list> <throw-spec>
2036 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2039 if (D) Range = D->getSourceRange();
2041 bool IsInLambda = false;
2042 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2043 CallingConv CC = T->getCallConv();
2044 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2045 if (MD->getParent()->isLambda())
2047 if (MD->isInstance())
2048 HasThisQuals = true;
2049 if (isa<CXXDestructorDecl>(MD)) {
2051 } else if (isa<CXXConstructorDecl>(MD)) {
2053 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2054 StructorType == Ctor_DefaultClosure) &&
2057 CC = getASTContext().getDefaultCallingConvention(
2058 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2062 // If this is a C++ instance method, mangle the CVR qualifiers for the
2065 Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals());
2066 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2067 mangleRefQualifier(Proto->getRefQualifier());
2068 mangleQualifiers(Quals, /*IsMember=*/false);
2071 mangleCallingConvention(CC);
2073 // <return-type> ::= <type>
2074 // ::= @ # structors (they have no declared return type)
2076 if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2077 // The scalar deleting destructor takes an extra int argument which is not
2078 // reflected in the AST.
2079 if (StructorType == Dtor_Deleting) {
2080 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2083 // The vbase destructor returns void which is not reflected in the AST.
2084 if (StructorType == Dtor_Complete) {
2089 if (IsCtorClosure) {
2090 // Default constructor closure and copy constructor closure both return
2094 if (StructorType == Ctor_DefaultClosure) {
2095 // Default constructor closure always has no arguments.
2097 } else if (StructorType == Ctor_CopyingClosure) {
2098 // Copy constructor closure always takes an unqualified reference.
2099 mangleArgumentType(getASTContext().getLValueReferenceType(
2100 Proto->getParamType(0)
2101 ->getAs<LValueReferenceType>()
2103 /*SpelledAsLValue=*/true),
2107 llvm_unreachable("unexpected constructor closure!");
2114 QualType ResultType = T->getReturnType();
2115 if (const auto *AT =
2116 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2118 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2120 assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2121 "shouldn't need to mangle __auto_type!");
2122 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2124 } else if (IsInLambda) {
2127 if (ResultType->isVoidType())
2128 ResultType = ResultType.getUnqualifiedType();
2129 mangleType(ResultType, Range, QMM_Result);
2133 // <argument-list> ::= X # void
2135 // ::= <type>* Z # varargs
2137 // Function types without prototypes can arise when mangling a function type
2138 // within an overloadable function in C. We mangle these as the absence of
2139 // any parameter types (not even an empty parameter list).
2141 } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2144 // Happens for function pointer type arguments for example.
2145 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2146 mangleArgumentType(Proto->getParamType(I), Range);
2147 // Mangle each pass_object_size parameter as if it's a parameter of enum
2148 // type passed directly after the parameter with the pass_object_size
2149 // attribute. The aforementioned enum's name is __pass_object_size, and we
2150 // pretend it resides in a top-level namespace called __clang.
2152 // FIXME: Is there a defined extension notation for the MS ABI, or is it
2153 // necessary to just cross our fingers and hope this type+namespace
2154 // combination doesn't conflict with anything?
2156 if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2157 manglePassObjectSizeArg(P);
2159 // <builtin-type> ::= Z # ellipsis
2160 if (Proto->isVariadic())
2166 mangleThrowSpecification(Proto);
2169 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2170 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
2171 // # pointer. in 64-bit mode *all*
2172 // # 'this' pointers are 64-bit.
2173 // ::= <global-function>
2174 // <member-function> ::= A # private: near
2175 // ::= B # private: far
2176 // ::= C # private: static near
2177 // ::= D # private: static far
2178 // ::= E # private: virtual near
2179 // ::= F # private: virtual far
2180 // ::= I # protected: near
2181 // ::= J # protected: far
2182 // ::= K # protected: static near
2183 // ::= L # protected: static far
2184 // ::= M # protected: virtual near
2185 // ::= N # protected: virtual far
2186 // ::= Q # public: near
2187 // ::= R # public: far
2188 // ::= S # public: static near
2189 // ::= T # public: static far
2190 // ::= U # public: virtual near
2191 // ::= V # public: virtual far
2192 // <global-function> ::= Y # global near
2193 // ::= Z # global far
2194 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2195 bool IsVirtual = MD->isVirtual();
2196 // When mangling vbase destructor variants, ignore whether or not the
2197 // underlying destructor was defined to be virtual.
2198 if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2199 StructorType == Dtor_Complete) {
2202 switch (MD->getAccess()) {
2204 llvm_unreachable("Unsupported access specifier");
2233 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2234 // <calling-convention> ::= A # __cdecl
2235 // ::= B # __export __cdecl
2237 // ::= D # __export __pascal
2238 // ::= E # __thiscall
2239 // ::= F # __export __thiscall
2240 // ::= G # __stdcall
2241 // ::= H # __export __stdcall
2242 // ::= I # __fastcall
2243 // ::= J # __export __fastcall
2244 // ::= Q # __vectorcall
2245 // ::= w # __regcall
2246 // The 'export' calling conventions are from a bygone era
2247 // (*cough*Win16*cough*) when functions were declared for export with
2248 // that keyword. (It didn't actually export them, it just made them so
2249 // that they could be in a DLL and somebody from another module could call
2254 llvm_unreachable("Unsupported CC for mangling");
2257 case CC_C: Out << 'A'; break;
2258 case CC_X86Pascal: Out << 'C'; break;
2259 case CC_X86ThisCall: Out << 'E'; break;
2260 case CC_X86StdCall: Out << 'G'; break;
2261 case CC_X86FastCall: Out << 'I'; break;
2262 case CC_X86VectorCall: Out << 'Q'; break;
2263 case CC_Swift: Out << 'S'; break;
2264 case CC_PreserveMost: Out << 'U'; break;
2265 case CC_X86RegCall: Out << 'w'; break;
2268 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2269 mangleCallingConvention(T->getCallConv());
2271 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2272 const FunctionProtoType *FT) {
2273 // <throw-spec> ::= Z # throw(...) (default)
2274 // ::= @ # throw() or __declspec/__attribute__((nothrow))
2276 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2277 // all actually mangled as 'Z'. (They're ignored because their associated
2278 // functionality isn't implemented, and probably never will be.)
2282 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2283 Qualifiers, SourceRange Range) {
2284 // Probably should be mangled as a template instantiation; need to see what
2286 DiagnosticsEngine &Diags = Context.getDiags();
2287 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2288 "cannot mangle this unresolved dependent type yet");
2289 Diags.Report(Range.getBegin(), DiagID)
2293 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2294 // <union-type> ::= T <name>
2295 // <struct-type> ::= U <name>
2296 // <class-type> ::= V <name>
2297 // <enum-type> ::= W4 <name>
2298 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2315 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2317 mangleType(cast<TagType>(T)->getDecl());
2319 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2321 mangleType(cast<TagType>(T)->getDecl());
2323 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2324 mangleTagTypeKind(TD->getTagKind());
2328 // If you add a call to this, consider updating isArtificialTagType() too.
2329 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2330 TagTypeKind TK, StringRef UnqualifiedName,
2331 ArrayRef<StringRef> NestedNames) {
2332 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2333 mangleTagTypeKind(TK);
2335 // Always start with the unqualified name.
2336 mangleSourceName(UnqualifiedName);
2338 for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2339 mangleSourceName(*I);
2341 // Terminate the whole name with an '@'.
2345 // <type> ::= <array-type>
2346 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2347 // [Y <dimension-count> <dimension>+]
2348 // <element-type> # as global, E is never required
2349 // It's supposed to be the other way around, but for some strange reason, it
2350 // isn't. Today this behavior is retained for the sole purpose of backwards
2352 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2353 // This isn't a recursive mangling, so now we have to do it all in this
2355 manglePointerCVQualifiers(T->getElementType().getQualifiers());
2356 mangleType(T->getElementType(), SourceRange());
2358 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2360 llvm_unreachable("Should have been special cased");
2362 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2364 llvm_unreachable("Should have been special cased");
2366 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2367 Qualifiers, SourceRange) {
2368 llvm_unreachable("Should have been special cased");
2370 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2371 Qualifiers, SourceRange) {
2372 llvm_unreachable("Should have been special cased");
2374 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2375 QualType ElementTy(T, 0);
2376 SmallVector<llvm::APInt, 3> Dimensions;
2378 if (ElementTy->isConstantArrayType()) {
2379 const ConstantArrayType *CAT =
2380 getASTContext().getAsConstantArrayType(ElementTy);
2381 Dimensions.push_back(CAT->getSize());
2382 ElementTy = CAT->getElementType();
2383 } else if (ElementTy->isIncompleteArrayType()) {
2384 const IncompleteArrayType *IAT =
2385 getASTContext().getAsIncompleteArrayType(ElementTy);
2386 Dimensions.push_back(llvm::APInt(32, 0));
2387 ElementTy = IAT->getElementType();
2388 } else if (ElementTy->isVariableArrayType()) {
2389 const VariableArrayType *VAT =
2390 getASTContext().getAsVariableArrayType(ElementTy);
2391 Dimensions.push_back(llvm::APInt(32, 0));
2392 ElementTy = VAT->getElementType();
2393 } else if (ElementTy->isDependentSizedArrayType()) {
2394 // The dependent expression has to be folded into a constant (TODO).
2395 const DependentSizedArrayType *DSAT =
2396 getASTContext().getAsDependentSizedArrayType(ElementTy);
2397 DiagnosticsEngine &Diags = Context.getDiags();
2398 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2399 "cannot mangle this dependent-length array yet");
2400 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2401 << DSAT->getBracketsRange();
2408 // <dimension-count> ::= <number> # number of extra dimensions
2409 mangleNumber(Dimensions.size());
2410 for (const llvm::APInt &Dimension : Dimensions)
2411 mangleNumber(Dimension.getLimitedValue());
2412 mangleType(ElementTy, SourceRange(), QMM_Escape);
2415 // <type> ::= <pointer-to-member-type>
2416 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2417 // <class name> <type>
2418 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2419 Qualifiers Quals, SourceRange Range) {
2420 QualType PointeeType = T->getPointeeType();
2421 manglePointerCVQualifiers(Quals);
2422 manglePointerExtQualifiers(Quals, PointeeType);
2423 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2425 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2426 mangleFunctionType(FPT, nullptr, true);
2428 mangleQualifiers(PointeeType.getQualifiers(), true);
2429 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2430 mangleType(PointeeType, Range, QMM_Drop);
2434 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2435 Qualifiers, SourceRange Range) {
2436 DiagnosticsEngine &Diags = Context.getDiags();
2437 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2438 "cannot mangle this template type parameter type yet");
2439 Diags.Report(Range.getBegin(), DiagID)
2443 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2444 Qualifiers, SourceRange Range) {
2445 DiagnosticsEngine &Diags = Context.getDiags();
2446 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2447 "cannot mangle this substituted parameter pack yet");
2448 Diags.Report(Range.getBegin(), DiagID)
2452 // <type> ::= <pointer-type>
2453 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2454 // # the E is required for 64-bit non-static pointers
2455 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2456 SourceRange Range) {
2457 QualType PointeeType = T->getPointeeType();
2458 manglePointerCVQualifiers(Quals);
2459 manglePointerExtQualifiers(Quals, PointeeType);
2460 mangleType(PointeeType, Range);
2463 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2464 Qualifiers Quals, SourceRange Range) {
2465 QualType PointeeType = T->getPointeeType();
2466 switch (Quals.getObjCLifetime()) {
2467 case Qualifiers::OCL_None:
2468 case Qualifiers::OCL_ExplicitNone:
2470 case Qualifiers::OCL_Autoreleasing:
2471 case Qualifiers::OCL_Strong:
2472 case Qualifiers::OCL_Weak:
2473 return mangleObjCLifetime(PointeeType, Quals, Range);
2475 manglePointerCVQualifiers(Quals);
2476 manglePointerExtQualifiers(Quals, PointeeType);
2477 mangleType(PointeeType, Range);
2480 // <type> ::= <reference-type>
2481 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2482 // # the E is required for 64-bit non-static lvalue references
2483 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2484 Qualifiers Quals, SourceRange Range) {
2485 QualType PointeeType = T->getPointeeType();
2486 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2488 manglePointerExtQualifiers(Quals, PointeeType);
2489 mangleType(PointeeType, Range);
2492 // <type> ::= <r-value-reference-type>
2493 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2494 // # the E is required for 64-bit non-static rvalue references
2495 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2496 Qualifiers Quals, SourceRange Range) {
2497 QualType PointeeType = T->getPointeeType();
2498 assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2500 manglePointerExtQualifiers(Quals, PointeeType);
2501 mangleType(PointeeType, Range);
2504 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2505 SourceRange Range) {
2506 QualType ElementType = T->getElementType();
2508 llvm::SmallString<64> TemplateMangling;
2509 llvm::raw_svector_ostream Stream(TemplateMangling);
2510 MicrosoftCXXNameMangler Extra(Context, Stream);
2512 Extra.mangleSourceName("_Complex");
2513 Extra.mangleType(ElementType, Range, QMM_Escape);
2515 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2518 // Returns true for types that mangleArtificalTagType() gets called for with
2519 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2520 // mangling matters.
2521 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2523 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2524 const Type *ty = T.getTypePtr();
2525 switch (ty->getTypeClass()) {
2529 case Type::Vector: {
2530 // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2531 // but since mangleType(VectorType*) always calls mangleArtificalTagType()
2532 // just always return true (the other vector types are clang-only).
2538 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2539 SourceRange Range) {
2540 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2541 assert(ET && "vectors with non-builtin elements are unsupported");
2542 uint64_t Width = getASTContext().getTypeSize(T);
2543 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2544 // doesn't match the Intel types uses a custom mangling below.
2545 size_t OutSizeBefore = Out.tell();
2546 llvm::Triple::ArchType AT =
2547 getASTContext().getTargetInfo().getTriple().getArch();
2548 if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2549 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2550 mangleArtificalTagType(TTK_Union, "__m64");
2551 } else if (Width >= 128) {
2552 if (ET->getKind() == BuiltinType::Float)
2553 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width));
2554 else if (ET->getKind() == BuiltinType::LongLong)
2555 mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2556 else if (ET->getKind() == BuiltinType::Double)
2557 mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2561 bool IsBuiltin = Out.tell() != OutSizeBefore;
2563 // The MS ABI doesn't have a special mangling for vector types, so we define
2564 // our own mangling to handle uses of __vector_size__ on user-specified
2565 // types, and for extensions like __v4sf.
2567 llvm::SmallString<64> TemplateMangling;
2568 llvm::raw_svector_ostream Stream(TemplateMangling);
2569 MicrosoftCXXNameMangler Extra(Context, Stream);
2571 Extra.mangleSourceName("__vector");
2572 Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2573 Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2574 /*IsBoolean=*/false);
2576 mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"});
2580 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2581 Qualifiers Quals, SourceRange Range) {
2582 mangleType(static_cast<const VectorType *>(T), Quals, Range);
2585 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2586 Qualifiers, SourceRange Range) {
2587 DiagnosticsEngine &Diags = Context.getDiags();
2588 unsigned DiagID = Diags.getCustomDiagID(
2589 DiagnosticsEngine::Error,
2590 "cannot mangle this dependent-sized vector type yet");
2591 Diags.Report(Range.getBegin(), DiagID) << Range;
2594 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2595 Qualifiers, SourceRange Range) {
2596 DiagnosticsEngine &Diags = Context.getDiags();
2597 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2598 "cannot mangle this dependent-sized extended vector type yet");
2599 Diags.Report(Range.getBegin(), DiagID)
2603 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2604 Qualifiers, SourceRange Range) {
2605 DiagnosticsEngine &Diags = Context.getDiags();
2606 unsigned DiagID = Diags.getCustomDiagID(
2607 DiagnosticsEngine::Error,
2608 "cannot mangle this dependent address space type yet");
2609 Diags.Report(Range.getBegin(), DiagID) << Range;
2612 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2614 // ObjC interfaces are mangled as if they were structs with a name that is
2615 // not a valid C/C++ identifier
2616 mangleTagTypeKind(TTK_Struct);
2617 mangle(T->getDecl(), ".objc_cls_");
2620 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2621 SourceRange Range) {
2622 if (T->qual_empty())
2623 return mangleType(T->getBaseType(), Range, QMM_Drop);
2625 ArgBackRefMap OuterArgsContext;
2626 BackRefVec OuterTemplateContext;
2628 TypeBackReferences.swap(OuterArgsContext);
2629 NameBackReferences.swap(OuterTemplateContext);
2631 mangleTagTypeKind(TTK_Struct);
2635 mangleSourceName(".objc_object");
2636 else if (T->isObjCClass())
2637 mangleSourceName(".objc_class");
2639 mangleSourceName((".objc_cls_" + T->getInterface()->getName()).str());
2641 for (const auto &Q : T->quals())
2642 mangleObjCProtocol(Q);
2647 TypeBackReferences.swap(OuterArgsContext);
2648 NameBackReferences.swap(OuterTemplateContext);
2651 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2652 Qualifiers Quals, SourceRange Range) {
2653 QualType PointeeType = T->getPointeeType();
2654 manglePointerCVQualifiers(Quals);
2655 manglePointerExtQualifiers(Quals, PointeeType);
2659 mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2662 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2663 Qualifiers, SourceRange) {
2664 llvm_unreachable("Cannot mangle injected class name type.");
2667 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2668 Qualifiers, SourceRange Range) {
2669 DiagnosticsEngine &Diags = Context.getDiags();
2670 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2671 "cannot mangle this template specialization type yet");
2672 Diags.Report(Range.getBegin(), DiagID)
2676 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2677 SourceRange Range) {
2678 DiagnosticsEngine &Diags = Context.getDiags();
2679 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2680 "cannot mangle this dependent name type yet");
2681 Diags.Report(Range.getBegin(), DiagID)
2685 void MicrosoftCXXNameMangler::mangleType(
2686 const DependentTemplateSpecializationType *T, Qualifiers,
2687 SourceRange Range) {
2688 DiagnosticsEngine &Diags = Context.getDiags();
2689 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2690 "cannot mangle this dependent template specialization type yet");
2691 Diags.Report(Range.getBegin(), DiagID)
2695 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2696 SourceRange Range) {
2697 DiagnosticsEngine &Diags = Context.getDiags();
2698 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2699 "cannot mangle this pack expansion yet");
2700 Diags.Report(Range.getBegin(), DiagID)
2704 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2705 SourceRange Range) {
2706 DiagnosticsEngine &Diags = Context.getDiags();
2707 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2708 "cannot mangle this typeof(type) yet");
2709 Diags.Report(Range.getBegin(), DiagID)
2713 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2714 SourceRange Range) {
2715 DiagnosticsEngine &Diags = Context.getDiags();
2716 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2717 "cannot mangle this typeof(expression) yet");
2718 Diags.Report(Range.getBegin(), DiagID)
2722 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2723 SourceRange Range) {
2724 DiagnosticsEngine &Diags = Context.getDiags();
2725 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2726 "cannot mangle this decltype() yet");
2727 Diags.Report(Range.getBegin(), DiagID)
2731 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2732 Qualifiers, SourceRange Range) {
2733 DiagnosticsEngine &Diags = Context.getDiags();
2734 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2735 "cannot mangle this unary transform type yet");
2736 Diags.Report(Range.getBegin(), DiagID)
2740 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2741 SourceRange Range) {
2742 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2744 DiagnosticsEngine &Diags = Context.getDiags();
2745 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2746 "cannot mangle this 'auto' type yet");
2747 Diags.Report(Range.getBegin(), DiagID)
2751 void MicrosoftCXXNameMangler::mangleType(
2752 const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2753 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2755 DiagnosticsEngine &Diags = Context.getDiags();
2756 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2757 "cannot mangle this deduced class template specialization type yet");
2758 Diags.Report(Range.getBegin(), DiagID)
2762 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2763 SourceRange Range) {
2764 QualType ValueType = T->getValueType();
2766 llvm::SmallString<64> TemplateMangling;
2767 llvm::raw_svector_ostream Stream(TemplateMangling);
2768 MicrosoftCXXNameMangler Extra(Context, Stream);
2770 Extra.mangleSourceName("_Atomic");
2771 Extra.mangleType(ValueType, Range, QMM_Escape);
2773 mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2776 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2777 SourceRange Range) {
2778 DiagnosticsEngine &Diags = Context.getDiags();
2779 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2780 "cannot mangle this OpenCL pipe type yet");
2781 Diags.Report(Range.getBegin(), DiagID)
2785 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2787 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2788 "Invalid mangleName() call, argument is not a variable or function!");
2789 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2790 "Invalid mangleName() call on 'structor decl!");
2792 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2793 getASTContext().getSourceManager(),
2794 "Mangling declaration");
2796 msvc_hashing_ostream MHO(Out);
2797 MicrosoftCXXNameMangler Mangler(*this, MHO);
2798 return Mangler.mangle(D);
2801 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2802 // <virtual-adjustment>
2803 // <no-adjustment> ::= A # private near
2804 // ::= B # private far
2805 // ::= I # protected near
2806 // ::= J # protected far
2807 // ::= Q # public near
2808 // ::= R # public far
2809 // <static-adjustment> ::= G <static-offset> # private near
2810 // ::= H <static-offset> # private far
2811 // ::= O <static-offset> # protected near
2812 // ::= P <static-offset> # protected far
2813 // ::= W <static-offset> # public near
2814 // ::= X <static-offset> # public far
2815 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2816 // ::= $1 <virtual-shift> <static-offset> # private far
2817 // ::= $2 <virtual-shift> <static-offset> # protected near
2818 // ::= $3 <virtual-shift> <static-offset> # protected far
2819 // ::= $4 <virtual-shift> <static-offset> # public near
2820 // ::= $5 <virtual-shift> <static-offset> # public far
2821 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2822 // <vtordisp-shift> ::= <offset-to-vtordisp>
2823 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2824 // <offset-to-vtordisp>
2825 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2826 const ThisAdjustment &Adjustment,
2827 MicrosoftCXXNameMangler &Mangler,
2829 if (!Adjustment.Virtual.isEmpty()) {
2832 switch (MD->getAccess()) {
2834 llvm_unreachable("Unsupported access specifier");
2844 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2845 Out << 'R' << AccessSpec;
2846 Mangler.mangleNumber(
2847 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2848 Mangler.mangleNumber(
2849 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2850 Mangler.mangleNumber(
2851 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2852 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2855 Mangler.mangleNumber(
2856 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2857 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2859 } else if (Adjustment.NonVirtual != 0) {
2860 switch (MD->getAccess()) {
2862 llvm_unreachable("Unsupported access specifier");
2872 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2874 switch (MD->getAccess()) {
2876 llvm_unreachable("Unsupported access specifier");
2889 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
2890 const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
2892 msvc_hashing_ostream MHO(Out);
2893 MicrosoftCXXNameMangler Mangler(*this, MHO);
2894 Mangler.getStream() << '?';
2895 Mangler.mangleVirtualMemPtrThunk(MD, ML);
2898 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2899 const ThunkInfo &Thunk,
2901 msvc_hashing_ostream MHO(Out);
2902 MicrosoftCXXNameMangler Mangler(*this, MHO);
2903 Mangler.getStream() << '?';
2904 Mangler.mangleName(MD);
2905 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, MHO);
2906 if (!Thunk.Return.isEmpty())
2907 assert(Thunk.Method != nullptr &&
2908 "Thunk info should hold the overridee decl");
2910 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2911 Mangler.mangleFunctionType(
2912 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2915 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2916 const CXXDestructorDecl *DD, CXXDtorType Type,
2917 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2918 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2919 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2920 // mangling manually until we support both deleting dtor types.
2921 assert(Type == Dtor_Deleting);
2922 msvc_hashing_ostream MHO(Out);
2923 MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
2924 Mangler.getStream() << "??_E";
2925 Mangler.mangleName(DD->getParent());
2926 mangleThunkThisAdjustment(DD, Adjustment, Mangler, MHO);
2927 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2930 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2931 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2933 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2934 // <cvr-qualifiers> [<name>] @
2935 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2936 // is always '6' for vftables.
2937 msvc_hashing_ostream MHO(Out);
2938 MicrosoftCXXNameMangler Mangler(*this, MHO);
2939 if (Derived->hasAttr<DLLImportAttr>())
2940 Mangler.getStream() << "??_S";
2942 Mangler.getStream() << "??_7";
2943 Mangler.mangleName(Derived);
2944 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2945 for (const CXXRecordDecl *RD : BasePath)
2946 Mangler.mangleName(RD);
2947 Mangler.getStream() << '@';
2950 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2951 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2953 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2954 // <cvr-qualifiers> [<name>] @
2955 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2956 // is always '7' for vbtables.
2957 msvc_hashing_ostream MHO(Out);
2958 MicrosoftCXXNameMangler Mangler(*this, MHO);
2959 Mangler.getStream() << "??_8";
2960 Mangler.mangleName(Derived);
2961 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2962 for (const CXXRecordDecl *RD : BasePath)
2963 Mangler.mangleName(RD);
2964 Mangler.getStream() << '@';
2967 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2968 msvc_hashing_ostream MHO(Out);
2969 MicrosoftCXXNameMangler Mangler(*this, MHO);
2970 Mangler.getStream() << "??_R0";
2971 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2972 Mangler.getStream() << "@8";
2975 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2977 MicrosoftCXXNameMangler Mangler(*this, Out);
2978 Mangler.getStream() << '.';
2979 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2982 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2983 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2984 msvc_hashing_ostream MHO(Out);
2985 MicrosoftCXXNameMangler Mangler(*this, MHO);
2986 Mangler.getStream() << "??_K";
2987 Mangler.mangleName(SrcRD);
2988 Mangler.getStream() << "$C";
2989 Mangler.mangleName(DstRD);
2992 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
2995 uint32_t NumEntries,
2997 msvc_hashing_ostream MHO(Out);
2998 MicrosoftCXXNameMangler Mangler(*this, MHO);
2999 Mangler.getStream() << "_TI";
3001 Mangler.getStream() << 'C';
3003 Mangler.getStream() << 'V';
3005 Mangler.getStream() << 'U';
3006 Mangler.getStream() << NumEntries;
3007 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3010 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3011 QualType T, uint32_t NumEntries, raw_ostream &Out) {
3012 msvc_hashing_ostream MHO(Out);
3013 MicrosoftCXXNameMangler Mangler(*this, MHO);
3014 Mangler.getStream() << "_CTA";
3015 Mangler.getStream() << NumEntries;
3016 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3019 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3020 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3021 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3023 MicrosoftCXXNameMangler Mangler(*this, Out);
3024 Mangler.getStream() << "_CT";
3026 llvm::SmallString<64> RTTIMangling;
3028 llvm::raw_svector_ostream Stream(RTTIMangling);
3029 msvc_hashing_ostream MHO(Stream);
3030 mangleCXXRTTI(T, MHO);
3032 Mangler.getStream() << RTTIMangling;
3034 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
3035 // in fact, superfluous but I'm not sure the change was made consciously.
3036 llvm::SmallString<64> CopyCtorMangling;
3037 if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
3038 LangOptions::MSVC2015) &&
3040 llvm::raw_svector_ostream Stream(CopyCtorMangling);
3041 msvc_hashing_ostream MHO(Stream);
3042 mangleCXXCtor(CD, CT, MHO);
3044 Mangler.getStream() << CopyCtorMangling;
3046 Mangler.getStream() << Size;
3047 if (VBPtrOffset == -1) {
3049 Mangler.getStream() << NVOffset;
3052 Mangler.getStream() << NVOffset;
3053 Mangler.getStream() << VBPtrOffset;
3054 Mangler.getStream() << VBIndex;
3058 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3059 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3060 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3061 msvc_hashing_ostream MHO(Out);
3062 MicrosoftCXXNameMangler Mangler(*this, MHO);
3063 Mangler.getStream() << "??_R1";
3064 Mangler.mangleNumber(NVOffset);
3065 Mangler.mangleNumber(VBPtrOffset);
3066 Mangler.mangleNumber(VBTableOffset);
3067 Mangler.mangleNumber(Flags);
3068 Mangler.mangleName(Derived);
3069 Mangler.getStream() << "8";
3072 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3073 const CXXRecordDecl *Derived, raw_ostream &Out) {
3074 msvc_hashing_ostream MHO(Out);
3075 MicrosoftCXXNameMangler Mangler(*this, MHO);
3076 Mangler.getStream() << "??_R2";
3077 Mangler.mangleName(Derived);
3078 Mangler.getStream() << "8";
3081 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3082 const CXXRecordDecl *Derived, raw_ostream &Out) {
3083 msvc_hashing_ostream MHO(Out);
3084 MicrosoftCXXNameMangler Mangler(*this, MHO);
3085 Mangler.getStream() << "??_R3";
3086 Mangler.mangleName(Derived);
3087 Mangler.getStream() << "8";
3090 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3091 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3093 // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3094 // <cvr-qualifiers> [<name>] @
3095 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3096 // is always '6' for vftables.
3097 llvm::SmallString<64> VFTableMangling;
3098 llvm::raw_svector_ostream Stream(VFTableMangling);
3099 mangleCXXVFTable(Derived, BasePath, Stream);
3101 if (VFTableMangling.startswith("??@")) {
3102 assert(VFTableMangling.endswith("@"));
3103 Out << VFTableMangling << "??_R4@";
3107 assert(VFTableMangling.startswith("??_7") ||
3108 VFTableMangling.startswith("??_S"));
3110 Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3113 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3114 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3115 msvc_hashing_ostream MHO(Out);
3116 MicrosoftCXXNameMangler Mangler(*this, MHO);
3117 // The function body is in the same comdat as the function with the handler,
3118 // so the numbering here doesn't have to be the same across TUs.
3120 // <mangled-name> ::= ?filt$ <filter-number> @0
3121 Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3122 Mangler.mangleName(EnclosingDecl);
3125 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3126 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3127 msvc_hashing_ostream MHO(Out);
3128 MicrosoftCXXNameMangler Mangler(*this, MHO);
3129 // The function body is in the same comdat as the function with the handler,
3130 // so the numbering here doesn't have to be the same across TUs.
3132 // <mangled-name> ::= ?fin$ <filter-number> @0
3133 Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3134 Mangler.mangleName(EnclosingDecl);
3137 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3138 // This is just a made up unique string for the purposes of tbaa. undname
3139 // does *not* know how to demangle it.
3140 MicrosoftCXXNameMangler Mangler(*this, Out);
3141 Mangler.getStream() << '?';
3142 Mangler.mangleType(T, SourceRange());
3145 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3148 msvc_hashing_ostream MHO(Out);
3149 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3153 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3156 msvc_hashing_ostream MHO(Out);
3157 MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3161 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3162 const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3163 msvc_hashing_ostream MHO(Out);
3164 MicrosoftCXXNameMangler Mangler(*this, MHO);
3166 Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3167 Mangler.mangle(VD, "");
3170 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3171 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3172 msvc_hashing_ostream MHO(Out);
3173 MicrosoftCXXNameMangler Mangler(*this, MHO);
3175 Mangler.getStream() << "?$TSS" << GuardNum << '@';
3176 Mangler.mangleNestedName(VD);
3177 Mangler.getStream() << "@4HA";
3180 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3182 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3183 // ::= ?__J <postfix> @5 <scope-depth>
3184 // ::= ?$S <guard-num> @ <postfix> @4IA
3186 // The first mangling is what MSVC uses to guard static locals in inline
3187 // functions. It uses a different mangling in external functions to support
3188 // guarding more than 32 variables. MSVC rejects inline functions with more
3189 // than 32 static locals. We don't fully implement the second mangling
3190 // because those guards are not externally visible, and instead use LLVM's
3191 // default renaming when creating a new guard variable.
3192 msvc_hashing_ostream MHO(Out);
3193 MicrosoftCXXNameMangler Mangler(*this, MHO);
3195 bool Visible = VD->isExternallyVisible();
3197 Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3199 Mangler.getStream() << "?$S1@";
3201 unsigned ScopeDepth = 0;
3202 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3203 // If we do not have a discriminator and are emitting a guard variable for
3204 // use at global scope, then mangling the nested name will not be enough to
3205 // remove ambiguities.
3206 Mangler.mangle(VD, "");
3208 Mangler.mangleNestedName(VD);
3209 Mangler.getStream() << (Visible ? "@5" : "@4IA");
3211 Mangler.mangleNumber(ScopeDepth);
3214 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3217 msvc_hashing_ostream MHO(Out);
3218 MicrosoftCXXNameMangler Mangler(*this, MHO);
3219 Mangler.getStream() << "??__" << CharCode;
3220 Mangler.mangleName(D);
3221 if (D->isStaticDataMember()) {
3222 Mangler.mangleVariableEncoding(D);
3223 Mangler.getStream() << '@';
3225 // This is the function class mangling. These stubs are global, non-variadic,
3226 // cdecl functions that return void and take no args.
3227 Mangler.getStream() << "YAXXZ";
3230 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3232 // <initializer-name> ::= ?__E <name> YAXXZ
3233 mangleInitFiniStub(D, 'E', Out);
3237 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3239 // <destructor-name> ::= ?__F <name> YAXXZ
3240 mangleInitFiniStub(D, 'F', Out);
3243 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3245 // <char-type> ::= 0 # char, char16_t, char32_t
3246 // # (little endian char data in mangling)
3247 // ::= 1 # wchar_t (big endian char data in mangling)
3249 // <literal-length> ::= <non-negative integer> # the length of the literal
3251 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
3252 // # trailing null bytes
3254 // <encoded-string> ::= <simple character> # uninteresting character
3255 // ::= '?$' <hex digit> <hex digit> # these two nibbles
3256 // # encode the byte for the
3258 // ::= '?' [a-z] # \xe1 - \xfa
3259 // ::= '?' [A-Z] # \xc1 - \xda
3260 // ::= '?' [0-9] # [,/\:. \n\t'-]
3262 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3263 // <encoded-string> '@'
3264 MicrosoftCXXNameMangler Mangler(*this, Out);
3265 Mangler.getStream() << "??_C@_";
3267 // The actual string length might be different from that of the string literal
3269 // char foo[3] = "foobar";
3270 // char bar[42] = "foobar";
3271 // Where it is truncated or zero-padded to fit the array. This is the length
3272 // used for mangling, and any trailing null-bytes also need to be mangled.
3273 unsigned StringLength = getASTContext()
3274 .getAsConstantArrayType(SL->getType())
3277 unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3279 // <char-type>: The "kind" of string literal is encoded into the mangled name.
3281 Mangler.getStream() << '1';
3283 Mangler.getStream() << '0';
3285 // <literal-length>: The next part of the mangled name consists of the length
3286 // of the string in bytes.
3287 Mangler.mangleNumber(StringByteLength);
3289 auto GetLittleEndianByte = [&SL](unsigned Index) {
3290 unsigned CharByteWidth = SL->getCharByteWidth();
3291 if (Index / CharByteWidth >= SL->getLength())
3292 return static_cast<char>(0);
3293 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3294 unsigned OffsetInCodeUnit = Index % CharByteWidth;
3295 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3298 auto GetBigEndianByte = [&SL](unsigned Index) {
3299 unsigned CharByteWidth = SL->getCharByteWidth();
3300 if (Index / CharByteWidth >= SL->getLength())
3301 return static_cast<char>(0);
3302 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3303 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3304 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3307 // CRC all the bytes of the StringLiteral.
3309 for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3310 JC.update(GetLittleEndianByte(I));
3312 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3314 Mangler.mangleNumber(JC.getCRC());
3316 // <encoded-string>: The mangled name also contains the first 32 bytes
3317 // (including null-terminator bytes) of the encoded StringLiteral.
3318 // Each character is encoded by splitting them into bytes and then encoding
3319 // the constituent bytes.
3320 auto MangleByte = [&Mangler](char Byte) {
3321 // There are five different manglings for characters:
3322 // - [a-zA-Z0-9_$]: A one-to-one mapping.
3323 // - ?[a-z]: The range from \xe1 to \xfa.
3324 // - ?[A-Z]: The range from \xc1 to \xda.
3325 // - ?[0-9]: The set of [,/\:. \n\t'-].
3326 // - ?$XX: A fallback which maps nibbles.
3327 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3328 Mangler.getStream() << Byte;
3329 } else if (isLetter(Byte & 0x7f)) {
3330 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3332 const char SpecialChars[] = {',', '/', '\\', ':', '.',
3333 ' ', '\n', '\t', '\'', '-'};
3335 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
3336 if (Pos != std::end(SpecialChars)) {
3337 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3339 Mangler.getStream() << "?$";
3340 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3341 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3346 // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3347 unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3348 unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3349 for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3351 MangleByte(GetBigEndianByte(I));
3353 MangleByte(GetLittleEndianByte(I));
3356 Mangler.getStream() << '@';
3359 MicrosoftMangleContext *
3360 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3361 return new MicrosoftMangleContextImpl(Context, Diags);