Bug Summary

File:clang/lib/AST/MicrosoftMangle.cpp
Warning:line 2791, 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 -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/AST/MicrosoftMangle.cpp

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

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include/clang/AST/TypeNodes.inc

1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* An x-macro database of Clang type nodes *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* *|
7\*===----------------------------------------------------------------------===*/
8
9#ifndef ABSTRACT_TYPE
10# define ABSTRACT_TYPE(Class, Base) TYPE(Class, Base)
11#endif
12#ifndef NON_CANONICAL_TYPE
13# define NON_CANONICAL_TYPE(Class, Base) TYPE(Class, Base)
14#endif
15#ifndef DEPENDENT_TYPE
16# define DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
17#endif
18#ifndef NON_CANONICAL_UNLESS_DEPENDENT_TYPE
19# define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
20#endif
21NON_CANONICAL_TYPE(Adjusted, Type)
22NON_CANONICAL_TYPE(Decayed, AdjustedType)
23ABSTRACT_TYPE(Array, Type)
24TYPE(ConstantArray, ArrayType)
25DEPENDENT_TYPE(DependentSizedArray, ArrayType)
26TYPE(IncompleteArray, ArrayType)
27TYPE(VariableArray, ArrayType)
28TYPE(Atomic, Type)
29NON_CANONICAL_TYPE(Attributed, Type)
30TYPE(BlockPointer, Type)
31TYPE(Builtin, Type)
32TYPE(Complex, Type)
33NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Decltype, Type)
34ABSTRACT_TYPE(Deduced, Type)
35TYPE(Auto, DeducedType)
36TYPE(DeducedTemplateSpecialization, DeducedType)
37DEPENDENT_TYPE(DependentAddressSpace, Type)
38DEPENDENT_TYPE(DependentExtInt, Type)
39DEPENDENT_TYPE(DependentName, Type)
40DEPENDENT_TYPE(DependentSizedExtVector, Type)
41DEPENDENT_TYPE(DependentTemplateSpecialization, Type)
42DEPENDENT_TYPE(DependentVector, Type)
43NON_CANONICAL_TYPE(Elaborated, Type)
44TYPE(ExtInt, Type)
45ABSTRACT_TYPE(Function, Type)
46TYPE(FunctionNoProto, FunctionType)
47TYPE(FunctionProto, FunctionType)
48DEPENDENT_TYPE(InjectedClassName, Type)
49NON_CANONICAL_TYPE(MacroQualified, Type)
50ABSTRACT_TYPE(Matrix, Type)
51TYPE(ConstantMatrix, MatrixType)
52DEPENDENT_TYPE(DependentSizedMatrix, MatrixType)
53TYPE(MemberPointer, Type)
54TYPE(ObjCObjectPointer, Type)
55TYPE(ObjCObject, Type)
20
'ty' is a 'ObjCObjectType'
21
Calling 'MicrosoftCXXNameMangler::mangleType'
56TYPE(ObjCInterface, ObjCObjectType)
57NON_CANONICAL_TYPE(ObjCTypeParam, Type)
58DEPENDENT_TYPE(PackExpansion, Type)
59NON_CANONICAL_TYPE(Paren, Type)
60TYPE(Pipe, Type)
61TYPE(Pointer, Type)
62ABSTRACT_TYPE(Reference, Type)
63TYPE(LValueReference, ReferenceType)
64TYPE(RValueReference, ReferenceType)
65DEPENDENT_TYPE(SubstTemplateTypeParmPack, Type)
66NON_CANONICAL_TYPE(SubstTemplateTypeParm, Type)
67ABSTRACT_TYPE(Tag, Type)
68TYPE(Enum, TagType)
69TYPE(Record, TagType)
70NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TemplateSpecialization, Type)
71DEPENDENT_TYPE(TemplateTypeParm, Type)
72NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOfExpr, Type)
73NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOf, Type)
74NON_CANONICAL_TYPE(Typedef, Type)
75NON_CANONICAL_UNLESS_DEPENDENT_TYPE(UnaryTransform, Type)
76DEPENDENT_TYPE(UnresolvedUsing, Type)
77TYPE(Vector, Type)
78TYPE(ExtVector, VectorType)
79#ifdef LAST_TYPE
80LAST_TYPE(ExtVector)
81#undef LAST_TYPE
82#endif
83#ifdef LEAF_TYPE
84LEAF_TYPE(Builtin)
85LEAF_TYPE(Enum)
86LEAF_TYPE(InjectedClassName)
87LEAF_TYPE(ObjCInterface)
88LEAF_TYPE(Record)
89LEAF_TYPE(TemplateTypeParm)
90#undef LEAF_TYPE
91#endif
92#undef TYPE
93#undef ABSTRACT_TYPE
94#undef ABSTRACT_TYPE
95#undef NON_CANONICAL_TYPE
96#undef DEPENDENT_TYPE
97#undef NON_CANONICAL_UNLESS_DEPENDENT_TYPE