Bug Summary

File:clang/lib/AST/MicrosoftMangle.cpp
Warning:line 3163, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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