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/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MathExtras.h"
32 using namespace clang;
36 /// \brief Retrieve the declaration context that should be used when mangling
37 /// the given declaration.
38 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
39 // The ABI assumes that lambda closure types that occur within
40 // default arguments live in the context of the function. However, due to
41 // the way in which Clang parses and creates function declarations, this is
42 // not the case: the lambda closure type ends up living in the context
43 // where the function itself resides, because the function declaration itself
44 // had not yet been created. Fix the context here.
45 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
47 if (ParmVarDecl *ContextParam =
48 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
49 return ContextParam->getDeclContext();
52 // Perform the same check for block literals.
53 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
54 if (ParmVarDecl *ContextParam =
55 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
56 return ContextParam->getDeclContext();
59 const DeclContext *DC = D->getDeclContext();
60 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
61 return getEffectiveDeclContext(CD);
66 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
67 return getEffectiveDeclContext(cast<Decl>(DC));
70 static const FunctionDecl *getStructor(const NamedDecl *ND) {
71 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
72 return FTD->getTemplatedDecl();
74 const auto *FD = cast<FunctionDecl>(ND);
75 if (const auto *FTD = FD->getPrimaryTemplate())
76 return FTD->getTemplatedDecl();
81 static bool isLambda(const NamedDecl *ND) {
82 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
86 return Record->isLambda();
89 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
90 /// Microsoft Visual C++ ABI.
91 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
92 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
93 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
94 llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
95 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
96 llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
97 llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
100 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
101 : MicrosoftMangleContext(Context, Diags) {}
102 bool shouldMangleCXXName(const NamedDecl *D) override;
103 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
104 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
105 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
106 raw_ostream &) override;
107 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
108 raw_ostream &) override;
109 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
110 const ThisAdjustment &ThisAdjustment,
111 raw_ostream &) override;
112 void mangleCXXVFTable(const CXXRecordDecl *Derived,
113 ArrayRef<const CXXRecordDecl *> BasePath,
114 raw_ostream &Out) override;
115 void mangleCXXVBTable(const CXXRecordDecl *Derived,
116 ArrayRef<const CXXRecordDecl *> BasePath,
117 raw_ostream &Out) override;
118 void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
119 const CXXRecordDecl *DstRD,
120 raw_ostream &Out) override;
121 void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
122 uint32_t NumEntries, raw_ostream &Out) override;
123 void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
124 raw_ostream &Out) override;
125 void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
126 CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
127 int32_t VBPtrOffset, uint32_t VBIndex,
128 raw_ostream &Out) override;
129 void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
130 raw_ostream &Out) override;
131 void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
132 void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
133 void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
134 uint32_t NVOffset, int32_t VBPtrOffset,
135 uint32_t VBTableOffset, uint32_t Flags,
136 raw_ostream &Out) override;
137 void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
138 raw_ostream &Out) override;
139 void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
140 raw_ostream &Out) override;
142 mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
143 ArrayRef<const CXXRecordDecl *> BasePath,
144 raw_ostream &Out) override;
145 void mangleTypeName(QualType T, raw_ostream &) override;
146 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
147 raw_ostream &) override;
148 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
149 raw_ostream &) override;
150 void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
151 raw_ostream &) override;
152 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
153 void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
154 raw_ostream &Out) override;
155 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
156 void mangleDynamicAtExitDestructor(const VarDecl *D,
157 raw_ostream &Out) override;
158 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
159 raw_ostream &Out) override;
160 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
161 raw_ostream &Out) override;
162 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
163 void mangleCXXVTableBitSet(const CXXRecordDecl *RD,
164 raw_ostream &Out) override;
165 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
166 // Lambda closure types are already numbered.
170 const DeclContext *DC = getEffectiveDeclContext(ND);
171 if (!DC->isFunctionOrMethod())
174 // Use the canonical number for externally visible decls.
175 if (ND->isExternallyVisible()) {
176 disc = getASTContext().getManglingNumber(ND);
180 // Anonymous tags are already numbered.
181 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
182 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
186 // Make up a reasonable number for internal decls.
187 unsigned &discriminator = Uniquifier[ND];
189 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
190 disc = discriminator + 1;
194 unsigned getLambdaId(const CXXRecordDecl *RD) {
195 assert(RD->isLambda() && "RD must be a lambda!");
196 assert(!RD->isExternallyVisible() && "RD must not be visible!");
197 assert(RD->getLambdaManglingNumber() == 0 &&
198 "RD must not have a mangling number!");
199 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
200 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
201 return Result.first->second;
205 void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
208 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
209 /// Microsoft Visual C++ ABI.
210 class MicrosoftCXXNameMangler {
211 MicrosoftMangleContextImpl &Context;
214 /// The "structor" is the top-level declaration being mangled, if
215 /// that's not a template specialization; otherwise it's the pattern
216 /// for that specialization.
217 const NamedDecl *Structor;
218 unsigned StructorType;
220 typedef llvm::SmallVector<std::string, 10> BackRefVec;
221 BackRefVec NameBackReferences;
223 typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
224 ArgBackRefMap TypeBackReferences;
226 ASTContext &getASTContext() const { return Context.getASTContext(); }
228 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
229 // this check into mangleQualifiers().
230 const bool PointersAre64Bit;
233 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
235 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
236 : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
237 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
240 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
241 const CXXConstructorDecl *D, CXXCtorType Type)
242 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
243 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
246 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
247 const CXXDestructorDecl *D, CXXDtorType Type)
248 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
249 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
252 raw_ostream &getStream() const { return Out; }
254 void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
255 void mangleName(const NamedDecl *ND);
256 void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
257 void mangleVariableEncoding(const VarDecl *VD);
258 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
259 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
260 const CXXMethodDecl *MD);
261 void mangleVirtualMemPtrThunk(
262 const CXXMethodDecl *MD,
263 const MicrosoftVTableContext::MethodVFTableLocation &ML);
264 void mangleNumber(int64_t Number);
265 void mangleType(QualType T, SourceRange Range,
266 QualifierMangleMode QMM = QMM_Mangle);
267 void mangleFunctionType(const FunctionType *T,
268 const FunctionDecl *D = nullptr,
269 bool ForceThisQuals = false);
270 void mangleNestedName(const NamedDecl *ND);
273 void mangleUnqualifiedName(const NamedDecl *ND) {
274 mangleUnqualifiedName(ND, ND->getDeclName());
276 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
277 void mangleSourceName(StringRef Name);
278 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
279 void mangleCXXDtorType(CXXDtorType T);
280 void mangleQualifiers(Qualifiers Quals, bool IsMember);
281 void mangleRefQualifier(RefQualifierKind RefQualifier);
282 void manglePointerCVQualifiers(Qualifiers Quals);
283 void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
285 void mangleUnscopedTemplateName(const TemplateDecl *ND);
287 mangleTemplateInstantiationName(const TemplateDecl *TD,
288 const TemplateArgumentList &TemplateArgs);
289 void mangleObjCMethodName(const ObjCMethodDecl *MD);
291 void mangleArgumentType(QualType T, SourceRange Range);
293 // Declare manglers for every type class.
294 #define ABSTRACT_TYPE(CLASS, PARENT)
295 #define NON_CANONICAL_TYPE(CLASS, PARENT)
296 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
299 #include "clang/AST/TypeNodes.def"
301 #undef NON_CANONICAL_TYPE
304 void mangleType(const TagDecl *TD);
305 void mangleDecayedArrayType(const ArrayType *T);
306 void mangleArrayType(const ArrayType *T);
307 void mangleFunctionClass(const FunctionDecl *FD);
308 void mangleCallingConvention(CallingConv CC);
309 void mangleCallingConvention(const FunctionType *T);
310 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
311 void mangleExpression(const Expr *E);
312 void mangleThrowSpecification(const FunctionProtoType *T);
314 void mangleTemplateArgs(const TemplateDecl *TD,
315 const TemplateArgumentList &TemplateArgs);
316 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
317 const NamedDecl *Parm);
321 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
322 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
323 LanguageLinkage L = FD->getLanguageLinkage();
324 // Overloadable functions need mangling.
325 if (FD->hasAttr<OverloadableAttr>())
328 // The ABI expects that we would never mangle "typical" user-defined entry
329 // points regardless of visibility or freestanding-ness.
331 // N.B. This is distinct from asking about "main". "main" has a lot of
332 // special rules associated with it in the standard while these
333 // user-defined entry points are outside of the purview of the standard.
334 // For example, there can be only one definition for "main" in a standards
335 // compliant program; however nothing forbids the existence of wmain and
336 // WinMain in the same translation unit.
337 if (FD->isMSVCRTEntryPoint())
340 // C++ functions and those whose names are not a simple identifier need
342 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
345 // C functions are not mangled.
346 if (L == CLanguageLinkage)
350 // Otherwise, no mangling is done outside C++ mode.
351 if (!getASTContext().getLangOpts().CPlusPlus)
354 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
355 // C variables are not mangled.
359 // Variables at global scope with non-internal linkage are not mangled.
360 const DeclContext *DC = getEffectiveDeclContext(D);
361 // Check for extern variable declared locally.
362 if (DC->isFunctionOrMethod() && D->hasLinkage())
363 while (!DC->isNamespace() && !DC->isTranslationUnit())
364 DC = getEffectiveParentContext(DC);
366 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
367 !isa<VarTemplateSpecializationDecl>(D))
375 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
379 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
380 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
381 // Therefore it's really important that we don't decorate the
382 // name with leading underscores or leading/trailing at signs. So, by
383 // default, we emit an asm marker at the start so we get the name right.
384 // Callers can override this with a custom prefix.
386 // <mangled-name> ::= ? <name> <type-encoding>
389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
390 mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
391 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
392 mangleVariableEncoding(VD);
394 // TODO: Fields? Can MSVC even mangle them?
395 // Issue a diagnostic for now.
396 DiagnosticsEngine &Diags = Context.getDiags();
397 unsigned DiagID = Diags.getCustomDiagID(
398 DiagnosticsEngine::Error, "cannot mangle this declaration yet");
399 Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
403 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
405 // <type-encoding> ::= <function-class> <function-type>
407 // Since MSVC operates on the type as written and not the canonical type, it
408 // actually matters which decl we have here. MSVC appears to choose the
409 // first, since it is most likely to be the declaration in a header file.
410 FD = FD->getFirstDecl();
412 // We should never ever see a FunctionNoProtoType at this point.
413 // We don't even know how to mangle their types anyway :).
414 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
416 // extern "C" functions can hold entities that must be mangled.
417 // As it stands, these functions still need to get expressed in the full
418 // external name. They have their class and type omitted, replaced with '9'.
420 // We would like to mangle all extern "C" functions using this additional
421 // component but this would break compatibility with MSVC's behavior.
422 // Instead, do this when we know that compatibility isn't important (in
423 // other words, when it is an overloaded extern "C" funciton).
424 if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
427 mangleFunctionClass(FD);
429 mangleFunctionType(FT, FD);
435 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
436 // <type-encoding> ::= <storage-class> <variable-type>
437 // <storage-class> ::= 0 # private static member
438 // ::= 1 # protected static member
439 // ::= 2 # public static member
441 // ::= 4 # static local
443 // The first character in the encoding (after the name) is the storage class.
444 if (VD->isStaticDataMember()) {
445 // If it's a static member, it also encodes the access level.
446 switch (VD->getAccess()) {
448 case AS_private: Out << '0'; break;
449 case AS_protected: Out << '1'; break;
450 case AS_public: Out << '2'; break;
453 else if (!VD->isStaticLocal())
457 // Now mangle the type.
458 // <variable-type> ::= <type> <cvr-qualifiers>
459 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
460 // Pointers and references are odd. The type of 'int * const foo;' gets
461 // mangled as 'QAHA' instead of 'PAHB', for example.
462 SourceRange SR = VD->getSourceRange();
463 QualType Ty = VD->getType();
464 if (Ty->isPointerType() || Ty->isReferenceType() ||
465 Ty->isMemberPointerType()) {
466 mangleType(Ty, SR, QMM_Drop);
467 manglePointerExtQualifiers(
468 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
469 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
470 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
471 // Member pointers are suffixed with a back reference to the member
472 // pointer's class name.
473 mangleName(MPT->getClass()->getAsCXXRecordDecl());
475 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
476 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
477 // Global arrays are funny, too.
478 mangleDecayedArrayType(AT);
479 if (AT->getElementType()->isArrayType())
482 mangleQualifiers(Ty.getQualifiers(), false);
484 mangleType(Ty, SR, QMM_Drop);
485 mangleQualifiers(Ty.getQualifiers(), false);
489 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
490 const ValueDecl *VD) {
491 // <member-data-pointer> ::= <integer-literal>
492 // ::= $F <number> <number>
493 // ::= $G <number> <number> <number>
496 int64_t VBTableOffset;
497 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
499 FieldOffset = getASTContext().getFieldOffset(VD);
500 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
501 "cannot take address of bitfield");
502 FieldOffset /= getASTContext().getCharWidth();
506 if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
507 FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
509 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
516 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
517 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
518 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
519 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
524 mangleNumber(FieldOffset);
526 // The C++ standard doesn't allow base-to-derived member pointer conversions
527 // in template parameter contexts, so the vbptr offset of data member pointers
529 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
531 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
532 mangleNumber(VBTableOffset);
536 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
537 const CXXMethodDecl *MD) {
538 // <member-function-pointer> ::= $1? <name>
539 // ::= $H? <name> <number>
540 // ::= $I? <name> <number> <number>
541 // ::= $J? <name> <number> <number> <number>
543 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
547 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
548 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
549 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
550 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
553 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
555 uint64_t NVOffset = 0;
556 uint64_t VBTableOffset = 0;
557 uint64_t VBPtrOffset = 0;
559 Out << '$' << Code << '?';
560 if (MD->isVirtual()) {
561 MicrosoftVTableContext *VTContext =
562 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
563 const MicrosoftVTableContext::MethodVFTableLocation &ML =
564 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
565 mangleVirtualMemPtrThunk(MD, ML);
566 NVOffset = ML.VFPtrOffset.getQuantity();
567 VBTableOffset = ML.VBTableIndex * 4;
569 const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
570 VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
574 mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
577 if (VBTableOffset == 0 &&
578 IM == MSInheritanceAttr::Keyword_virtual_inheritance)
579 NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
581 // Null single inheritance member functions are encoded as a simple nullptr.
582 if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
586 if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
591 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
592 mangleNumber(static_cast<uint32_t>(NVOffset));
593 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
594 mangleNumber(VBPtrOffset);
595 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
596 mangleNumber(VBTableOffset);
599 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
600 const CXXMethodDecl *MD,
601 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
602 // Get the vftable offset.
603 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
604 getASTContext().getTargetInfo().getPointerWidth(0));
605 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
608 mangleName(MD->getParent());
610 mangleNumber(OffsetInVFTable);
612 mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
615 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
616 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
618 // Always start with the unqualified name.
619 mangleUnqualifiedName(ND);
621 mangleNestedName(ND);
623 // Terminate the whole name with an '@'.
627 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
628 // <non-negative integer> ::= A@ # when Number == 0
629 // ::= <decimal digit> # when 1 <= Number <= 10
630 // ::= <hex digit>+ @ # when Number >= 10
632 // <number> ::= [?] <non-negative integer>
634 uint64_t Value = static_cast<uint64_t>(Number);
642 else if (Value >= 1 && Value <= 10)
645 // Numbers that are not encoded as decimal digits are represented as nibbles
646 // in the range of ASCII characters 'A' to 'P'.
647 // The number 0x123450 would be encoded as 'BCDEFA'
648 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
649 MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
650 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
651 for (; Value != 0; Value >>= 4)
652 *I++ = 'A' + (Value & 0xf);
653 Out.write(I.base(), I - BufferRef.rbegin());
658 static const TemplateDecl *
659 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
660 // Check if we have a function template.
661 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
662 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
663 TemplateArgs = FD->getTemplateSpecializationArgs();
668 // Check if we have a class template.
669 if (const ClassTemplateSpecializationDecl *Spec =
670 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
671 TemplateArgs = &Spec->getTemplateArgs();
672 return Spec->getSpecializedTemplate();
675 // Check if we have a variable template.
676 if (const VarTemplateSpecializationDecl *Spec =
677 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
678 TemplateArgs = &Spec->getTemplateArgs();
679 return Spec->getSpecializedTemplate();
685 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
686 DeclarationName Name) {
687 // <unqualified-name> ::= <operator-name>
688 // ::= <ctor-dtor-name>
690 // ::= <template-name>
692 // Check if we have a template.
693 const TemplateArgumentList *TemplateArgs = nullptr;
694 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
695 // Function templates aren't considered for name back referencing. This
696 // makes sense since function templates aren't likely to occur multiple
697 // times in a symbol.
698 // FIXME: Test alias template mangling with MSVC 2013.
699 if (!isa<ClassTemplateDecl>(TD)) {
700 mangleTemplateInstantiationName(TD, *TemplateArgs);
705 // Here comes the tricky thing: if we need to mangle something like
706 // void foo(A::X<Y>, B::X<Y>),
707 // the X<Y> part is aliased. However, if you need to mangle
708 // void foo(A::X<A::Y>, A::X<B::Y>),
709 // the A::X<> part is not aliased.
710 // That said, from the mangler's perspective we have a structure like this:
711 // namespace[s] -> type[ -> template-parameters]
712 // but from the Clang perspective we have
713 // type [ -> template-parameters]
715 // What we do is we create a new mangler, mangle the same type (without
716 // a namespace suffix) to a string using the extra mangler and then use
717 // the mangled type name as a key to check the mangling of different types
720 llvm::SmallString<64> TemplateMangling;
721 llvm::raw_svector_ostream Stream(TemplateMangling);
722 MicrosoftCXXNameMangler Extra(Context, Stream);
723 Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
726 mangleSourceName(TemplateMangling);
730 switch (Name.getNameKind()) {
731 case DeclarationName::Identifier: {
732 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
733 mangleSourceName(II->getName());
737 // Otherwise, an anonymous entity. We must have a declaration.
738 assert(ND && "mangling empty name without declaration");
740 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
741 if (NS->isAnonymousNamespace()) {
747 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
748 // We must have an anonymous union or struct declaration.
749 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
750 assert(RD && "expected variable decl to have a record type");
751 // Anonymous types with no tag or typedef get the name of their
752 // declarator mangled in. If they have no declarator, number them with
754 llvm::SmallString<64> Name("$S");
755 // Get a unique id for the anonymous struct.
756 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
757 mangleSourceName(Name.str());
761 // We must have an anonymous struct.
762 const TagDecl *TD = cast<TagDecl>(ND);
763 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
764 assert(TD->getDeclContext() == D->getDeclContext() &&
765 "Typedef should not be in another decl context!");
766 assert(D->getDeclName().getAsIdentifierInfo() &&
767 "Typedef was not named!");
768 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
772 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
773 if (Record->isLambda()) {
774 llvm::SmallString<10> Name("<lambda_");
776 if (Record->getLambdaManglingNumber())
777 LambdaId = Record->getLambdaManglingNumber();
779 LambdaId = Context.getLambdaId(Record);
781 Name += llvm::utostr(LambdaId);
784 mangleSourceName(Name);
789 llvm::SmallString<64> Name("<unnamed-type-");
790 if (TD->hasDeclaratorForAnonDecl()) {
791 // Anonymous types with no tag or typedef get the name of their
792 // declarator mangled in if they have one.
793 Name += TD->getDeclaratorForAnonDecl()->getName();
795 // Otherwise, number the types using a $S prefix.
797 Name += llvm::utostr(Context.getAnonymousStructId(TD));
800 mangleSourceName(Name.str());
804 case DeclarationName::ObjCZeroArgSelector:
805 case DeclarationName::ObjCOneArgSelector:
806 case DeclarationName::ObjCMultiArgSelector:
807 llvm_unreachable("Can't mangle Objective-C selector names here!");
809 case DeclarationName::CXXConstructorName:
810 if (Structor == getStructor(ND)) {
811 if (StructorType == Ctor_CopyingClosure) {
815 if (StructorType == Ctor_DefaultClosure) {
823 case DeclarationName::CXXDestructorName:
825 // If the named decl is the C++ destructor we're mangling,
826 // use the type we were given.
827 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
829 // Otherwise, use the base destructor name. This is relevant if a
830 // class with a destructor is declared within a destructor.
831 mangleCXXDtorType(Dtor_Base);
834 case DeclarationName::CXXConversionFunctionName:
835 // <operator-name> ::= ?B # (cast)
836 // The target type is encoded as the return type.
840 case DeclarationName::CXXOperatorName:
841 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
844 case DeclarationName::CXXLiteralOperatorName: {
846 mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
850 case DeclarationName::CXXUsingDirective:
851 llvm_unreachable("Can't mangle a using directive name!");
855 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
856 // <postfix> ::= <unqualified-name> [<postfix>]
857 // ::= <substitution> [<postfix>]
858 const DeclContext *DC = getEffectiveDeclContext(ND);
860 while (!DC->isTranslationUnit()) {
861 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
863 if (Context.getNextDiscriminator(ND, Disc)) {
870 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
871 DiagnosticsEngine &Diags = Context.getDiags();
873 Diags.getCustomDiagID(DiagnosticsEngine::Error,
874 "cannot mangle a local inside this block yet");
875 Diags.Report(BD->getLocation(), DiagID);
877 // FIXME: This is completely, utterly, wrong; see ItaniumMangle
878 // for how this should be done.
879 Out << "__block_invoke" << Context.getBlockId(BD, false);
882 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
883 mangleObjCMethodName(Method);
884 } else if (isa<NamedDecl>(DC)) {
885 ND = cast<NamedDecl>(DC);
886 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
890 mangleUnqualifiedName(ND);
892 DC = DC->getParent();
896 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
897 // Microsoft uses the names on the case labels for these dtor variants. Clang
898 // uses the Itanium terminology internally. Everything in this ABI delegates
899 // towards the base dtor.
901 // <operator-name> ::= ?1 # destructor
902 case Dtor_Base: Out << "?1"; return;
903 // <operator-name> ::= ?_D # vbase destructor
904 case Dtor_Complete: Out << "?_D"; return;
905 // <operator-name> ::= ?_G # scalar deleting destructor
906 case Dtor_Deleting: Out << "?_G"; return;
907 // <operator-name> ::= ?_E # vector deleting destructor
908 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
911 llvm_unreachable("not expecting a COMDAT");
913 llvm_unreachable("Unsupported dtor type?");
916 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
917 SourceLocation Loc) {
921 // <operator-name> ::= ?2 # new
922 case OO_New: Out << "?2"; break;
923 // <operator-name> ::= ?3 # delete
924 case OO_Delete: Out << "?3"; break;
925 // <operator-name> ::= ?4 # =
926 case OO_Equal: Out << "?4"; break;
927 // <operator-name> ::= ?5 # >>
928 case OO_GreaterGreater: Out << "?5"; break;
929 // <operator-name> ::= ?6 # <<
930 case OO_LessLess: Out << "?6"; break;
931 // <operator-name> ::= ?7 # !
932 case OO_Exclaim: Out << "?7"; break;
933 // <operator-name> ::= ?8 # ==
934 case OO_EqualEqual: Out << "?8"; break;
935 // <operator-name> ::= ?9 # !=
936 case OO_ExclaimEqual: Out << "?9"; break;
937 // <operator-name> ::= ?A # []
938 case OO_Subscript: Out << "?A"; break;
940 // <operator-name> ::= ?C # ->
941 case OO_Arrow: Out << "?C"; break;
942 // <operator-name> ::= ?D # *
943 case OO_Star: Out << "?D"; break;
944 // <operator-name> ::= ?E # ++
945 case OO_PlusPlus: Out << "?E"; break;
946 // <operator-name> ::= ?F # --
947 case OO_MinusMinus: Out << "?F"; break;
948 // <operator-name> ::= ?G # -
949 case OO_Minus: Out << "?G"; break;
950 // <operator-name> ::= ?H # +
951 case OO_Plus: Out << "?H"; break;
952 // <operator-name> ::= ?I # &
953 case OO_Amp: Out << "?I"; break;
954 // <operator-name> ::= ?J # ->*
955 case OO_ArrowStar: Out << "?J"; break;
956 // <operator-name> ::= ?K # /
957 case OO_Slash: Out << "?K"; break;
958 // <operator-name> ::= ?L # %
959 case OO_Percent: Out << "?L"; break;
960 // <operator-name> ::= ?M # <
961 case OO_Less: Out << "?M"; break;
962 // <operator-name> ::= ?N # <=
963 case OO_LessEqual: Out << "?N"; break;
964 // <operator-name> ::= ?O # >
965 case OO_Greater: Out << "?O"; break;
966 // <operator-name> ::= ?P # >=
967 case OO_GreaterEqual: Out << "?P"; break;
968 // <operator-name> ::= ?Q # ,
969 case OO_Comma: Out << "?Q"; break;
970 // <operator-name> ::= ?R # ()
971 case OO_Call: Out << "?R"; break;
972 // <operator-name> ::= ?S # ~
973 case OO_Tilde: Out << "?S"; break;
974 // <operator-name> ::= ?T # ^
975 case OO_Caret: Out << "?T"; break;
976 // <operator-name> ::= ?U # |
977 case OO_Pipe: Out << "?U"; break;
978 // <operator-name> ::= ?V # &&
979 case OO_AmpAmp: Out << "?V"; break;
980 // <operator-name> ::= ?W # ||
981 case OO_PipePipe: Out << "?W"; break;
982 // <operator-name> ::= ?X # *=
983 case OO_StarEqual: Out << "?X"; break;
984 // <operator-name> ::= ?Y # +=
985 case OO_PlusEqual: Out << "?Y"; break;
986 // <operator-name> ::= ?Z # -=
987 case OO_MinusEqual: Out << "?Z"; break;
988 // <operator-name> ::= ?_0 # /=
989 case OO_SlashEqual: Out << "?_0"; break;
990 // <operator-name> ::= ?_1 # %=
991 case OO_PercentEqual: Out << "?_1"; break;
992 // <operator-name> ::= ?_2 # >>=
993 case OO_GreaterGreaterEqual: Out << "?_2"; break;
994 // <operator-name> ::= ?_3 # <<=
995 case OO_LessLessEqual: Out << "?_3"; break;
996 // <operator-name> ::= ?_4 # &=
997 case OO_AmpEqual: Out << "?_4"; break;
998 // <operator-name> ::= ?_5 # |=
999 case OO_PipeEqual: Out << "?_5"; break;
1000 // <operator-name> ::= ?_6 # ^=
1001 case OO_CaretEqual: Out << "?_6"; break;
1006 // ?_B # local static guard
1008 // ?_D # vbase destructor
1009 // ?_E # vector deleting destructor
1010 // ?_F # default constructor closure
1011 // ?_G # scalar deleting destructor
1012 // ?_H # vector constructor iterator
1013 // ?_I # vector destructor iterator
1014 // ?_J # vector vbase constructor iterator
1015 // ?_K # virtual displacement map
1016 // ?_L # eh vector constructor iterator
1017 // ?_M # eh vector destructor iterator
1018 // ?_N # eh vector vbase constructor iterator
1019 // ?_O # copy constructor closure
1020 // ?_P<name> # udt returning <name>
1022 // ?_R0 # RTTI Type Descriptor
1023 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1024 // ?_R2 # RTTI Base Class Array
1025 // ?_R3 # RTTI Class Hierarchy Descriptor
1026 // ?_R4 # RTTI Complete Object Locator
1027 // ?_S # local vftable
1028 // ?_T # local vftable constructor closure
1029 // <operator-name> ::= ?_U # new[]
1030 case OO_Array_New: Out << "?_U"; break;
1031 // <operator-name> ::= ?_V # delete[]
1032 case OO_Array_Delete: Out << "?_V"; break;
1034 case OO_Conditional: {
1035 DiagnosticsEngine &Diags = Context.getDiags();
1036 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1037 "cannot mangle this conditional operator yet");
1038 Diags.Report(Loc, DiagID);
1043 case NUM_OVERLOADED_OPERATORS:
1044 llvm_unreachable("Not an overloaded operator");
1048 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1049 // <source name> ::= <identifier> @
1050 BackRefVec::iterator Found =
1051 std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1052 if (Found == NameBackReferences.end()) {
1053 if (NameBackReferences.size() < 10)
1054 NameBackReferences.push_back(Name);
1057 Out << (Found - NameBackReferences.begin());
1061 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1062 Context.mangleObjCMethodName(MD, Out);
1065 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1066 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1067 // <template-name> ::= <unscoped-template-name> <template-args>
1068 // ::= <substitution>
1069 // Always start with the unqualified name.
1071 // Templates have their own context for back references.
1072 ArgBackRefMap OuterArgsContext;
1073 BackRefVec OuterTemplateContext;
1074 NameBackReferences.swap(OuterTemplateContext);
1075 TypeBackReferences.swap(OuterArgsContext);
1077 mangleUnscopedTemplateName(TD);
1078 mangleTemplateArgs(TD, TemplateArgs);
1080 // Restore the previous back reference contexts.
1081 NameBackReferences.swap(OuterTemplateContext);
1082 TypeBackReferences.swap(OuterArgsContext);
1086 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1087 // <unscoped-template-name> ::= ?$ <unqualified-name>
1089 mangleUnqualifiedName(TD);
1092 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1094 // <integer-literal> ::= $0 <number>
1096 // Make sure booleans are encoded as 0/1.
1097 if (IsBoolean && Value.getBoolValue())
1099 else if (Value.isSigned())
1100 mangleNumber(Value.getSExtValue());
1102 mangleNumber(Value.getZExtValue());
1105 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1106 // See if this is a constant expression.
1108 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1109 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1113 // Look through no-op casts like template parameter substitutions.
1114 E = E->IgnoreParenNoopCasts(Context.getASTContext());
1116 const CXXUuidofExpr *UE = nullptr;
1117 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1118 if (UO->getOpcode() == UO_AddrOf)
1119 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1121 UE = dyn_cast<CXXUuidofExpr>(E);
1124 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1125 // const __s_GUID _GUID_{lower case UUID with underscores}
1126 StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1127 std::string Name = "_GUID_" + Uuid.lower();
1128 std::replace(Name.begin(), Name.end(), '-', '_');
1130 // If we had to peek through an address-of operator, treat this like we are
1131 // dealing with a pointer type. Otherwise, treat it like a const reference.
1133 // N.B. This matches up with the handling of TemplateArgument::Declaration
1134 // in mangleTemplateArg
1139 Out << Name << "@@3U__s_GUID@@B";
1143 // As bad as this diagnostic is, it's better than crashing.
1144 DiagnosticsEngine &Diags = Context.getDiags();
1145 unsigned DiagID = Diags.getCustomDiagID(
1146 DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1147 Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1148 << E->getSourceRange();
1151 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1152 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1153 // <template-args> ::= <template-arg>+
1154 const TemplateParameterList *TPL = TD->getTemplateParameters();
1155 assert(TPL->size() == TemplateArgs.size() &&
1156 "size mismatch between args and parms!");
1159 for (const TemplateArgument &TA : TemplateArgs.asArray())
1160 mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1163 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1164 const TemplateArgument &TA,
1165 const NamedDecl *Parm) {
1166 // <template-arg> ::= <type>
1167 // ::= <integer-literal>
1168 // ::= <member-data-pointer>
1169 // ::= <member-function-pointer>
1170 // ::= $E? <name> <type-encoding>
1171 // ::= $1? <name> <type-encoding>
1173 // ::= <template-args>
1175 switch (TA.getKind()) {
1176 case TemplateArgument::Null:
1177 llvm_unreachable("Can't mangle null template arguments!");
1178 case TemplateArgument::TemplateExpansion:
1179 llvm_unreachable("Can't mangle template expansion arguments!");
1180 case TemplateArgument::Type: {
1181 QualType T = TA.getAsType();
1182 mangleType(T, SourceRange(), QMM_Escape);
1185 case TemplateArgument::Declaration: {
1186 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1187 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1188 mangleMemberDataPointer(
1189 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1190 cast<ValueDecl>(ND));
1191 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1192 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1193 if (MD && MD->isInstance()) {
1194 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1198 mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1201 mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1205 case TemplateArgument::Integral:
1206 mangleIntegerLiteral(TA.getAsIntegral(),
1207 TA.getIntegralType()->isBooleanType());
1209 case TemplateArgument::NullPtr: {
1210 QualType T = TA.getNullPtrType();
1211 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1212 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1213 if (MPT->isMemberFunctionPointerType() && isa<ClassTemplateDecl>(TD)) {
1214 mangleMemberFunctionPointer(RD, nullptr);
1217 if (MPT->isMemberDataPointer()) {
1218 if (isa<ClassTemplateDecl>(TD)) {
1219 mangleMemberDataPointer(RD, nullptr);
1222 // nullptr data pointers are always represented with a single field
1223 // which is initialized with either 0 or -1. Why -1? Well, we need to
1224 // distinguish the case where the data member is at offset zero in the
1226 // However, we are free to use 0 *if* we would use multiple fields for
1227 // non-nullptr member pointers.
1228 if (!RD->nullFieldOffsetIsZero()) {
1229 mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1234 mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1237 case TemplateArgument::Expression:
1238 mangleExpression(TA.getAsExpr());
1240 case TemplateArgument::Pack: {
1241 ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1242 if (TemplateArgs.empty()) {
1243 if (isa<TemplateTypeParmDecl>(Parm) ||
1244 isa<TemplateTemplateParmDecl>(Parm))
1245 // MSVC 2015 changed the mangling for empty expanded template packs,
1246 // use the old mangling for link compatibility for old versions.
1247 Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1248 LangOptions::MSVC2015)
1251 else if (isa<NonTypeTemplateParmDecl>(Parm))
1254 llvm_unreachable("unexpected template parameter decl!");
1256 for (const TemplateArgument &PA : TemplateArgs)
1257 mangleTemplateArg(TD, PA, Parm);
1261 case TemplateArgument::Template: {
1262 const NamedDecl *ND =
1263 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1264 if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1266 } else if (isa<TypeAliasDecl>(ND)) {
1270 llvm_unreachable("unexpected template template NamedDecl!");
1277 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1279 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1280 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1281 // 'I' means __restrict (32/64-bit).
1282 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1284 // <base-cvr-qualifiers> ::= A # near
1285 // ::= B # near const
1286 // ::= C # near volatile
1287 // ::= D # near const volatile
1288 // ::= E # far (16-bit)
1289 // ::= F # far const (16-bit)
1290 // ::= G # far volatile (16-bit)
1291 // ::= H # far const volatile (16-bit)
1292 // ::= I # huge (16-bit)
1293 // ::= J # huge const (16-bit)
1294 // ::= K # huge volatile (16-bit)
1295 // ::= L # huge const volatile (16-bit)
1296 // ::= M <basis> # based
1297 // ::= N <basis> # based const
1298 // ::= O <basis> # based volatile
1299 // ::= P <basis> # based const volatile
1300 // ::= Q # near member
1301 // ::= R # near const member
1302 // ::= S # near volatile member
1303 // ::= T # near const volatile member
1304 // ::= U # far member (16-bit)
1305 // ::= V # far const member (16-bit)
1306 // ::= W # far volatile member (16-bit)
1307 // ::= X # far const volatile member (16-bit)
1308 // ::= Y # huge member (16-bit)
1309 // ::= Z # huge const member (16-bit)
1310 // ::= 0 # huge volatile member (16-bit)
1311 // ::= 1 # huge const volatile member (16-bit)
1312 // ::= 2 <basis> # based member
1313 // ::= 3 <basis> # based const member
1314 // ::= 4 <basis> # based volatile member
1315 // ::= 5 <basis> # based const volatile member
1316 // ::= 6 # near function (pointers only)
1317 // ::= 7 # far function (pointers only)
1318 // ::= 8 # near method (pointers only)
1319 // ::= 9 # far method (pointers only)
1320 // ::= _A <basis> # based function (pointers only)
1321 // ::= _B <basis> # based function (far?) (pointers only)
1322 // ::= _C <basis> # based method (pointers only)
1323 // ::= _D <basis> # based method (far?) (pointers only)
1324 // ::= _E # block (Clang)
1325 // <basis> ::= 0 # __based(void)
1326 // ::= 1 # __based(segment)?
1327 // ::= 2 <name> # __based(name)
1330 // ::= 5 # not really based
1331 bool HasConst = Quals.hasConst(),
1332 HasVolatile = Quals.hasVolatile();
1335 if (HasConst && HasVolatile) {
1337 } else if (HasVolatile) {
1339 } else if (HasConst) {
1345 if (HasConst && HasVolatile) {
1347 } else if (HasVolatile) {
1349 } else if (HasConst) {
1356 // FIXME: For now, just drop all extension qualifiers on the floor.
1360 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1361 // <ref-qualifier> ::= G # lvalue reference
1362 // ::= H # rvalue-reference
1363 switch (RefQualifier) {
1377 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1378 QualType PointeeType) {
1379 bool HasRestrict = Quals.hasRestrict();
1380 if (PointersAre64Bit &&
1381 (PointeeType.isNull() || !PointeeType->isFunctionType()))
1388 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1389 // <pointer-cv-qualifiers> ::= P # no qualifiers
1392 // ::= S # const volatile
1393 bool HasConst = Quals.hasConst(),
1394 HasVolatile = Quals.hasVolatile();
1396 if (HasConst && HasVolatile) {
1398 } else if (HasVolatile) {
1400 } else if (HasConst) {
1407 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1408 SourceRange Range) {
1409 // MSVC will backreference two canonically equivalent types that have slightly
1410 // different manglings when mangled alone.
1412 // Decayed types do not match up with non-decayed versions of the same type.
1415 // void (*x)(void) will not form a backreference with void x(void)
1417 if (const auto *DT = T->getAs<DecayedType>()) {
1418 QualType OriginalType = DT->getOriginalType();
1419 // All decayed ArrayTypes should be treated identically; as-if they were
1420 // a decayed IncompleteArrayType.
1421 if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1422 OriginalType = getASTContext().getIncompleteArrayType(
1423 AT->getElementType(), AT->getSizeModifier(),
1424 AT->getIndexTypeCVRQualifiers());
1426 TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1427 // If the original parameter was textually written as an array,
1428 // instead treat the decayed parameter like it's const.
1431 // int [] -> int * const
1432 if (OriginalType->isArrayType())
1435 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1438 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1440 if (Found == TypeBackReferences.end()) {
1441 size_t OutSizeBefore = Out.tell();
1443 mangleType(T, Range, QMM_Drop);
1445 // See if it's worth creating a back reference.
1446 // Only types longer than 1 character are considered
1447 // and only 10 back references slots are available:
1448 bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1449 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1450 size_t Size = TypeBackReferences.size();
1451 TypeBackReferences[TypePtr] = Size;
1454 Out << Found->second;
1458 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1459 QualifierMangleMode QMM) {
1460 // Don't use the canonical types. MSVC includes things like 'const' on
1461 // pointer arguments to function pointers that canonicalization strips away.
1462 T = T.getDesugaredType(getASTContext());
1463 Qualifiers Quals = T.getLocalQualifiers();
1464 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1465 // If there were any Quals, getAsArrayType() pushed them onto the array
1467 if (QMM == QMM_Mangle)
1469 else if (QMM == QMM_Escape || QMM == QMM_Result)
1471 mangleArrayType(AT);
1475 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1476 T->isReferenceType() || T->isBlockPointerType();
1482 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1484 mangleFunctionType(FT);
1487 mangleQualifiers(Quals, false);
1490 if (!IsPointer && Quals) {
1492 mangleQualifiers(Quals, false);
1496 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1498 mangleQualifiers(Quals, false);
1503 const Type *ty = T.getTypePtr();
1505 switch (ty->getTypeClass()) {
1506 #define ABSTRACT_TYPE(CLASS, PARENT)
1507 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1509 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1511 #define TYPE(CLASS, PARENT) \
1513 mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1515 #include "clang/AST/TypeNodes.def"
1516 #undef ABSTRACT_TYPE
1517 #undef NON_CANONICAL_TYPE
1522 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1523 SourceRange Range) {
1524 // <type> ::= <builtin-type>
1525 // <builtin-type> ::= X # void
1526 // ::= C # signed char
1528 // ::= E # unsigned char
1530 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1532 // ::= I # unsigned int
1534 // ::= K # unsigned long
1538 // ::= O # long double (__float80 is mangled differently)
1539 // ::= _J # long long, __int64
1540 // ::= _K # unsigned long long, __int64
1541 // ::= _L # __int128
1542 // ::= _M # unsigned __int128
1544 // _O # <array in parameter>
1545 // ::= _T # __float80 (Intel)
1547 // ::= _Z # __float80 (Digital Mars)
1548 switch (T->getKind()) {
1549 case BuiltinType::Void: Out << 'X'; break;
1550 case BuiltinType::SChar: Out << 'C'; break;
1551 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1552 case BuiltinType::UChar: Out << 'E'; break;
1553 case BuiltinType::Short: Out << 'F'; break;
1554 case BuiltinType::UShort: Out << 'G'; break;
1555 case BuiltinType::Int: Out << 'H'; break;
1556 case BuiltinType::UInt: Out << 'I'; break;
1557 case BuiltinType::Long: Out << 'J'; break;
1558 case BuiltinType::ULong: Out << 'K'; break;
1559 case BuiltinType::Float: Out << 'M'; break;
1560 case BuiltinType::Double: Out << 'N'; break;
1561 // TODO: Determine size and mangle accordingly
1562 case BuiltinType::LongDouble: Out << 'O'; break;
1563 case BuiltinType::LongLong: Out << "_J"; break;
1564 case BuiltinType::ULongLong: Out << "_K"; break;
1565 case BuiltinType::Int128: Out << "_L"; break;
1566 case BuiltinType::UInt128: Out << "_M"; break;
1567 case BuiltinType::Bool: Out << "_N"; break;
1568 case BuiltinType::Char16: Out << "_S"; break;
1569 case BuiltinType::Char32: Out << "_U"; break;
1570 case BuiltinType::WChar_S:
1571 case BuiltinType::WChar_U: Out << "_W"; break;
1573 #define BUILTIN_TYPE(Id, SingletonId)
1574 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1575 case BuiltinType::Id:
1576 #include "clang/AST/BuiltinTypes.def"
1577 case BuiltinType::Dependent:
1578 llvm_unreachable("placeholder types shouldn't get to name mangling");
1580 case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1581 case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1582 case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1584 case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1585 case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1586 case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1587 case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1588 case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1589 case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1590 case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1591 case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1593 case BuiltinType::NullPtr: Out << "$$T"; break;
1595 case BuiltinType::Half: {
1596 DiagnosticsEngine &Diags = Context.getDiags();
1597 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1598 "cannot mangle this built-in %0 type yet");
1599 Diags.Report(Range.getBegin(), DiagID)
1600 << T->getName(Context.getASTContext().getPrintingPolicy())
1607 // <type> ::= <function-type>
1608 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1610 // Structors only appear in decls, so at this point we know it's not a
1612 // FIXME: This may not be lambda-friendly.
1613 if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1615 mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1618 mangleFunctionType(T);
1621 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1622 Qualifiers, SourceRange) {
1623 llvm_unreachable("Can't mangle K&R function prototypes");
1626 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1627 const FunctionDecl *D,
1628 bool ForceThisQuals) {
1629 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1630 // <return-type> <argument-list> <throw-spec>
1631 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1634 if (D) Range = D->getSourceRange();
1636 bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1637 CallingConv CC = T->getCallConv();
1638 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1639 if (MD->isInstance())
1640 HasThisQuals = true;
1641 if (isa<CXXDestructorDecl>(MD)) {
1643 } else if (isa<CXXConstructorDecl>(MD)) {
1645 IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1646 StructorType == Ctor_DefaultClosure) &&
1647 getStructor(MD) == Structor;
1649 CC = getASTContext().getDefaultCallingConvention(
1650 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1654 // If this is a C++ instance method, mangle the CVR qualifiers for the
1657 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1658 manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1659 mangleRefQualifier(Proto->getRefQualifier());
1660 mangleQualifiers(Quals, /*IsMember=*/false);
1663 mangleCallingConvention(CC);
1665 // <return-type> ::= <type>
1666 // ::= @ # structors (they have no declared return type)
1668 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1669 StructorType == Dtor_Deleting) {
1670 // The scalar deleting destructor takes an extra int argument.
1671 // However, the FunctionType generated has 0 arguments.
1672 // FIXME: This is a temporary hack.
1673 // Maybe should fix the FunctionType creation instead?
1674 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1677 if (IsCtorClosure) {
1678 // Default constructor closure and copy constructor closure both return
1682 if (StructorType == Ctor_DefaultClosure) {
1683 // Default constructor closure always has no arguments.
1685 } else if (StructorType == Ctor_CopyingClosure) {
1686 // Copy constructor closure always takes an unqualified reference.
1687 mangleArgumentType(getASTContext().getLValueReferenceType(
1688 Proto->getParamType(0)
1689 ->getAs<LValueReferenceType>()
1691 /*SpelledAsLValue=*/true),
1695 llvm_unreachable("unexpected constructor closure!");
1702 QualType ResultType = Proto->getReturnType();
1703 if (const auto *AT =
1704 dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1706 mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1708 mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1711 if (ResultType->isVoidType())
1712 ResultType = ResultType.getUnqualifiedType();
1713 mangleType(ResultType, Range, QMM_Result);
1717 // <argument-list> ::= X # void
1719 // ::= <type>* Z # varargs
1720 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1723 // Happens for function pointer type arguments for example.
1724 for (const QualType &Arg : Proto->param_types())
1725 mangleArgumentType(Arg, Range);
1726 // <builtin-type> ::= Z # ellipsis
1727 if (Proto->isVariadic())
1733 mangleThrowSpecification(Proto);
1736 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1737 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1738 // # pointer. in 64-bit mode *all*
1739 // # 'this' pointers are 64-bit.
1740 // ::= <global-function>
1741 // <member-function> ::= A # private: near
1742 // ::= B # private: far
1743 // ::= C # private: static near
1744 // ::= D # private: static far
1745 // ::= E # private: virtual near
1746 // ::= F # private: virtual far
1747 // ::= I # protected: near
1748 // ::= J # protected: far
1749 // ::= K # protected: static near
1750 // ::= L # protected: static far
1751 // ::= M # protected: virtual near
1752 // ::= N # protected: virtual far
1753 // ::= Q # public: near
1754 // ::= R # public: far
1755 // ::= S # public: static near
1756 // ::= T # public: static far
1757 // ::= U # public: virtual near
1758 // ::= V # public: virtual far
1759 // <global-function> ::= Y # global near
1760 // ::= Z # global far
1761 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1762 switch (MD->getAccess()) {
1764 llvm_unreachable("Unsupported access specifier");
1768 else if (MD->isVirtual())
1776 else if (MD->isVirtual())
1784 else if (MD->isVirtual())
1793 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1794 // <calling-convention> ::= A # __cdecl
1795 // ::= B # __export __cdecl
1797 // ::= D # __export __pascal
1798 // ::= E # __thiscall
1799 // ::= F # __export __thiscall
1800 // ::= G # __stdcall
1801 // ::= H # __export __stdcall
1802 // ::= I # __fastcall
1803 // ::= J # __export __fastcall
1804 // ::= Q # __vectorcall
1805 // The 'export' calling conventions are from a bygone era
1806 // (*cough*Win16*cough*) when functions were declared for export with
1807 // that keyword. (It didn't actually export them, it just made them so
1808 // that they could be in a DLL and somebody from another module could call
1813 llvm_unreachable("Unsupported CC for mangling");
1814 case CC_X86_64Win64:
1816 case CC_C: Out << 'A'; break;
1817 case CC_X86Pascal: Out << 'C'; break;
1818 case CC_X86ThisCall: Out << 'E'; break;
1819 case CC_X86StdCall: Out << 'G'; break;
1820 case CC_X86FastCall: Out << 'I'; break;
1821 case CC_X86VectorCall: Out << 'Q'; break;
1824 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1825 mangleCallingConvention(T->getCallConv());
1827 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1828 const FunctionProtoType *FT) {
1829 // <throw-spec> ::= Z # throw(...) (default)
1830 // ::= @ # throw() or __declspec/__attribute__((nothrow))
1832 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1833 // all actually mangled as 'Z'. (They're ignored because their associated
1834 // functionality isn't implemented, and probably never will be.)
1838 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1839 Qualifiers, SourceRange Range) {
1840 // Probably should be mangled as a template instantiation; need to see what
1842 DiagnosticsEngine &Diags = Context.getDiags();
1843 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1844 "cannot mangle this unresolved dependent type yet");
1845 Diags.Report(Range.getBegin(), DiagID)
1849 // <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1850 // <union-type> ::= T <name>
1851 // <struct-type> ::= U <name>
1852 // <class-type> ::= V <name>
1853 // <enum-type> ::= W4 <name>
1854 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
1856 mangleType(cast<TagType>(T)->getDecl());
1858 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
1860 mangleType(cast<TagType>(T)->getDecl());
1862 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1863 switch (TD->getTagKind()) {
1881 // <type> ::= <array-type>
1882 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1883 // [Y <dimension-count> <dimension>+]
1884 // <element-type> # as global, E is never required
1885 // It's supposed to be the other way around, but for some strange reason, it
1886 // isn't. Today this behavior is retained for the sole purpose of backwards
1888 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
1889 // This isn't a recursive mangling, so now we have to do it all in this
1891 manglePointerCVQualifiers(T->getElementType().getQualifiers());
1892 mangleType(T->getElementType(), SourceRange());
1894 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
1896 llvm_unreachable("Should have been special cased");
1898 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
1900 llvm_unreachable("Should have been special cased");
1902 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1903 Qualifiers, SourceRange) {
1904 llvm_unreachable("Should have been special cased");
1906 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1907 Qualifiers, SourceRange) {
1908 llvm_unreachable("Should have been special cased");
1910 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
1911 QualType ElementTy(T, 0);
1912 SmallVector<llvm::APInt, 3> Dimensions;
1914 if (ElementTy->isConstantArrayType()) {
1915 const ConstantArrayType *CAT =
1916 getASTContext().getAsConstantArrayType(ElementTy);
1917 Dimensions.push_back(CAT->getSize());
1918 ElementTy = CAT->getElementType();
1919 } else if (ElementTy->isIncompleteArrayType()) {
1920 const IncompleteArrayType *IAT =
1921 getASTContext().getAsIncompleteArrayType(ElementTy);
1922 Dimensions.push_back(llvm::APInt(32, 0));
1923 ElementTy = IAT->getElementType();
1924 } else if (ElementTy->isVariableArrayType()) {
1925 const VariableArrayType *VAT =
1926 getASTContext().getAsVariableArrayType(ElementTy);
1927 Dimensions.push_back(llvm::APInt(32, 0));
1928 ElementTy = VAT->getElementType();
1929 } else if (ElementTy->isDependentSizedArrayType()) {
1930 // The dependent expression has to be folded into a constant (TODO).
1931 const DependentSizedArrayType *DSAT =
1932 getASTContext().getAsDependentSizedArrayType(ElementTy);
1933 DiagnosticsEngine &Diags = Context.getDiags();
1934 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1935 "cannot mangle this dependent-length array yet");
1936 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1937 << DSAT->getBracketsRange();
1944 // <dimension-count> ::= <number> # number of extra dimensions
1945 mangleNumber(Dimensions.size());
1946 for (const llvm::APInt &Dimension : Dimensions)
1947 mangleNumber(Dimension.getLimitedValue());
1948 mangleType(ElementTy, SourceRange(), QMM_Escape);
1951 // <type> ::= <pointer-to-member-type>
1952 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1953 // <class name> <type>
1954 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
1955 SourceRange Range) {
1956 QualType PointeeType = T->getPointeeType();
1957 manglePointerCVQualifiers(Quals);
1958 manglePointerExtQualifiers(Quals, PointeeType);
1959 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1961 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1962 mangleFunctionType(FPT, nullptr, true);
1964 mangleQualifiers(PointeeType.getQualifiers(), true);
1965 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1966 mangleType(PointeeType, Range, QMM_Drop);
1970 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1971 Qualifiers, SourceRange Range) {
1972 DiagnosticsEngine &Diags = Context.getDiags();
1973 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1974 "cannot mangle this template type parameter type yet");
1975 Diags.Report(Range.getBegin(), DiagID)
1979 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
1980 Qualifiers, SourceRange Range) {
1981 DiagnosticsEngine &Diags = Context.getDiags();
1982 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1983 "cannot mangle this substituted parameter pack yet");
1984 Diags.Report(Range.getBegin(), DiagID)
1988 // <type> ::= <pointer-type>
1989 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1990 // # the E is required for 64-bit non-static pointers
1991 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
1992 SourceRange Range) {
1993 QualType PointeeType = T->getPointeeType();
1994 manglePointerCVQualifiers(Quals);
1995 manglePointerExtQualifiers(Quals, PointeeType);
1996 mangleType(PointeeType, Range);
1998 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1999 Qualifiers Quals, SourceRange Range) {
2000 QualType PointeeType = T->getPointeeType();
2001 manglePointerCVQualifiers(Quals);
2002 manglePointerExtQualifiers(Quals, PointeeType);
2003 // Object pointers never have qualifiers.
2005 mangleType(PointeeType, Range);
2008 // <type> ::= <reference-type>
2009 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2010 // # the E is required for 64-bit non-static lvalue references
2011 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2012 Qualifiers Quals, SourceRange Range) {
2013 QualType PointeeType = T->getPointeeType();
2014 Out << (Quals.hasVolatile() ? 'B' : 'A');
2015 manglePointerExtQualifiers(Quals, PointeeType);
2016 mangleType(PointeeType, Range);
2019 // <type> ::= <r-value-reference-type>
2020 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2021 // # the E is required for 64-bit non-static rvalue references
2022 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2023 Qualifiers Quals, SourceRange Range) {
2024 QualType PointeeType = T->getPointeeType();
2025 Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
2026 manglePointerExtQualifiers(Quals, PointeeType);
2027 mangleType(PointeeType, Range);
2030 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2031 SourceRange Range) {
2032 DiagnosticsEngine &Diags = Context.getDiags();
2033 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2034 "cannot mangle this complex number type yet");
2035 Diags.Report(Range.getBegin(), DiagID)
2039 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2040 SourceRange Range) {
2041 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2042 assert(ET && "vectors with non-builtin elements are unsupported");
2043 uint64_t Width = getASTContext().getTypeSize(T);
2044 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
2045 // doesn't match the Intel types uses a custom mangling below.
2046 bool IsBuiltin = true;
2047 llvm::Triple::ArchType AT =
2048 getASTContext().getTargetInfo().getTriple().getArch();
2049 if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2050 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2052 } else if (Width >= 128) {
2053 if (ET->getKind() == BuiltinType::Float)
2054 Out << "T__m" << Width;
2055 else if (ET->getKind() == BuiltinType::LongLong)
2056 Out << "T__m" << Width << 'i';
2057 else if (ET->getKind() == BuiltinType::Double)
2058 Out << "U__m" << Width << 'd';
2069 // The MS ABI doesn't have a special mangling for vector types, so we define
2070 // our own mangling to handle uses of __vector_size__ on user-specified
2071 // types, and for extensions like __v4sf.
2072 Out << "T__clang_vec" << T->getNumElements() << '_';
2073 mangleType(ET, Quals, Range);
2079 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T, Qualifiers,
2080 SourceRange Range) {
2081 DiagnosticsEngine &Diags = Context.getDiags();
2082 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2083 "cannot mangle this extended vector type yet");
2084 Diags.Report(Range.getBegin(), DiagID)
2087 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2088 Qualifiers, SourceRange Range) {
2089 DiagnosticsEngine &Diags = Context.getDiags();
2090 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2091 "cannot mangle this dependent-sized extended vector type yet");
2092 Diags.Report(Range.getBegin(), DiagID)
2096 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2098 // ObjC interfaces have structs underlying them.
2100 mangleName(T->getDecl());
2103 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2104 SourceRange Range) {
2105 // We don't allow overloading by different protocol qualification,
2106 // so mangling them isn't necessary.
2107 mangleType(T->getBaseType(), Range);
2110 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2111 Qualifiers Quals, SourceRange Range) {
2112 QualType PointeeType = T->getPointeeType();
2113 manglePointerCVQualifiers(Quals);
2114 manglePointerExtQualifiers(Quals, PointeeType);
2118 mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2121 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2122 Qualifiers, SourceRange) {
2123 llvm_unreachable("Cannot mangle injected class name type.");
2126 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2127 Qualifiers, SourceRange Range) {
2128 DiagnosticsEngine &Diags = Context.getDiags();
2129 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2130 "cannot mangle this template specialization type yet");
2131 Diags.Report(Range.getBegin(), DiagID)
2135 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2136 SourceRange Range) {
2137 DiagnosticsEngine &Diags = Context.getDiags();
2138 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2139 "cannot mangle this dependent name type yet");
2140 Diags.Report(Range.getBegin(), DiagID)
2144 void MicrosoftCXXNameMangler::mangleType(
2145 const DependentTemplateSpecializationType *T, Qualifiers,
2146 SourceRange Range) {
2147 DiagnosticsEngine &Diags = Context.getDiags();
2148 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2149 "cannot mangle this dependent template specialization type yet");
2150 Diags.Report(Range.getBegin(), DiagID)
2154 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2155 SourceRange Range) {
2156 DiagnosticsEngine &Diags = Context.getDiags();
2157 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2158 "cannot mangle this pack expansion yet");
2159 Diags.Report(Range.getBegin(), DiagID)
2163 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2164 SourceRange Range) {
2165 DiagnosticsEngine &Diags = Context.getDiags();
2166 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2167 "cannot mangle this typeof(type) yet");
2168 Diags.Report(Range.getBegin(), DiagID)
2172 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2173 SourceRange Range) {
2174 DiagnosticsEngine &Diags = Context.getDiags();
2175 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2176 "cannot mangle this typeof(expression) yet");
2177 Diags.Report(Range.getBegin(), DiagID)
2181 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2182 SourceRange Range) {
2183 DiagnosticsEngine &Diags = Context.getDiags();
2184 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2185 "cannot mangle this decltype() yet");
2186 Diags.Report(Range.getBegin(), DiagID)
2190 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2191 Qualifiers, SourceRange Range) {
2192 DiagnosticsEngine &Diags = Context.getDiags();
2193 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2194 "cannot mangle this unary transform type yet");
2195 Diags.Report(Range.getBegin(), DiagID)
2199 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2200 SourceRange Range) {
2201 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2203 DiagnosticsEngine &Diags = Context.getDiags();
2204 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2205 "cannot mangle this 'auto' type yet");
2206 Diags.Report(Range.getBegin(), DiagID)
2210 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2211 SourceRange Range) {
2212 DiagnosticsEngine &Diags = Context.getDiags();
2213 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2214 "cannot mangle this C11 atomic type yet");
2215 Diags.Report(Range.getBegin(), DiagID)
2219 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2221 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2222 "Invalid mangleName() call, argument is not a variable or function!");
2223 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2224 "Invalid mangleName() call on 'structor decl!");
2226 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2227 getASTContext().getSourceManager(),
2228 "Mangling declaration");
2230 MicrosoftCXXNameMangler Mangler(*this, Out);
2231 return Mangler.mangle(D);
2234 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2235 // <virtual-adjustment>
2236 // <no-adjustment> ::= A # private near
2237 // ::= B # private far
2238 // ::= I # protected near
2239 // ::= J # protected far
2240 // ::= Q # public near
2241 // ::= R # public far
2242 // <static-adjustment> ::= G <static-offset> # private near
2243 // ::= H <static-offset> # private far
2244 // ::= O <static-offset> # protected near
2245 // ::= P <static-offset> # protected far
2246 // ::= W <static-offset> # public near
2247 // ::= X <static-offset> # public far
2248 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2249 // ::= $1 <virtual-shift> <static-offset> # private far
2250 // ::= $2 <virtual-shift> <static-offset> # protected near
2251 // ::= $3 <virtual-shift> <static-offset> # protected far
2252 // ::= $4 <virtual-shift> <static-offset> # public near
2253 // ::= $5 <virtual-shift> <static-offset> # public far
2254 // <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2255 // <vtordisp-shift> ::= <offset-to-vtordisp>
2256 // <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2257 // <offset-to-vtordisp>
2258 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2259 const ThisAdjustment &Adjustment,
2260 MicrosoftCXXNameMangler &Mangler,
2262 if (!Adjustment.Virtual.isEmpty()) {
2265 switch (MD->getAccess()) {
2267 llvm_unreachable("Unsupported access specifier");
2277 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2278 Out << 'R' << AccessSpec;
2279 Mangler.mangleNumber(
2280 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2281 Mangler.mangleNumber(
2282 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2283 Mangler.mangleNumber(
2284 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2285 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2288 Mangler.mangleNumber(
2289 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2290 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2292 } else if (Adjustment.NonVirtual != 0) {
2293 switch (MD->getAccess()) {
2295 llvm_unreachable("Unsupported access specifier");
2305 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2307 switch (MD->getAccess()) {
2309 llvm_unreachable("Unsupported access specifier");
2323 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2325 MicrosoftVTableContext *VTContext =
2326 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2327 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2328 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2330 MicrosoftCXXNameMangler Mangler(*this, Out);
2331 Mangler.getStream() << "\01?";
2332 Mangler.mangleVirtualMemPtrThunk(MD, ML);
2335 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2336 const ThunkInfo &Thunk,
2338 MicrosoftCXXNameMangler Mangler(*this, Out);
2340 Mangler.mangleName(MD);
2341 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2342 if (!Thunk.Return.isEmpty())
2343 assert(Thunk.Method != nullptr &&
2344 "Thunk info should hold the overridee decl");
2346 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2347 Mangler.mangleFunctionType(
2348 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2351 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2352 const CXXDestructorDecl *DD, CXXDtorType Type,
2353 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2354 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2355 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2356 // mangling manually until we support both deleting dtor types.
2357 assert(Type == Dtor_Deleting);
2358 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2360 Mangler.mangleName(DD->getParent());
2361 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2362 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2365 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2366 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2368 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2369 // <cvr-qualifiers> [<name>] @
2370 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2371 // is always '6' for vftables.
2372 MicrosoftCXXNameMangler Mangler(*this, Out);
2373 Mangler.getStream() << "\01??_7";
2374 Mangler.mangleName(Derived);
2375 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2376 for (const CXXRecordDecl *RD : BasePath)
2377 Mangler.mangleName(RD);
2378 Mangler.getStream() << '@';
2381 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2382 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2384 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2385 // <cvr-qualifiers> [<name>] @
2386 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2387 // is always '7' for vbtables.
2388 MicrosoftCXXNameMangler Mangler(*this, Out);
2389 Mangler.getStream() << "\01??_8";
2390 Mangler.mangleName(Derived);
2391 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2392 for (const CXXRecordDecl *RD : BasePath)
2393 Mangler.mangleName(RD);
2394 Mangler.getStream() << '@';
2397 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2398 MicrosoftCXXNameMangler Mangler(*this, Out);
2399 Mangler.getStream() << "\01??_R0";
2400 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2401 Mangler.getStream() << "@8";
2404 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2406 MicrosoftCXXNameMangler Mangler(*this, Out);
2407 Mangler.getStream() << '.';
2408 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2411 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
2414 MicrosoftCXXNameMangler Mangler(*this, Out);
2415 Mangler.getStream() << "llvm.eh.handlertype.";
2416 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2417 Mangler.getStream() << '.' << Flags;
2420 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2421 const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2422 MicrosoftCXXNameMangler Mangler(*this, Out);
2423 Mangler.getStream() << "\01??_K";
2424 Mangler.mangleName(SrcRD);
2425 Mangler.getStream() << "$C";
2426 Mangler.mangleName(DstRD);
2429 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2432 uint32_t NumEntries,
2434 MicrosoftCXXNameMangler Mangler(*this, Out);
2435 Mangler.getStream() << "_TI";
2437 Mangler.getStream() << 'C';
2439 Mangler.getStream() << 'V';
2440 Mangler.getStream() << NumEntries;
2441 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2444 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2445 QualType T, uint32_t NumEntries, raw_ostream &Out) {
2446 MicrosoftCXXNameMangler Mangler(*this, Out);
2447 Mangler.getStream() << "_CTA";
2448 Mangler.getStream() << NumEntries;
2449 Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2452 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2453 QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2454 uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2456 MicrosoftCXXNameMangler Mangler(*this, Out);
2457 Mangler.getStream() << "_CT";
2459 llvm::SmallString<64> RTTIMangling;
2461 llvm::raw_svector_ostream Stream(RTTIMangling);
2462 mangleCXXRTTI(T, Stream);
2464 Mangler.getStream() << RTTIMangling.substr(1);
2466 // VS2015 CTP6 omits the copy-constructor in the mangled name. This name is,
2467 // in fact, superfluous but I'm not sure the change was made consciously.
2468 // TODO: Revisit this when VS2015 gets released.
2469 llvm::SmallString<64> CopyCtorMangling;
2471 llvm::raw_svector_ostream Stream(CopyCtorMangling);
2472 mangleCXXCtor(CD, CT, Stream);
2474 Mangler.getStream() << CopyCtorMangling.substr(1);
2476 Mangler.getStream() << Size;
2477 if (VBPtrOffset == -1) {
2479 Mangler.getStream() << NVOffset;
2482 Mangler.getStream() << NVOffset;
2483 Mangler.getStream() << VBPtrOffset;
2484 Mangler.getStream() << VBIndex;
2488 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2489 const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2490 uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2491 MicrosoftCXXNameMangler Mangler(*this, Out);
2492 Mangler.getStream() << "\01??_R1";
2493 Mangler.mangleNumber(NVOffset);
2494 Mangler.mangleNumber(VBPtrOffset);
2495 Mangler.mangleNumber(VBTableOffset);
2496 Mangler.mangleNumber(Flags);
2497 Mangler.mangleName(Derived);
2498 Mangler.getStream() << "8";
2501 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2502 const CXXRecordDecl *Derived, raw_ostream &Out) {
2503 MicrosoftCXXNameMangler Mangler(*this, Out);
2504 Mangler.getStream() << "\01??_R2";
2505 Mangler.mangleName(Derived);
2506 Mangler.getStream() << "8";
2509 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2510 const CXXRecordDecl *Derived, raw_ostream &Out) {
2511 MicrosoftCXXNameMangler Mangler(*this, Out);
2512 Mangler.getStream() << "\01??_R3";
2513 Mangler.mangleName(Derived);
2514 Mangler.getStream() << "8";
2517 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2518 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2520 // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2521 // <cvr-qualifiers> [<name>] @
2522 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2523 // is always '6' for vftables.
2524 MicrosoftCXXNameMangler Mangler(*this, Out);
2525 Mangler.getStream() << "\01??_R4";
2526 Mangler.mangleName(Derived);
2527 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2528 for (const CXXRecordDecl *RD : BasePath)
2529 Mangler.mangleName(RD);
2530 Mangler.getStream() << '@';
2533 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2534 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2535 MicrosoftCXXNameMangler Mangler(*this, Out);
2536 // The function body is in the same comdat as the function with the handler,
2537 // so the numbering here doesn't have to be the same across TUs.
2539 // <mangled-name> ::= ?filt$ <filter-number> @0
2540 Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2541 Mangler.mangleName(EnclosingDecl);
2544 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2545 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2546 MicrosoftCXXNameMangler Mangler(*this, Out);
2547 // The function body is in the same comdat as the function with the handler,
2548 // so the numbering here doesn't have to be the same across TUs.
2550 // <mangled-name> ::= ?fin$ <filter-number> @0
2551 Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2552 Mangler.mangleName(EnclosingDecl);
2555 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2556 // This is just a made up unique string for the purposes of tbaa. undname
2557 // does *not* know how to demangle it.
2558 MicrosoftCXXNameMangler Mangler(*this, Out);
2559 Mangler.getStream() << '?';
2560 Mangler.mangleType(T, SourceRange());
2563 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2566 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2570 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2573 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2577 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2580 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2581 "cannot mangle this reference temporary yet");
2582 getDiags().Report(VD->getLocation(), DiagID);
2585 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2586 const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2587 MicrosoftCXXNameMangler Mangler(*this, Out);
2589 Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2590 Mangler.mangleNestedName(VD);
2593 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2595 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2596 // ::= ?__J <postfix> @5 <scope-depth>
2597 // ::= ?$S <guard-num> @ <postfix> @4IA
2599 // The first mangling is what MSVC uses to guard static locals in inline
2600 // functions. It uses a different mangling in external functions to support
2601 // guarding more than 32 variables. MSVC rejects inline functions with more
2602 // than 32 static locals. We don't fully implement the second mangling
2603 // because those guards are not externally visible, and instead use LLVM's
2604 // default renaming when creating a new guard variable.
2605 MicrosoftCXXNameMangler Mangler(*this, Out);
2607 bool Visible = VD->isExternallyVisible();
2609 Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2611 Mangler.getStream() << "\01?$S1@";
2613 unsigned ScopeDepth = 0;
2614 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2615 // If we do not have a discriminator and are emitting a guard variable for
2616 // use at global scope, then mangling the nested name will not be enough to
2617 // remove ambiguities.
2618 Mangler.mangle(VD, "");
2620 Mangler.mangleNestedName(VD);
2621 Mangler.getStream() << (Visible ? "@5" : "@4IA");
2623 Mangler.mangleNumber(ScopeDepth);
2626 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2629 MicrosoftCXXNameMangler Mangler(*this, Out);
2630 Mangler.getStream() << "\01??__" << CharCode;
2631 Mangler.mangleName(D);
2632 if (D->isStaticDataMember()) {
2633 Mangler.mangleVariableEncoding(D);
2634 Mangler.getStream() << '@';
2636 // This is the function class mangling. These stubs are global, non-variadic,
2637 // cdecl functions that return void and take no args.
2638 Mangler.getStream() << "YAXXZ";
2641 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2643 // <initializer-name> ::= ?__E <name> YAXXZ
2644 mangleInitFiniStub(D, Out, 'E');
2648 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2650 // <destructor-name> ::= ?__F <name> YAXXZ
2651 mangleInitFiniStub(D, Out, 'F');
2654 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2656 // <char-type> ::= 0 # char
2658 // ::= ??? # char16_t/char32_t will need a mangling too...
2660 // <literal-length> ::= <non-negative integer> # the length of the literal
2662 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
2663 // # null-terminator
2665 // <encoded-string> ::= <simple character> # uninteresting character
2666 // ::= '?$' <hex digit> <hex digit> # these two nibbles
2667 // # encode the byte for the
2669 // ::= '?' [a-z] # \xe1 - \xfa
2670 // ::= '?' [A-Z] # \xc1 - \xda
2671 // ::= '?' [0-9] # [,/\:. \n\t'-]
2673 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2674 // <encoded-string> '@'
2675 MicrosoftCXXNameMangler Mangler(*this, Out);
2676 Mangler.getStream() << "\01??_C@_";
2678 // <char-type>: The "kind" of string literal is encoded into the mangled name.
2680 Mangler.getStream() << '1';
2682 Mangler.getStream() << '0';
2684 // <literal-length>: The next part of the mangled name consists of the length
2686 // The StringLiteral does not consider the NUL terminator byte(s) but the
2688 // N.B. The length is in terms of bytes, not characters.
2689 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2691 // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2692 // properties of our CRC:
2698 // XorOut : 00000000
2700 uint32_t CRC = 0xFFFFFFFFU;
2702 auto UpdateCRC = [&CRC](char Byte) {
2703 for (unsigned i = 0; i < 8; ++i) {
2704 bool Bit = CRC & 0x80000000U;
2705 if (Byte & (1U << i))
2713 auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2714 unsigned CharByteWidth = SL->getCharByteWidth();
2715 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2716 unsigned OffsetInCodeUnit = Index % CharByteWidth;
2717 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2720 auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2721 unsigned CharByteWidth = SL->getCharByteWidth();
2722 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2723 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2724 return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2727 // CRC all the bytes of the StringLiteral.
2728 for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2729 UpdateCRC(GetLittleEndianByte(I));
2731 // The NUL terminator byte(s) were not present earlier,
2732 // we need to manually process those bytes into the CRC.
2733 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2737 // The literature refers to the process of reversing the bits in the final CRC
2738 // output as "reflection".
2739 CRC = llvm::reverseBits(CRC);
2741 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2743 Mangler.mangleNumber(CRC);
2745 // <encoded-string>: The mangled name also contains the first 32 _characters_
2746 // (including null-terminator bytes) of the StringLiteral.
2747 // Each character is encoded by splitting them into bytes and then encoding
2748 // the constituent bytes.
2749 auto MangleByte = [&Mangler](char Byte) {
2750 // There are five different manglings for characters:
2751 // - [a-zA-Z0-9_$]: A one-to-one mapping.
2752 // - ?[a-z]: The range from \xe1 to \xfa.
2753 // - ?[A-Z]: The range from \xc1 to \xda.
2754 // - ?[0-9]: The set of [,/\:. \n\t'-].
2755 // - ?$XX: A fallback which maps nibbles.
2756 if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2757 Mangler.getStream() << Byte;
2758 } else if (isLetter(Byte & 0x7f)) {
2759 Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2761 const char SpecialChars[] = {',', '/', '\\', ':', '.',
2762 ' ', '\n', '\t', '\'', '-'};
2764 std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2765 if (Pos != std::end(SpecialChars)) {
2766 Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2768 Mangler.getStream() << "?$";
2769 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2770 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2775 // Enforce our 32 character max.
2776 unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2777 for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2780 MangleByte(GetBigEndianByte(I));
2782 MangleByte(GetLittleEndianByte(I));
2784 // Encode the NUL terminator if there is room.
2785 if (NumCharsToMangle < 32)
2786 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2790 Mangler.getStream() << '@';
2793 void MicrosoftMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
2795 if (!RD->isExternallyVisible()) {
2796 // This part of the identifier needs to be unique across all translation
2797 // units in the linked program. The scheme fails if multiple translation
2798 // units are compiled using the same relative source file path, or if
2799 // multiple translation units are built from the same source file.
2800 SourceManager &SM = getASTContext().getSourceManager();
2801 Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
2804 MicrosoftCXXNameMangler mangler(*this, Out);
2805 mangler.mangleName(RD);
2808 MicrosoftMangleContext *
2809 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2810 return new MicrosoftMangleContextImpl(Context, Diags);