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

source code of clang/lib/AST/MicrosoftMangle.cpp