Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ItaniumMangle.cpp
Warning:line 294, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ItaniumMangle.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ItaniumMangle.cpp
1//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
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// Implements C++ name mangling according to the Itanium C++ ABI,
10// which is used in GCC 3.2 and newer (and many compilers that are
11// ABI-compatible with GCC):
12//
13// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclOpenMP.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/Mangle.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/ABI.h"
31#include "clang/Basic/Module.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Thunk.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace clang;
40
41namespace {
42
43static bool isLocalContainerContext(const DeclContext *DC) {
44 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
45}
46
47static const FunctionDecl *getStructor(const FunctionDecl *fn) {
48 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
49 return ftd->getTemplatedDecl();
50
51 return fn;
52}
53
54static const NamedDecl *getStructor(const NamedDecl *decl) {
55 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
56 return (fn ? getStructor(fn) : decl);
57}
58
59static bool isLambda(const NamedDecl *ND) {
60 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
61 if (!Record)
62 return false;
63
64 return Record->isLambda();
65}
66
67static const unsigned UnknownArity = ~0U;
68
69class ItaniumMangleContextImpl : public ItaniumMangleContext {
70 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
71 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
72 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
73 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
74 NamespaceDecl *StdNamespace = nullptr;
75
76 bool NeedsUniqueInternalLinkageNames = false;
77
78public:
79 explicit ItaniumMangleContextImpl(
80 ASTContext &Context, DiagnosticsEngine &Diags,
81 DiscriminatorOverrideTy DiscriminatorOverride)
82 : ItaniumMangleContext(Context, Diags),
83 DiscriminatorOverride(DiscriminatorOverride) {}
84
85 /// @name Mangler Entry Points
86 /// @{
87
88 bool shouldMangleCXXName(const NamedDecl *D) override;
89 bool shouldMangleStringLiteral(const StringLiteral *) override {
90 return false;
91 }
92
93 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
94 void needsUniqueInternalLinkageNames() override {
95 NeedsUniqueInternalLinkageNames = true;
96 }
97
98 void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
99 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
100 raw_ostream &) override;
101 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
102 const ThisAdjustment &ThisAdjustment,
103 raw_ostream &) override;
104 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
105 raw_ostream &) override;
106 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
107 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
108 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
109 const CXXRecordDecl *Type, raw_ostream &) override;
110 void mangleCXXRTTI(QualType T, raw_ostream &) override;
111 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
112 void mangleTypeName(QualType T, raw_ostream &) override;
113
114 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
115 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
116 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
117 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
118 void mangleDynamicAtExitDestructor(const VarDecl *D,
119 raw_ostream &Out) override;
120 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
121 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
122 raw_ostream &Out) override;
123 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
124 raw_ostream &Out) override;
125 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
126 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
127 raw_ostream &) override;
128
129 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
130
131 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
132
133 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
134 // Lambda closure types are already numbered.
135 if (isLambda(ND))
136 return false;
137
138 // Anonymous tags are already numbered.
139 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
140 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
141 return false;
142 }
143
144 // Use the canonical number for externally visible decls.
145 if (ND->isExternallyVisible()) {
146 unsigned discriminator = getASTContext().getManglingNumber(ND);
147 if (discriminator == 1)
148 return false;
149 disc = discriminator - 2;
150 return true;
151 }
152
153 // Make up a reasonable number for internal decls.
154 unsigned &discriminator = Uniquifier[ND];
155 if (!discriminator) {
156 const DeclContext *DC = getEffectiveDeclContext(ND);
157 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
158 }
159 if (discriminator == 1)
160 return false;
161 disc = discriminator-2;
162 return true;
163 }
164
165 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
166 // This function matches the one in MicrosoftMangle, which returns
167 // the string that is used in lambda mangled names.
168 assert(Lambda->isLambda() && "RD must be a lambda!")(static_cast <bool> (Lambda->isLambda() && "RD must be a lambda!"
) ? void (0) : __assert_fail ("Lambda->isLambda() && \"RD must be a lambda!\""
, "clang/lib/AST/ItaniumMangle.cpp", 168, __extension__ __PRETTY_FUNCTION__
))
;
169 std::string Name("<lambda");
170 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
171 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
172 unsigned LambdaId;
173 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
174 const FunctionDecl *Func =
175 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
176
177 if (Func) {
178 unsigned DefaultArgNo =
179 Func->getNumParams() - Parm->getFunctionScopeIndex();
180 Name += llvm::utostr(DefaultArgNo);
181 Name += "_";
182 }
183
184 if (LambdaManglingNumber)
185 LambdaId = LambdaManglingNumber;
186 else
187 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
188
189 Name += llvm::utostr(LambdaId);
190 Name += '>';
191 return Name;
192 }
193
194 DiscriminatorOverrideTy getDiscriminatorOverride() const override {
195 return DiscriminatorOverride;
196 }
197
198 NamespaceDecl *getStdNamespace();
199
200 const DeclContext *getEffectiveDeclContext(const Decl *D);
201 const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
202 return getEffectiveDeclContext(cast<Decl>(DC));
203 }
204
205 bool isInternalLinkageDecl(const NamedDecl *ND);
206 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
207
208 /// @}
209};
210
211/// Manage the mangling of a single name.
212class CXXNameMangler {
213 ItaniumMangleContextImpl &Context;
214 raw_ostream &Out;
215 bool NullOut = false;
216 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
217 /// This mode is used when mangler creates another mangler recursively to
218 /// calculate ABI tags for the function return value or the variable type.
219 /// Also it is required to avoid infinite recursion in some cases.
220 bool DisableDerivedAbiTags = false;
221
222 /// The "structor" is the top-level declaration being mangled, if
223 /// that's not a template specialization; otherwise it's the pattern
224 /// for that specialization.
225 const NamedDecl *Structor;
226 unsigned StructorType = 0;
227
228 /// The next substitution sequence number.
229 unsigned SeqID = 0;
230
231 class FunctionTypeDepthState {
232 unsigned Bits;
233
234 enum { InResultTypeMask = 1 };
235
236 public:
237 FunctionTypeDepthState() : Bits(0) {}
238
239 /// The number of function types we're inside.
240 unsigned getDepth() const {
241 return Bits >> 1;
242 }
243
244 /// True if we're in the return type of the innermost function type.
245 bool isInResultType() const {
246 return Bits & InResultTypeMask;
247 }
248
249 FunctionTypeDepthState push() {
250 FunctionTypeDepthState tmp = *this;
251 Bits = (Bits & ~InResultTypeMask) + 2;
252 return tmp;
253 }
254
255 void enterResultType() {
256 Bits |= InResultTypeMask;
257 }
258
259 void leaveResultType() {
260 Bits &= ~InResultTypeMask;
261 }
262
263 void pop(FunctionTypeDepthState saved) {
264 assert(getDepth() == saved.getDepth() + 1)(static_cast <bool> (getDepth() == saved.getDepth() + 1
) ? void (0) : __assert_fail ("getDepth() == saved.getDepth() + 1"
, "clang/lib/AST/ItaniumMangle.cpp", 264, __extension__ __PRETTY_FUNCTION__
))
;
265 Bits = saved.Bits;
266 }
267
268 } FunctionTypeDepth;
269
270 // abi_tag is a gcc attribute, taking one or more strings called "tags".
271 // The goal is to annotate against which version of a library an object was
272 // built and to be able to provide backwards compatibility ("dual abi").
273 // For more information see docs/ItaniumMangleAbiTags.rst.
274 typedef SmallVector<StringRef, 4> AbiTagList;
275
276 // State to gather all implicit and explicit tags used in a mangled name.
277 // Must always have an instance of this while emitting any name to keep
278 // track.
279 class AbiTagState final {
280 public:
281 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
282 Parent = LinkHead;
283 LinkHead = this;
284 }
285
286 // No copy, no move.
287 AbiTagState(const AbiTagState &) = delete;
288 AbiTagState &operator=(const AbiTagState &) = delete;
289
290 ~AbiTagState() { pop(); }
291
292 void write(raw_ostream &Out, const NamedDecl *ND,
293 const AbiTagList *AdditionalAbiTags) {
294 ND = cast<NamedDecl>(ND->getCanonicalDecl());
14
Called C++ object pointer is null
295 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
296 assert((static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 298, __extension__ __PRETTY_FUNCTION__
))
297 !AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 298, __extension__ __PRETTY_FUNCTION__
))
298 "only function and variables need a list of additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "only function and variables need a list of additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"only function and variables need a list of additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 298, __extension__ __PRETTY_FUNCTION__
))
;
299 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
300 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
301 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
302 AbiTag->tags().end());
303 }
304 // Don't emit abi tags for namespaces.
305 return;
306 }
307 }
308
309 AbiTagList TagList;
310 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
311 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
312 AbiTag->tags().end());
313 TagList.insert(TagList.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 }
316
317 if (AdditionalAbiTags) {
318 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
319 AdditionalAbiTags->end());
320 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 }
323
324 llvm::sort(TagList);
325 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
326
327 writeSortedUniqueAbiTags(Out, TagList);
328 }
329
330 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
331 void setUsedAbiTags(const AbiTagList &AbiTags) {
332 UsedAbiTags = AbiTags;
333 }
334
335 const AbiTagList &getEmittedAbiTags() const {
336 return EmittedAbiTags;
337 }
338
339 const AbiTagList &getSortedUniqueUsedAbiTags() {
340 llvm::sort(UsedAbiTags);
341 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
342 UsedAbiTags.end());
343 return UsedAbiTags;
344 }
345
346 private:
347 //! All abi tags used implicitly or explicitly.
348 AbiTagList UsedAbiTags;
349 //! All explicit abi tags (i.e. not from namespace).
350 AbiTagList EmittedAbiTags;
351
352 AbiTagState *&LinkHead;
353 AbiTagState *Parent = nullptr;
354
355 void pop() {
356 assert(LinkHead == this &&(static_cast <bool> (LinkHead == this && "abi tag link head must point to us on destruction"
) ? void (0) : __assert_fail ("LinkHead == this && \"abi tag link head must point to us on destruction\""
, "clang/lib/AST/ItaniumMangle.cpp", 357, __extension__ __PRETTY_FUNCTION__
))
357 "abi tag link head must point to us on destruction")(static_cast <bool> (LinkHead == this && "abi tag link head must point to us on destruction"
) ? void (0) : __assert_fail ("LinkHead == this && \"abi tag link head must point to us on destruction\""
, "clang/lib/AST/ItaniumMangle.cpp", 357, __extension__ __PRETTY_FUNCTION__
))
;
358 if (Parent) {
359 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
360 UsedAbiTags.begin(), UsedAbiTags.end());
361 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
362 EmittedAbiTags.begin(),
363 EmittedAbiTags.end());
364 }
365 LinkHead = Parent;
366 }
367
368 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
369 for (const auto &Tag : AbiTags) {
370 EmittedAbiTags.push_back(Tag);
371 Out << "B";
372 Out << Tag.size();
373 Out << Tag;
374 }
375 }
376 };
377
378 AbiTagState *AbiTags = nullptr;
379 AbiTagState AbiTagsRoot;
380
381 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
382 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
383
384 ASTContext &getASTContext() const { return Context.getASTContext(); }
385
386 bool isStd(const NamespaceDecl *NS);
387 bool isStdNamespace(const DeclContext *DC);
388
389 const RecordDecl *GetLocalClassDecl(const Decl *D);
390 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
391 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
392 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
393 llvm::StringRef Name, bool HasAllocator);
394
395public:
396 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
397 const NamedDecl *D = nullptr, bool NullOut_ = false)
398 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
399 AbiTagsRoot(AbiTags) {
400 // These can't be mangled without a ctor type or dtor type.
401 assert(!D || (!isa<CXXDestructorDecl>(D) &&(static_cast <bool> (!D || (!isa<CXXDestructorDecl>
(D) && !isa<CXXConstructorDecl>(D))) ? void (0)
: __assert_fail ("!D || (!isa<CXXDestructorDecl>(D) && !isa<CXXConstructorDecl>(D))"
, "clang/lib/AST/ItaniumMangle.cpp", 402, __extension__ __PRETTY_FUNCTION__
))
402 !isa<CXXConstructorDecl>(D)))(static_cast <bool> (!D || (!isa<CXXDestructorDecl>
(D) && !isa<CXXConstructorDecl>(D))) ? void (0)
: __assert_fail ("!D || (!isa<CXXDestructorDecl>(D) && !isa<CXXConstructorDecl>(D))"
, "clang/lib/AST/ItaniumMangle.cpp", 402, __extension__ __PRETTY_FUNCTION__
))
;
403 }
404 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
405 const CXXConstructorDecl *D, CXXCtorType Type)
406 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
407 AbiTagsRoot(AbiTags) {}
408 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
409 const CXXDestructorDecl *D, CXXDtorType Type)
410 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
411 AbiTagsRoot(AbiTags) {}
412
413 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
414 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
415 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
416 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
417 Substitutions(Outer.Substitutions),
418 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
419
420 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
421 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
422 NullOut = true;
423 }
424
425 raw_ostream &getStream() { return Out; }
426
427 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
428 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
429
430 void mangle(GlobalDecl GD);
431 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
432 void mangleNumber(const llvm::APSInt &I);
433 void mangleNumber(int64_t Number);
434 void mangleFloat(const llvm::APFloat &F);
435 void mangleFunctionEncoding(GlobalDecl GD);
436 void mangleSeqID(unsigned SeqID);
437 void mangleName(GlobalDecl GD);
438 void mangleType(QualType T);
439 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
440 void mangleLambdaSig(const CXXRecordDecl *Lambda);
441 void mangleModuleNamePrefix(StringRef Name);
442
443private:
444
445 bool mangleSubstitution(const NamedDecl *ND);
446 bool mangleSubstitution(QualType T);
447 bool mangleSubstitution(TemplateName Template);
448 bool mangleSubstitution(uintptr_t Ptr);
449
450 void mangleExistingSubstitution(TemplateName name);
451
452 bool mangleStandardSubstitution(const NamedDecl *ND);
453
454 void addSubstitution(const NamedDecl *ND) {
455 ND = cast<NamedDecl>(ND->getCanonicalDecl());
456
457 addSubstitution(reinterpret_cast<uintptr_t>(ND));
458 }
459 void addSubstitution(QualType T);
460 void addSubstitution(TemplateName Template);
461 void addSubstitution(uintptr_t Ptr);
462 // Destructive copy substitutions from other mangler.
463 void extendSubstitutions(CXXNameMangler* Other);
464
465 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
466 bool recursive = false);
467 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
468 DeclarationName name,
469 const TemplateArgumentLoc *TemplateArgs,
470 unsigned NumTemplateArgs,
471 unsigned KnownArity = UnknownArity);
472
473 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
474
475 void mangleNameWithAbiTags(GlobalDecl GD,
476 const AbiTagList *AdditionalAbiTags);
477 void mangleModuleName(const NamedDecl *ND);
478 void mangleTemplateName(const TemplateDecl *TD,
479 const TemplateArgument *TemplateArgs,
480 unsigned NumTemplateArgs);
481 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
482 const AbiTagList *AdditionalAbiTags) {
483 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
484 UnknownArity, AdditionalAbiTags);
485 }
486 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
487 const DeclContext *DC, unsigned KnownArity,
488 const AbiTagList *AdditionalAbiTags);
489 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
490 const AbiTagList *AdditionalAbiTags);
491 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
492 const AbiTagList *AdditionalAbiTags);
493 void mangleSourceName(const IdentifierInfo *II);
494 void mangleRegCallName(const IdentifierInfo *II);
495 void mangleDeviceStubName(const IdentifierInfo *II);
496 void mangleSourceNameWithAbiTags(
497 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
498 void mangleLocalName(GlobalDecl GD,
499 const AbiTagList *AdditionalAbiTags);
500 void mangleBlockForPrefix(const BlockDecl *Block);
501 void mangleUnqualifiedBlock(const BlockDecl *Block);
502 void mangleTemplateParamDecl(const NamedDecl *Decl);
503 void mangleLambda(const CXXRecordDecl *Lambda);
504 void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
505 const AbiTagList *AdditionalAbiTags,
506 bool NoFunction=false);
507 void mangleNestedName(const TemplateDecl *TD,
508 const TemplateArgument *TemplateArgs,
509 unsigned NumTemplateArgs);
510 void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
511 const NamedDecl *PrefixND,
512 const AbiTagList *AdditionalAbiTags);
513 void manglePrefix(NestedNameSpecifier *qualifier);
514 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
515 void manglePrefix(QualType type);
516 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
517 void mangleTemplatePrefix(TemplateName Template);
518 const NamedDecl *getClosurePrefix(const Decl *ND);
519 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
520 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
521 StringRef Prefix = "");
522 void mangleOperatorName(DeclarationName Name, unsigned Arity);
523 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
524 void mangleVendorQualifier(StringRef qualifier);
525 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
526 void mangleRefQualifier(RefQualifierKind RefQualifier);
527
528 void mangleObjCMethodName(const ObjCMethodDecl *MD);
529
530 // Declare manglers for every type class.
531#define ABSTRACT_TYPE(CLASS, PARENT)
532#define NON_CANONICAL_TYPE(CLASS, PARENT)
533#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
534#include "clang/AST/TypeNodes.inc"
535
536 void mangleType(const TagType*);
537 void mangleType(TemplateName);
538 static StringRef getCallingConvQualifierName(CallingConv CC);
539 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
540 void mangleExtFunctionInfo(const FunctionType *T);
541 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
542 const FunctionDecl *FD = nullptr);
543 void mangleNeonVectorType(const VectorType *T);
544 void mangleNeonVectorType(const DependentVectorType *T);
545 void mangleAArch64NeonVectorType(const VectorType *T);
546 void mangleAArch64NeonVectorType(const DependentVectorType *T);
547 void mangleAArch64FixedSveVectorType(const VectorType *T);
548 void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
549
550 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
551 void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
552 void mangleFixedPointLiteral();
553 void mangleNullPointer(QualType T);
554
555 void mangleMemberExprBase(const Expr *base, bool isArrow);
556 void mangleMemberExpr(const Expr *base, bool isArrow,
557 NestedNameSpecifier *qualifier,
558 NamedDecl *firstQualifierLookup,
559 DeclarationName name,
560 const TemplateArgumentLoc *TemplateArgs,
561 unsigned NumTemplateArgs,
562 unsigned knownArity);
563 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
564 void mangleInitListElements(const InitListExpr *InitList);
565 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
566 bool AsTemplateArg = false);
567 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
568 void mangleCXXDtorType(CXXDtorType T);
569
570 void mangleTemplateArgs(TemplateName TN,
571 const TemplateArgumentLoc *TemplateArgs,
572 unsigned NumTemplateArgs);
573 void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs,
574 unsigned NumTemplateArgs);
575 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
576 void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
577 void mangleTemplateArgExpr(const Expr *E);
578 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
579 bool NeedExactType = false);
580
581 void mangleTemplateParameter(unsigned Depth, unsigned Index);
582
583 void mangleFunctionParam(const ParmVarDecl *parm);
584
585 void writeAbiTags(const NamedDecl *ND,
586 const AbiTagList *AdditionalAbiTags);
587
588 // Returns sorted unique list of ABI tags.
589 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
590 // Returns sorted unique list of ABI tags.
591 AbiTagList makeVariableTypeTags(const VarDecl *VD);
592};
593
594}
595
596NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
597 if (!StdNamespace) {
598 StdNamespace = NamespaceDecl::Create(
599 getASTContext(), getASTContext().getTranslationUnitDecl(),
600 /*Inline*/ false, SourceLocation(), SourceLocation(),
601 &getASTContext().Idents.get("std"),
602 /*PrevDecl*/ nullptr);
603 StdNamespace->setImplicit();
604 }
605 return StdNamespace;
606}
607
608/// Retrieve the declaration context that should be used when mangling the given
609/// declaration.
610const DeclContext *
611ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
612 // The ABI assumes that lambda closure types that occur within
613 // default arguments live in the context of the function. However, due to
614 // the way in which Clang parses and creates function declarations, this is
615 // not the case: the lambda closure type ends up living in the context
616 // where the function itself resides, because the function declaration itself
617 // had not yet been created. Fix the context here.
618 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
619 if (RD->isLambda())
620 if (ParmVarDecl *ContextParam =
621 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
622 return ContextParam->getDeclContext();
623 }
624
625 // Perform the same check for block literals.
626 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
627 if (ParmVarDecl *ContextParam =
628 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
629 return ContextParam->getDeclContext();
630 }
631
632 // On ARM and AArch64, the va_list tag is always mangled as if in the std
633 // namespace. We do not represent va_list as actually being in the std
634 // namespace in C because this would result in incorrect debug info in C,
635 // among other things. It is important for both languages to have the same
636 // mangling in order for -fsanitize=cfi-icall to work.
637 if (D == getASTContext().getVaListTagDecl()) {
638 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
639 if (T.isARM() || T.isThumb() || T.isAArch64())
640 return getStdNamespace();
641 }
642
643 const DeclContext *DC = D->getDeclContext();
644 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
645 isa<OMPDeclareMapperDecl>(DC)) {
646 return getEffectiveDeclContext(cast<Decl>(DC));
647 }
648
649 if (const auto *VD = dyn_cast<VarDecl>(D))
650 if (VD->isExternC())
651 return getASTContext().getTranslationUnitDecl();
652
653 if (const auto *FD = dyn_cast<FunctionDecl>(D))
654 if (FD->isExternC())
655 return getASTContext().getTranslationUnitDecl();
656
657 return DC->getRedeclContext();
658}
659
660bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
661 if (ND && ND->getFormalLinkage() == InternalLinkage &&
662 !ND->isExternallyVisible() &&
663 getEffectiveDeclContext(ND)->isFileContext() &&
664 !ND->isInAnonymousNamespace())
665 return true;
666 return false;
667}
668
669// Check if this Function Decl needs a unique internal linkage name.
670bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
671 const NamedDecl *ND) {
672 if (!NeedsUniqueInternalLinkageNames || !ND)
673 return false;
674
675 const auto *FD = dyn_cast<FunctionDecl>(ND);
676 if (!FD)
677 return false;
678
679 // For C functions without prototypes, return false as their
680 // names should not be mangled.
681 if (!FD->getType()->getAs<FunctionProtoType>())
682 return false;
683
684 if (isInternalLinkageDecl(ND))
685 return true;
686
687 return false;
688}
689
690bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
691 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
692 LanguageLinkage L = FD->getLanguageLinkage();
693 // Overloadable functions need mangling.
694 if (FD->hasAttr<OverloadableAttr>())
695 return true;
696
697 // "main" is not mangled.
698 if (FD->isMain())
699 return false;
700
701 // The Windows ABI expects that we would never mangle "typical"
702 // user-defined entry points regardless of visibility or freestanding-ness.
703 //
704 // N.B. This is distinct from asking about "main". "main" has a lot of
705 // special rules associated with it in the standard while these
706 // user-defined entry points are outside of the purview of the standard.
707 // For example, there can be only one definition for "main" in a standards
708 // compliant program; however nothing forbids the existence of wmain and
709 // WinMain in the same translation unit.
710 if (FD->isMSVCRTEntryPoint())
711 return false;
712
713 // C++ functions and those whose names are not a simple identifier need
714 // mangling.
715 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
716 return true;
717
718 // C functions are not mangled.
719 if (L == CLanguageLinkage)
720 return false;
721 }
722
723 // Otherwise, no mangling is done outside C++ mode.
724 if (!getASTContext().getLangOpts().CPlusPlus)
725 return false;
726
727 if (const auto *VD = dyn_cast<VarDecl>(D)) {
728 // Decompositions are mangled.
729 if (isa<DecompositionDecl>(VD))
730 return true;
731
732 // C variables are not mangled.
733 if (VD->isExternC())
734 return false;
735
736 // Variables at global scope are not mangled unless they have internal
737 // linkage or are specializations or are attached to a named module.
738 const DeclContext *DC = getEffectiveDeclContext(D);
739 // Check for extern variable declared locally.
740 if (DC->isFunctionOrMethod() && D->hasLinkage())
741 while (!DC->isFileContext())
742 DC = getEffectiveParentContext(DC);
743 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
744 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
745 !isa<VarTemplateSpecializationDecl>(VD) &&
746 !VD->getOwningModuleForLinkage())
747 return false;
748 }
749
750 return true;
751}
752
753void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
754 const AbiTagList *AdditionalAbiTags) {
755 assert(AbiTags && "require AbiTagState")(static_cast <bool> (AbiTags && "require AbiTagState"
) ? void (0) : __assert_fail ("AbiTags && \"require AbiTagState\""
, "clang/lib/AST/ItaniumMangle.cpp", 755, __extension__ __PRETTY_FUNCTION__
))
;
8
Assuming field 'AbiTags' is non-null
9
'?' condition is true
756 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
10
Assuming field 'DisableDerivedAbiTags' is true
11
'?' condition is true
12
Passing null pointer value via 2nd parameter 'ND'
13
Calling 'AbiTagState::write'
757}
758
759void CXXNameMangler::mangleSourceNameWithAbiTags(
760 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
761 mangleSourceName(ND->getIdentifier());
762 writeAbiTags(ND, AdditionalAbiTags);
763}
764
765void CXXNameMangler::mangle(GlobalDecl GD) {
766 // <mangled-name> ::= _Z <encoding>
767 // ::= <data name>
768 // ::= <special-name>
769 Out << "_Z";
770 if (isa<FunctionDecl>(GD.getDecl()))
771 mangleFunctionEncoding(GD);
772 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
773 BindingDecl>(GD.getDecl()))
774 mangleName(GD);
775 else if (const IndirectFieldDecl *IFD =
776 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
777 mangleName(IFD->getAnonField());
778 else
779 llvm_unreachable("unexpected kind of global decl")::llvm::llvm_unreachable_internal("unexpected kind of global decl"
, "clang/lib/AST/ItaniumMangle.cpp", 779)
;
780}
781
782void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
783 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
784 // <encoding> ::= <function name> <bare-function-type>
785
786 // Don't mangle in the type if this isn't a decl we should typically mangle.
787 if (!Context.shouldMangleDeclName(FD)) {
788 mangleName(GD);
789 return;
790 }
791
792 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
793 if (ReturnTypeAbiTags.empty()) {
794 // There are no tags for return type, the simplest case.
795 mangleName(GD);
796 mangleFunctionEncodingBareType(FD);
797 return;
798 }
799
800 // Mangle function name and encoding to temporary buffer.
801 // We have to output name and encoding to the same mangler to get the same
802 // substitution as it will be in final mangling.
803 SmallString<256> FunctionEncodingBuf;
804 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
805 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
806 // Output name of the function.
807 FunctionEncodingMangler.disableDerivedAbiTags();
808 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
809
810 // Remember length of the function name in the buffer.
811 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
812 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
813
814 // Get tags from return type that are not present in function name or
815 // encoding.
816 const AbiTagList &UsedAbiTags =
817 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
818 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
819 AdditionalAbiTags.erase(
820 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
821 UsedAbiTags.begin(), UsedAbiTags.end(),
822 AdditionalAbiTags.begin()),
823 AdditionalAbiTags.end());
824
825 // Output name with implicit tags and function encoding from temporary buffer.
826 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
827 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
828
829 // Function encoding could create new substitutions so we have to add
830 // temp mangled substitutions to main mangler.
831 extendSubstitutions(&FunctionEncodingMangler);
832}
833
834void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
835 if (FD->hasAttr<EnableIfAttr>()) {
836 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
837 Out << "Ua9enable_ifI";
838 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
839 E = FD->getAttrs().end();
840 I != E; ++I) {
841 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
842 if (!EIA)
843 continue;
844 if (Context.getASTContext().getLangOpts().getClangABICompat() >
845 LangOptions::ClangABI::Ver11) {
846 mangleTemplateArgExpr(EIA->getCond());
847 } else {
848 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
849 // even though <template-arg> should not include an X/E around
850 // <expr-primary>.
851 Out << 'X';
852 mangleExpression(EIA->getCond());
853 Out << 'E';
854 }
855 }
856 Out << 'E';
857 FunctionTypeDepth.pop(Saved);
858 }
859
860 // When mangling an inheriting constructor, the bare function type used is
861 // that of the inherited constructor.
862 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
863 if (auto Inherited = CD->getInheritedConstructor())
864 FD = Inherited.getConstructor();
865
866 // Whether the mangling of a function type includes the return type depends on
867 // the context and the nature of the function. The rules for deciding whether
868 // the return type is included are:
869 //
870 // 1. Template functions (names or types) have return types encoded, with
871 // the exceptions listed below.
872 // 2. Function types not appearing as part of a function name mangling,
873 // e.g. parameters, pointer types, etc., have return type encoded, with the
874 // exceptions listed below.
875 // 3. Non-template function names do not have return types encoded.
876 //
877 // The exceptions mentioned in (1) and (2) above, for which the return type is
878 // never included, are
879 // 1. Constructors.
880 // 2. Destructors.
881 // 3. Conversion operator functions, e.g. operator int.
882 bool MangleReturnType = false;
883 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
884 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
885 isa<CXXConversionDecl>(FD)))
886 MangleReturnType = true;
887
888 // Mangle the type of the primary template.
889 FD = PrimaryTemplate->getTemplatedDecl();
890 }
891
892 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
893 MangleReturnType, FD);
894}
895
896/// Return whether a given namespace is the 'std' namespace.
897bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
898 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
899 return false;
900
901 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
902 return II && II->isStr("std");
903}
904
905// isStdNamespace - Return whether a given decl context is a toplevel 'std'
906// namespace.
907bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
908 if (!DC->isNamespace())
909 return false;
910
911 return isStd(cast<NamespaceDecl>(DC));
912}
913
914static const GlobalDecl
915isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
916 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
917 // Check if we have a function template.
918 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
919 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
920 TemplateArgs = FD->getTemplateSpecializationArgs();
921 return GD.getWithDecl(TD);
922 }
923 }
924
925 // Check if we have a class template.
926 if (const ClassTemplateSpecializationDecl *Spec =
927 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
928 TemplateArgs = &Spec->getTemplateArgs();
929 return GD.getWithDecl(Spec->getSpecializedTemplate());
930 }
931
932 // Check if we have a variable template.
933 if (const VarTemplateSpecializationDecl *Spec =
934 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
935 TemplateArgs = &Spec->getTemplateArgs();
936 return GD.getWithDecl(Spec->getSpecializedTemplate());
937 }
938
939 return GlobalDecl();
940}
941
942static TemplateName asTemplateName(GlobalDecl GD) {
943 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
944 return TemplateName(const_cast<TemplateDecl*>(TD));
945}
946
947void CXXNameMangler::mangleName(GlobalDecl GD) {
948 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
949 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
950 // Variables should have implicit tags from its type.
951 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
952 if (VariableTypeAbiTags.empty()) {
953 // Simple case no variable type tags.
954 mangleNameWithAbiTags(VD, nullptr);
955 return;
956 }
957
958 // Mangle variable name to null stream to collect tags.
959 llvm::raw_null_ostream NullOutStream;
960 CXXNameMangler VariableNameMangler(*this, NullOutStream);
961 VariableNameMangler.disableDerivedAbiTags();
962 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
963
964 // Get tags from variable type that are not present in its name.
965 const AbiTagList &UsedAbiTags =
966 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
967 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
968 AdditionalAbiTags.erase(
969 std::set_difference(VariableTypeAbiTags.begin(),
970 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
971 UsedAbiTags.end(), AdditionalAbiTags.begin()),
972 AdditionalAbiTags.end());
973
974 // Output name with implicit tags.
975 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
976 } else {
977 mangleNameWithAbiTags(GD, nullptr);
978 }
979}
980
981const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
982 const DeclContext *DC = Context.getEffectiveDeclContext(D);
983 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
984 if (isLocalContainerContext(DC))
985 return dyn_cast<RecordDecl>(D);
986 D = cast<Decl>(DC);
987 DC = Context.getEffectiveDeclContext(D);
988 }
989 return nullptr;
990}
991
992void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
993 const AbiTagList *AdditionalAbiTags) {
994 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
995 // <name> ::= [<module-name>] <nested-name>
996 // ::= [<module-name>] <unscoped-name>
997 // ::= [<module-name>] <unscoped-template-name> <template-args>
998 // ::= <local-name>
999 //
1000 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1001
1002 // If this is an extern variable declared locally, the relevant DeclContext
1003 // is that of the containing namespace, or the translation unit.
1004 // FIXME: This is a hack; extern variables declared locally should have
1005 // a proper semantic declaration context!
1006 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
1007 while (!DC->isNamespace() && !DC->isTranslationUnit())
1008 DC = Context.getEffectiveParentContext(DC);
1009 else if (GetLocalClassDecl(ND)) {
1010 mangleLocalName(GD, AdditionalAbiTags);
1011 return;
1012 }
1013
1014 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"context cannot be LinkageSpecDecl") ? void (0) : __assert_fail
("!isa<LinkageSpecDecl>(DC) && \"context cannot be LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 1014, __extension__ __PRETTY_FUNCTION__
))
;
1015
1016 if (isLocalContainerContext(DC)) {
1017 mangleLocalName(GD, AdditionalAbiTags);
1018 return;
1019 }
1020
1021 // Closures can require a nested-name mangling even if they're semantically
1022 // in the global namespace.
1023 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1024 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1025 return;
1026 }
1027
1028 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1029 // Check if we have a template.
1030 const TemplateArgumentList *TemplateArgs = nullptr;
1031 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1032 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1033 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1034 return;
1035 }
1036
1037 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1038 return;
1039 }
1040
1041 mangleNestedName(GD, DC, AdditionalAbiTags);
1042}
1043
1044void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1045 if (ND->isExternallyVisible())
1046 if (Module *M = ND->getOwningModuleForLinkage())
1047 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1048}
1049
1050// <module-name> ::= <module-subname>
1051// ::= <module-name> <module-subname>
1052// ::= <substitution>
1053// <module-subname> ::= W <source-name>
1054// ::= W P <source-name> # not (yet) needed
1055void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
1056 // <substitution> ::= S <seq-id> _
1057 auto It = ModuleSubstitutions.find(Name);
1058 if (It != ModuleSubstitutions.end()) {
1059 Out << 'S';
1060 mangleSeqID(It->second);
1061 return;
1062 }
1063
1064 // FIXME: Preserve hierarchy in module names rather than flattening
1065 // them to strings; use Module*s as substitution keys.
1066 auto Parts = Name.rsplit('.');
1067 if (Parts.second.empty())
1068 Parts.second = Parts.first;
1069 else
1070 mangleModuleNamePrefix(Parts.first);
1071
1072 Out << 'W';
1073 Out << Parts.second.size() << Parts.second;
1074 ModuleSubstitutions.insert({Name, SeqID++});
1075}
1076
1077void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1078 const TemplateArgument *TemplateArgs,
1079 unsigned NumTemplateArgs) {
1080 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1081
1082 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1083 mangleUnscopedTemplateName(TD, DC, nullptr);
1084 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
1085 } else {
1086 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
1087 }
1088}
1089
1090void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1091 const AbiTagList *AdditionalAbiTags) {
1092 // <unscoped-name> ::= <unqualified-name>
1093 // ::= St <unqualified-name> # ::std::
1094
1095 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"unskipped LinkageSpecDecl") ? void (0) : __assert_fail ("!isa<LinkageSpecDecl>(DC) && \"unskipped LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 1095, __extension__ __PRETTY_FUNCTION__
))
;
1096 if (isStdNamespace(DC))
1097 Out << "St";
1098
1099 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1100}
1101
1102void CXXNameMangler::mangleUnscopedTemplateName(
1103 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1104 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1105 // <unscoped-template-name> ::= <unscoped-name>
1106 // ::= <substitution>
1107 if (mangleSubstitution(ND))
1108 return;
1109
1110 // <template-template-param> ::= <template-param>
1111 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1112 assert(!AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "template template param cannot have abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"template template param cannot have abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1113, __extension__ __PRETTY_FUNCTION__
))
1113 "template template param cannot have abi tags")(static_cast <bool> (!AdditionalAbiTags && "template template param cannot have abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"template template param cannot have abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1113, __extension__ __PRETTY_FUNCTION__
))
;
1114 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1115 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1116 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1117 } else {
1118 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1119 AdditionalAbiTags);
1120 }
1121
1122 addSubstitution(ND);
1123}
1124
1125void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1126 // ABI:
1127 // Floating-point literals are encoded using a fixed-length
1128 // lowercase hexadecimal string corresponding to the internal
1129 // representation (IEEE on Itanium), high-order bytes first,
1130 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1131 // on Itanium.
1132 // The 'without leading zeroes' thing seems to be an editorial
1133 // mistake; see the discussion on cxx-abi-dev beginning on
1134 // 2012-01-16.
1135
1136 // Our requirements here are just barely weird enough to justify
1137 // using a custom algorithm instead of post-processing APInt::toString().
1138
1139 llvm::APInt valueBits = f.bitcastToAPInt();
1140 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1141 assert(numCharacters != 0)(static_cast <bool> (numCharacters != 0) ? void (0) : __assert_fail
("numCharacters != 0", "clang/lib/AST/ItaniumMangle.cpp", 1141
, __extension__ __PRETTY_FUNCTION__))
;
1142
1143 // Allocate a buffer of the right number of characters.
1144 SmallVector<char, 20> buffer(numCharacters);
1145
1146 // Fill the buffer left-to-right.
1147 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1148 // The bit-index of the next hex digit.
1149 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1150
1151 // Project out 4 bits starting at 'digitIndex'.
1152 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1153 hexDigit >>= (digitBitIndex % 64);
1154 hexDigit &= 0xF;
1155
1156 // Map that over to a lowercase hex digit.
1157 static const char charForHex[16] = {
1158 '0', '1', '2', '3', '4', '5', '6', '7',
1159 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1160 };
1161 buffer[stringIndex] = charForHex[hexDigit];
1162 }
1163
1164 Out.write(buffer.data(), numCharacters);
1165}
1166
1167void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1168 Out << 'L';
1169 mangleType(T);
1170 mangleFloat(V);
1171 Out << 'E';
1172}
1173
1174void CXXNameMangler::mangleFixedPointLiteral() {
1175 DiagnosticsEngine &Diags = Context.getDiags();
1176 unsigned DiagID = Diags.getCustomDiagID(
1177 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1178 Diags.Report(DiagID);
1179}
1180
1181void CXXNameMangler::mangleNullPointer(QualType T) {
1182 // <expr-primary> ::= L <type> 0 E
1183 Out << 'L';
1184 mangleType(T);
1185 Out << "0E";
1186}
1187
1188void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1189 if (Value.isSigned() && Value.isNegative()) {
1190 Out << 'n';
1191 Value.abs().print(Out, /*signed*/ false);
1192 } else {
1193 Value.print(Out, /*signed*/ false);
1194 }
1195}
1196
1197void CXXNameMangler::mangleNumber(int64_t Number) {
1198 // <number> ::= [n] <non-negative decimal integer>
1199 if (Number < 0) {
1200 Out << 'n';
1201 Number = -Number;
1202 }
1203
1204 Out << Number;
1205}
1206
1207void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1208 // <call-offset> ::= h <nv-offset> _
1209 // ::= v <v-offset> _
1210 // <nv-offset> ::= <offset number> # non-virtual base override
1211 // <v-offset> ::= <offset number> _ <virtual offset number>
1212 // # virtual base override, with vcall offset
1213 if (!Virtual) {
1214 Out << 'h';
1215 mangleNumber(NonVirtual);
1216 Out << '_';
1217 return;
1218 }
1219
1220 Out << 'v';
1221 mangleNumber(NonVirtual);
1222 Out << '_';
1223 mangleNumber(Virtual);
1224 Out << '_';
1225}
1226
1227void CXXNameMangler::manglePrefix(QualType type) {
1228 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1229 if (!mangleSubstitution(QualType(TST, 0))) {
1230 mangleTemplatePrefix(TST->getTemplateName());
1231
1232 // FIXME: GCC does not appear to mangle the template arguments when
1233 // the template in question is a dependent template name. Should we
1234 // emulate that badness?
1235 mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
1236 TST->getNumArgs());
1237 addSubstitution(QualType(TST, 0));
1238 }
1239 } else if (const auto *DTST =
1240 type->getAs<DependentTemplateSpecializationType>()) {
1241 if (!mangleSubstitution(QualType(DTST, 0))) {
1242 TemplateName Template = getASTContext().getDependentTemplateName(
1243 DTST->getQualifier(), DTST->getIdentifier());
1244 mangleTemplatePrefix(Template);
1245
1246 // FIXME: GCC does not appear to mangle the template arguments when
1247 // the template in question is a dependent template name. Should we
1248 // emulate that badness?
1249 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
1250 addSubstitution(QualType(DTST, 0));
1251 }
1252 } else {
1253 // We use the QualType mangle type variant here because it handles
1254 // substitutions.
1255 mangleType(type);
1256 }
1257}
1258
1259/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1260///
1261/// \param recursive - true if this is being called recursively,
1262/// i.e. if there is more prefix "to the right".
1263void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1264 bool recursive) {
1265
1266 // x, ::x
1267 // <unresolved-name> ::= [gs] <base-unresolved-name>
1268
1269 // T::x / decltype(p)::x
1270 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1271
1272 // T::N::x /decltype(p)::N::x
1273 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1274 // <base-unresolved-name>
1275
1276 // A::x, N::y, A<T>::z; "gs" means leading "::"
1277 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1278 // <base-unresolved-name>
1279
1280 switch (qualifier->getKind()) {
1281 case NestedNameSpecifier::Global:
1282 Out << "gs";
1283
1284 // We want an 'sr' unless this is the entire NNS.
1285 if (recursive)
1286 Out << "sr";
1287
1288 // We never want an 'E' here.
1289 return;
1290
1291 case NestedNameSpecifier::Super:
1292 llvm_unreachable("Can't mangle __super specifier")::llvm::llvm_unreachable_internal("Can't mangle __super specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 1292)
;
1293
1294 case NestedNameSpecifier::Namespace:
1295 if (qualifier->getPrefix())
1296 mangleUnresolvedPrefix(qualifier->getPrefix(),
1297 /*recursive*/ true);
1298 else
1299 Out << "sr";
1300 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1301 break;
1302 case NestedNameSpecifier::NamespaceAlias:
1303 if (qualifier->getPrefix())
1304 mangleUnresolvedPrefix(qualifier->getPrefix(),
1305 /*recursive*/ true);
1306 else
1307 Out << "sr";
1308 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1309 break;
1310
1311 case NestedNameSpecifier::TypeSpec:
1312 case NestedNameSpecifier::TypeSpecWithTemplate: {
1313 const Type *type = qualifier->getAsType();
1314
1315 // We only want to use an unresolved-type encoding if this is one of:
1316 // - a decltype
1317 // - a template type parameter
1318 // - a template template parameter with arguments
1319 // In all of these cases, we should have no prefix.
1320 if (qualifier->getPrefix()) {
1321 mangleUnresolvedPrefix(qualifier->getPrefix(),
1322 /*recursive*/ true);
1323 } else {
1324 // Otherwise, all the cases want this.
1325 Out << "sr";
1326 }
1327
1328 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1329 return;
1330
1331 break;
1332 }
1333
1334 case NestedNameSpecifier::Identifier:
1335 // Member expressions can have these without prefixes.
1336 if (qualifier->getPrefix())
1337 mangleUnresolvedPrefix(qualifier->getPrefix(),
1338 /*recursive*/ true);
1339 else
1340 Out << "sr";
1341
1342 mangleSourceName(qualifier->getAsIdentifier());
1343 // An Identifier has no type information, so we can't emit abi tags for it.
1344 break;
1345 }
1346
1347 // If this was the innermost part of the NNS, and we fell out to
1348 // here, append an 'E'.
1349 if (!recursive)
1350 Out << 'E';
1351}
1352
1353/// Mangle an unresolved-name, which is generally used for names which
1354/// weren't resolved to specific entities.
1355void CXXNameMangler::mangleUnresolvedName(
1356 NestedNameSpecifier *qualifier, DeclarationName name,
1357 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1358 unsigned knownArity) {
1359 if (qualifier) mangleUnresolvedPrefix(qualifier);
1360 switch (name.getNameKind()) {
1361 // <base-unresolved-name> ::= <simple-id>
1362 case DeclarationName::Identifier:
1363 mangleSourceName(name.getAsIdentifierInfo());
1364 break;
1365 // <base-unresolved-name> ::= dn <destructor-name>
1366 case DeclarationName::CXXDestructorName:
1367 Out << "dn";
1368 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1369 break;
1370 // <base-unresolved-name> ::= on <operator-name>
1371 case DeclarationName::CXXConversionFunctionName:
1372 case DeclarationName::CXXLiteralOperatorName:
1373 case DeclarationName::CXXOperatorName:
1374 Out << "on";
1375 mangleOperatorName(name, knownArity);
1376 break;
1377 case DeclarationName::CXXConstructorName:
1378 llvm_unreachable("Can't mangle a constructor name!")::llvm::llvm_unreachable_internal("Can't mangle a constructor name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1378)
;
1379 case DeclarationName::CXXUsingDirective:
1380 llvm_unreachable("Can't mangle a using directive name!")::llvm::llvm_unreachable_internal("Can't mangle a using directive name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1380)
;
1381 case DeclarationName::CXXDeductionGuideName:
1382 llvm_unreachable("Can't mangle a deduction guide name!")::llvm::llvm_unreachable_internal("Can't mangle a deduction guide name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1382)
;
1383 case DeclarationName::ObjCMultiArgSelector:
1384 case DeclarationName::ObjCOneArgSelector:
1385 case DeclarationName::ObjCZeroArgSelector:
1386 llvm_unreachable("Can't mangle Objective-C selector names here!")::llvm::llvm_unreachable_internal("Can't mangle Objective-C selector names here!"
, "clang/lib/AST/ItaniumMangle.cpp", 1386)
;
1387 }
1388
1389 // The <simple-id> and on <operator-name> productions end in an optional
1390 // <template-args>.
1391 if (TemplateArgs)
1392 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1393}
1394
1395void CXXNameMangler::mangleUnqualifiedName(
1396 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1397 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1398 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1
Assuming null pointer is passed into cast
2
'ND' initialized to a null pointer value
1399 // <unqualified-name> ::= [<module-name>] <operator-name>
1400 // ::= <ctor-dtor-name>
1401 // ::= [<module-name>] <source-name>
1402 // ::= [<module-name>] DC <source-name>* E
1403
1404 if (ND
2.1
'ND' is null
&& DC && DC->isFileContext())
1405 mangleModuleName(ND);
1406
1407 unsigned Arity = KnownArity;
1408 switch (Name.getNameKind()) {
3
Control jumps to 'case CXXDestructorName:' at line 1628
1409 case DeclarationName::Identifier: {
1410 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1411
1412 // We mangle decomposition declarations as the names of their bindings.
1413 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1414 // FIXME: Non-standard mangling for decomposition declarations:
1415 //
1416 // <unqualified-name> ::= DC <source-name>* E
1417 //
1418 // Proposed on cxx-abi-dev on 2016-08-12
1419 Out << "DC";
1420 for (auto *BD : DD->bindings())
1421 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1422 Out << 'E';
1423 writeAbiTags(ND, AdditionalAbiTags);
1424 break;
1425 }
1426
1427 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1428 // We follow MSVC in mangling GUID declarations as if they were variables
1429 // with a particular reserved name. Continue the pretense here.
1430 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1431 llvm::raw_svector_ostream GUIDOS(GUID);
1432 Context.mangleMSGuidDecl(GD, GUIDOS);
1433 Out << GUID.size() << GUID;
1434 break;
1435 }
1436
1437 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1438 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1439 Out << "TA";
1440 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1441 TPO->getValue(), /*TopLevel=*/true);
1442 break;
1443 }
1444
1445 if (II) {
1446 // Match GCC's naming convention for internal linkage symbols, for
1447 // symbols that are not actually visible outside of this TU. GCC
1448 // distinguishes between internal and external linkage symbols in
1449 // its mangling, to support cases like this that were valid C++ prior
1450 // to DR426:
1451 //
1452 // void test() { extern void foo(); }
1453 // static void foo();
1454 //
1455 // Don't bother with the L marker for names in anonymous namespaces; the
1456 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1457 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1458 // implying internal linkage.
1459 if (Context.isInternalLinkageDecl(ND))
1460 Out << 'L';
1461
1462 auto *FD = dyn_cast<FunctionDecl>(ND);
1463 bool IsRegCall = FD &&
1464 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1465 clang::CC_X86RegCall;
1466 bool IsDeviceStub =
1467 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1468 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1469 if (IsDeviceStub)
1470 mangleDeviceStubName(II);
1471 else if (IsRegCall)
1472 mangleRegCallName(II);
1473 else
1474 mangleSourceName(II);
1475
1476 writeAbiTags(ND, AdditionalAbiTags);
1477 break;
1478 }
1479
1480 // Otherwise, an anonymous entity. We must have a declaration.
1481 assert(ND && "mangling empty name without declaration")(static_cast <bool> (ND && "mangling empty name without declaration"
) ? void (0) : __assert_fail ("ND && \"mangling empty name without declaration\""
, "clang/lib/AST/ItaniumMangle.cpp", 1481, __extension__ __PRETTY_FUNCTION__
))
;
1482
1483 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1484 if (NS->isAnonymousNamespace()) {
1485 // This is how gcc mangles these names.
1486 Out << "12_GLOBAL__N_1";
1487 break;
1488 }
1489 }
1490
1491 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1492 // We must have an anonymous union or struct declaration.
1493 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1494
1495 // Itanium C++ ABI 5.1.2:
1496 //
1497 // For the purposes of mangling, the name of an anonymous union is
1498 // considered to be the name of the first named data member found by a
1499 // pre-order, depth-first, declaration-order walk of the data members of
1500 // the anonymous union. If there is no such data member (i.e., if all of
1501 // the data members in the union are unnamed), then there is no way for
1502 // a program to refer to the anonymous union, and there is therefore no
1503 // need to mangle its name.
1504 assert(RD->isAnonymousStructOrUnion()(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"Expected anonymous struct or union!") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"Expected anonymous struct or union!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1505, __extension__ __PRETTY_FUNCTION__
))
1505 && "Expected anonymous struct or union!")(static_cast <bool> (RD->isAnonymousStructOrUnion() &&
"Expected anonymous struct or union!") ? void (0) : __assert_fail
("RD->isAnonymousStructOrUnion() && \"Expected anonymous struct or union!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1505, __extension__ __PRETTY_FUNCTION__
))
;
1506 const FieldDecl *FD = RD->findFirstNamedDataMember();
1507
1508 // It's actually possible for various reasons for us to get here
1509 // with an empty anonymous struct / union. Fortunately, it
1510 // doesn't really matter what name we generate.
1511 if (!FD) break;
1512 assert(FD->getIdentifier() && "Data member name isn't an identifier!")(static_cast <bool> (FD->getIdentifier() && "Data member name isn't an identifier!"
) ? void (0) : __assert_fail ("FD->getIdentifier() && \"Data member name isn't an identifier!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1512, __extension__ __PRETTY_FUNCTION__
))
;
1513
1514 mangleSourceName(FD->getIdentifier());
1515 // Not emitting abi tags: internal name anyway.
1516 break;
1517 }
1518
1519 // Class extensions have no name as a category, and it's possible
1520 // for them to be the semantic parent of certain declarations
1521 // (primarily, tag decls defined within declarations). Such
1522 // declarations will always have internal linkage, so the name
1523 // doesn't really matter, but we shouldn't crash on them. For
1524 // safety, just handle all ObjC containers here.
1525 if (isa<ObjCContainerDecl>(ND))
1526 break;
1527
1528 // We must have an anonymous struct.
1529 const TagDecl *TD = cast<TagDecl>(ND);
1530 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1531 assert(TD->getDeclContext() == D->getDeclContext() &&(static_cast <bool> (TD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("TD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1532, __extension__ __PRETTY_FUNCTION__
))
1532 "Typedef should not be in another decl context!")(static_cast <bool> (TD->getDeclContext() == D->getDeclContext
() && "Typedef should not be in another decl context!"
) ? void (0) : __assert_fail ("TD->getDeclContext() == D->getDeclContext() && \"Typedef should not be in another decl context!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1532, __extension__ __PRETTY_FUNCTION__
))
;
1533 assert(D->getDeclName().getAsIdentifierInfo() &&(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1534, __extension__ __PRETTY_FUNCTION__
))
1534 "Typedef was not named!")(static_cast <bool> (D->getDeclName().getAsIdentifierInfo
() && "Typedef was not named!") ? void (0) : __assert_fail
("D->getDeclName().getAsIdentifierInfo() && \"Typedef was not named!\""
, "clang/lib/AST/ItaniumMangle.cpp", 1534, __extension__ __PRETTY_FUNCTION__
))
;
1535 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1536 assert(!AdditionalAbiTags && "Type cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1536, __extension__ __PRETTY_FUNCTION__
))
;
1537 // Explicit abi tags are still possible; take from underlying type, not
1538 // from typedef.
1539 writeAbiTags(TD, nullptr);
1540 break;
1541 }
1542
1543 // <unnamed-type-name> ::= <closure-type-name>
1544 //
1545 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1546 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1547 // # Parameter types or 'v' for 'void'.
1548 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1549 llvm::Optional<unsigned> DeviceNumber =
1550 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1551
1552 // If we have a device-number via the discriminator, use that to mangle
1553 // the lambda, otherwise use the typical lambda-mangling-number. In either
1554 // case, a '0' should be mangled as a normal unnamed class instead of as a
1555 // lambda.
1556 if (Record->isLambda() &&
1557 ((DeviceNumber && *DeviceNumber > 0) ||
1558 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1559 assert(!AdditionalAbiTags &&(static_cast <bool> (!AdditionalAbiTags && "Lambda type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Lambda type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1560, __extension__ __PRETTY_FUNCTION__
))
1560 "Lambda type cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Lambda type cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Lambda type cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1560, __extension__ __PRETTY_FUNCTION__
))
;
1561 mangleLambda(Record);
1562 break;
1563 }
1564 }
1565
1566 if (TD->isExternallyVisible()) {
1567 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1568 Out << "Ut";
1569 if (UnnamedMangle > 1)
1570 Out << UnnamedMangle - 2;
1571 Out << '_';
1572 writeAbiTags(TD, AdditionalAbiTags);
1573 break;
1574 }
1575
1576 // Get a unique id for the anonymous struct. If it is not a real output
1577 // ID doesn't matter so use fake one.
1578 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1579
1580 // Mangle it as a source name in the form
1581 // [n] $_<id>
1582 // where n is the length of the string.
1583 SmallString<8> Str;
1584 Str += "$_";
1585 Str += llvm::utostr(AnonStructId);
1586
1587 Out << Str.size();
1588 Out << Str;
1589 break;
1590 }
1591
1592 case DeclarationName::ObjCZeroArgSelector:
1593 case DeclarationName::ObjCOneArgSelector:
1594 case DeclarationName::ObjCMultiArgSelector:
1595 llvm_unreachable("Can't mangle Objective-C selector names here!")::llvm::llvm_unreachable_internal("Can't mangle Objective-C selector names here!"
, "clang/lib/AST/ItaniumMangle.cpp", 1595)
;
1596
1597 case DeclarationName::CXXConstructorName: {
1598 const CXXRecordDecl *InheritedFrom = nullptr;
1599 TemplateName InheritedTemplateName;
1600 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1601 if (auto Inherited =
1602 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1603 InheritedFrom = Inherited.getConstructor()->getParent();
1604 InheritedTemplateName =
1605 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1606 InheritedTemplateArgs =
1607 Inherited.getConstructor()->getTemplateSpecializationArgs();
1608 }
1609
1610 if (ND == Structor)
1611 // If the named decl is the C++ constructor we're mangling, use the type
1612 // we were given.
1613 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1614 else
1615 // Otherwise, use the complete constructor name. This is relevant if a
1616 // class with a constructor is declared within a constructor.
1617 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1618
1619 // FIXME: The template arguments are part of the enclosing prefix or
1620 // nested-name, but it's more convenient to mangle them here.
1621 if (InheritedTemplateArgs)
1622 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1623
1624 writeAbiTags(ND, AdditionalAbiTags);
1625 break;
1626 }
1627
1628 case DeclarationName::CXXDestructorName:
1629 if (ND == Structor)
4
Assuming 'ND' is not equal to field 'Structor'
5
Taking false branch
1630 // If the named decl is the C++ destructor we're mangling, use the type we
1631 // were given.
1632 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1633 else
1634 // Otherwise, use the complete destructor name. This is relevant if a
1635 // class with a destructor is declared within a destructor.
1636 mangleCXXDtorType(Dtor_Complete);
1637 writeAbiTags(ND, AdditionalAbiTags);
6
Passing null pointer value via 1st parameter 'ND'
7
Calling 'CXXNameMangler::writeAbiTags'
1638 break;
1639
1640 case DeclarationName::CXXOperatorName:
1641 if (ND && Arity == UnknownArity) {
1642 Arity = cast<FunctionDecl>(ND)->getNumParams();
1643
1644 // If we have a member function, we need to include the 'this' pointer.
1645 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1646 if (!MD->isStatic())
1647 Arity++;
1648 }
1649 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1650 case DeclarationName::CXXConversionFunctionName:
1651 case DeclarationName::CXXLiteralOperatorName:
1652 mangleOperatorName(Name, Arity);
1653 writeAbiTags(ND, AdditionalAbiTags);
1654 break;
1655
1656 case DeclarationName::CXXDeductionGuideName:
1657 llvm_unreachable("Can't mangle a deduction guide name!")::llvm::llvm_unreachable_internal("Can't mangle a deduction guide name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1657)
;
1658
1659 case DeclarationName::CXXUsingDirective:
1660 llvm_unreachable("Can't mangle a using directive name!")::llvm::llvm_unreachable_internal("Can't mangle a using directive name!"
, "clang/lib/AST/ItaniumMangle.cpp", 1660)
;
1661 }
1662}
1663
1664void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1665 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1666 // <number> ::= [n] <non-negative decimal integer>
1667 // <identifier> ::= <unqualified source code identifier>
1668 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1669 << II->getName();
1670}
1671
1672void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1673 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1674 // <number> ::= [n] <non-negative decimal integer>
1675 // <identifier> ::= <unqualified source code identifier>
1676 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1677 << II->getName();
1678}
1679
1680void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1681 // <source-name> ::= <positive length number> <identifier>
1682 // <number> ::= [n] <non-negative decimal integer>
1683 // <identifier> ::= <unqualified source code identifier>
1684 Out << II->getLength() << II->getName();
1685}
1686
1687void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1688 const DeclContext *DC,
1689 const AbiTagList *AdditionalAbiTags,
1690 bool NoFunction) {
1691 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1692 // <nested-name>
1693 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1694 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1695 // <template-args> E
1696
1697 Out << 'N';
1698 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1699 Qualifiers MethodQuals = Method->getMethodQualifiers();
1700 // We do not consider restrict a distinguishing attribute for overloading
1701 // purposes so we must not mangle it.
1702 MethodQuals.removeRestrict();
1703 mangleQualifiers(MethodQuals);
1704 mangleRefQualifier(Method->getRefQualifier());
1705 }
1706
1707 // Check if we have a template.
1708 const TemplateArgumentList *TemplateArgs = nullptr;
1709 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1710 mangleTemplatePrefix(TD, NoFunction);
1711 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1712 } else {
1713 manglePrefix(DC, NoFunction);
1714 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1715 }
1716
1717 Out << 'E';
1718}
1719void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1720 const TemplateArgument *TemplateArgs,
1721 unsigned NumTemplateArgs) {
1722 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1723
1724 Out << 'N';
1725
1726 mangleTemplatePrefix(TD);
1727 mangleTemplateArgs(asTemplateName(TD), TemplateArgs, NumTemplateArgs);
1728
1729 Out << 'E';
1730}
1731
1732void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1733 GlobalDecl GD, const NamedDecl *PrefixND,
1734 const AbiTagList *AdditionalAbiTags) {
1735 // A <closure-prefix> represents a variable or field, not a regular
1736 // DeclContext, so needs special handling. In this case we're mangling a
1737 // limited form of <nested-name>:
1738 //
1739 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1740
1741 Out << 'N';
1742
1743 mangleClosurePrefix(PrefixND);
1744 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1745
1746 Out << 'E';
1747}
1748
1749static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1750 GlobalDecl GD;
1751 // The Itanium spec says:
1752 // For entities in constructors and destructors, the mangling of the
1753 // complete object constructor or destructor is used as the base function
1754 // name, i.e. the C1 or D1 version.
1755 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1756 GD = GlobalDecl(CD, Ctor_Complete);
1757 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1758 GD = GlobalDecl(DD, Dtor_Complete);
1759 else
1760 GD = GlobalDecl(cast<FunctionDecl>(DC));
1761 return GD;
1762}
1763
1764void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1765 const AbiTagList *AdditionalAbiTags) {
1766 const Decl *D = GD.getDecl();
1767 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1768 // := Z <function encoding> E s [<discriminator>]
1769 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1770 // _ <entity name>
1771 // <discriminator> := _ <non-negative number>
1772 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D))(static_cast <bool> (isa<NamedDecl>(D) || isa<
BlockDecl>(D)) ? void (0) : __assert_fail ("isa<NamedDecl>(D) || isa<BlockDecl>(D)"
, "clang/lib/AST/ItaniumMangle.cpp", 1772, __extension__ __PRETTY_FUNCTION__
))
;
1773 const RecordDecl *RD = GetLocalClassDecl(D);
1774 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1775
1776 Out << 'Z';
1777
1778 {
1779 AbiTagState LocalAbiTags(AbiTags);
1780
1781 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1782 mangleObjCMethodName(MD);
1783 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1784 mangleBlockForPrefix(BD);
1785 else
1786 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1787
1788 // Implicit ABI tags (from namespace) are not available in the following
1789 // entity; reset to actually emitted tags, which are available.
1790 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1791 }
1792
1793 Out << 'E';
1794
1795 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1796 // be a bug that is fixed in trunk.
1797
1798 if (RD) {
1799 // The parameter number is omitted for the last parameter, 0 for the
1800 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1801 // <entity name> will of course contain a <closure-type-name>: Its
1802 // numbering will be local to the particular argument in which it appears
1803 // -- other default arguments do not affect its encoding.
1804 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1805 if (CXXRD && CXXRD->isLambda()) {
1806 if (const ParmVarDecl *Parm
1807 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1808 if (const FunctionDecl *Func
1809 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1810 Out << 'd';
1811 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1812 if (Num > 1)
1813 mangleNumber(Num - 2);
1814 Out << '_';
1815 }
1816 }
1817 }
1818
1819 // Mangle the name relative to the closest enclosing function.
1820 // equality ok because RD derived from ND above
1821 if (D == RD) {
1822 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1823 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1824 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1825 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1826 else
1827 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1828 assert(!AdditionalAbiTags && "Block cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Block cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Block cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1828, __extension__ __PRETTY_FUNCTION__
))
;
1829 mangleUnqualifiedBlock(BD);
1830 } else {
1831 const NamedDecl *ND = cast<NamedDecl>(D);
1832 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1833 AdditionalAbiTags, true /*NoFunction*/);
1834 }
1835 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1836 // Mangle a block in a default parameter; see above explanation for
1837 // lambdas.
1838 if (const ParmVarDecl *Parm
1839 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1840 if (const FunctionDecl *Func
1841 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1842 Out << 'd';
1843 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1844 if (Num > 1)
1845 mangleNumber(Num - 2);
1846 Out << '_';
1847 }
1848 }
1849
1850 assert(!AdditionalAbiTags && "Block cannot have additional abi tags")(static_cast <bool> (!AdditionalAbiTags && "Block cannot have additional abi tags"
) ? void (0) : __assert_fail ("!AdditionalAbiTags && \"Block cannot have additional abi tags\""
, "clang/lib/AST/ItaniumMangle.cpp", 1850, __extension__ __PRETTY_FUNCTION__
))
;
1851 mangleUnqualifiedBlock(BD);
1852 } else {
1853 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1854 }
1855
1856 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1857 unsigned disc;
1858 if (Context.getNextDiscriminator(ND, disc)) {
1859 if (disc < 10)
1860 Out << '_' << disc;
1861 else
1862 Out << "__" << disc << '_';
1863 }
1864 }
1865}
1866
1867void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1868 if (GetLocalClassDecl(Block)) {
1869 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1870 return;
1871 }
1872 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1873 if (isLocalContainerContext(DC)) {
1874 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1875 return;
1876 }
1877 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1878 mangleClosurePrefix(PrefixND);
1879 else
1880 manglePrefix(DC);
1881 mangleUnqualifiedBlock(Block);
1882}
1883
1884void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1885 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1886 // <data-member-prefix> now, with no substitutions and no <template-args>.
1887 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1888 if (getASTContext().getLangOpts().getClangABICompat() <=
1889 LangOptions::ClangABI::Ver12 &&
1890 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1891 Context->getDeclContext()->isRecord()) {
1892 const auto *ND = cast<NamedDecl>(Context);
1893 if (ND->getIdentifier()) {
1894 mangleSourceNameWithAbiTags(ND);
1895 Out << 'M';
1896 }
1897 }
1898 }
1899
1900 // If we have a block mangling number, use it.
1901 unsigned Number = Block->getBlockManglingNumber();
1902 // Otherwise, just make up a number. It doesn't matter what it is because
1903 // the symbol in question isn't externally visible.
1904 if (!Number)
1905 Number = Context.getBlockId(Block, false);
1906 else {
1907 // Stored mangling numbers are 1-based.
1908 --Number;
1909 }
1910 Out << "Ub";
1911 if (Number > 0)
1912 Out << Number - 1;
1913 Out << '_';
1914}
1915
1916// <template-param-decl>
1917// ::= Ty # template type parameter
1918// ::= Tn <type> # template non-type parameter
1919// ::= Tt <template-param-decl>* E # template template parameter
1920// ::= Tp <template-param-decl> # template parameter pack
1921void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1922 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1923 if (Ty->isParameterPack())
1924 Out << "Tp";
1925 Out << "Ty";
1926 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1927 if (Tn->isExpandedParameterPack()) {
1928 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1929 Out << "Tn";
1930 mangleType(Tn->getExpansionType(I));
1931 }
1932 } else {
1933 QualType T = Tn->getType();
1934 if (Tn->isParameterPack()) {
1935 Out << "Tp";
1936 if (auto *PackExpansion = T->getAs<PackExpansionType>())
1937 T = PackExpansion->getPattern();
1938 }
1939 Out << "Tn";
1940 mangleType(T);
1941 }
1942 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1943 if (Tt->isExpandedParameterPack()) {
1944 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1945 ++I) {
1946 Out << "Tt";
1947 for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1948 mangleTemplateParamDecl(Param);
1949 Out << "E";
1950 }
1951 } else {
1952 if (Tt->isParameterPack())
1953 Out << "Tp";
1954 Out << "Tt";
1955 for (auto *Param : *Tt->getTemplateParameters())
1956 mangleTemplateParamDecl(Param);
1957 Out << "E";
1958 }
1959 }
1960}
1961
1962void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1963 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1964 // <data-member-prefix> now, with no substitutions.
1965 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1966 if (getASTContext().getLangOpts().getClangABICompat() <=
1967 LangOptions::ClangABI::Ver12 &&
1968 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1969 !isa<ParmVarDecl>(Context)) {
1970 if (const IdentifierInfo *Name
1971 = cast<NamedDecl>(Context)->getIdentifier()) {
1972 mangleSourceName(Name);
1973 const TemplateArgumentList *TemplateArgs = nullptr;
1974 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1975 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1976 Out << 'M';
1977 }
1978 }
1979 }
1980
1981 Out << "Ul";
1982 mangleLambdaSig(Lambda);
1983 Out << "E";
1984
1985 // The number is omitted for the first closure type with a given
1986 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1987 // (in lexical order) with that same <lambda-sig> and context.
1988 //
1989 // The AST keeps track of the number for us.
1990 //
1991 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
1992 // and host-side compilations, an extra device mangle context may be created
1993 // if the host-side CXX ABI has different numbering for lambda. In such case,
1994 // if the mangle context is that device-side one, use the device-side lambda
1995 // mangling number for this lambda.
1996 llvm::Optional<unsigned> DeviceNumber =
1997 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
1998 unsigned Number =
1999 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2000
2001 assert(Number > 0 && "Lambda should be mangled as an unnamed class")(static_cast <bool> (Number > 0 && "Lambda should be mangled as an unnamed class"
) ? void (0) : __assert_fail ("Number > 0 && \"Lambda should be mangled as an unnamed class\""
, "clang/lib/AST/ItaniumMangle.cpp", 2001, __extension__ __PRETTY_FUNCTION__
))
;
2002 if (Number > 1)
2003 mangleNumber(Number - 2);
2004 Out << '_';
2005}
2006
2007void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2008 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2009 mangleTemplateParamDecl(D);
2010 auto *Proto =
2011 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2012 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2013 Lambda->getLambdaStaticInvoker());
2014}
2015
2016void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2017 switch (qualifier->getKind()) {
2018 case NestedNameSpecifier::Global:
2019 // nothing
2020 return;
2021
2022 case NestedNameSpecifier::Super:
2023 llvm_unreachable("Can't mangle __super specifier")::llvm::llvm_unreachable_internal("Can't mangle __super specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2023)
;
2024
2025 case NestedNameSpecifier::Namespace:
2026 mangleName(qualifier->getAsNamespace());
2027 return;
2028
2029 case NestedNameSpecifier::NamespaceAlias:
2030 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2031 return;
2032
2033 case NestedNameSpecifier::TypeSpec:
2034 case NestedNameSpecifier::TypeSpecWithTemplate:
2035 manglePrefix(QualType(qualifier->getAsType(), 0));
2036 return;
2037
2038 case NestedNameSpecifier::Identifier:
2039 // Member expressions can have these without prefixes, but that
2040 // should end up in mangleUnresolvedPrefix instead.
2041 assert(qualifier->getPrefix())(static_cast <bool> (qualifier->getPrefix()) ? void (
0) : __assert_fail ("qualifier->getPrefix()", "clang/lib/AST/ItaniumMangle.cpp"
, 2041, __extension__ __PRETTY_FUNCTION__))
;
2042 manglePrefix(qualifier->getPrefix());
2043
2044 mangleSourceName(qualifier->getAsIdentifier());
2045 return;
2046 }
2047
2048 llvm_unreachable("unexpected nested name specifier")::llvm::llvm_unreachable_internal("unexpected nested name specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2048)
;
2049}
2050
2051void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2052 // <prefix> ::= <prefix> <unqualified-name>
2053 // ::= <template-prefix> <template-args>
2054 // ::= <closure-prefix>
2055 // ::= <template-param>
2056 // ::= # empty
2057 // ::= <substitution>
2058
2059 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl")(static_cast <bool> (!isa<LinkageSpecDecl>(DC) &&
"prefix cannot be LinkageSpecDecl") ? void (0) : __assert_fail
("!isa<LinkageSpecDecl>(DC) && \"prefix cannot be LinkageSpecDecl\""
, "clang/lib/AST/ItaniumMangle.cpp", 2059, __extension__ __PRETTY_FUNCTION__
))
;
2060
2061 if (DC->isTranslationUnit())
2062 return;
2063
2064 if (NoFunction && isLocalContainerContext(DC))
2065 return;
2066
2067 assert(!isLocalContainerContext(DC))(static_cast <bool> (!isLocalContainerContext(DC)) ? void
(0) : __assert_fail ("!isLocalContainerContext(DC)", "clang/lib/AST/ItaniumMangle.cpp"
, 2067, __extension__ __PRETTY_FUNCTION__))
;
2068
2069 const NamedDecl *ND = cast<NamedDecl>(DC);
2070 if (mangleSubstitution(ND))
2071 return;
2072
2073 // Check if we have a template-prefix or a closure-prefix.
2074 const TemplateArgumentList *TemplateArgs = nullptr;
2075 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2076 mangleTemplatePrefix(TD);
2077 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2078 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2079 mangleClosurePrefix(PrefixND, NoFunction);
2080 mangleUnqualifiedName(ND, nullptr, nullptr);
2081 } else {
2082 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2083 manglePrefix(DC, NoFunction);
2084 mangleUnqualifiedName(ND, DC, nullptr);
2085 }
2086
2087 addSubstitution(ND);
2088}
2089
2090void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2091 // <template-prefix> ::= <prefix> <template unqualified-name>
2092 // ::= <template-param>
2093 // ::= <substitution>
2094 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2095 return mangleTemplatePrefix(TD);
2096
2097 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2098 assert(Dependent && "unexpected template name kind")(static_cast <bool> (Dependent && "unexpected template name kind"
) ? void (0) : __assert_fail ("Dependent && \"unexpected template name kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 2098, __extension__ __PRETTY_FUNCTION__
))
;
2099
2100 // Clang 11 and before mangled the substitution for a dependent template name
2101 // after already having emitted (a substitution for) the prefix.
2102 bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
2103 LangOptions::ClangABI::Ver11;
2104 if (!Clang11Compat && mangleSubstitution(Template))
2105 return;
2106
2107 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2108 manglePrefix(Qualifier);
2109
2110 if (Clang11Compat && mangleSubstitution(Template))
2111 return;
2112
2113 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2114 mangleSourceName(Id);
2115 else
2116 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2117
2118 addSubstitution(Template);
2119}
2120
2121void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2122 bool NoFunction) {
2123 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2124 // <template-prefix> ::= <prefix> <template unqualified-name>
2125 // ::= <template-param>
2126 // ::= <substitution>
2127 // <template-template-param> ::= <template-param>
2128 // <substitution>
2129
2130 if (mangleSubstitution(ND))
2131 return;
2132
2133 // <template-template-param> ::= <template-param>
2134 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2135 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2136 } else {
2137 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2138 manglePrefix(DC, NoFunction);
2139 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2140 mangleUnqualifiedName(GD, DC, nullptr);
2141 else
2142 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2143 nullptr);
2144 }
2145
2146 addSubstitution(ND);
2147}
2148
2149const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2150 if (getASTContext().getLangOpts().getClangABICompat() <=
2151 LangOptions::ClangABI::Ver12)
2152 return nullptr;
2153
2154 const NamedDecl *Context = nullptr;
2155 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2156 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2157 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2158 if (RD->isLambda())
2159 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2160 }
2161 if (!Context)
2162 return nullptr;
2163
2164 // Only lambdas within the initializer of a non-local variable or non-static
2165 // data member get a <closure-prefix>.
2166 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2167 isa<FieldDecl>(Context))
2168 return Context;
2169
2170 return nullptr;
2171}
2172
2173void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2174 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2175 // ::= <template-prefix> <template-args> M
2176 if (mangleSubstitution(ND))
2177 return;
2178
2179 const TemplateArgumentList *TemplateArgs = nullptr;
2180 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2181 mangleTemplatePrefix(TD, NoFunction);
2182 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2183 } else {
2184 const auto *DC = Context.getEffectiveDeclContext(ND);
2185 manglePrefix(DC, NoFunction);
2186 mangleUnqualifiedName(ND, DC, nullptr);
2187 }
2188
2189 Out << 'M';
2190
2191 addSubstitution(ND);
2192}
2193
2194/// Mangles a template name under the production <type>. Required for
2195/// template template arguments.
2196/// <type> ::= <class-enum-type>
2197/// ::= <template-param>
2198/// ::= <substitution>
2199void CXXNameMangler::mangleType(TemplateName TN) {
2200 if (mangleSubstitution(TN))
2201 return;
2202
2203 TemplateDecl *TD = nullptr;
2204
2205 switch (TN.getKind()) {
2206 case TemplateName::QualifiedTemplate:
2207 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
2208 goto HaveDecl;
2209
2210 case TemplateName::UsingTemplate:
2211 case TemplateName::Template:
2212 TD = TN.getAsTemplateDecl();
2213 goto HaveDecl;
2214
2215 HaveDecl:
2216 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2217 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2218 else
2219 mangleName(TD);
2220 break;
2221
2222 case TemplateName::OverloadedTemplate:
2223 case TemplateName::AssumedTemplate:
2224 llvm_unreachable("can't mangle an overloaded template name as a <type>")::llvm::llvm_unreachable_internal("can't mangle an overloaded template name as a <type>"
, "clang/lib/AST/ItaniumMangle.cpp", 2224)
;
2225
2226 case TemplateName::DependentTemplate: {
2227 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2228 assert(Dependent->isIdentifier())(static_cast <bool> (Dependent->isIdentifier()) ? void
(0) : __assert_fail ("Dependent->isIdentifier()", "clang/lib/AST/ItaniumMangle.cpp"
, 2228, __extension__ __PRETTY_FUNCTION__))
;
2229
2230 // <class-enum-type> ::= <name>
2231 // <name> ::= <nested-name>
2232 mangleUnresolvedPrefix(Dependent->getQualifier());
2233 mangleSourceName(Dependent->getIdentifier());
2234 break;
2235 }
2236
2237 case TemplateName::SubstTemplateTemplateParm: {
2238 // Substituted template parameters are mangled as the substituted
2239 // template. This will check for the substitution twice, which is
2240 // fine, but we have to return early so that we don't try to *add*
2241 // the substitution twice.
2242 SubstTemplateTemplateParmStorage *subst
2243 = TN.getAsSubstTemplateTemplateParm();
2244 mangleType(subst->getReplacement());
2245 return;
2246 }
2247
2248 case TemplateName::SubstTemplateTemplateParmPack: {
2249 // FIXME: not clear how to mangle this!
2250 // template <template <class> class T...> class A {
2251 // template <template <class> class U...> void foo(B<T,U> x...);
2252 // };
2253 Out << "_SUBSTPACK_";
2254 break;
2255 }
2256 }
2257
2258 addSubstitution(TN);
2259}
2260
2261bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2262 StringRef Prefix) {
2263 // Only certain other types are valid as prefixes; enumerate them.
2264 switch (Ty->getTypeClass()) {
2265 case Type::Builtin:
2266 case Type::Complex:
2267 case Type::Adjusted:
2268 case Type::Decayed:
2269 case Type::Pointer:
2270 case Type::BlockPointer:
2271 case Type::LValueReference:
2272 case Type::RValueReference:
2273 case Type::MemberPointer:
2274 case Type::ConstantArray:
2275 case Type::IncompleteArray:
2276 case Type::VariableArray:
2277 case Type::DependentSizedArray:
2278 case Type::DependentAddressSpace:
2279 case Type::DependentVector:
2280 case Type::DependentSizedExtVector:
2281 case Type::Vector:
2282 case Type::ExtVector:
2283 case Type::ConstantMatrix:
2284 case Type::DependentSizedMatrix:
2285 case Type::FunctionProto:
2286 case Type::FunctionNoProto:
2287 case Type::Paren:
2288 case Type::Attributed:
2289 case Type::BTFTagAttributed:
2290 case Type::Auto:
2291 case Type::DeducedTemplateSpecialization:
2292 case Type::PackExpansion:
2293 case Type::ObjCObject:
2294 case Type::ObjCInterface:
2295 case Type::ObjCObjectPointer:
2296 case Type::ObjCTypeParam:
2297 case Type::Atomic:
2298 case Type::Pipe:
2299 case Type::MacroQualified:
2300 case Type::BitInt:
2301 case Type::DependentBitInt:
2302 llvm_unreachable("type is illegal as a nested name specifier")::llvm::llvm_unreachable_internal("type is illegal as a nested name specifier"
, "clang/lib/AST/ItaniumMangle.cpp", 2302)
;
2303
2304 case Type::SubstTemplateTypeParmPack:
2305 // FIXME: not clear how to mangle this!
2306 // template <class T...> class A {
2307 // template <class U...> void foo(decltype(T::foo(U())) x...);
2308 // };
2309 Out << "_SUBSTPACK_";
2310 break;
2311
2312 // <unresolved-type> ::= <template-param>
2313 // ::= <decltype>
2314 // ::= <template-template-param> <template-args>
2315 // (this last is not official yet)
2316 case Type::TypeOfExpr:
2317 case Type::TypeOf:
2318 case Type::Decltype:
2319 case Type::TemplateTypeParm:
2320 case Type::UnaryTransform:
2321 case Type::SubstTemplateTypeParm:
2322 unresolvedType:
2323 // Some callers want a prefix before the mangled type.
2324 Out << Prefix;
2325
2326 // This seems to do everything we want. It's not really
2327 // sanctioned for a substituted template parameter, though.
2328 mangleType(Ty);
2329
2330 // We never want to print 'E' directly after an unresolved-type,
2331 // so we return directly.
2332 return true;
2333
2334 case Type::Typedef:
2335 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2336 break;
2337
2338 case Type::UnresolvedUsing:
2339 mangleSourceNameWithAbiTags(
2340 cast<UnresolvedUsingType>(Ty)->getDecl());
2341 break;
2342
2343 case Type::Enum:
2344 case Type::Record:
2345 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2346 break;
2347
2348 case Type::TemplateSpecialization: {
2349 const TemplateSpecializationType *TST =
2350 cast<TemplateSpecializationType>(Ty);
2351 TemplateName TN = TST->getTemplateName();
2352 switch (TN.getKind()) {
2353 case TemplateName::Template:
2354 case TemplateName::QualifiedTemplate: {
2355 TemplateDecl *TD = TN.getAsTemplateDecl();
2356
2357 // If the base is a template template parameter, this is an
2358 // unresolved type.
2359 assert(TD && "no template for template specialization type")(static_cast <bool> (TD && "no template for template specialization type"
) ? void (0) : __assert_fail ("TD && \"no template for template specialization type\""
, "clang/lib/AST/ItaniumMangle.cpp", 2359, __extension__ __PRETTY_FUNCTION__
))
;
2360 if (isa<TemplateTemplateParmDecl>(TD))
2361 goto unresolvedType;
2362
2363 mangleSourceNameWithAbiTags(TD);
2364 break;
2365 }
2366
2367 case TemplateName::OverloadedTemplate:
2368 case TemplateName::AssumedTemplate:
2369 case TemplateName::DependentTemplate:
2370 llvm_unreachable("invalid base for a template specialization type")::llvm::llvm_unreachable_internal("invalid base for a template specialization type"
, "clang/lib/AST/ItaniumMangle.cpp", 2370)
;
2371
2372 case TemplateName::SubstTemplateTemplateParm: {
2373 SubstTemplateTemplateParmStorage *subst =
2374 TN.getAsSubstTemplateTemplateParm();
2375 mangleExistingSubstitution(subst->getReplacement());
2376 break;
2377 }
2378
2379 case TemplateName::SubstTemplateTemplateParmPack: {
2380 // FIXME: not clear how to mangle this!
2381 // template <template <class U> class T...> class A {
2382 // template <class U...> void foo(decltype(T<U>::foo) x...);
2383 // };
2384 Out << "_SUBSTPACK_";
2385 break;
2386 }
2387 case TemplateName::UsingTemplate: {
2388 TemplateDecl *TD = TN.getAsTemplateDecl();
2389 assert(TD && !isa<TemplateTemplateParmDecl>(TD))(static_cast <bool> (TD && !isa<TemplateTemplateParmDecl
>(TD)) ? void (0) : __assert_fail ("TD && !isa<TemplateTemplateParmDecl>(TD)"
, "clang/lib/AST/ItaniumMangle.cpp", 2389, __extension__ __PRETTY_FUNCTION__
))
;
2390 mangleSourceNameWithAbiTags(TD);
2391 break;
2392 }
2393 }
2394
2395 // Note: we don't pass in the template name here. We are mangling the
2396 // original source-level template arguments, so we shouldn't consider
2397 // conversions to the corresponding template parameter.
2398 // FIXME: Other compilers mangle partially-resolved template arguments in
2399 // unresolved-qualifier-levels.
2400 mangleTemplateArgs(TemplateName(), TST->getArgs(), TST->getNumArgs());
2401 break;
2402 }
2403
2404 case Type::InjectedClassName:
2405 mangleSourceNameWithAbiTags(
2406 cast<InjectedClassNameType>(Ty)->getDecl());
2407 break;
2408
2409 case Type::DependentName:
2410 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2411 break;
2412
2413 case Type::DependentTemplateSpecialization: {
2414 const DependentTemplateSpecializationType *DTST =
2415 cast<DependentTemplateSpecializationType>(Ty);
2416 TemplateName Template = getASTContext().getDependentTemplateName(
2417 DTST->getQualifier(), DTST->getIdentifier());
2418 mangleSourceName(DTST->getIdentifier());
2419 mangleTemplateArgs(Template, DTST->getArgs(), DTST->getNumArgs());
2420 break;
2421 }
2422
2423 case Type::Using:
2424 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2425 Prefix);
2426 case Type::Elaborated:
2427 return mangleUnresolvedTypeOrSimpleId(
2428 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2429 }
2430
2431 return false;
2432}
2433
2434void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2435 switch (Name.getNameKind()) {
2436 case DeclarationName::CXXConstructorName:
2437 case DeclarationName::CXXDestructorName:
2438 case DeclarationName::CXXDeductionGuideName:
2439 case DeclarationName::CXXUsingDirective:
2440 case DeclarationName::Identifier:
2441 case DeclarationName::ObjCMultiArgSelector:
2442 case DeclarationName::ObjCOneArgSelector:
2443 case DeclarationName::ObjCZeroArgSelector:
2444 llvm_unreachable("Not an operator name")::llvm::llvm_unreachable_internal("Not an operator name", "clang/lib/AST/ItaniumMangle.cpp"
, 2444)
;
2445
2446 case DeclarationName::CXXConversionFunctionName:
2447 // <operator-name> ::= cv <type> # (cast)
2448 Out << "cv";
2449 mangleType(Name.getCXXNameType());
2450 break;
2451
2452 case DeclarationName::CXXLiteralOperatorName:
2453 Out << "li";
2454 mangleSourceName(Name.getCXXLiteralIdentifier());
2455 return;
2456
2457 case DeclarationName::CXXOperatorName:
2458 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2459 break;
2460 }
2461}
2462
2463void
2464CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2465 switch (OO) {
2466 // <operator-name> ::= nw # new
2467 case OO_New: Out << "nw"; break;
2468 // ::= na # new[]
2469 case OO_Array_New: Out << "na"; break;
2470 // ::= dl # delete
2471 case OO_Delete: Out << "dl"; break;
2472 // ::= da # delete[]
2473 case OO_Array_Delete: Out << "da"; break;
2474 // ::= ps # + (unary)
2475 // ::= pl # + (binary or unknown)
2476 case OO_Plus:
2477 Out << (Arity == 1? "ps" : "pl"); break;
2478 // ::= ng # - (unary)
2479 // ::= mi # - (binary or unknown)
2480 case OO_Minus:
2481 Out << (Arity == 1? "ng" : "mi"); break;
2482 // ::= ad # & (unary)
2483 // ::= an # & (binary or unknown)
2484 case OO_Amp:
2485 Out << (Arity == 1? "ad" : "an"); break;
2486 // ::= de # * (unary)
2487 // ::= ml # * (binary or unknown)
2488 case OO_Star:
2489 // Use binary when unknown.
2490 Out << (Arity == 1? "de" : "ml"); break;
2491 // ::= co # ~
2492 case OO_Tilde: Out << "co"; break;
2493 // ::= dv # /
2494 case OO_Slash: Out << "dv"; break;
2495 // ::= rm # %
2496 case OO_Percent: Out << "rm"; break;
2497 // ::= or # |
2498 case OO_Pipe: Out << "or"; break;
2499 // ::= eo # ^
2500 case OO_Caret: Out << "eo"; break;
2501 // ::= aS # =
2502 case OO_Equal: Out << "aS"; break;
2503 // ::= pL # +=
2504 case OO_PlusEqual: Out << "pL"; break;
2505 // ::= mI # -=
2506 case OO_MinusEqual: Out << "mI"; break;
2507 // ::= mL # *=
2508 case OO_StarEqual: Out << "mL"; break;
2509 // ::= dV # /=
2510 case OO_SlashEqual: Out << "dV"; break;
2511 // ::= rM # %=
2512 case OO_PercentEqual: Out << "rM"; break;
2513 // ::= aN # &=
2514 case OO_AmpEqual: Out << "aN"; break;
2515 // ::= oR # |=
2516 case OO_PipeEqual: Out << "oR"; break;
2517 // ::= eO # ^=
2518 case OO_CaretEqual: Out << "eO"; break;
2519 // ::= ls # <<
2520 case OO_LessLess: Out << "ls"; break;
2521 // ::= rs # >>
2522 case OO_GreaterGreater: Out << "rs"; break;
2523 // ::= lS # <<=
2524 case OO_LessLessEqual: Out << "lS"; break;
2525 // ::= rS # >>=
2526 case OO_GreaterGreaterEqual: Out << "rS"; break;
2527 // ::= eq # ==
2528 case OO_EqualEqual: Out << "eq"; break;
2529 // ::= ne # !=
2530 case OO_ExclaimEqual: Out << "ne"; break;
2531 // ::= lt # <
2532 case OO_Less: Out << "lt"; break;
2533 // ::= gt # >
2534 case OO_Greater: Out << "gt"; break;
2535 // ::= le # <=
2536 case OO_LessEqual: Out << "le"; break;
2537 // ::= ge # >=
2538 case OO_GreaterEqual: Out << "ge"; break;
2539 // ::= nt # !
2540 case OO_Exclaim: Out << "nt"; break;
2541 // ::= aa # &&
2542 case OO_AmpAmp: Out << "aa"; break;
2543 // ::= oo # ||
2544 case OO_PipePipe: Out << "oo"; break;
2545 // ::= pp # ++
2546 case OO_PlusPlus: Out << "pp"; break;
2547 // ::= mm # --
2548 case OO_MinusMinus: Out << "mm"; break;
2549 // ::= cm # ,
2550 case OO_Comma: Out << "cm"; break;
2551 // ::= pm # ->*
2552 case OO_ArrowStar: Out << "pm"; break;
2553 // ::= pt # ->
2554 case OO_Arrow: Out << "pt"; break;
2555 // ::= cl # ()
2556 case OO_Call: Out << "cl"; break;
2557 // ::= ix # []
2558 case OO_Subscript: Out << "ix"; break;
2559
2560 // ::= qu # ?
2561 // The conditional operator can't be overloaded, but we still handle it when
2562 // mangling expressions.
2563 case OO_Conditional: Out << "qu"; break;
2564 // Proposal on cxx-abi-dev, 2015-10-21.
2565 // ::= aw # co_await
2566 case OO_Coawait: Out << "aw"; break;
2567 // Proposed in cxx-abi github issue 43.
2568 // ::= ss # <=>
2569 case OO_Spaceship: Out << "ss"; break;
2570
2571 case OO_None:
2572 case NUM_OVERLOADED_OPERATORS:
2573 llvm_unreachable("Not an overloaded operator")::llvm::llvm_unreachable_internal("Not an overloaded operator"
, "clang/lib/AST/ItaniumMangle.cpp", 2573)
;
2574 }
2575}
2576
2577void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2578 // Vendor qualifiers come first and if they are order-insensitive they must
2579 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2580
2581 // <type> ::= U <addrspace-expr>
2582 if (DAST) {
2583 Out << "U2ASI";
2584 mangleExpression(DAST->getAddrSpaceExpr());
2585 Out << "E";
2586 }
2587
2588 // Address space qualifiers start with an ordinary letter.
2589 if (Quals.hasAddressSpace()) {
2590 // Address space extension:
2591 //
2592 // <type> ::= U <target-addrspace>
2593 // <type> ::= U <OpenCL-addrspace>
2594 // <type> ::= U <CUDA-addrspace>
2595
2596 SmallString<64> ASString;
2597 LangAS AS = Quals.getAddressSpace();
2598
2599 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2600 // <target-addrspace> ::= "AS" <address-space-number>
2601 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2602 if (TargetAS != 0 ||
2603 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2604 ASString = "AS" + llvm::utostr(TargetAS);
2605 } else {
2606 switch (AS) {
2607 default: llvm_unreachable("Not a language specific address space")::llvm::llvm_unreachable_internal("Not a language specific address space"
, "clang/lib/AST/ItaniumMangle.cpp", 2607)
;
2608 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2609 // "private"| "generic" | "device" |
2610 // "host" ]
2611 case LangAS::opencl_global:
2612 ASString = "CLglobal";
2613 break;
2614 case LangAS::opencl_global_device:
2615 ASString = "CLdevice";
2616 break;
2617 case LangAS::opencl_global_host:
2618 ASString = "CLhost";
2619 break;
2620 case LangAS::opencl_local:
2621 ASString = "CLlocal";
2622 break;
2623 case LangAS::opencl_constant:
2624 ASString = "CLconstant";
2625 break;
2626 case LangAS::opencl_private:
2627 ASString = "CLprivate";
2628 break;
2629 case LangAS::opencl_generic:
2630 ASString = "CLgeneric";
2631 break;
2632 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2633 // "device" | "host" ]
2634 case LangAS::sycl_global:
2635 ASString = "SYglobal";
2636 break;
2637 case LangAS::sycl_global_device:
2638 ASString = "SYdevice";
2639 break;
2640 case LangAS::sycl_global_host:
2641 ASString = "SYhost";
2642 break;
2643 case LangAS::sycl_local:
2644 ASString = "SYlocal";
2645 break;
2646 case LangAS::sycl_private:
2647 ASString = "SYprivate";
2648 break;
2649 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2650 case LangAS::cuda_device:
2651 ASString = "CUdevice";
2652 break;
2653 case LangAS::cuda_constant:
2654 ASString = "CUconstant";
2655 break;
2656 case LangAS::cuda_shared:
2657 ASString = "CUshared";
2658 break;
2659 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2660 case LangAS::ptr32_sptr:
2661 ASString = "ptr32_sptr";
2662 break;
2663 case LangAS::ptr32_uptr:
2664 ASString = "ptr32_uptr";
2665 break;
2666 case LangAS::ptr64:
2667 ASString = "ptr64";
2668 break;
2669 }
2670 }
2671 if (!ASString.empty())
2672 mangleVendorQualifier(ASString);
2673 }
2674
2675 // The ARC ownership qualifiers start with underscores.
2676 // Objective-C ARC Extension:
2677 //
2678 // <type> ::= U "__strong"
2679 // <type> ::= U "__weak"
2680 // <type> ::= U "__autoreleasing"
2681 //
2682 // Note: we emit __weak first to preserve the order as
2683 // required by the Itanium ABI.
2684 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2685 mangleVendorQualifier("__weak");
2686
2687 // __unaligned (from -fms-extensions)
2688 if (Quals.hasUnaligned())
2689 mangleVendorQualifier("__unaligned");
2690
2691 // Remaining ARC ownership qualifiers.
2692 switch (Quals.getObjCLifetime()) {
2693 case Qualifiers::OCL_None:
2694 break;
2695
2696 case Qualifiers::OCL_Weak:
2697 // Do nothing as we already handled this case above.
2698 break;
2699
2700 case Qualifiers::OCL_Strong:
2701 mangleVendorQualifier("__strong");
2702 break;
2703
2704 case Qualifiers::OCL_Autoreleasing:
2705 mangleVendorQualifier("__autoreleasing");
2706 break;
2707
2708 case Qualifiers::OCL_ExplicitNone:
2709 // The __unsafe_unretained qualifier is *not* mangled, so that
2710 // __unsafe_unretained types in ARC produce the same manglings as the
2711 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2712 // better ABI compatibility.
2713 //
2714 // It's safe to do this because unqualified 'id' won't show up
2715 // in any type signatures that need to be mangled.
2716 break;
2717 }
2718
2719 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2720 if (Quals.hasRestrict())
2721 Out << 'r';
2722 if (Quals.hasVolatile())
2723 Out << 'V';
2724 if (Quals.hasConst())
2725 Out << 'K';
2726}
2727
2728void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2729 Out << 'U' << name.size() << name;
2730}
2731
2732void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2733 // <ref-qualifier> ::= R # lvalue reference
2734 // ::= O # rvalue-reference
2735 switch (RefQualifier) {
2736 case RQ_None:
2737 break;
2738
2739 case RQ_LValue:
2740 Out << 'R';
2741 break;
2742
2743 case RQ_RValue:
2744 Out << 'O';
2745 break;
2746 }
2747}
2748
2749void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2750 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2751}
2752
2753static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2754 ASTContext &Ctx) {
2755 if (Quals)
2756 return true;
2757 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2758 return true;
2759 if (Ty->isOpenCLSpecificType())
2760 return true;
2761 if (Ty->isBuiltinType())
2762 return false;
2763 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2764 // substitution candidates.
2765 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2766 isa<AutoType>(Ty))
2767 return false;
2768 // A placeholder type for class template deduction is substitutable with
2769 // its corresponding template name; this is handled specially when mangling
2770 // the type.
2771 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2772 if (DeducedTST->getDeducedType().isNull())
2773 return false;
2774 return true;
2775}
2776
2777void CXXNameMangler::mangleType(QualType T) {
2778 // If our type is instantiation-dependent but not dependent, we mangle
2779 // it as it was written in the source, removing any top-level sugar.
2780 // Otherwise, use the canonical type.
2781 //
2782 // FIXME: This is an approximation of the instantiation-dependent name
2783 // mangling rules, since we should really be using the type as written and
2784 // augmented via semantic analysis (i.e., with implicit conversions and
2785 // default template arguments) for any instantiation-dependent type.
2786 // Unfortunately, that requires several changes to our AST:
2787 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2788 // uniqued, so that we can handle substitutions properly
2789 // - Default template arguments will need to be represented in the
2790 // TemplateSpecializationType, since they need to be mangled even though
2791 // they aren't written.
2792 // - Conversions on non-type template arguments need to be expressed, since
2793 // they can affect the mangling of sizeof/alignof.
2794 //
2795 // FIXME: This is wrong when mapping to the canonical type for a dependent
2796 // type discards instantiation-dependent portions of the type, such as for:
2797 //
2798 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2799 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2800 //
2801 // It's also wrong in the opposite direction when instantiation-dependent,
2802 // canonically-equivalent types differ in some irrelevant portion of inner
2803 // type sugar. In such cases, we fail to form correct substitutions, eg:
2804 //
2805 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2806 //
2807 // We should instead canonicalize the non-instantiation-dependent parts,
2808 // regardless of whether the type as a whole is dependent or instantiation
2809 // dependent.
2810 if (!T->isInstantiationDependentType() || T->isDependentType())
2811 T = T.getCanonicalType();
2812 else {
2813 // Desugar any types that are purely sugar.
2814 do {
2815 // Don't desugar through template specialization types that aren't
2816 // type aliases. We need to mangle the template arguments as written.
2817 if (const TemplateSpecializationType *TST
2818 = dyn_cast<TemplateSpecializationType>(T))
2819 if (!TST->isTypeAlias())
2820 break;
2821
2822 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2823 // instantation-dependent qualifiers. See
2824 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2825
2826 QualType Desugared
2827 = T.getSingleStepDesugaredType(Context.getASTContext());
2828 if (Desugared == T)
2829 break;
2830
2831 T = Desugared;
2832 } while (true);
2833 }
2834 SplitQualType split = T.split();
2835 Qualifiers quals = split.Quals;
2836 const Type *ty = split.Ty;
2837
2838 bool isSubstitutable =
2839 isTypeSubstitutable(quals, ty, Context.getASTContext());
2840 if (isSubstitutable && mangleSubstitution(T))
2841 return;
2842
2843 // If we're mangling a qualified array type, push the qualifiers to
2844 // the element type.
2845 if (quals && isa<ArrayType>(T)) {
2846 ty = Context.getASTContext().getAsArrayType(T);
2847 quals = Qualifiers();
2848
2849 // Note that we don't update T: we want to add the
2850 // substitution at the original type.
2851 }
2852
2853 if (quals || ty->isDependentAddressSpaceType()) {
2854 if (const DependentAddressSpaceType *DAST =
2855 dyn_cast<DependentAddressSpaceType>(ty)) {
2856 SplitQualType splitDAST = DAST->getPointeeType().split();
2857 mangleQualifiers(splitDAST.Quals, DAST);
2858 mangleType(QualType(splitDAST.Ty, 0));
2859 } else {
2860 mangleQualifiers(quals);
2861
2862 // Recurse: even if the qualified type isn't yet substitutable,
2863 // the unqualified type might be.
2864 mangleType(QualType(ty, 0));
2865 }
2866 } else {
2867 switch (ty->getTypeClass()) {
2868#define ABSTRACT_TYPE(CLASS, PARENT)
2869#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2870 case Type::CLASS: \
2871 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type")::llvm::llvm_unreachable_internal("can't mangle non-canonical type "
#CLASS "Type", "clang/lib/AST/ItaniumMangle.cpp", 2871)
; \
2872 return;
2873#define TYPE(CLASS, PARENT) \
2874 case Type::CLASS: \
2875 mangleType(static_cast<const CLASS##Type*>(ty)); \
2876 break;
2877#include "clang/AST/TypeNodes.inc"
2878 }
2879 }
2880
2881 // Add the substitution.
2882 if (isSubstitutable)
2883 addSubstitution(T);
2884}
2885
2886void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2887 if (!mangleStandardSubstitution(ND))
2888 mangleName(ND);
2889}
2890
2891void CXXNameMangler::mangleType(const BuiltinType *T) {
2892 // <type> ::= <builtin-type>
2893 // <builtin-type> ::= v # void
2894 // ::= w # wchar_t
2895 // ::= b # bool
2896 // ::= c # char
2897 // ::= a # signed char
2898 // ::= h # unsigned char
2899 // ::= s # short
2900 // ::= t # unsigned short
2901 // ::= i # int
2902 // ::= j # unsigned int
2903 // ::= l # long
2904 // ::= m # unsigned long
2905 // ::= x # long long, __int64
2906 // ::= y # unsigned long long, __int64
2907 // ::= n # __int128
2908 // ::= o # unsigned __int128
2909 // ::= f # float
2910 // ::= d # double
2911 // ::= e # long double, __float80
2912 // ::= g # __float128
2913 // ::= g # __ibm128
2914 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2915 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2916 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2917 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2918 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2919 // ::= Di # char32_t
2920 // ::= Ds # char16_t
2921 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2922 // ::= u <source-name> # vendor extended type
2923 std::string type_name;
2924 switch (T->getKind()) {
2925 case BuiltinType::Void:
2926 Out << 'v';
2927 break;
2928 case BuiltinType::Bool:
2929 Out << 'b';
2930 break;
2931 case BuiltinType::Char_U:
2932 case BuiltinType::Char_S:
2933 Out << 'c';
2934 break;
2935 case BuiltinType::UChar:
2936 Out << 'h';
2937 break;
2938 case BuiltinType::UShort:
2939 Out << 't';
2940 break;
2941 case BuiltinType::UInt:
2942 Out << 'j';
2943 break;
2944 case BuiltinType::ULong:
2945 Out << 'm';
2946 break;
2947 case BuiltinType::ULongLong:
2948 Out << 'y';
2949 break;
2950 case BuiltinType::UInt128:
2951 Out << 'o';
2952 break;
2953 case BuiltinType::SChar:
2954 Out << 'a';
2955 break;
2956 case BuiltinType::WChar_S:
2957 case BuiltinType::WChar_U:
2958 Out << 'w';
2959 break;
2960 case BuiltinType::Char8:
2961 Out << "Du";
2962 break;
2963 case BuiltinType::Char16:
2964 Out << "Ds";
2965 break;
2966 case BuiltinType::Char32:
2967 Out << "Di";
2968 break;
2969 case BuiltinType::Short:
2970 Out << 's';
2971 break;
2972 case BuiltinType::Int:
2973 Out << 'i';
2974 break;
2975 case BuiltinType::Long:
2976 Out << 'l';
2977 break;
2978 case BuiltinType::LongLong:
2979 Out << 'x';
2980 break;
2981 case BuiltinType::Int128:
2982 Out << 'n';
2983 break;
2984 case BuiltinType::Float16:
2985 Out << "DF16_";
2986 break;
2987 case BuiltinType::ShortAccum:
2988 case BuiltinType::Accum:
2989 case BuiltinType::LongAccum:
2990 case BuiltinType::UShortAccum:
2991 case BuiltinType::UAccum:
2992 case BuiltinType::ULongAccum:
2993 case BuiltinType::ShortFract:
2994 case BuiltinType::Fract:
2995 case BuiltinType::LongFract:
2996 case BuiltinType::UShortFract:
2997 case BuiltinType::UFract:
2998 case BuiltinType::ULongFract:
2999 case BuiltinType::SatShortAccum:
3000 case BuiltinType::SatAccum:
3001 case BuiltinType::SatLongAccum:
3002 case BuiltinType::SatUShortAccum:
3003 case BuiltinType::SatUAccum:
3004 case BuiltinType::SatULongAccum:
3005 case BuiltinType::SatShortFract:
3006 case BuiltinType::SatFract:
3007 case BuiltinType::SatLongFract:
3008 case BuiltinType::SatUShortFract:
3009 case BuiltinType::SatUFract:
3010 case BuiltinType::SatULongFract:
3011 llvm_unreachable("Fixed point types are disabled for c++")::llvm::llvm_unreachable_internal("Fixed point types are disabled for c++"
, "clang/lib/AST/ItaniumMangle.cpp", 3011)
;
3012 case BuiltinType::Half:
3013 Out << "Dh";
3014 break;
3015 case BuiltinType::Float:
3016 Out << 'f';
3017 break;
3018 case BuiltinType::Double:
3019 Out << 'd';
3020 break;
3021 case BuiltinType::LongDouble: {
3022 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3023 getASTContext().getLangOpts().OpenMPIsDevice
3024 ? getASTContext().getAuxTargetInfo()
3025 : &getASTContext().getTargetInfo();
3026 Out << TI->getLongDoubleMangling();
3027 break;
3028 }
3029 case BuiltinType::Float128: {
3030 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3031 getASTContext().getLangOpts().OpenMPIsDevice
3032 ? getASTContext().getAuxTargetInfo()
3033 : &getASTContext().getTargetInfo();
3034 Out << TI->getFloat128Mangling();
3035 break;
3036 }
3037 case BuiltinType::BFloat16: {
3038 const TargetInfo *TI = &getASTContext().getTargetInfo();
3039 Out << TI->getBFloat16Mangling();
3040 break;
3041 }
3042 case BuiltinType::Ibm128: {
3043 const TargetInfo *TI = &getASTContext().getTargetInfo();
3044 Out << TI->getIbm128Mangling();
3045 break;
3046 }
3047 case BuiltinType::NullPtr:
3048 Out << "Dn";
3049 break;
3050
3051#define BUILTIN_TYPE(Id, SingletonId)
3052#define PLACEHOLDER_TYPE(Id, SingletonId) \
3053 case BuiltinType::Id:
3054#include "clang/AST/BuiltinTypes.def"
3055 case BuiltinType::Dependent:
3056 if (!NullOut)
3057 llvm_unreachable("mangling a placeholder type")::llvm::llvm_unreachable_internal("mangling a placeholder type"
, "clang/lib/AST/ItaniumMangle.cpp", 3057)
;
3058 break;
3059 case BuiltinType::ObjCId:
3060 Out << "11objc_object";
3061 break;
3062 case BuiltinType::ObjCClass:
3063 Out << "10objc_class";
3064 break;
3065 case BuiltinType::ObjCSel:
3066 Out << "13objc_selector";
3067 break;
3068#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3069 case BuiltinType::Id: \
3070 type_name = "ocl_" #ImgType "_" #Suffix; \
3071 Out << type_name.size() << type_name; \
3072 break;
3073#include "clang/Basic/OpenCLImageTypes.def"
3074 case BuiltinType::OCLSampler:
3075 Out << "11ocl_sampler";
3076 break;
3077 case BuiltinType::OCLEvent:
3078 Out << "9ocl_event";
3079 break;
3080 case BuiltinType::OCLClkEvent:
3081 Out << "12ocl_clkevent";
3082 break;
3083 case BuiltinType::OCLQueue:
3084 Out << "9ocl_queue";
3085 break;
3086 case BuiltinType::OCLReserveID:
3087 Out << "13ocl_reserveid";
3088 break;
3089#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3090 case BuiltinType::Id: \
3091 type_name = "ocl_" #ExtType; \
3092 Out << type_name.size() << type_name; \
3093 break;
3094#include "clang/Basic/OpenCLExtensionTypes.def"
3095 // The SVE types are effectively target-specific. The mangling scheme
3096 // is defined in the appendices to the Procedure Call Standard for the
3097 // Arm Architecture.
3098#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3099 ElBits, IsSigned, IsFP, IsBF) \
3100 case BuiltinType::Id: \
3101 type_name = MangledName; \
3102 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3103 << type_name; \
3104 break;
3105#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3106 case BuiltinType::Id: \
3107 type_name = MangledName; \
3108 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3109 << type_name; \
3110 break;
3111#include "clang/Basic/AArch64SVEACLETypes.def"
3112#define PPC_VECTOR_TYPE(Name, Id, Size) \
3113 case BuiltinType::Id: \
3114 type_name = #Name; \
3115 Out << 'u' << type_name.size() << type_name; \
3116 break;
3117#include "clang/Basic/PPCTypes.def"
3118 // TODO: Check the mangling scheme for RISC-V V.
3119#define RVV_TYPE(Name, Id, SingletonId) \
3120 case BuiltinType::Id: \
3121 type_name = Name; \
3122 Out << 'u' << type_name.size() << type_name; \
3123 break;
3124#include "clang/Basic/RISCVVTypes.def"
3125 }
3126}
3127
3128StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3129 switch (CC) {
3130 case CC_C:
3131 return "";
3132
3133 case CC_X86VectorCall:
3134 case CC_X86Pascal:
3135 case CC_X86RegCall:
3136 case CC_AAPCS:
3137 case CC_AAPCS_VFP:
3138 case CC_AArch64VectorCall:
3139 case CC_IntelOclBicc:
3140 case CC_SpirFunction:
3141 case CC_OpenCLKernel:
3142 case CC_PreserveMost:
3143 case CC_PreserveAll:
3144 // FIXME: we should be mangling all of the above.
3145 return "";
3146
3147 case CC_X86ThisCall:
3148 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3149 // used explicitly. At this point, we don't have that much information in
3150 // the AST, since clang tends to bake the convention into the canonical
3151 // function type. thiscall only rarely used explicitly, so don't mangle it
3152 // for now.
3153 return "";
3154
3155 case CC_X86StdCall:
3156 return "stdcall";
3157 case CC_X86FastCall:
3158 return "fastcall";
3159 case CC_X86_64SysV:
3160 return "sysv_abi";
3161 case CC_Win64:
3162 return "ms_abi";
3163 case CC_Swift:
3164 return "swiftcall";
3165 case CC_SwiftAsync:
3166 return "swiftasynccall";
3167 }
3168 llvm_unreachable("bad calling convention")::llvm::llvm_unreachable_internal("bad calling convention", "clang/lib/AST/ItaniumMangle.cpp"
, 3168)
;
3169}
3170
3171void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3172 // Fast path.
3173 if (T->getExtInfo() == FunctionType::ExtInfo())
3174 return;
3175
3176 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3177 // This will get more complicated in the future if we mangle other
3178 // things here; but for now, since we mangle ns_returns_retained as
3179 // a qualifier on the result type, we can get away with this:
3180 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3181 if (!CCQualifier.empty())
3182 mangleVendorQualifier(CCQualifier);
3183
3184 // FIXME: regparm
3185 // FIXME: noreturn
3186}
3187
3188void
3189CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3190 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3191
3192 // Note that these are *not* substitution candidates. Demanglers might
3193 // have trouble with this if the parameter type is fully substituted.
3194
3195 switch (PI.getABI()) {
3196 case ParameterABI::Ordinary:
3197 break;
3198
3199 // All of these start with "swift", so they come before "ns_consumed".
3200 case ParameterABI::SwiftContext:
3201 case ParameterABI::SwiftAsyncContext:
3202 case ParameterABI::SwiftErrorResult:
3203 case ParameterABI::SwiftIndirectResult:
3204 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3205 break;
3206 }
3207
3208 if (PI.isConsumed())
3209 mangleVendorQualifier("ns_consumed");
3210
3211 if (PI.isNoEscape())
3212 mangleVendorQualifier("noescape");
3213}
3214
3215// <type> ::= <function-type>
3216// <function-type> ::= [<CV-qualifiers>] F [Y]
3217// <bare-function-type> [<ref-qualifier>] E
3218void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3219 mangleExtFunctionInfo(T);
3220
3221 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3222 // e.g. "const" in "int (A::*)() const".
3223 mangleQualifiers(T->getMethodQuals());
3224
3225 // Mangle instantiation-dependent exception-specification, if present,
3226 // per cxx-abi-dev proposal on 2016-10-11.
3227 if (T->hasInstantiationDependentExceptionSpec()) {
3228 if (isComputedNoexcept(T->getExceptionSpecType())) {
3229 Out << "DO";
3230 mangleExpression(T->getNoexceptExpr());
3231 Out << "E";
3232 } else {
3233 assert(T->getExceptionSpecType() == EST_Dynamic)(static_cast <bool> (T->getExceptionSpecType() == EST_Dynamic
) ? void (0) : __assert_fail ("T->getExceptionSpecType() == EST_Dynamic"
, "clang/lib/AST/ItaniumMangle.cpp", 3233, __extension__ __PRETTY_FUNCTION__
))
;
3234 Out << "Dw";
3235 for (auto ExceptTy : T->exceptions())
3236 mangleType(ExceptTy);
3237 Out << "E";
3238 }
3239 } else if (T->isNothrow()) {
3240 Out << "Do";
3241 }
3242
3243 Out << 'F';
3244
3245 // FIXME: We don't have enough information in the AST to produce the 'Y'
3246 // encoding for extern "C" function types.
3247 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3248
3249 // Mangle the ref-qualifier, if present.
3250 mangleRefQualifier(T->getRefQualifier());
3251
3252 Out << 'E';
3253}
3254
3255void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3256 // Function types without prototypes can arise when mangling a function type
3257 // within an overloadable function in C. We mangle these as the absence of any
3258 // parameter types (not even an empty parameter list).
3259 Out << 'F';
3260
3261 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3262
3263 FunctionTypeDepth.enterResultType();
3264 mangleType(T->getReturnType());
3265 FunctionTypeDepth.leaveResultType();
3266
3267 FunctionTypeDepth.pop(saved);
3268 Out << 'E';
3269}
3270
3271void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3272 bool MangleReturnType,
3273 const FunctionDecl *FD) {
3274 // Record that we're in a function type. See mangleFunctionParam
3275 // for details on what we're trying to achieve here.
3276 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3277
3278 // <bare-function-type> ::= <signature type>+
3279 if (MangleReturnType) {
3280 FunctionTypeDepth.enterResultType();
3281
3282 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3283 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3284 mangleVendorQualifier("ns_returns_retained");
3285
3286 // Mangle the return type without any direct ARC ownership qualifiers.
3287 QualType ReturnTy = Proto->getReturnType();
3288 if (ReturnTy.getObjCLifetime()) {
3289 auto SplitReturnTy = ReturnTy.split();
3290 SplitReturnTy.Quals.removeObjCLifetime();
3291 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3292 }
3293 mangleType(ReturnTy);
3294
3295 FunctionTypeDepth.leaveResultType();
3296 }
3297
3298 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3299 // <builtin-type> ::= v # void
3300 Out << 'v';
3301
3302 FunctionTypeDepth.pop(saved);
3303 return;
3304 }
3305
3306 assert(!FD || FD->getNumParams() == Proto->getNumParams())(static_cast <bool> (!FD || FD->getNumParams() == Proto
->getNumParams()) ? void (0) : __assert_fail ("!FD || FD->getNumParams() == Proto->getNumParams()"
, "clang/lib/AST/ItaniumMangle.cpp", 3306, __extension__ __PRETTY_FUNCTION__
))
;
3307 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3308 // Mangle extended parameter info as order-sensitive qualifiers here.
3309 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3310 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3311 }
3312
3313 // Mangle the type.
3314 QualType ParamTy = Proto->getParamType(I);
3315 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3316
3317 if (FD) {
3318 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3319 // Attr can only take 1 character, so we can hardcode the length below.
3320 assert(Attr->getType() <= 9 && Attr->getType() >= 0)(static_cast <bool> (Attr->getType() <= 9 &&
Attr->getType() >= 0) ? void (0) : __assert_fail ("Attr->getType() <= 9 && Attr->getType() >= 0"
, "clang/lib/AST/ItaniumMangle.cpp", 3320, __extension__ __PRETTY_FUNCTION__
))
;
3321 if (Attr->isDynamic())
3322 Out << "U25pass_dynamic_object_size" << Attr->getType();
3323 else
3324 Out << "U17pass_object_size" << Attr->getType();
3325 }
3326 }
3327 }
3328
3329 FunctionTypeDepth.pop(saved);
3330
3331 // <builtin-type> ::= z # ellipsis
3332 if (Proto->isVariadic())
3333 Out << 'z';
3334}
3335
3336// <type> ::= <class-enum-type>
3337// <class-enum-type> ::= <name>
3338void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3339 mangleName(T->getDecl());
3340}
3341
3342// <type> ::= <class-enum-type>
3343// <class-enum-type> ::= <name>
3344void CXXNameMangler::mangleType(const EnumType *T) {
3345 mangleType(static_cast<const TagType*>(T));
3346}
3347void CXXNameMangler::mangleType(const RecordType *T) {
3348 mangleType(static_cast<const TagType*>(T));
3349}
3350void CXXNameMangler::mangleType(const TagType *T) {
3351 mangleName(T->getDecl());
3352}
3353
3354// <type> ::= <array-type>
3355// <array-type> ::= A <positive dimension number> _ <element type>
3356// ::= A [<dimension expression>] _ <element type>
3357void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3358 Out << 'A' << T->getSize() << '_';
3359 mangleType(T->getElementType());
3360}
3361void CXXNameMangler::mangleType(const VariableArrayType *T) {
3362 Out << 'A';
3363 // decayed vla types (size 0) will just be skipped.
3364 if (T->getSizeExpr())
3365 mangleExpression(T->getSizeExpr());
3366 Out << '_';
3367 mangleType(T->getElementType());
3368}
3369void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3370 Out << 'A';
3371 // A DependentSizedArrayType might not have size expression as below
3372 //
3373 // template<int ...N> int arr[] = {N...};
3374 if (T->getSizeExpr())
3375 mangleExpression(T->getSizeExpr());
3376 Out << '_';
3377 mangleType(T->getElementType());
3378}
3379void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3380 Out << "A_";
3381 mangleType(T->getElementType());
3382}
3383
3384// <type> ::= <pointer-to-member-type>
3385// <pointer-to-member-type> ::= M <class type> <member type>
3386void CXXNameMangler::mangleType(const MemberPointerType *T) {
3387 Out << 'M';
3388 mangleType(QualType(T->getClass(), 0));
3389 QualType PointeeType = T->getPointeeType();
3390 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3391 mangleType(FPT);
3392
3393 // Itanium C++ ABI 5.1.8:
3394 //
3395 // The type of a non-static member function is considered to be different,
3396 // for the purposes of substitution, from the type of a namespace-scope or
3397 // static member function whose type appears similar. The types of two
3398 // non-static member functions are considered to be different, for the
3399 // purposes of substitution, if the functions are members of different
3400 // classes. In other words, for the purposes of substitution, the class of
3401 // which the function is a member is considered part of the type of
3402 // function.
3403
3404 // Given that we already substitute member function pointers as a
3405 // whole, the net effect of this rule is just to unconditionally
3406 // suppress substitution on the function type in a member pointer.
3407 // We increment the SeqID here to emulate adding an entry to the
3408 // substitution table.
3409 ++SeqID;
3410 } else
3411 mangleType(PointeeType);
3412}
3413
3414// <type> ::= <template-param>
3415void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3416 mangleTemplateParameter(T->getDepth(), T->getIndex());
3417}
3418
3419// <type> ::= <template-param>
3420void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3421 // FIXME: not clear how to mangle this!
3422 // template <class T...> class A {
3423 // template <class U...> void foo(T(*)(U) x...);
3424 // };
3425 Out << "_SUBSTPACK_";
3426}
3427
3428// <type> ::= P <type> # pointer-to
3429void CXXNameMangler::mangleType(const PointerType *T) {
3430 Out << 'P';
3431 mangleType(T->getPointeeType());
3432}
3433void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3434 Out << 'P';
3435 mangleType(T->getPointeeType());
3436}
3437
3438// <type> ::= R <type> # reference-to
3439void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3440 Out << 'R';
3441 mangleType(T->getPointeeType());
3442}
3443
3444// <type> ::= O <type> # rvalue reference-to (C++0x)
3445void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3446 Out << 'O';
3447 mangleType(T->getPointeeType());
3448}
3449
3450// <type> ::= C <type> # complex pair (C 2000)
3451void CXXNameMangler::mangleType(const ComplexType *T) {
3452 Out << 'C';
3453 mangleType(T->getElementType());
3454}
3455
3456// ARM's ABI for Neon vector types specifies that they should be mangled as
3457// if they are structs (to match ARM's initial implementation). The
3458// vector type must be one of the special types predefined by ARM.
3459void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3460 QualType EltType = T->getElementType();
3461 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType")(static_cast <bool> (EltType->isBuiltinType() &&
"Neon vector element not a BuiltinType") ? void (0) : __assert_fail
("EltType->isBuiltinType() && \"Neon vector element not a BuiltinType\""
, "clang/lib/AST/ItaniumMangle.cpp", 3461, __extension__ __PRETTY_FUNCTION__
))
;
3462 const char *EltName = nullptr;
3463 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3464 switch (cast<BuiltinType>(EltType)->getKind()) {
3465 case BuiltinType::SChar:
3466 case BuiltinType::UChar:
3467 EltName = "poly8_t";
3468 break;
3469 case BuiltinType::Short:
3470 case BuiltinType::UShort:
3471 EltName = "poly16_t";
3472 break;
3473 case BuiltinType::LongLong:
3474 case BuiltinType::ULongLong:
3475 EltName = "poly64_t";
3476 break;
3477 default: llvm_unreachable("unexpected Neon polynomial vector element type")::llvm::llvm_unreachable_internal("unexpected Neon polynomial vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3477)
;
3478 }
3479 } else {
3480 switch (cast<BuiltinType>(EltType)->getKind()) {
3481 case BuiltinType::SChar: EltName = "int8_t"; break;
3482 case BuiltinType::UChar: EltName = "uint8_t"; break;
3483 case BuiltinType::Short: EltName = "int16_t"; break;
3484 case BuiltinType::UShort: EltName = "uint16_t"; break;
3485 case BuiltinType::Int: EltName = "int32_t"; break;
3486 case BuiltinType::UInt: EltName = "uint32_t"; break;
3487 case BuiltinType::LongLong: EltName = "int64_t"; break;
3488 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3489 case BuiltinType::Double: EltName = "float64_t"; break;
3490 case BuiltinType::Float: EltName = "float32_t"; break;
3491 case BuiltinType::Half: EltName = "float16_t"; break;
3492 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3493 default:
3494 llvm_unreachable("unexpected Neon vector element type")::llvm::llvm_unreachable_internal("unexpected Neon vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3494)
;
3495 }
3496 }
3497 const char *BaseName = nullptr;
3498 unsigned BitSize = (T->getNumElements() *
3499 getASTContext().getTypeSize(EltType));
3500 if (BitSize == 64)
3501 BaseName = "__simd64_";
3502 else {
3503 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits")(static_cast <bool> (BitSize == 128 && "Neon vector type not 64 or 128 bits"
) ? void (0) : __assert_fail ("BitSize == 128 && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3503, __extension__ __PRETTY_FUNCTION__
))
;
3504 BaseName = "__simd128_";
3505 }
3506 Out << strlen(BaseName) + strlen(EltName);
3507 Out << BaseName << EltName;
3508}
3509
3510void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3511 DiagnosticsEngine &Diags = Context.getDiags();
3512 unsigned DiagID = Diags.getCustomDiagID(
3513 DiagnosticsEngine::Error,
3514 "cannot mangle this dependent neon vector type yet");
3515 Diags.Report(T->getAttributeLoc(), DiagID);
3516}
3517
3518static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3519 switch (EltType->getKind()) {
3520 case BuiltinType::SChar:
3521 return "Int8";
3522 case BuiltinType::Short:
3523 return "Int16";
3524 case BuiltinType::Int:
3525 return "Int32";
3526 case BuiltinType::Long:
3527 case BuiltinType::LongLong:
3528 return "Int64";
3529 case BuiltinType::UChar:
3530 return "Uint8";
3531 case BuiltinType::UShort:
3532 return "Uint16";
3533 case BuiltinType::UInt:
3534 return "Uint32";
3535 case BuiltinType::ULong:
3536 case BuiltinType::ULongLong:
3537 return "Uint64";
3538 case BuiltinType::Half:
3539 return "Float16";
3540 case BuiltinType::Float:
3541 return "Float32";
3542 case BuiltinType::Double:
3543 return "Float64";
3544 case BuiltinType::BFloat16:
3545 return "Bfloat16";
3546 default:
3547 llvm_unreachable("Unexpected vector element base type")::llvm::llvm_unreachable_internal("Unexpected vector element base type"
, "clang/lib/AST/ItaniumMangle.cpp", 3547)
;
3548 }
3549}
3550
3551// AArch64's ABI for Neon vector types specifies that they should be mangled as
3552// the equivalent internal name. The vector type must be one of the special
3553// types predefined by ARM.
3554void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3555 QualType EltType = T->getElementType();
3556 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType")(static_cast <bool> (EltType->isBuiltinType() &&
"Neon vector element not a BuiltinType") ? void (0) : __assert_fail
("EltType->isBuiltinType() && \"Neon vector element not a BuiltinType\""
, "clang/lib/AST/ItaniumMangle.cpp", 3556, __extension__ __PRETTY_FUNCTION__
))
;
3557 unsigned BitSize =
3558 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3559 (void)BitSize; // Silence warning.
3560
3561 assert((BitSize == 64 || BitSize == 128) &&(static_cast <bool> ((BitSize == 64 || BitSize == 128) &&
"Neon vector type not 64 or 128 bits") ? void (0) : __assert_fail
("(BitSize == 64 || BitSize == 128) && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3562, __extension__ __PRETTY_FUNCTION__
))
3562 "Neon vector type not 64 or 128 bits")(static_cast <bool> ((BitSize == 64 || BitSize == 128) &&
"Neon vector type not 64 or 128 bits") ? void (0) : __assert_fail
("(BitSize == 64 || BitSize == 128) && \"Neon vector type not 64 or 128 bits\""
, "clang/lib/AST/ItaniumMangle.cpp", 3562, __extension__ __PRETTY_FUNCTION__
))
;
3563
3564 StringRef EltName;
3565 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3566 switch (cast<BuiltinType>(EltType)->getKind()) {
3567 case BuiltinType::UChar:
3568 EltName = "Poly8";
3569 break;
3570 case BuiltinType::UShort:
3571 EltName = "Poly16";
3572 break;
3573 case BuiltinType::ULong:
3574 case BuiltinType::ULongLong:
3575 EltName = "Poly64";
3576 break;
3577 default:
3578 llvm_unreachable("unexpected Neon polynomial vector element type")::llvm::llvm_unreachable_internal("unexpected Neon polynomial vector element type"
, "clang/lib/AST/ItaniumMangle.cpp", 3578)
;
3579 }
3580 } else
3581 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3582
3583 std::string TypeName =
3584 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3585 Out << TypeName.length() << TypeName;
3586}
3587void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3588 DiagnosticsEngine &Diags = Context.getDiags();
3589 unsigned DiagID = Diags.getCustomDiagID(
3590 DiagnosticsEngine::Error,
3591 "cannot mangle this dependent neon vector type yet");
3592 Diags.Report(T->getAttributeLoc(), DiagID);
3593}
3594
3595// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3596// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3597// type as the sizeless variants.
3598//
3599// The mangling scheme for VLS types is implemented as a "pseudo" template:
3600//
3601// '__SVE_VLS<<type>, <vector length>>'
3602//
3603// Combining the existing SVE type and a specific vector length (in bits).
3604// For example:
3605//
3606// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3607//
3608// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3609//
3610// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3611//
3612// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3613//
3614// The latest ACLE specification (00bet5) does not contain details of this
3615// mangling scheme, it will be specified in the next revision. The mangling
3616// scheme is otherwise defined in the appendices to the Procedure Call Standard
3617// for the Arm Architecture, see
3618// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3619void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3620 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector ||(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3622, __extension__ __PRETTY_FUNCTION__
))
3621 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) &&(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3622, __extension__ __PRETTY_FUNCTION__
))
3622 "expected fixed-length SVE vector!")(static_cast <bool> ((T->getVectorKind() == VectorType
::SveFixedLengthDataVector || T->getVectorKind() == VectorType
::SveFixedLengthPredicateVector) && "expected fixed-length SVE vector!"
) ? void (0) : __assert_fail ("(T->getVectorKind() == VectorType::SveFixedLengthDataVector || T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && \"expected fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3622, __extension__ __PRETTY_FUNCTION__
))
;
3623
3624 QualType EltType = T->getElementType();
3625 assert(EltType->isBuiltinType() &&(static_cast <bool> (EltType->isBuiltinType() &&
"expected builtin type for fixed-length SVE vector!") ? void
(0) : __assert_fail ("EltType->isBuiltinType() && \"expected builtin type for fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3626, __extension__ __PRETTY_FUNCTION__
))
3626 "expected builtin type for fixed-length SVE vector!")(static_cast <bool> (EltType->isBuiltinType() &&
"expected builtin type for fixed-length SVE vector!") ? void
(0) : __assert_fail ("EltType->isBuiltinType() && \"expected builtin type for fixed-length SVE vector!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3626, __extension__ __PRETTY_FUNCTION__
))
;
3627
3628 StringRef TypeName;
3629 switch (cast<BuiltinType>(EltType)->getKind()) {
3630 case BuiltinType::SChar:
3631 TypeName = "__SVInt8_t";
3632 break;
3633 case BuiltinType::UChar: {
3634 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector)
3635 TypeName = "__SVUint8_t";
3636 else
3637 TypeName = "__SVBool_t";
3638 break;
3639 }
3640 case BuiltinType::Short:
3641 TypeName = "__SVInt16_t";
3642 break;
3643 case BuiltinType::UShort:
3644 TypeName = "__SVUint16_t";
3645 break;
3646 case BuiltinType::Int:
3647 TypeName = "__SVInt32_t";
3648 break;
3649 case BuiltinType::UInt:
3650 TypeName = "__SVUint32_t";
3651 break;
3652 case BuiltinType::Long:
3653 TypeName = "__SVInt64_t";
3654 break;
3655 case BuiltinType::ULong:
3656 TypeName = "__SVUint64_t";
3657 break;
3658 case BuiltinType::Half:
3659 TypeName = "__SVFloat16_t";
3660 break;
3661 case BuiltinType::Float:
3662 TypeName = "__SVFloat32_t";
3663 break;
3664 case BuiltinType::Double:
3665 TypeName = "__SVFloat64_t";
3666 break;
3667 case BuiltinType::BFloat16:
3668 TypeName = "__SVBfloat16_t";
3669 break;
3670 default:
3671 llvm_unreachable("unexpected element type for fixed-length SVE vector!")::llvm::llvm_unreachable_internal("unexpected element type for fixed-length SVE vector!"
, "clang/lib/AST/ItaniumMangle.cpp", 3671)
;
3672 }
3673
3674 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3675
3676 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
3677 VecSizeInBits *= 8;
3678
3679 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3680 << VecSizeInBits << "EE";
3681}
3682
3683void CXXNameMangler::mangleAArch64FixedSveVectorType(
3684 const DependentVectorType *T) {
3685 DiagnosticsEngine &Diags = Context.getDiags();
3686 unsigned DiagID = Diags.getCustomDiagID(
3687 DiagnosticsEngine::Error,
3688 "cannot mangle this dependent fixed-length SVE vector type yet");
3689 Diags.Report(T->getAttributeLoc(), DiagID);
3690}
3691
3692// GNU extension: vector types
3693// <type> ::= <vector-type>
3694// <vector-type> ::= Dv <positive dimension number> _
3695// <extended element type>
3696// ::= Dv [<dimension expression>] _ <element type>
3697// <extended element type> ::= <element type>
3698// ::= p # AltiVec vector pixel
3699// ::= b # Altivec vector bool
3700void CXXNameMangler::mangleType(const VectorType *T) {
3701 if ((T->getVectorKind() == VectorType::NeonVector ||
3702 T->getVectorKind() == VectorType::NeonPolyVector)) {
3703 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3704 llvm::Triple::ArchType Arch =
3705 getASTContext().getTargetInfo().getTriple().getArch();
3706 if ((Arch == llvm::Triple::aarch64 ||
3707 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3708 mangleAArch64NeonVectorType(T);
3709 else
3710 mangleNeonVectorType(T);
3711 return;
3712 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
3713 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
3714 mangleAArch64FixedSveVectorType(T);
3715 return;
3716 }
3717 Out << "Dv" << T->getNumElements() << '_';
3718 if (T->getVectorKind() == VectorType::AltiVecPixel)
3719 Out << 'p';
3720 else if (T->getVectorKind() == VectorType::AltiVecBool)
3721 Out << 'b';
3722 else
3723 mangleType(T->getElementType());
3724}
3725
3726void CXXNameMangler::mangleType(const DependentVectorType *T) {
3727 if ((T->getVectorKind() == VectorType::NeonVector ||
3728 T->getVectorKind() == VectorType::NeonPolyVector)) {
3729 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3730 llvm::Triple::ArchType Arch =
3731 getASTContext().getTargetInfo().getTriple().getArch();
3732 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3733 !Target.isOSDarwin())
3734 mangleAArch64NeonVectorType(T);
3735 else
3736 mangleNeonVectorType(T);
3737 return;
3738 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
3739 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
3740 mangleAArch64FixedSveVectorType(T);
3741 return;
3742 }
3743
3744 Out << "Dv";
3745 mangleExpression(T->getSizeExpr());
3746 Out << '_';
3747 if (T->getVectorKind() == VectorType::AltiVecPixel)
3748 Out << 'p';
3749 else if (T->getVectorKind() == VectorType::AltiVecBool)
3750 Out << 'b';
3751 else
3752 mangleType(T->getElementType());
3753}
3754
3755void CXXNameMangler::mangleType(const ExtVectorType *T) {
3756 mangleType(static_cast<const VectorType*>(T));
3757}
3758void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3759 Out << "Dv";
3760 mangleExpression(T->getSizeExpr());
3761 Out << '_';
3762 mangleType(T->getElementType());
3763}
3764
3765void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
3766 // Mangle matrix types as a vendor extended type:
3767 // u<Len>matrix_typeI<Rows><Columns><element type>E
3768
3769 StringRef VendorQualifier = "matrix_type";
3770 Out << "u" << VendorQualifier.size() << VendorQualifier;
3771
3772 Out << "I";
3773 auto &ASTCtx = getASTContext();
3774 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
3775 llvm::APSInt Rows(BitWidth);
3776 Rows = T->getNumRows();
3777 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
3778 llvm::APSInt Columns(BitWidth);
3779 Columns = T->getNumColumns();
3780 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
3781 mangleType(T->getElementType());
3782 Out << "E";
3783}
3784
3785void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
3786 // Mangle matrix types as a vendor extended type:
3787 // u<Len>matrix_typeI<row expr><column expr><element type>E
3788 StringRef VendorQualifier = "matrix_type";
3789 Out << "u" << VendorQualifier.size() << VendorQualifier;
3790
3791 Out << "I";
3792 mangleTemplateArgExpr(T->getRowExpr());
3793 mangleTemplateArgExpr(T->getColumnExpr());
3794 mangleType(T->getElementType());
3795 Out << "E";
3796}
3797
3798void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3799 SplitQualType split = T->getPointeeType().split();
3800 mangleQualifiers(split.Quals, T);
3801 mangleType(QualType(split.Ty, 0));
3802}
3803
3804void CXXNameMangler::mangleType(const PackExpansionType *T) {
3805 // <type> ::= Dp <type> # pack expansion (C++0x)
3806 Out << "Dp";
3807 mangleType(T->getPattern());
3808}
3809
3810void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3811 mangleSourceName(T->getDecl()->getIdentifier());
3812}
3813
3814void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3815 // Treat __kindof as a vendor extended type qualifier.
3816 if (T->isKindOfType())
3817 Out << "U8__kindof";
3818
3819 if (!T->qual_empty()) {
3820 // Mangle protocol qualifiers.
3821 SmallString<64> QualStr;
3822 llvm::raw_svector_ostream QualOS(QualStr);
3823 QualOS << "objcproto";
3824 for (const auto *I : T->quals()) {
3825 StringRef name = I->getName();
3826 QualOS << name.size() << name;
3827 }
3828 Out << 'U' << QualStr.size() << QualStr;
3829 }
3830
3831 mangleType(T->getBaseType());
3832
3833 if (T->isSpecialized()) {
3834 // Mangle type arguments as I <type>+ E
3835 Out << 'I';
3836 for (auto typeArg : T->getTypeArgs())
3837 mangleType(typeArg);
3838 Out << 'E';
3839 }
3840}
3841
3842void CXXNameMangler::mangleType(const BlockPointerType *T) {
3843 Out << "U13block_pointer";
3844 mangleType(T->getPointeeType());
3845}
3846
3847void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3848 // Mangle injected class name types as if the user had written the
3849 // specialization out fully. It may not actually be possible to see
3850 // this mangling, though.
3851 mangleType(T->getInjectedSpecializationType());
3852}
3853
3854void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3855 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3856 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3857 } else {
3858 if (mangleSubstitution(QualType(T, 0)))
3859 return;
3860
3861 mangleTemplatePrefix(T->getTemplateName());
3862
3863 // FIXME: GCC does not appear to mangle the template arguments when
3864 // the template in question is a dependent template name. Should we
3865 // emulate that badness?
3866 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
3867 addSubstitution(QualType(T, 0));
3868 }
3869}
3870
3871void CXXNameMangler::mangleType(const DependentNameType *T) {
3872 // Proposal by cxx-abi-dev, 2014-03-26
3873 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3874 // # dependent elaborated type specifier using
3875 // # 'typename'
3876 // ::= Ts <name> # dependent elaborated type specifier using
3877 // # 'struct' or 'class'
3878 // ::= Tu <name> # dependent elaborated type specifier using
3879 // # 'union'
3880 // ::= Te <name> # dependent elaborated type specifier using
3881 // # 'enum'
3882 switch (T->getKeyword()) {
3883 case ETK_None:
3884 case ETK_Typename:
3885 break;
3886 case ETK_Struct:
3887 case ETK_Class:
3888 case ETK_Interface:
3889 Out << "Ts";
3890 break;
3891 case ETK_Union:
3892 Out << "Tu";
3893 break;
3894 case ETK_Enum:
3895 Out << "Te";
3896 break;
3897 }
3898 // Typename types are always nested
3899 Out << 'N';
3900 manglePrefix(T->getQualifier());
3901 mangleSourceName(T->getIdentifier());
3902 Out << 'E';
3903}
3904
3905void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3906 // Dependently-scoped template types are nested if they have a prefix.
3907 Out << 'N';
3908
3909 // TODO: avoid making this TemplateName.
3910 TemplateName Prefix =
3911 getASTContext().getDependentTemplateName(T->getQualifier(),
3912 T->getIdentifier());
3913 mangleTemplatePrefix(Prefix);
3914
3915 // FIXME: GCC does not appear to mangle the template arguments when
3916 // the template in question is a dependent template name. Should we
3917 // emulate that badness?
3918 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());
3919 Out << 'E';
3920}
3921
3922void CXXNameMangler::mangleType(const TypeOfType *T) {
3923 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3924 // "extension with parameters" mangling.
3925 Out << "u6typeof";
3926}
3927
3928void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3929 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3930 // "extension with parameters" mangling.
3931 Out << "u6typeof";
3932}
3933
3934void CXXNameMangler::mangleType(const DecltypeType *T) {
3935 Expr *E = T->getUnderlyingExpr();
3936
3937 // type ::= Dt <expression> E # decltype of an id-expression
3938 // # or class member access
3939 // ::= DT <expression> E # decltype of an expression
3940
3941 // This purports to be an exhaustive list of id-expressions and
3942 // class member accesses. Note that we do not ignore parentheses;
3943 // parentheses change the semantics of decltype for these
3944 // expressions (and cause the mangler to use the other form).
3945 if (isa<DeclRefExpr>(E) ||
3946 isa<MemberExpr>(E) ||
3947 isa<UnresolvedLookupExpr>(E) ||
3948 isa<DependentScopeDeclRefExpr>(E) ||
3949 isa<CXXDependentScopeMemberExpr>(E) ||
3950 isa<UnresolvedMemberExpr>(E))
3951 Out << "Dt";
3952 else
3953 Out << "DT";
3954 mangleExpression(E);
3955 Out << 'E';
3956}
3957
3958void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3959 // If this is dependent, we need to record that. If not, we simply
3960 // mangle it as the underlying type since they are equivalent.
3961 if (T->isDependentType()) {
3962 Out << 'U';
3963
3964 switch (T->getUTTKind()) {
3965 case UnaryTransformType::EnumUnderlyingType:
3966 Out << "3eut";
3967 break;
3968 }
3969 }
3970
3971 mangleType(T->getBaseType());
3972}
3973
3974void CXXNameMangler::mangleType(const AutoType *T) {
3975 assert(T->getDeducedType().isNull() &&(static_cast <bool> (T->getDeducedType().isNull() &&
"Deduced AutoType shouldn't be handled here!") ? void (0) : __assert_fail
("T->getDeducedType().isNull() && \"Deduced AutoType shouldn't be handled here!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3976, __extension__ __PRETTY_FUNCTION__
))
3976 "Deduced AutoType shouldn't be handled here!")(static_cast <bool> (T->getDeducedType().isNull() &&
"Deduced AutoType shouldn't be handled here!") ? void (0) : __assert_fail
("T->getDeducedType().isNull() && \"Deduced AutoType shouldn't be handled here!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3976, __extension__ __PRETTY_FUNCTION__
))
;
3977 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&(static_cast <bool> (T->getKeyword() != AutoTypeKeyword
::GNUAutoType && "shouldn't need to mangle __auto_type!"
) ? void (0) : __assert_fail ("T->getKeyword() != AutoTypeKeyword::GNUAutoType && \"shouldn't need to mangle __auto_type!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3978, __extension__ __PRETTY_FUNCTION__
))
3978 "shouldn't need to mangle __auto_type!")(static_cast <bool> (T->getKeyword() != AutoTypeKeyword
::GNUAutoType && "shouldn't need to mangle __auto_type!"
) ? void (0) : __assert_fail ("T->getKeyword() != AutoTypeKeyword::GNUAutoType && \"shouldn't need to mangle __auto_type!\""
, "clang/lib/AST/ItaniumMangle.cpp", 3978, __extension__ __PRETTY_FUNCTION__
))
;
3979 // <builtin-type> ::= Da # auto
3980 // ::= Dc # decltype(auto)
3981 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3982}
3983
3984void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3985 QualType Deduced = T->getDeducedType();
3986 if (!Deduced.isNull())
3987 return mangleType(Deduced);
3988
3989 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
3990 assert(TD && "shouldn't form deduced TST unless we know we have a template")(static_cast <bool> (TD && "shouldn't form deduced TST unless we know we have a template"
) ? void (0) : __assert_fail ("TD && \"shouldn't form deduced TST unless we know we have a template\""
, "clang/lib/AST/ItaniumMangle.cpp", 3990, __extension__ __PRETTY_FUNCTION__
))
;
3991
3992 if (mangleSubstitution(TD))
3993 return;
3994
3995 mangleName(GlobalDecl(TD));
3996 addSubstitution(TD);
3997}
3998
3999void CXXNameMangler::mangleType(const AtomicType *T) {
4000 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4001 // (Until there's a standardized mangling...)
4002 Out << "U7_Atomic";
4003 mangleType(T->getValueType());
4004}
4005
4006void CXXNameMangler::mangleType(const PipeType *T) {
4007 // Pipe type mangling rules are described in SPIR 2.0 specification
4008 // A.1 Data types and A.3 Summary of changes
4009 // <type> ::= 8ocl_pipe
4010 Out << "8ocl_pipe";
4011}
4012
4013void CXXNameMangler::mangleType(const BitIntType *T) {
4014 // 5.1.5.2 Builtin types
4015 // <type> ::= DB <number | instantiation-dependent expression> _
4016 // ::= DU <number | instantiation-dependent expression> _
4017 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4018}
4019
4020void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4021 // 5.1.5.2 Builtin types
4022 // <type> ::= DB <number | instantiation-dependent expression> _
4023 // ::= DU <number | instantiation-dependent expression> _
4024 Out << "D" << (T->isUnsigned() ? "U" : "B");
4025 mangleExpression(T->getNumBitsExpr());
4026 Out << "_";
4027}
4028
4029void CXXNameMangler::mangleIntegerLiteral(QualType T,
4030 const llvm::APSInt &Value) {
4031 // <expr-primary> ::= L <type> <value number> E # integer literal
4032 Out << 'L';
4033
4034 mangleType(T);
4035 if (T->isBooleanType()) {
4036 // Boolean values are encoded as 0/1.
4037 Out << (Value.getBoolValue() ? '1' : '0');
4038 } else {
4039 mangleNumber(Value);
4040 }
4041 Out << 'E';
4042
4043}
4044
4045void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4046 // Ignore member expressions involving anonymous unions.
4047 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4048 if (!RT->getDecl()->isAnonymousStructOrUnion())
4049 break;
4050 const auto *ME = dyn_cast<MemberExpr>(Base);
4051 if (!ME)
4052 break;
4053 Base = ME->getBase();
4054 IsArrow = ME->isArrow();
4055 }
4056
4057 if (Base->isImplicitCXXThis()) {
4058 // Note: GCC mangles member expressions to the implicit 'this' as
4059 // *this., whereas we represent them as this->. The Itanium C++ ABI
4060 // does not specify anything here, so we follow GCC.
4061 Out << "dtdefpT";
4062 } else {
4063 Out << (IsArrow ? "pt" : "dt");
4064 mangleExpression(Base);
4065 }
4066}
4067
4068/// Mangles a member expression.
4069void CXXNameMangler::mangleMemberExpr(const Expr *base,
4070 bool isArrow,
4071 NestedNameSpecifier *qualifier,
4072 NamedDecl *firstQualifierLookup,
4073 DeclarationName member,
4074 const TemplateArgumentLoc *TemplateArgs,
4075 unsigned NumTemplateArgs,
4076 unsigned arity) {
4077 // <expression> ::= dt <expression> <unresolved-name>
4078 // ::= pt <expression> <unresolved-name>
4079 if (base)
4080 mangleMemberExprBase(base, isArrow);
4081 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4082}
4083
4084/// Look at the callee of the given call expression and determine if
4085/// it's a parenthesized id-expression which would have triggered ADL
4086/// otherwise.
4087static bool isParenthesizedADLCallee(const CallExpr *call) {
4088 const Expr *callee = call->getCallee();
4089 const Expr *fn = callee->IgnoreParens();
4090
4091 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4092 // too, but for those to appear in the callee, it would have to be
4093 // parenthesized.
4094 if (callee == fn) return false;
4095
4096 // Must be an unresolved lookup.
4097 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4098 if (!lookup) return false;
4099
4100 assert(!lookup->requiresADL())(static_cast <bool> (!lookup->requiresADL()) ? void (
0) : __assert_fail ("!lookup->requiresADL()", "clang/lib/AST/ItaniumMangle.cpp"
, 4100, __extension__ __PRETTY_FUNCTION__))
;
4101
4102 // Must be an unqualified lookup.
4103 if (lookup->getQualifier()) return false;
4104
4105 // Must not have found a class member. Note that if one is a class
4106 // member, they're all class members.
4107 if (lookup->getNumDecls() > 0 &&
4108 (*lookup->decls_begin())->isCXXClassMember())
4109 return false;
4110
4111 // Otherwise, ADL would have been triggered.
4112 return true;
4113}
4114
4115void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4116 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4117 Out << CastEncoding;
4118 mangleType(ECE->getType());
4119 mangleExpression(ECE->getSubExpr());
4120}
4121
4122void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4123 if (auto *Syntactic = InitList->getSyntacticForm())
4124 InitList = Syntactic;
4125 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4126 mangleExpression(InitList->getInit(i));
4127}
4128
4129void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4130 bool AsTemplateArg) {
4131 // <expression> ::= <unary operator-name> <expression>
4132 // ::= <binary operator-name> <expression> <expression>
4133 // ::= <trinary operator-name> <expression> <expression> <expression>
4134 // ::= cv <type> expression # conversion with one argument
4135 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4136 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4137 // ::= sc <type> <expression> # static_cast<type> (expression)
4138 // ::= cc <type> <expression> # const_cast<type> (expression)
4139 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4140 // ::= st <type> # sizeof (a type)
4141 // ::= at <type> # alignof (a type)
4142 // ::= <template-param>
4143 // ::= <function-param>
4144 // ::= fpT # 'this' expression (part of <function-param>)
4145 // ::= sr <type> <unqualified-name> # dependent name
4146 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4147 // ::= ds <expression> <expression> # expr.*expr
4148 // ::= sZ <template-param> # size of a parameter pack
4149 // ::= sZ <function-param> # size of a function parameter pack
4150 // ::= u <source-name> <template-arg>* E # vendor extended expression
4151 // ::= <expr-primary>
4152 // <expr-primary> ::= L <type> <value number> E # integer literal
4153 // ::= L <type> <value float> E # floating literal
4154 // ::= L <type> <string type> E # string literal
4155 // ::= L <nullptr type> E # nullptr literal "LDnE"
4156 // ::= L <pointer type> 0 E # null pointer template argument
4157 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4158 // ::= L <mangled-name> E # external name
4159 QualType ImplicitlyConvertedToType;
4160
4161 // A top-level expression that's not <expr-primary> needs to be wrapped in
4162 // X...E in a template arg.
4163 bool IsPrimaryExpr = true;
4164 auto NotPrimaryExpr = [&] {
4165 if (AsTemplateArg && IsPrimaryExpr)
4166 Out << 'X';
4167 IsPrimaryExpr = false;
4168 };
4169
4170 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4171 switch (D->getKind()) {
4172 default:
4173 // <expr-primary> ::= L <mangled-name> E # external name
4174 Out << 'L';
4175 mangle(D);
4176 Out << 'E';
4177 break;
4178
4179 case Decl::ParmVar:
4180 NotPrimaryExpr();
4181 mangleFunctionParam(cast<ParmVarDecl>(D));
4182 break;
4183
4184 case Decl::EnumConstant: {
4185 // <expr-primary>
4186 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4187 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4188 break;
4189 }
4190
4191 case Decl::NonTypeTemplateParm:
4192 NotPrimaryExpr();
4193 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4194 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4195 break;
4196 }
4197 };
4198
4199 // 'goto recurse' is used when handling a simple "unwrapping" node which
4200 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4201 // to be preserved.
4202recurse:
4203 switch (E->getStmtClass()) {
4204 case Expr::NoStmtClass:
4205#define ABSTRACT_STMT(Type)
4206#define EXPR(Type, Base)
4207#define STMT(Type, Base) \
4208 case Expr::Type##Class:
4209#include "clang/AST/StmtNodes.inc"
4210 // fallthrough
4211
4212 // These all can only appear in local or variable-initialization
4213 // contexts and so should never appear in a mangling.
4214 case Expr::AddrLabelExprClass:
4215 case Expr::DesignatedInitUpdateExprClass:
4216 case Expr::ImplicitValueInitExprClass:
4217 case Expr::ArrayInitLoopExprClass:
4218 case Expr::ArrayInitIndexExprClass:
4219 case Expr::NoInitExprClass:
4220 case Expr::ParenListExprClass:
4221 case Expr::MSPropertyRefExprClass:
4222 case Expr::MSPropertySubscriptExprClass:
4223 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4224 case Expr::RecoveryExprClass:
4225 case Expr::OMPArraySectionExprClass:
4226 case Expr::OMPArrayShapingExprClass:
4227 case Expr::OMPIteratorExprClass:
4228 case Expr::CXXInheritedCtorInitExprClass:
4229 llvm_unreachable("unexpected statement kind")::llvm::llvm_unreachable_internal("unexpected statement kind"
, "clang/lib/AST/ItaniumMangle.cpp", 4229)
;
4230
4231 case Expr::ConstantExprClass:
4232 E = cast<ConstantExpr>(E)->getSubExpr();
4233 goto recurse;
4234
4235 // FIXME: invent manglings for all these.
4236 case Expr::BlockExprClass:
4237 case Expr::ChooseExprClass:
4238 case Expr::CompoundLiteralExprClass:
4239 case Expr::ExtVectorElementExprClass:
4240 case Expr::GenericSelectionExprClass:
4241 case Expr::ObjCEncodeExprClass:
4242 case Expr::ObjCIsaExprClass:
4243 case Expr::ObjCIvarRefExprClass:
4244 case Expr::ObjCMessageExprClass:
4245 case Expr::ObjCPropertyRefExprClass:
4246 case Expr::ObjCProtocolExprClass:
4247 case Expr::ObjCSelectorExprClass:
4248 case Expr::ObjCStringLiteralClass:
4249 case Expr::ObjCBoxedExprClass:
4250 case Expr::ObjCArrayLiteralClass:
4251 case Expr::ObjCDictionaryLiteralClass:
4252 case Expr::ObjCSubscriptRefExprClass:
4253 case Expr::ObjCIndirectCopyRestoreExprClass:
4254 case Expr::ObjCAvailabilityCheckExprClass:
4255 case Expr::OffsetOfExprClass:
4256 case Expr::PredefinedExprClass:
4257 case Expr::ShuffleVectorExprClass:
4258 case Expr::ConvertVectorExprClass:
4259 case Expr::StmtExprClass:
4260 case Expr::TypeTraitExprClass:
4261 case Expr::RequiresExprClass:
4262 case Expr::ArrayTypeTraitExprClass:
4263 case Expr::ExpressionTraitExprClass:
4264 case Expr::VAArgExprClass:
4265 case Expr::CUDAKernelCallExprClass:
4266 case Expr::AsTypeExprClass:
4267 case Expr::PseudoObjectExprClass:
4268 case Expr::AtomicExprClass:
4269 case Expr::SourceLocExprClass:
4270 case Expr::BuiltinBitCastExprClass:
4271 {
4272 NotPrimaryExpr();
4273 if (!NullOut) {
4274 // As bad as this diagnostic is, it's better than crashing.
4275 DiagnosticsEngine &Diags = Context.getDiags();
4276 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4277 "cannot yet mangle expression type %0");
4278 Diags.Report(E->getExprLoc(), DiagID)
4279 << E->getStmtClassName() << E->getSourceRange();
4280 return;
4281 }
4282 break;
4283 }
4284
4285 case Expr::CXXUuidofExprClass: {
4286 NotPrimaryExpr();
4287 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4288 // As of clang 12, uuidof uses the vendor extended expression
4289 // mangling. Previously, it used a special-cased nonstandard extension.
4290 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4291 LangOptions::ClangABI::Ver11) {
4292 Out << "u8__uuidof";
4293 if (UE->isTypeOperand())
4294 mangleType(UE->getTypeOperand(Context.getASTContext()));
4295 else
4296 mangleTemplateArgExpr(UE->getExprOperand());
4297 Out << 'E';
4298 } else {
4299 if (UE->isTypeOperand()) {
4300 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4301 Out << "u8__uuidoft";
4302 mangleType(UuidT);
4303 } else {
4304 Expr *UuidExp = UE->getExprOperand();
4305 Out << "u8__uuidofz";
4306 mangleExpression(UuidExp);
4307 }
4308 }
4309 break;
4310 }
4311
4312 // Even gcc-4.5 doesn't mangle this.
4313 case Expr::BinaryConditionalOperatorClass: {
4314 NotPrimaryExpr();
4315 DiagnosticsEngine &Diags = Context.getDiags();
4316 unsigned DiagID =
4317 Diags.getCustomDiagID(DiagnosticsEngine::Error,
4318 "?: operator with omitted middle operand cannot be mangled");
4319 Diags.Report(E->getExprLoc(), DiagID)
4320 << E->getStmtClassName() << E->getSourceRange();
4321 return;
4322 }
4323
4324 // These are used for internal purposes and cannot be meaningfully mangled.
4325 case Expr::OpaqueValueExprClass:
4326 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?")::llvm::llvm_unreachable_internal("cannot mangle opaque value; mangling wrong thing?"
, "clang/lib/AST/ItaniumMangle.cpp", 4326)
;
4327
4328 case Expr::InitListExprClass: {
4329 NotPrimaryExpr();
4330 Out << "il";
4331 mangleInitListElements(cast<InitListExpr>(E));
4332 Out << "E";
4333 break;
4334 }
4335
4336 case Expr::DesignatedInitExprClass: {
4337 NotPrimaryExpr();
4338 auto *DIE = cast<DesignatedInitExpr>(E);
4339 for (const auto &Designator : DIE->designators()) {
4340 if (Designator.isFieldDesignator()) {
4341 Out << "di";
4342 mangleSourceName(Designator.getFieldName());
4343 } else if (Designator.isArrayDesignator()) {
4344 Out << "dx";
4345 mangleExpression(DIE->getArrayIndex(Designator));
4346 } else {
4347 assert(Designator.isArrayRangeDesignator() &&(static_cast <bool> (Designator.isArrayRangeDesignator(
) && "unknown designator kind") ? void (0) : __assert_fail
("Designator.isArrayRangeDesignator() && \"unknown designator kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 4348, __extension__ __PRETTY_FUNCTION__
))
4348 "unknown designator kind")(static_cast <bool> (Designator.isArrayRangeDesignator(
) && "unknown designator kind") ? void (0) : __assert_fail
("Designator.isArrayRangeDesignator() && \"unknown designator kind\""
, "clang/lib/AST/ItaniumMangle.cpp", 4348, __extension__ __PRETTY_FUNCTION__
))
;
4349 Out << "dX";
4350 mangleExpression(DIE->getArrayRangeStart(Designator));
4351 mangleExpression(DIE->getArrayRangeEnd(Designator));
4352 }
4353 }
4354 mangleExpression(DIE->getInit());
4355 break;
4356 }
4357
4358 case Expr::CXXDefaultArgExprClass:
4359 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4360 goto recurse;
4361
4362 case Expr::CXXDefaultInitExprClass:
4363 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4364 goto recurse;
4365
4366 case Expr::CXXStdInitializerListExprClass:
4367 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4368 goto recurse;
4369
4370 case Expr::SubstNonTypeTemplateParmExprClass:
4371 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4372 goto recurse;
4373
4374 case Expr::UserDefinedLiteralClass:
4375 // We follow g++'s approach of mangling a UDL as a call to the literal
4376 // operator.
4377 case Expr::CXXMemberCallExprClass: // fallthrough
4378 case Expr::CallExprClass: {
4379 NotPrimaryExpr();
4380 const CallExpr *CE = cast<CallExpr>(E);
4381
4382 // <expression> ::= cp <simple-id> <expression>* E
4383 // We use this mangling only when the call would use ADL except
4384 // for being parenthesized. Per discussion with David
4385 // Vandervoorde, 2011.04.25.
4386 if (isParenthesizedADLCallee(CE)) {
4387 Out << "cp";
4388 // The callee here is a parenthesized UnresolvedLookupExpr with
4389 // no qualifier and should always get mangled as a <simple-id>
4390 // anyway.
4391
4392 // <expression> ::= cl <expression>* E
4393 } else {
4394 Out << "cl";
4395 }
4396
4397 unsigned CallArity = CE->getNumArgs();
4398 for (const Expr *Arg : CE->arguments())
4399 if (isa<PackExpansionExpr>(Arg))
4400 CallArity = UnknownArity;
4401
4402 mangleExpression(CE->getCallee(), CallArity);
4403 for (const Expr *Arg : CE->arguments())
4404 mangleExpression(Arg);
4405 Out << 'E';
4406 break;
4407 }
4408
4409 case Expr::CXXNewExprClass: {
4410 NotPrimaryExpr();
4411 const CXXNewExpr *New = cast<CXXNewExpr>(E);
4412 if (New->isGlobalNew()) Out << "gs";
4413 Out << (New->isArray() ? "na" : "nw");
4414 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
4415 E = New->placement_arg_end(); I != E; ++I)
4416 mangleExpression(*I);
4417 Out << '_';
4418 mangleType(New->getAllocatedType());
4419 if (New->hasInitializer()) {
4420 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
4421 Out << "il";
4422 else
4423 Out << "pi";
4424 const Expr *Init = New->getInitializer();
4425 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4426 // Directly inline the initializers.
4427 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4428 E = CCE->arg_end();
4429 I != E; ++I)
4430 mangleExpression(*I);
4431 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4432 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4433 mangleExpression(PLE->getExpr(i));
4434 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
4435 isa<InitListExpr>(Init)) {
4436 // Only take InitListExprs apart for list-initialization.
4437 mangleInitListElements(cast<InitListExpr>(Init));
4438 } else
4439 mangleExpression(Init);
4440 }
4441 Out << 'E';
4442 break;
4443 }
4444
4445 case Expr::CXXPseudoDestructorExprClass: {
4446 NotPrimaryExpr();
4447 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4448 if (const Expr *Base = PDE->getBase())
4449 mangleMemberExprBase(Base, PDE->isArrow());
4450 NestedNameSpecifier *Qualifier = PDE->getQualifier();
4451 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4452 if (Qualifier) {
4453 mangleUnresolvedPrefix(Qualifier,
4454 /*recursive=*/true);
4455 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4456 Out << 'E';
4457 } else {
4458 Out << "sr";
4459 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4460 Out << 'E';
4461 }
4462 } else if (Qualifier) {
4463 mangleUnresolvedPrefix(Qualifier);
4464 }
4465 // <base-unresolved-name> ::= dn <destructor-name>
4466 Out << "dn";
4467 QualType DestroyedType = PDE->getDestroyedType();
4468 mangleUnresolvedTypeOrSimpleId(DestroyedType);
4469 break;
4470 }
4471
4472 case Expr::MemberExprClass: {
4473 NotPrimaryExpr();
4474 const MemberExpr *ME = cast<MemberExpr>(E);
4475 mangleMemberExpr(ME->getBase(), ME->isArrow(),
4476 ME->getQualifier(), nullptr,
4477 ME->getMemberDecl()->getDeclName(),
4478 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4479 Arity);
4480 break;
4481 }
4482
4483 case Expr::UnresolvedMemberExprClass: {
4484 NotPrimaryExpr();
4485 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4486 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4487 ME->isArrow(), ME->getQualifier(), nullptr,
4488 ME->getMemberName(),
4489 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4490 Arity);
4491 break;
4492 }
4493
4494 case Expr::CXXDependentScopeMemberExprClass: {
4495 NotPrimaryExpr();
4496 const CXXDependentScopeMemberExpr *ME
4497 = cast<CXXDependentScopeMemberExpr>(E);
4498 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4499 ME->isArrow(), ME->getQualifier(),
4500 ME->getFirstQualifierFoundInScope(),
4501 ME->getMember(),
4502 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4503 Arity);
4504 break;
4505 }
4506
4507 case Expr::UnresolvedLookupExprClass: {
4508 NotPrimaryExpr();
4509 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4510 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4511 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4512 Arity);
4513 break;
4514 }
4515
4516 case Expr::CXXUnresolvedConstructExprClass: {
4517 NotPrimaryExpr();
4518 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4519 unsigned N = CE->getNumArgs();
4520
4521 if (CE->isListInitialization()) {
4522 assert(N == 1 && "unexpected form for list initialization")(static_cast <bool> (N == 1 && "unexpected form for list initialization"
) ? void (0) : __assert_fail ("N == 1 && \"unexpected form for list initialization\""
, "clang/lib/AST/ItaniumMangle.cpp", 4522, __extension__ __PRETTY_FUNCTION__
))
;
4523 auto *IL = cast<InitListExpr>(CE->getArg(0));
4524 Out << "tl";
4525 mangleType(CE->getType());
4526 mangleInitListElements(IL);
4527 Out << "E";
4528 break;
4529 }
4530
4531 Out << "cv";
4532 mangleType(CE->getType());
4533 if (N != 1) Out << '_';
4534 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
4535 if (N != 1) Out << 'E';
4536 break;
4537 }
4538
4539 case Expr::CXXConstructExprClass: {
4540 // An implicit cast is silent, thus may contain <expr-primary>.
4541 const auto *CE = cast<CXXConstructExpr>(E);
4542 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
4543 assert((static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
4544 CE->getNumArgs() >= 1 &&(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
4545 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
4546 "implicit CXXConstructExpr must have one argument")(static_cast <bool> (CE->getNumArgs() >= 1 &&
(CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE
->getArg(1))) && "implicit CXXConstructExpr must have one argument"
) ? void (0) : __assert_fail ("CE->getNumArgs() >= 1 && (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && \"implicit CXXConstructExpr must have one argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 4546, __extension__ __PRETTY_FUNCTION__
))
;
4547 E = cast<CXXConstructExpr>(E)->getArg(0);
4548 goto recurse;
4549 }
4550 NotPrimaryExpr();
4551 Out << "il";
4552 for (auto *E : CE->arguments())
4553 mangleExpression(E);
4554 Out << "E";
4555 break;
4556 }
4557
4558 case Expr::CXXTemporaryObjectExprClass: {
4559 NotPrimaryExpr();
4560 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
4561 unsigned N = CE->getNumArgs();
4562 bool List = CE->isListInitialization();
4563
4564 if (List)
4565 Out << "tl";
4566 else
4567 Out << "cv";
4568 mangleType(CE->getType());
4569 if (!List && N != 1)
4570 Out << '_';
4571 if (CE->isStdInitListInitialization()) {
4572 // We implicitly created a std::initializer_list<T> for the first argument
4573 // of a constructor of type U in an expression of the form U{a, b, c}.
4574 // Strip all the semantic gunk off the initializer list.
4575 auto *SILE =
4576 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
4577 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
4578 mangleInitListElements(ILE);
4579 } else {
4580 for (auto *E : CE->arguments())
4581 mangleExpression(E);
4582 }
4583 if (List || N != 1)
4584 Out << 'E';
4585 break;
4586 }
4587
4588 case Expr::CXXScalarValueInitExprClass:
4589 NotPrimaryExpr();
4590 Out << "cv";
4591 mangleType(E->getType());
4592 Out << "_E";
4593 break;
4594
4595 case Expr::CXXNoexceptExprClass:
4596 NotPrimaryExpr();
4597 Out << "nx";
4598 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
4599 break;
4600
4601 case Expr::UnaryExprOrTypeTraitExprClass: {
4602 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
4603 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
4604
4605 if (!SAE->isInstantiationDependent()) {
4606 // Itanium C++ ABI:
4607 // If the operand of a sizeof or alignof operator is not
4608 // instantiation-dependent it is encoded as an integer literal
4609 // reflecting the result of the operator.
4610 //
4611 // If the result of the operator is implicitly converted to a known
4612 // integer type, that type is used for the literal; otherwise, the type
4613 // of std::size_t or std::ptrdiff_t is used.
4614 QualType T = (ImplicitlyConvertedToType.isNull() ||
4615 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
4616 : ImplicitlyConvertedToType;
4617 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
4618 mangleIntegerLiteral(T, V);
4619 break;
4620 }
4621
4622 NotPrimaryExpr(); // But otherwise, they are not.
4623
4624 auto MangleAlignofSizeofArg = [&] {
4625 if (SAE->isArgumentType()) {
4626 Out << 't';
4627 mangleType(SAE->getArgumentType());
4628 } else {
4629 Out << 'z';
4630 mangleExpression(SAE->getArgumentExpr());
4631 }
4632 };
4633
4634 switch(SAE->getKind()) {
4635 case UETT_SizeOf:
4636 Out << 's';
4637 MangleAlignofSizeofArg();
4638 break;
4639 case UETT_PreferredAlignOf:
4640 // As of clang 12, we mangle __alignof__ differently than alignof. (They
4641 // have acted differently since Clang 8, but were previously mangled the
4642 // same.)
4643 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4644 LangOptions::ClangABI::Ver11) {
4645 Out << "u11__alignof__";
4646 if (SAE->isArgumentType())
4647 mangleType(SAE->getArgumentType());
4648 else
4649 mangleTemplateArgExpr(SAE->getArgumentExpr());
4650 Out << 'E';
4651 break;
4652 }
4653 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4654 case UETT_AlignOf:
4655 Out << 'a';
4656 MangleAlignofSizeofArg();
4657 break;
4658 case UETT_VecStep: {
4659 DiagnosticsEngine &Diags = Context.getDiags();
4660 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4661 "cannot yet mangle vec_step expression");
4662 Diags.Report(DiagID);
4663 return;
4664 }
4665 case UETT_OpenMPRequiredSimdAlign: {
4666 DiagnosticsEngine &Diags = Context.getDiags();
4667 unsigned DiagID = Diags.getCustomDiagID(
4668 DiagnosticsEngine::Error,
4669 "cannot yet mangle __builtin_omp_required_simd_align expression");
4670 Diags.Report(DiagID);
4671 return;
4672 }
4673 }
4674 break;
4675 }
4676
4677 case Expr::CXXThrowExprClass: {
4678 NotPrimaryExpr();
4679 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4680 // <expression> ::= tw <expression> # throw expression
4681 // ::= tr # rethrow
4682 if (TE->getSubExpr()) {
4683 Out << "tw";
4684 mangleExpression(TE->getSubExpr());
4685 } else {
4686 Out << "tr";
4687 }
4688 break;
4689 }
4690
4691 case Expr::CXXTypeidExprClass: {
4692 NotPrimaryExpr();
4693 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4694 // <expression> ::= ti <type> # typeid (type)
4695 // ::= te <expression> # typeid (expression)
4696 if (TIE->isTypeOperand()) {
4697 Out << "ti";
4698 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4699 } else {
4700 Out << "te";
4701 mangleExpression(TIE->getExprOperand());
4702 }
4703 break;
4704 }
4705
4706 case Expr::CXXDeleteExprClass: {
4707 NotPrimaryExpr();
4708 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4709 // <expression> ::= [gs] dl <expression> # [::] delete expr
4710 // ::= [gs] da <expression> # [::] delete [] expr
4711 if (DE->isGlobalDelete()) Out << "gs";
4712 Out << (DE->isArrayForm() ? "da" : "dl");
4713 mangleExpression(DE->getArgument());
4714 break;
4715 }
4716
4717 case Expr::UnaryOperatorClass: {
4718 NotPrimaryExpr();
4719 const UnaryOperator *UO = cast<UnaryOperator>(E);
4720 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4721 /*Arity=*/1);
4722 mangleExpression(UO->getSubExpr());
4723 break;
4724 }
4725
4726 case Expr::ArraySubscriptExprClass: {
4727 NotPrimaryExpr();
4728 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4729
4730 // Array subscript is treated as a syntactically weird form of
4731 // binary operator.
4732 Out << "ix";
4733 mangleExpression(AE->getLHS());
4734 mangleExpression(AE->getRHS());
4735 break;
4736 }
4737
4738 case Expr::MatrixSubscriptExprClass: {
4739 NotPrimaryExpr();
4740 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
4741 Out << "ixix";
4742 mangleExpression(ME->getBase());
4743 mangleExpression(ME->getRowIdx());
4744 mangleExpression(ME->getColumnIdx());
4745 break;
4746 }
4747
4748 case Expr::CompoundAssignOperatorClass: // fallthrough
4749 case Expr::BinaryOperatorClass: {
4750 NotPrimaryExpr();
4751 const BinaryOperator *BO = cast<BinaryOperator>(E);
4752 if (BO->getOpcode() == BO_PtrMemD)
4753 Out << "ds";
4754 else
4755 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4756 /*Arity=*/2);
4757 mangleExpression(BO->getLHS());
4758 mangleExpression(BO->getRHS());
4759 break;
4760 }
4761
4762 case Expr::CXXRewrittenBinaryOperatorClass: {
4763 NotPrimaryExpr();
4764 // The mangled form represents the original syntax.
4765 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
4766 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4767 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4768 /*Arity=*/2);
4769 mangleExpression(Decomposed.LHS);
4770 mangleExpression(Decomposed.RHS);
4771 break;
4772 }
4773
4774 case Expr::ConditionalOperatorClass: {
4775 NotPrimaryExpr();
4776 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4777 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4778 mangleExpression(CO->getCond());
4779 mangleExpression(CO->getLHS(), Arity);
4780 mangleExpression(CO->getRHS(), Arity);
4781 break;
4782 }
4783
4784 case Expr::ImplicitCastExprClass: {
4785 ImplicitlyConvertedToType = E->getType();
4786 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4787 goto recurse;
4788 }
4789
4790 case Expr::ObjCBridgedCastExprClass: {
4791 NotPrimaryExpr();
4792 // Mangle ownership casts as a vendor extended operator __bridge,
4793 // __bridge_transfer, or __bridge_retain.
4794 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4795 Out << "v1U" << Kind.size() << Kind;
4796 mangleCastExpression(E, "cv");
4797 break;
4798 }
4799
4800 case Expr::CStyleCastExprClass:
4801 NotPrimaryExpr();
4802 mangleCastExpression(E, "cv");
4803 break;
4804
4805 case Expr::CXXFunctionalCastExprClass: {
4806 NotPrimaryExpr();
4807 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4808 // FIXME: Add isImplicit to CXXConstructExpr.
4809 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4810 if (CCE->getParenOrBraceRange().isInvalid())
4811 Sub = CCE->getArg(0)->IgnoreImplicit();
4812 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4813 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4814 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4815 Out << "tl";
4816 mangleType(E->getType());
4817 mangleInitListElements(IL);
4818 Out << "E";
4819 } else {
4820 mangleCastExpression(E, "cv");
4821 }
4822 break;
4823 }
4824
4825 case Expr::CXXStaticCastExprClass:
4826 NotPrimaryExpr();
4827 mangleCastExpression(E, "sc");
4828 break;
4829 case Expr::CXXDynamicCastExprClass:
4830 NotPrimaryExpr();
4831 mangleCastExpression(E, "dc");
4832 break;
4833 case Expr::CXXReinterpretCastExprClass:
4834 NotPrimaryExpr();
4835 mangleCastExpression(E, "rc");
4836 break;
4837 case Expr::CXXConstCastExprClass:
4838 NotPrimaryExpr();
4839 mangleCastExpression(E, "cc");
4840 break;
4841 case Expr::CXXAddrspaceCastExprClass:
4842 NotPrimaryExpr();
4843 mangleCastExpression(E, "ac");
4844 break;
4845
4846 case Expr::CXXOperatorCallExprClass: {
4847 NotPrimaryExpr();
4848 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4849 unsigned NumArgs = CE->getNumArgs();
4850 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4851 // (the enclosing MemberExpr covers the syntactic portion).
4852 if (CE->getOperator() != OO_Arrow)
4853 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4854 // Mangle the arguments.
4855 for (unsigned i = 0; i != NumArgs; ++i)
4856 mangleExpression(CE->getArg(i));
4857 break;
4858 }
4859
4860 case Expr::ParenExprClass:
4861 E = cast<ParenExpr>(E)->getSubExpr();
4862 goto recurse;
4863
4864 case Expr::ConceptSpecializationExprClass: {
4865 // <expr-primary> ::= L <mangled-name> E # external name
4866 Out << "L_Z";
4867 auto *CSE = cast<ConceptSpecializationExpr>(E);
4868 mangleTemplateName(CSE->getNamedConcept(),
4869 CSE->getTemplateArguments().data(),
4870 CSE->getTemplateArguments().size());
4871 Out << 'E';
4872 break;
4873 }
4874
4875 case Expr::DeclRefExprClass:
4876 // MangleDeclRefExpr helper handles primary-vs-nonprimary
4877 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4878 break;
4879
4880 case Expr::SubstNonTypeTemplateParmPackExprClass:
4881 NotPrimaryExpr();
4882 // FIXME: not clear how to mangle this!
4883 // template <unsigned N...> class A {
4884 // template <class U...> void foo(U (&x)[N]...);
4885 // };
4886 Out << "_SUBSTPACK_";
4887 break;
4888
4889 case Expr::FunctionParmPackExprClass: {
4890 NotPrimaryExpr();
4891 // FIXME: not clear how to mangle this!
4892 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4893 Out << "v110_SUBSTPACK";
4894 MangleDeclRefExpr(FPPE->getParameterPack());
4895 break;
4896 }
4897
4898 case Expr::DependentScopeDeclRefExprClass: {
4899 NotPrimaryExpr();
4900 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4901 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4902 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4903 Arity);
4904 break;
4905 }
4906
4907 case Expr::CXXBindTemporaryExprClass:
4908 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
4909 goto recurse;
4910
4911 case Expr::ExprWithCleanupsClass:
4912 E = cast<ExprWithCleanups>(E)->getSubExpr();
4913 goto recurse;
4914
4915 case Expr::FloatingLiteralClass: {
4916 // <expr-primary>
4917 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4918 mangleFloatLiteral(FL->getType(), FL->getValue());
4919 break;
4920 }
4921
4922 case Expr::FixedPointLiteralClass:
4923 // Currently unimplemented -- might be <expr-primary> in future?
4924 mangleFixedPointLiteral();
4925 break;
4926
4927 case Expr::CharacterLiteralClass:
4928 // <expr-primary>
4929 Out << 'L';
4930 mangleType(E->getType());
4931 Out << cast<CharacterLiteral>(E)->getValue();
4932 Out << 'E';
4933 break;
4934
4935 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4936 case Expr::ObjCBoolLiteralExprClass:
4937 // <expr-primary>
4938 Out << "Lb";
4939 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4940 Out << 'E';
4941 break;
4942
4943 case Expr::CXXBoolLiteralExprClass:
4944 // <expr-primary>
4945 Out << "Lb";
4946 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4947 Out << 'E';
4948 break;
4949
4950 case Expr::IntegerLiteralClass: {
4951 // <expr-primary>
4952 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4953 if (E->getType()->isSignedIntegerType())
4954 Value.setIsSigned(true);
4955 mangleIntegerLiteral(E->getType(), Value);
4956 break;
4957 }
4958
4959 case Expr::ImaginaryLiteralClass: {
4960 // <expr-primary>
4961 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4962 // Mangle as if a complex literal.
4963 // Proposal from David Vandevoorde, 2010.06.30.
4964 Out << 'L';
4965 mangleType(E->getType());
4966 if (const FloatingLiteral *Imag =
4967 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4968 // Mangle a floating-point zero of the appropriate type.
4969 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4970 Out << '_';
4971 mangleFloat(Imag->getValue());
4972 } else {
4973 Out << "0_";
4974 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4975 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4976 Value.setIsSigned(true);
4977 mangleNumber(Value);
4978 }
4979 Out << 'E';
4980 break;
4981 }
4982
4983 case Expr::StringLiteralClass: {
4984 // <expr-primary>
4985 // Revised proposal from David Vandervoorde, 2010.07.15.
4986 Out << 'L';
4987 assert(isa<ConstantArrayType>(E->getType()))(static_cast <bool> (isa<ConstantArrayType>(E->
getType())) ? void (0) : __assert_fail ("isa<ConstantArrayType>(E->getType())"
, "clang/lib/AST/ItaniumMangle.cpp", 4987, __extension__ __PRETTY_FUNCTION__
))
;
4988 mangleType(E->getType());
4989 Out << 'E';
4990 break;
4991 }
4992
4993 case Expr::GNUNullExprClass:
4994 // <expr-primary>
4995 // Mangle as if an integer literal 0.
4996 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
4997 break;
4998
4999 case Expr::CXXNullPtrLiteralExprClass: {
5000 // <expr-primary>
5001 Out << "LDnE";
5002 break;
5003 }
5004
5005 case Expr::LambdaExprClass: {
5006 // A lambda-expression can't appear in the signature of an
5007 // externally-visible declaration, so there's no standard mangling for
5008 // this, but mangling as a literal of the closure type seems reasonable.
5009 Out << "L";
5010 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5011 Out << "E";
5012 break;
5013 }
5014
5015 case Expr::PackExpansionExprClass:
5016 NotPrimaryExpr();
5017 Out << "sp";
5018 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5019 break;
5020
5021 case Expr::SizeOfPackExprClass: {
5022 NotPrimaryExpr();
5023 auto *SPE = cast<SizeOfPackExpr>(E);
5024 if (SPE->isPartiallySubstituted()) {
5025 Out << "sP";
5026 for (const auto &A : SPE->getPartialArguments())
5027 mangleTemplateArg(A, false);
5028 Out << "E";
5029 break;
5030 }
5031
5032 Out << "sZ";
5033 const NamedDecl *Pack = SPE->getPack();
5034 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5035 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5036 else if (const NonTypeTemplateParmDecl *NTTP
5037 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5038 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5039 else if (const TemplateTemplateParmDecl *TempTP
5040 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5041 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5042 else
5043 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5044 break;
5045 }
5046
5047 case Expr::MaterializeTemporaryExprClass:
5048 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5049 goto recurse;
5050
5051 case Expr::CXXFoldExprClass: {
5052 NotPrimaryExpr();
5053 auto *FE = cast<CXXFoldExpr>(E);
5054 if (FE->isLeftFold())
5055 Out << (FE->getInit() ? "fL" : "fl");
5056 else
5057 Out << (FE->getInit() ? "fR" : "fr");
5058
5059 if (FE->getOperator() == BO_PtrMemD)
5060 Out << "ds";
5061 else
5062 mangleOperatorName(
5063 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5064 /*Arity=*/2);
5065
5066 if (FE->getLHS())
5067 mangleExpression(FE->getLHS());
5068 if (FE->getRHS())
5069 mangleExpression(FE->getRHS());
5070 break;
5071 }
5072
5073 case Expr::CXXThisExprClass:
5074 NotPrimaryExpr();
5075 Out << "fpT";
5076 break;
5077
5078 case Expr::CoawaitExprClass:
5079 // FIXME: Propose a non-vendor mangling.
5080 NotPrimaryExpr();
5081 Out << "v18co_await";
5082 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5083 break;
5084
5085 case Expr::DependentCoawaitExprClass:
5086 // FIXME: Propose a non-vendor mangling.
5087 NotPrimaryExpr();
5088 Out << "v18co_await";
5089 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5090 break;
5091
5092 case Expr::CoyieldExprClass:
5093 // FIXME: Propose a non-vendor mangling.
5094 NotPrimaryExpr();
5095 Out << "v18co_yield";
5096 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5097 break;
5098 case Expr::SYCLUniqueStableNameExprClass: {
5099 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5100 NotPrimaryExpr();
5101
5102 Out << "u33__builtin_sycl_unique_stable_name";
5103 mangleType(USN->getTypeSourceInfo()->getType());
5104
5105 Out << "E";
5106 break;
5107 }
5108 }
5109
5110 if (AsTemplateArg && !IsPrimaryExpr)
5111 Out << 'E';
5112}
5113
5114/// Mangle an expression which refers to a parameter variable.
5115///
5116/// <expression> ::= <function-param>
5117/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5118/// <function-param> ::= fp <top-level CV-qualifiers>
5119/// <parameter-2 non-negative number> _ # L == 0, I > 0
5120/// <function-param> ::= fL <L-1 non-negative number>
5121/// p <top-level CV-qualifiers> _ # L > 0, I == 0
5122/// <function-param> ::= fL <L-1 non-negative number>
5123/// p <top-level CV-qualifiers>
5124/// <I-1 non-negative number> _ # L > 0, I > 0
5125///
5126/// L is the nesting depth of the parameter, defined as 1 if the
5127/// parameter comes from the innermost function prototype scope
5128/// enclosing the current context, 2 if from the next enclosing
5129/// function prototype scope, and so on, with one special case: if
5130/// we've processed the full parameter clause for the innermost
5131/// function type, then L is one less. This definition conveniently
5132/// makes it irrelevant whether a function's result type was written
5133/// trailing or leading, but is otherwise overly complicated; the
5134/// numbering was first designed without considering references to
5135/// parameter in locations other than return types, and then the
5136/// mangling had to be generalized without changing the existing
5137/// manglings.
5138///
5139/// I is the zero-based index of the parameter within its parameter
5140/// declaration clause. Note that the original ABI document describes
5141/// this using 1-based ordinals.
5142void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5143 unsigned parmDepth = parm->getFunctionScopeDepth();
5144 unsigned parmIndex = parm->getFunctionScopeIndex();
5145
5146 // Compute 'L'.
5147 // parmDepth does not include the declaring function prototype.
5148 // FunctionTypeDepth does account for that.
5149 assert(parmDepth < FunctionTypeDepth.getDepth())(static_cast <bool> (parmDepth < FunctionTypeDepth.getDepth
()) ? void (0) : __assert_fail ("parmDepth < FunctionTypeDepth.getDepth()"
, "clang/lib/AST/ItaniumMangle.cpp", 5149, __extension__ __PRETTY_FUNCTION__
))
;
5150 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5151 if (FunctionTypeDepth.isInResultType())
5152 nestingDepth--;
5153
5154 if (nestingDepth == 0) {
5155 Out << "fp";
5156 } else {
5157 Out << "fL" << (nestingDepth - 1) << 'p';
5158 }
5159
5160 // Top-level qualifiers. We don't have to worry about arrays here,
5161 // because parameters declared as arrays should already have been
5162 // transformed to have pointer type. FIXME: apparently these don't
5163 // get mangled if used as an rvalue of a known non-class type?
5164 assert(!parm->getType()->isArrayType()(static_cast <bool> (!parm->getType()->isArrayType
() && "parameter's type is still an array type?") ? void
(0) : __assert_fail ("!parm->getType()->isArrayType() && \"parameter's type is still an array type?\""
, "clang/lib/AST/ItaniumMangle.cpp", 5165, __extension__ __PRETTY_FUNCTION__
))
5165 && "parameter's type is still an array type?")(static_cast <bool> (!parm->getType()->isArrayType
() && "parameter's type is still an array type?") ? void
(0) : __assert_fail ("!parm->getType()->isArrayType() && \"parameter's type is still an array type?\""
, "clang/lib/AST/ItaniumMangle.cpp", 5165, __extension__ __PRETTY_FUNCTION__
))
;
5166
5167 if (const DependentAddressSpaceType *DAST =
5168 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5169 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5170 } else {
5171 mangleQualifiers(parm->getType().getQualifiers());
5172 }
5173
5174 // Parameter index.
5175 if (parmIndex != 0) {
5176 Out << (parmIndex - 1);
5177 }
5178 Out << '_';
5179}
5180
5181void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5182 const CXXRecordDecl *InheritedFrom) {
5183 // <ctor-dtor-name> ::= C1 # complete object constructor
5184 // ::= C2 # base object constructor
5185 // ::= CI1 <type> # complete inheriting constructor
5186 // ::= CI2 <type> # base inheriting constructor
5187 //
5188 // In addition, C5 is a comdat name with C1 and C2 in it.
5189 Out << 'C';
5190 if (InheritedFrom)
5191 Out << 'I';
5192 switch (T) {
5193 case Ctor_Complete:
5194 Out << '1';
5195 break;
5196 case Ctor_Base:
5197 Out << '2';
5198 break;
5199 case Ctor_Comdat:
5200 Out << '5';
5201 break;
5202 case Ctor_DefaultClosure:
5203 case Ctor_CopyingClosure:
5204 llvm_unreachable("closure constructors don't exist for the Itanium ABI!")::llvm::llvm_unreachable_internal("closure constructors don't exist for the Itanium ABI!"
, "clang/lib/AST/ItaniumMangle.cpp", 5204)
;
5205 }
5206 if (InheritedFrom)
5207 mangleName(InheritedFrom);
5208}
5209
5210void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5211 // <ctor-dtor-name> ::= D0 # deleting destructor
5212 // ::= D1 # complete object destructor
5213 // ::= D2 # base object destructor
5214 //
5215 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5216 switch (T) {
5217 case Dtor_Deleting:
5218 Out << "D0";
5219 break;
5220 case Dtor_Complete:
5221 Out << "D1";
5222 break;
5223 case Dtor_Base:
5224 Out << "D2";
5225 break;
5226 case Dtor_Comdat:
5227 Out << "D5";
5228 break;
5229 }
5230}
5231
5232namespace {
5233// Helper to provide ancillary information on a template used to mangle its
5234// arguments.
5235struct TemplateArgManglingInfo {
5236 TemplateDecl *ResolvedTemplate = nullptr;
5237 bool SeenPackExpansionIntoNonPack = false;
5238 const NamedDecl *UnresolvedExpandedPack = nullptr;
5239
5240 TemplateArgManglingInfo(TemplateName TN) {
5241 if (TemplateDecl *TD = TN.getAsTemplateDecl())
5242 ResolvedTemplate = TD;
5243 }
5244
5245 /// Do we need to mangle template arguments with exactly correct types?
5246 ///
5247 /// This should be called exactly once for each parameter / argument pair, in
5248 /// order.
5249 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
5250 // We need correct types when the template-name is unresolved or when it
5251 // names a template that is able to be overloaded.
5252 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5253 return true;
5254
5255 // Move to the next parameter.
5256 const NamedDecl *Param = UnresolvedExpandedPack;
5257 if (!Param) {
5258 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&(static_cast <bool> (ParamIdx < ResolvedTemplate->
getTemplateParameters()->size() && "no parameter for argument"
) ? void (0) : __assert_fail ("ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && \"no parameter for argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 5259, __extension__ __PRETTY_FUNCTION__
))
5259 "no parameter for argument")(static_cast <bool> (ParamIdx < ResolvedTemplate->
getTemplateParameters()->size() && "no parameter for argument"
) ? void (0) : __assert_fail ("ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && \"no parameter for argument\""
, "clang/lib/AST/ItaniumMangle.cpp", 5259, __extension__ __PRETTY_FUNCTION__
))
;
5260 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5261
5262 // If we reach an expanded parameter pack whose argument isn't in pack
5263 // form, that means Sema couldn't figure out which arguments belonged to
5264 // it, because it contains a pack expansion. Track the expanded pack for
5265 // all further template arguments until we hit that pack expansion.
5266 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5267 assert(getExpandedPackSize(Param) &&(static_cast <bool> (getExpandedPackSize(Param) &&
"failed to form pack argument for parameter pack") ? void (0
) : __assert_fail ("getExpandedPackSize(Param) && \"failed to form pack argument for parameter pack\""
, "clang/lib/AST/ItaniumMangle.cpp", 5268, __extension__ __PRETTY_FUNCTION__
))
5268 "failed to form pack argument for parameter pack")(static_cast <bool> (getExpandedPackSize(Param) &&
"failed to form pack argument for parameter pack") ? void (0
) : __assert_fail ("getExpandedPackSize(Param) && \"failed to form pack argument for parameter pack\""
, "clang/lib/AST/ItaniumMangle.cpp", 5268, __extension__ __PRETTY_FUNCTION__
))
;
5269 UnresolvedExpandedPack = Param;
5270 }
5271 }
5272
5273 // If we encounter a pack argument that is expanded into a non-pack
5274 // parameter, we can no longer track parameter / argument correspondence,
5275 // and need to use exact types from this point onwards.
5276 if (Arg.isPackExpansion() &&
5277 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5278 SeenPackExpansionIntoNonPack = true;
5279 return true;
5280 }
5281
5282 // We need exact types for function template arguments because they might be
5283 // overloaded on template parameter type. As a special case, a member
5284 // function template of a generic lambda is not overloadable.
5285 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
5286 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5287 if (!RD || !RD->isGenericLambda())
5288 return true;
5289 }
5290
5291 // Otherwise, we only need a correct type if the parameter has a deduced
5292 // type.
5293 //
5294 // Note: for an expanded parameter pack, getType() returns the type prior
5295 // to expansion. We could ask for the expanded type with getExpansionType(),
5296 // but it doesn't matter because substitution and expansion don't affect
5297 // whether a deduced type appears in the type.
5298 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
5299 return NTTP && NTTP->getType()->getContainedDeducedType();
5300 }
5301};
5302}
5303
5304void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5305 const TemplateArgumentLoc *TemplateArgs,
5306 unsigned NumTemplateArgs) {
5307 // <template-args> ::= I <template-arg>+ E
5308 Out << 'I';
5309 TemplateArgManglingInfo Info(TN);
5310 for (unsigned i = 0; i != NumTemplateArgs; ++i)
5311 mangleTemplateArg(TemplateArgs[i].getArgument(),
5312 Info.needExactType(i, TemplateArgs[i].getArgument()));
5313 Out << 'E';
5314}
5315
5316void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5317 const TemplateArgumentList &AL) {
5318 // <template-args> ::= I <template-arg>+ E
5319 Out << 'I';
5320 TemplateArgManglingInfo Info(TN);
5321 for (unsigned i = 0, e = AL.size(); i != e; ++i)
5322 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
5323 Out << 'E';
5324}
5325
5326void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5327 const TemplateArgument *TemplateArgs,
5328 unsigned NumTemplateArgs) {
5329 // <template-args> ::= I <template-arg>+ E
5330 Out << 'I';
5331 TemplateArgManglingInfo Info(TN);
5332 for (unsigned i = 0; i != NumTemplateArgs; ++i)
5333 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i]));
5334 Out << 'E';
5335}
5336
5337void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
5338 // <template-arg> ::= <type> # type or template
5339 // ::= X <expression> E # expression
5340 // ::= <expr-primary> # simple expressions
5341 // ::= J <template-arg>* E # argument pack
5342 if (!A.isInstantiationDependent() || A.isDependent())
5343 A = Context.getASTContext().getCanonicalTemplateArgument(A);
5344
5345 switch (A.getKind()) {
5346 case TemplateArgument::Null:
5347 llvm_unreachable("Cannot mangle NULL template argument")::llvm::llvm_unreachable_internal("Cannot mangle NULL template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5347)
;
5348
5349 case TemplateArgument::Type:
5350 mangleType(A.getAsType());
5351 break;
5352 case TemplateArgument::Template:
5353 // This is mangled as <type>.
5354 mangleType(A.getAsTemplate());
5355 break;
5356 case TemplateArgument::TemplateExpansion:
5357 // <type> ::= Dp <type> # pack expansion (C++0x)
5358 Out << "Dp";
5359 mangleType(A.getAsTemplateOrTemplatePattern());
5360 break;
5361 case TemplateArgument::Expression:
5362 mangleTemplateArgExpr(A.getAsExpr());
5363 break;
5364 case TemplateArgument::Integral:
5365 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
5366 break;
5367 case TemplateArgument::Declaration: {
5368 // <expr-primary> ::= L <mangled-name> E # external name
5369 ValueDecl *D = A.getAsDecl();
5370
5371 // Template parameter objects are modeled by reproducing a source form
5372 // produced as if by aggregate initialization.
5373 if (A.getParamTypeForDecl()->isRecordType()) {
5374 auto *TPO = cast<TemplateParamObjectDecl>(D);
5375 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
5376 TPO->getValue(), /*TopLevel=*/true,
5377 NeedExactType);
5378 break;
5379 }
5380
5381 ASTContext &Ctx = Context.getASTContext();
5382 APValue Value;
5383 if (D->isCXXInstanceMember())
5384 // Simple pointer-to-member with no conversion.
5385 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
5386 else if (D->getType()->isArrayType() &&
5387 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
5388 A.getParamTypeForDecl()) &&
5389 Ctx.getLangOpts().getClangABICompat() >
5390 LangOptions::ClangABI::Ver11)
5391 // Build a value corresponding to this implicit array-to-pointer decay.
5392 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5393 {APValue::LValuePathEntry::ArrayIndex(0)},
5394 /*OnePastTheEnd=*/false);
5395 else
5396 // Regular pointer or reference to a declaration.
5397 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5398 ArrayRef<APValue::LValuePathEntry>(),
5399 /*OnePastTheEnd=*/false);
5400 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
5401 NeedExactType);
5402 break;
5403 }
5404 case TemplateArgument::NullPtr: {
5405 mangleNullPointer(A.getNullPtrType());
5406 break;
5407 }
5408 case TemplateArgument::Pack: {
5409 // <template-arg> ::= J <template-arg>* E
5410 Out << 'J';
5411 for (const auto &P : A.pack_elements())
5412 mangleTemplateArg(P, NeedExactType);
5413 Out << 'E';
5414 }
5415 }
5416}
5417
5418void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
5419 ASTContext &Ctx = Context.getASTContext();
5420 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
5421 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
5422 return;
5423 }
5424
5425 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
5426 // correctly in cases where the template argument was
5427 // constructed from an expression rather than an already-evaluated
5428 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
5429 // 'Li0E'.
5430 //
5431 // We did special-case DeclRefExpr to attempt to DTRT for that one
5432 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
5433 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
5434 // the proper 'Xfp_E'.
5435 E = E->IgnoreParenImpCasts();
5436 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5437 const ValueDecl *D = DRE->getDecl();
5438 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
5439 Out << 'L';
5440 mangle(D);
5441 Out << 'E';
5442 return;
5443 }
5444 }
5445 Out << 'X';
5446 mangleExpression(E);
5447 Out << 'E';
5448}
5449
5450/// Determine whether a given value is equivalent to zero-initialization for
5451/// the purpose of discarding a trailing portion of a 'tl' mangling.
5452///
5453/// Note that this is not in general equivalent to determining whether the
5454/// value has an all-zeroes bit pattern.
5455static bool isZeroInitialized(QualType T, const APValue &V) {
5456 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
5457 // pathological cases due to using this, but it's a little awkward
5458 // to do this in linear time in general.
5459 switch (V.getKind()) {
5460 case APValue::None:
5461 case APValue::Indeterminate:
5462 case APValue::AddrLabelDiff:
5463 return false;
5464
5465 case APValue::Struct: {
5466 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5467 assert(RD && "unexpected type for record value")(static_cast <bool> (RD && "unexpected type for record value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for record value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5467, __extension__ __PRETTY_FUNCTION__
))
;
5468 unsigned I = 0;
5469 for (const CXXBaseSpecifier &BS : RD->bases()) {
5470 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
5471 return false;
5472 ++I;
5473 }
5474 I = 0;
5475 for (const FieldDecl *FD : RD->fields()) {
5476 if (!FD->isUnnamedBitfield() &&
5477 !isZeroInitialized(FD->getType(), V.getStructField(I)))
5478 return false;
5479 ++I;
5480 }
5481 return true;
5482 }
5483
5484 case APValue::Union: {
5485 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5486 assert(RD && "unexpected type for union value")(static_cast <bool> (RD && "unexpected type for union value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for union value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5486, __extension__ __PRETTY_FUNCTION__
))
;
5487 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
5488 for (const FieldDecl *FD : RD->fields()) {
5489 if (!FD->isUnnamedBitfield())
5490 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
5491 isZeroInitialized(FD->getType(), V.getUnionValue());
5492 }
5493 // If there are no fields (other than unnamed bitfields), the value is
5494 // necessarily zero-initialized.
5495 return true;
5496 }
5497
5498 case APValue::Array: {
5499 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
5500 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
5501 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
5502 return false;
5503 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
5504 }
5505
5506 case APValue::Vector: {
5507 const VectorType *VT = T->castAs<VectorType>();
5508 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
5509 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
5510 return false;
5511 return true;
5512 }
5513
5514 case APValue::Int:
5515 return !V.getInt();
5516
5517 case APValue::Float:
5518 return V.getFloat().isPosZero();
5519
5520 case APValue::FixedPoint:
5521 return !V.getFixedPoint().getValue();
5522
5523 case APValue::ComplexFloat:
5524 return V.getComplexFloatReal().isPosZero() &&
5525 V.getComplexFloatImag().isPosZero();
5526
5527 case APValue::ComplexInt:
5528 return !V.getComplexIntReal() && !V.getComplexIntImag();
5529
5530 case APValue::LValue:
5531 return V.isNullPointer();
5532
5533 case APValue::MemberPointer:
5534 return !V.getMemberPointerDecl();
5535 }
5536
5537 llvm_unreachable("Unhandled APValue::ValueKind enum")::llvm::llvm_unreachable_internal("Unhandled APValue::ValueKind enum"
, "clang/lib/AST/ItaniumMangle.cpp", 5537)
;
5538}
5539
5540static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
5541 QualType T = LV.getLValueBase().getType();
5542 for (APValue::LValuePathEntry E : LV.getLValuePath()) {
5543 if (const ArrayType *AT = Ctx.getAsArrayType(T))
5544 T = AT->getElementType();
5545 else if (const FieldDecl *FD =
5546 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
5547 T = FD->getType();
5548 else
5549 T = Ctx.getRecordType(
5550 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
5551 }
5552 return T;
5553}
5554
5555static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
5556 DiagnosticsEngine &Diags,
5557 const FieldDecl *FD) {
5558 // According to:
5559 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
5560 // For the purposes of mangling, the name of an anonymous union is considered
5561 // to be the name of the first named data member found by a pre-order,
5562 // depth-first, declaration-order walk of the data members of the anonymous
5563 // union.
5564
5565 if (FD->getIdentifier())
5566 return FD->getIdentifier();
5567
5568 // The only cases where the identifer of a FieldDecl would be blank is if the
5569 // field represents an anonymous record type or if it is an unnamed bitfield.
5570 // There is no type to descend into in the case of a bitfield, so we can just
5571 // return nullptr in that case.
5572 if (FD->isBitField())
5573 return nullptr;
5574 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
5575
5576 // Consider only the fields in declaration order, searched depth-first. We
5577 // don't care about the active member of the union, as all we are doing is
5578 // looking for a valid name. We also don't check bases, due to guidance from
5579 // the Itanium ABI folks.
5580 for (const FieldDecl *RDField : RD->fields()) {
5581 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
5582 return II;
5583 }
5584
5585 // According to the Itanium ABI: If there is no such data member (i.e., if all
5586 // of the data members in the union are unnamed), then there is no way for a
5587 // program to refer to the anonymous union, and there is therefore no need to
5588 // mangle its name. However, we should diagnose this anyway.
5589 unsigned DiagID = Diags.getCustomDiagID(
5590 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
5591 Diags.Report(UnionLoc, DiagID);
5592
5593 return nullptr;
5594}
5595
5596void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
5597 bool TopLevel,
5598 bool NeedExactType) {
5599 // Ignore all top-level cv-qualifiers, to match GCC.
5600 Qualifiers Quals;
5601 T = getASTContext().getUnqualifiedArrayType(T, Quals);
5602
5603 // A top-level expression that's not a primary expression is wrapped in X...E.
5604 bool IsPrimaryExpr = true;
5605 auto NotPrimaryExpr = [&] {
5606 if (TopLevel && IsPrimaryExpr)
5607 Out << 'X';
5608 IsPrimaryExpr = false;
5609 };
5610
5611 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
5612 switch (V.getKind()) {
5613 case APValue::None:
5614 case APValue::Indeterminate:
5615 Out << 'L';
5616 mangleType(T);
5617 Out << 'E';
5618 break;
5619
5620 case APValue::AddrLabelDiff:
5621 llvm_unreachable("unexpected value kind in template argument")::llvm::llvm_unreachable_internal("unexpected value kind in template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5621)
;
5622
5623 case APValue::Struct: {
5624 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5625 assert(RD && "unexpected type for record value")(static_cast <bool> (RD && "unexpected type for record value"
) ? void (0) : __assert_fail ("RD && \"unexpected type for record value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5625, __extension__ __PRETTY_FUNCTION__
))
;
5626
5627 // Drop trailing zero-initialized elements.
5628 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->field_begin(),
5629 RD->field_end());
5630 while (
5631 !Fields.empty() &&
5632 (Fields.back()->isUnnamedBitfield() ||
5633 isZeroInitialized(Fields.back()->getType(),
5634 V.getStructField(Fields.back()->getFieldIndex())))) {
5635 Fields.pop_back();
5636 }
5637 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
5638 if (Fields.empty()) {
5639 while (!Bases.empty() &&
5640 isZeroInitialized(Bases.back().getType(),
5641 V.getStructBase(Bases.size() - 1)))
5642 Bases = Bases.drop_back();
5643 }
5644
5645 // <expression> ::= tl <type> <braced-expression>* E
5646 NotPrimaryExpr();
5647 Out << "tl";
5648 mangleType(T);
5649 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
5650 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
5651 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
5652 if (Fields[I]->isUnnamedBitfield())
5653 continue;
5654 mangleValueInTemplateArg(Fields[I]->getType(),
5655 V.getStructField(Fields[I]->getFieldIndex()),
5656 false);
5657 }
5658 Out << 'E';
5659 break;
5660 }
5661
5662 case APValue::Union: {
5663 assert(T->getAsCXXRecordDecl() && "unexpected type for union value")(static_cast <bool> (T->getAsCXXRecordDecl() &&
"unexpected type for union value") ? void (0) : __assert_fail
("T->getAsCXXRecordDecl() && \"unexpected type for union value\""
, "clang/lib/AST/ItaniumMangle.cpp", 5663, __extension__ __PRETTY_FUNCTION__
))
;
5664 const FieldDecl *FD = V.getUnionField();
5665
5666 if (!FD) {
5667 Out << 'L';
5668 mangleType(T);
5669 Out << 'E';
5670 break;
5671 }
5672
5673 // <braced-expression> ::= di <field source-name> <braced-expression>
5674 NotPrimaryExpr();
5675 Out << "tl";
5676 mangleType(T);
5677 if (!isZeroInitialized(T, V)) {
5678 Out << "di";
5679 IdentifierInfo *II = (getUnionInitName(
5680 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
5681 if (II)
5682 mangleSourceName(II);
5683 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
5684 }
5685 Out << 'E';
5686 break;
5687 }
5688
5689 case APValue::Array: {
5690 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
5691
5692 NotPrimaryExpr();
5693 Out << "tl";
5694 mangleType(T);
5695
5696 // Drop trailing zero-initialized elements.
5697 unsigned N = V.getArraySize();
5698 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
5699 N = V.getArrayInitializedElts();
5700 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
5701 --N;
5702 }
5703
5704 for (unsigned I = 0; I != N; ++I) {
5705 const APValue &Elem = I < V.getArrayInitializedElts()
5706 ? V.getArrayInitializedElt(I)
5707 : V.getArrayFiller();
5708 mangleValueInTemplateArg(ElemT, Elem, false);
5709 }
5710 Out << 'E';
5711 break;
5712 }
5713
5714 case APValue::Vector: {
5715 const VectorType *VT = T->castAs<VectorType>();
5716
5717 NotPrimaryExpr();
5718 Out << "tl";
5719 mangleType(T);
5720 unsigned N = V.getVectorLength();
5721 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
5722 --N;
5723 for (unsigned I = 0; I != N; ++I)
5724 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
5725 Out << 'E';
5726 break;
5727 }
5728
5729 case APValue::Int:
5730 mangleIntegerLiteral(T, V.getInt());
5731 break;
5732
5733 case APValue::Float:
5734 mangleFloatLiteral(T, V.getFloat());
5735 break;
5736
5737 case APValue::FixedPoint:
5738 mangleFixedPointLiteral();
5739 break;
5740
5741 case APValue::ComplexFloat: {
5742 const ComplexType *CT = T->castAs<ComplexType>();
5743 NotPrimaryExpr();
5744 Out << "tl";
5745 mangleType(T);
5746 if (!V.getComplexFloatReal().isPosZero() ||
5747 !V.getComplexFloatImag().isPosZero())
5748 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
5749 if (!V.getComplexFloatImag().isPosZero())
5750 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
5751 Out << 'E';
5752 break;
5753 }
5754
5755 case APValue::ComplexInt: {
5756 const ComplexType *CT = T->castAs<ComplexType>();
5757 NotPrimaryExpr();
5758 Out << "tl";
5759 mangleType(T);
5760 if (V.getComplexIntReal().getBoolValue() ||
5761 V.getComplexIntImag().getBoolValue())
5762 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
5763 if (V.getComplexIntImag().getBoolValue())
5764 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
5765 Out << 'E';
5766 break;
5767 }
5768
5769 case APValue::LValue: {
5770 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5771 assert((T->isPointerType() || T->isReferenceType()) &&(static_cast <bool> ((T->isPointerType() || T->isReferenceType
()) && "unexpected type for LValue template arg") ? void
(0) : __assert_fail ("(T->isPointerType() || T->isReferenceType()) && \"unexpected type for LValue template arg\""
, "clang/lib/AST/ItaniumMangle.cpp", 5772, __extension__ __PRETTY_FUNCTION__
))
5772 "unexpected type for LValue template arg")(static_cast <bool> ((T->isPointerType() || T->isReferenceType
()) && "unexpected type for LValue template arg") ? void
(0) : __assert_fail ("(T->isPointerType() || T->isReferenceType()) && \"unexpected type for LValue template arg\""
, "clang/lib/AST/ItaniumMangle.cpp", 5772, __extension__ __PRETTY_FUNCTION__
))
;
5773
5774 if (V.isNullPointer()) {
5775 mangleNullPointer(T);
5776 break;
5777 }
5778
5779 APValue::LValueBase B = V.getLValueBase();
5780 if (!B) {
5781 // Non-standard mangling for integer cast to a pointer; this can only
5782 // occur as an extension.
5783 CharUnits Offset = V.getLValueOffset();
5784 if (Offset.isZero()) {
5785 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
5786 // a cast, because L <type> 0 E means something else.
5787 NotPrimaryExpr();
5788 Out << "rc";
5789 mangleType(T);
5790 Out << "Li0E";
5791 if (TopLevel)
5792 Out << 'E';
5793 } else {
5794 Out << "L";
5795 mangleType(T);
5796 Out << Offset.getQuantity() << 'E';
5797 }
5798 break;
5799 }
5800
5801 ASTContext &Ctx = Context.getASTContext();
5802
5803 enum { Base, Offset, Path } Kind;
5804 if (!V.hasLValuePath()) {
5805 // Mangle as (T*)((char*)&base + N).
5806 if (T->isReferenceType()) {
5807 NotPrimaryExpr();
5808 Out << "decvP";
5809 mangleType(T->getPointeeType());
5810 } else {
5811 NotPrimaryExpr();
5812 Out << "cv";
5813 mangleType(T);
5814 }
5815 Out << "plcvPcad";
5816 Kind = Offset;
5817 } else {
5818 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
5819 NotPrimaryExpr();
5820 // A final conversion to the template parameter's type is usually
5821 // folded into the 'so' mangling, but we can't do that for 'void*'
5822 // parameters without introducing collisions.
5823 if (NeedExactType && T->isVoidPointerType()) {
5824 Out << "cv";
5825 mangleType(T);
5826 }
5827 if (T->isPointerType())
5828 Out << "ad";
5829 Out << "so";
5830 mangleType(T->isVoidPointerType()
5831 ? getLValueType(Ctx, V).getUnqualifiedType()
5832 : T->getPointeeType());
5833 Kind = Path;
5834 } else {
5835 if (NeedExactType &&
5836 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
5837 Ctx.getLangOpts().getClangABICompat() >
5838 LangOptions::ClangABI::Ver11) {
5839 NotPrimaryExpr();
5840 Out << "cv";
5841 mangleType(T);
5842 }
5843 if (T->isPointerType()) {
5844 NotPrimaryExpr();
5845 Out << "ad";
5846 }
5847 Kind = Base;
5848 }
5849 }
5850
5851 QualType TypeSoFar = B.getType();
5852 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
5853 Out << 'L';
5854 mangle(VD);
5855 Out << 'E';
5856 } else if (auto *E = B.dyn_cast<const Expr*>()) {
5857 NotPrimaryExpr();
5858 mangleExpression(E);
5859 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
5860 NotPrimaryExpr();
5861 Out << "ti";
5862 mangleType(QualType(TI.getType(), 0));
5863 } else {
5864 // We should never see dynamic allocations here.
5865 llvm_unreachable("unexpected lvalue base kind in template argument")::llvm::llvm_unreachable_internal("unexpected lvalue base kind in template argument"
, "clang/lib/AST/ItaniumMangle.cpp", 5865)
;
5866 }
5867
5868 switch (Kind) {
5869 case Base:
5870 break;
5871
5872 case Offset:
5873 Out << 'L';
5874 mangleType(Ctx.getPointerDiffType());
5875 mangleNumber(V.getLValueOffset().getQuantity());
5876 Out << 'E';
5877 break;
5878
5879 case Path:
5880 // <expression> ::= so <referent type> <expr> [<offset number>]
5881 // <union-selector>* [p] E
5882 if (!V.getLValueOffset().isZero())
5883 mangleNumber(V.getLValueOffset().getQuantity());
5884
5885 // We model a past-the-end array pointer as array indexing with index N,
5886 // not with the "past the end" flag. Compensate for that.
5887 bool OnePastTheEnd = V.isLValueOnePastTheEnd();
5888
5889 for (APValue::LValuePathEntry E : V.getLValuePath()) {
5890 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
5891 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5892 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
5893 TypeSoFar = AT->getElementType();
5894 } else {
5895 const Decl *D = E.getAsBaseOrMember().getPointer();
5896 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5897 // <union-selector> ::= _ <number>
5898 if (FD->getParent()->isUnion()) {
5899 Out << '_';
5900 if (FD->getFieldIndex())
5901 Out << (FD->getFieldIndex() - 1);
5902 }
5903 TypeSoFar = FD->getType();
5904 } else {
5905 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
5906 }
5907 }
5908 }
5909
5910 if (OnePastTheEnd)
5911 Out << 'p';
5912 Out << 'E';
5913 break;
5914 }
5915
5916 break;
5917 }
5918
5919 case APValue::MemberPointer:
5920 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5921 if (!V.getMemberPointerDecl()) {
5922 mangleNullPointer(T);
5923 break;
5924 }
5925
5926 ASTContext &Ctx = Context.getASTContext();
5927
5928 NotPrimaryExpr();
5929 if (!V.getMemberPointerPath().empty()) {
5930 Out << "mc";
5931 mangleType(T);
5932 } else if (NeedExactType &&
5933 !Ctx.hasSameType(
5934 T->castAs<MemberPointerType>()->getPointeeType(),
5935 V.getMemberPointerDecl()->getType()) &&
5936 Ctx.getLangOpts().getClangABICompat() >
5937 LangOptions::ClangABI::Ver11) {
5938 Out << "cv";
5939 mangleType(T);
5940 }
5941 Out << "adL";
5942 mangle(V.getMemberPointerDecl());
5943 Out << 'E';
5944 if (!V.getMemberPointerPath().empty()) {
5945 CharUnits Offset =
5946 Context.getASTContext().getMemberPointerPathAdjustment(V);
5947 if (!Offset.isZero())
5948 mangleNumber(Offset.getQuantity());
5949 Out << 'E';
5950 }
5951 break;
5952 }
5953
5954 if (TopLevel && !IsPrimaryExpr)
5955 Out << 'E';
5956}
5957
5958void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
5959 // <template-param> ::= T_ # first template parameter
5960 // ::= T <parameter-2 non-negative number> _
5961 // ::= TL <L-1 non-negative number> __
5962 // ::= TL <L-1 non-negative number> _
5963 // <parameter-2 non-negative number> _
5964 //
5965 // The latter two manglings are from a proposal here:
5966 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
5967 Out << 'T';
5968 if (Depth != 0)
5969 Out << 'L' << (Depth - 1) << '_';
5970 if (Index != 0)
5971 Out << (Index - 1);
5972 Out << '_';
5973}
5974
5975void CXXNameMangler::mangleSeqID(unsigned SeqID) {
5976 if (SeqID == 0) {
5977 // Nothing.
5978 } else if (SeqID == 1) {
5979 Out << '0';
5980 } else {
5981 SeqID--;
5982
5983 // <seq-id> is encoded in base-36, using digits and upper case letters.
5984 char Buffer[7]; // log(2**32) / log(36) ~= 7
5985 MutableArrayRef<char> BufferRef(Buffer);
5986 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
5987
5988 for (; SeqID != 0; SeqID /= 36) {
5989 unsigned C = SeqID % 36;
5990 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
5991 }
5992
5993 Out.write(I.base(), I - BufferRef.rbegin());
5994 }
5995 Out << '_';
5996}
5997
5998void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
5999 bool result = mangleSubstitution(tname);
6000 assert(result && "no existing substitution for template name")(static_cast <bool> (result && "no existing substitution for template name"
) ? void (0) : __assert_fail ("result && \"no existing substitution for template name\""
, "clang/lib/AST/ItaniumMangle.cpp", 6000, __extension__ __PRETTY_FUNCTION__
))
;
6001 (void) result;
6002}
6003
6004// <substitution> ::= S <seq-id> _
6005// ::= S_
6006bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6007 // Try one of the standard substitutions first.
6008 if (mangleStandardSubstitution(ND))
6009 return true;
6010
6011 ND = cast<NamedDecl>(ND->getCanonicalDecl());
6012 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
6013}
6014
6015/// Determine whether the given type has any qualifiers that are relevant for
6016/// substitutions.
6017static bool hasMangledSubstitutionQualifiers(QualType T) {
6018 Qualifiers Qs = T.getQualifiers();
6019 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
6020}
6021
6022bool CXXNameMangler::mangleSubstitution(QualType T) {
6023 if (!hasMangledSubstitutionQualifiers(T)) {
6024 if (const RecordType *RT = T->getAs<RecordType>())
6025 return mangleSubstitution(RT->getDecl());
6026 }
6027
6028 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6029
6030 return mangleSubstitution(TypePtr);
6031}
6032
6033bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
6034 if (TemplateDecl *TD = Template.getAsTemplateDecl())
6035 return mangleSubstitution(TD);
6036
6037 Template = Context.getASTContext().getCanonicalTemplateName(Template);
6038 return mangleSubstitution(
6039 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6040}
6041
6042bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
6043 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
6044 if (I == Substitutions.end())
6045 return false;
6046
6047 unsigned SeqID = I->second;
6048 Out << 'S';
6049 mangleSeqID(SeqID);
6050
6051 return true;
6052}
6053
6054/// Returns whether S is a template specialization of std::Name with a single
6055/// argument of type A.
6056bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
6057 QualType A) {
6058 if (S.isNull())
6059 return false;
6060
6061 const RecordType *RT = S->getAs<RecordType>();
6062 if (!RT)
6063 return false;
6064
6065 const ClassTemplateSpecializationDecl *SD =
6066 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6067 if (!SD || !SD->getIdentifier()->isStr(Name))
6068 return false;
6069
6070 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6071 return false;
6072
6073 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6074 if (TemplateArgs.size() != 1)
6075 return false;
6076
6077 if (TemplateArgs[0].getAsType() != A)
6078 return false;
6079
6080 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6081 return false;
6082
6083 return true;
6084}
6085
6086/// Returns whether SD is a template specialization std::Name<char,
6087/// std::char_traits<char> [, std::allocator<char>]>
6088/// HasAllocator controls whether the 3rd template argument is needed.
6089bool CXXNameMangler::isStdCharSpecialization(
6090 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
6091 bool HasAllocator) {
6092 if (!SD->getIdentifier()->isStr(Name))
6093 return false;
6094
6095 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6096 if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
6097 return false;
6098
6099 QualType A = TemplateArgs[0].getAsType();
6100 if (A.isNull())
6101 return false;
6102 // Plain 'char' is named Char_S or Char_U depending on the target ABI.
6103 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
6104 !A->isSpecificBuiltinType(BuiltinType::Char_U))
6105 return false;
6106
6107 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
6108 return false;
6109
6110 if (HasAllocator &&
6111 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
6112 return false;
6113
6114 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6115 return false;
6116
6117 return true;
6118}
6119
6120bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
6121 // <substitution> ::= St # ::std::
6122 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
6123 if (isStd(NS)) {
6124 Out << "St";
6125 return true;
6126 }
6127 return false;
6128 }
6129
6130 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
6131 if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
6132 return false;
6133
6134 if (TD->getOwningModuleForLinkage())
6135 return false;
6136
6137 // <substitution> ::= Sa # ::std::allocator
6138 if (TD->getIdentifier()->isStr("allocator")) {
6139 Out << "Sa";
6140 return true;
6141 }
6142
6143 // <<substitution> ::= Sb # ::std::basic_string
6144 if (TD->getIdentifier()->isStr("basic_string")) {
6145 Out << "Sb";
6146 return true;
6147 }
6148 return false;
6149 }
6150
6151 if (const ClassTemplateSpecializationDecl *SD =
6152 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
6153 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6154 return false;
6155
6156 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6157 return false;
6158
6159 // <substitution> ::= Ss # ::std::basic_string<char,
6160 // ::std::char_traits<char>,
6161 // ::std::allocator<char> >
6162 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
6163 Out << "Ss";
6164 return true;
6165 }
6166
6167 // <substitution> ::= Si # ::std::basic_istream<char,
6168 // ::std::char_traits<char> >
6169 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
6170 Out << "Si";
6171 return true;
6172 }
6173
6174 // <substitution> ::= So # ::std::basic_ostream<char,
6175 // ::std::char_traits<char> >
6176 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
6177 Out << "So";
6178 return true;
6179 }
6180
6181 // <substitution> ::= Sd # ::std::basic_iostream<char,
6182 // ::std::char_traits<char> >
6183 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
6184 Out << "Sd";
6185 return true;
6186 }
6187 return false;
6188 }
6189
6190 return false;
6191}
6192
6193void CXXNameMangler::addSubstitution(QualType T) {
6194 if (!hasMangledSubstitutionQualifiers(T)) {
6195 if (const RecordType *RT = T->getAs<RecordType>()) {
6196 addSubstitution(RT->getDecl());
6197 return;
6198 }
6199 }
6200
6201 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6202 addSubstitution(TypePtr);
6203}
6204
6205void CXXNameMangler::addSubstitution(TemplateName Template) {
6206 if (TemplateDecl *TD = Template.getAsTemplateDecl())
6207 return addSubstitution(TD);
6208
6209 Template = Context.getASTContext().getCanonicalTemplateName(Template);
6210 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6211}
6212
6213void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
6214 assert(!Substitutions.count(Ptr) && "Substitution already exists!")(static_cast <bool> (!Substitutions.count(Ptr) &&
"Substitution already exists!") ? void (0) : __assert_fail (
"!Substitutions.count(Ptr) && \"Substitution already exists!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6214, __extension__ __PRETTY_FUNCTION__
))
;
6215 Substitutions[Ptr] = SeqID++;
6216}
6217
6218void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
6219 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!")(static_cast <bool> (Other->SeqID >= SeqID &&
"Must be superset of substitutions!") ? void (0) : __assert_fail
("Other->SeqID >= SeqID && \"Must be superset of substitutions!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6219, __extension__ __PRETTY_FUNCTION__
))
;
6220 if (Other->SeqID > SeqID) {
6221 Substitutions.swap(Other->Substitutions);
6222 SeqID = Other->SeqID;
6223 }
6224}
6225
6226CXXNameMangler::AbiTagList
6227CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
6228 // When derived abi tags are disabled there is no need to make any list.
6229 if (DisableDerivedAbiTags)
6230 return AbiTagList();
6231
6232 llvm::raw_null_ostream NullOutStream;
6233 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
6234 TrackReturnTypeTags.disableDerivedAbiTags();
6235
6236 const FunctionProtoType *Proto =
6237 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
6238 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
6239 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
6240 TrackReturnTypeTags.mangleType(Proto->getReturnType());
6241 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
6242 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
6243
6244 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6245}
6246
6247CXXNameMangler::AbiTagList
6248CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
6249 // When derived abi tags are disabled there is no need to make any list.
6250 if (DisableDerivedAbiTags)
6251 return AbiTagList();
6252
6253 llvm::raw_null_ostream NullOutStream;
6254 CXXNameMangler TrackVariableType(*this, NullOutStream);
6255 TrackVariableType.disableDerivedAbiTags();
6256
6257 TrackVariableType.mangleType(VD->getType());
6258
6259 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6260}
6261
6262bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
6263 const VarDecl *VD) {
6264 llvm::raw_null_ostream NullOutStream;
6265 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
6266 TrackAbiTags.mangle(VD);
6267 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
6268}
6269
6270//
6271
6272/// Mangles the name of the declaration D and emits that name to the given
6273/// output stream.
6274///
6275/// If the declaration D requires a mangled name, this routine will emit that
6276/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
6277/// and this routine will return false. In this case, the caller should just
6278/// emit the identifier of the declaration (\c D->getIdentifier()) as its
6279/// name.
6280void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
6281 raw_ostream &Out) {
6282 const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
6283 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&(static_cast <bool> ((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl
>(D)) && "Invalid mangleName() call, argument is not a variable or function!"
) ? void (0) : __assert_fail ("(isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && \"Invalid mangleName() call, argument is not a variable or function!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6284, __extension__ __PRETTY_FUNCTION__
))
6284 "Invalid mangleName() call, argument is not a variable or function!")(static_cast <bool> ((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl
>(D)) && "Invalid mangleName() call, argument is not a variable or function!"
) ? void (0) : __assert_fail ("(isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && \"Invalid mangleName() call, argument is not a variable or function!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6284, __extension__ __PRETTY_FUNCTION__
))
;
6285
6286 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
6287 getASTContext().getSourceManager(),
6288 "Mangling declaration");
6289
6290 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
6291 auto Type = GD.getCtorType();
6292 CXXNameMangler Mangler(*this, Out, CD, Type);
6293 return Mangler.mangle(GlobalDecl(CD, Type));
6294 }
6295
6296 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
6297 auto Type = GD.getDtorType();
6298 CXXNameMangler Mangler(*this, Out, DD, Type);
6299 return Mangler.mangle(GlobalDecl(DD, Type));
6300 }
6301
6302 CXXNameMangler Mangler(*this, Out, D);
6303 Mangler.mangle(GD);
6304}
6305
6306void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
6307 raw_ostream &Out) {
6308 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
6309 Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
6310}
6311
6312void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
6313 raw_ostream &Out) {
6314 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
6315 Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
6316}
6317
6318void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
6319 const ThunkInfo &Thunk,
6320 raw_ostream &Out) {
6321 // <special-name> ::= T <call-offset> <base encoding>
6322 // # base is the nominal target function of thunk
6323 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
6324 // # base is the nominal target function of thunk
6325 // # first call-offset is 'this' adjustment
6326 // # second call-offset is result adjustment
6327
6328 assert(!isa<CXXDestructorDecl>(MD) &&(static_cast <bool> (!isa<CXXDestructorDecl>(MD) &&
"Use mangleCXXDtor for destructor decls!") ? void (0) : __assert_fail
("!isa<CXXDestructorDecl>(MD) && \"Use mangleCXXDtor for destructor decls!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6329, __extension__ __PRETTY_FUNCTION__
))
6329 "Use mangleCXXDtor for destructor decls!")(static_cast <bool> (!isa<CXXDestructorDecl>(MD) &&
"Use mangleCXXDtor for destructor decls!") ? void (0) : __assert_fail
("!isa<CXXDestructorDecl>(MD) && \"Use mangleCXXDtor for destructor decls!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6329, __extension__ __PRETTY_FUNCTION__
))
;
6330 CXXNameMangler Mangler(*this, Out);
6331 Mangler.getStream() << "_ZT";
6332 if (!Thunk.Return.isEmpty())
6333 Mangler.getStream() << 'c';
6334
6335 // Mangle the 'this' pointer adjustment.
6336 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
6337 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
6338
6339 // Mangle the return pointer adjustment if there is one.
6340 if (!Thunk.Return.isEmpty())
6341 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
6342 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
6343
6344 Mangler.mangleFunctionEncoding(MD);
6345}
6346
6347void ItaniumMangleContextImpl::mangleCXXDtorThunk(
6348 const CXXDestructorDecl *DD, CXXDtorType Type,
6349 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
6350 // <special-name> ::= T <call-offset> <base encoding>
6351 // # base is the nominal target function of thunk
6352 CXXNameMangler Mangler(*this, Out, DD, Type);
6353 Mangler.getStream() << "_ZT";
6354
6355 // Mangle the 'this' pointer adjustment.
6356 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
6357 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
6358
6359 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
6360}
6361
6362/// Returns the mangled name for a guard variable for the passed in VarDecl.
6363void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
6364 raw_ostream &Out) {
6365 // <special-name> ::= GV <object name> # Guard variable for one-time
6366 // # initialization
6367 CXXNameMangler Mangler(*this, Out);
6368 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
6369 // be a bug that is fixed in trunk.
6370 Mangler.getStream() << "_ZGV";
6371 Mangler.mangleName(D);
6372}
6373
6374void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
6375 raw_ostream &Out) {
6376 // These symbols are internal in the Itanium ABI, so the names don't matter.
6377 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
6378 // avoid duplicate symbols.
6379 Out << "__cxx_global_var_init";
6380}
6381
6382void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
6383 raw_ostream &Out) {
6384 // Prefix the mangling of D with __dtor_.
6385 CXXNameMangler Mangler(*this, Out);
6386 Mangler.getStream() << "__dtor_";
6387 if (shouldMangleDeclName(D))
6388 Mangler.mangle(D);
6389 else
6390 Mangler.getStream() << D->getName();
6391}
6392
6393void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
6394 raw_ostream &Out) {
6395 // Clang generates these internal-linkage functions as part of its
6396 // implementation of the XL ABI.
6397 CXXNameMangler Mangler(*this, Out);
6398 Mangler.getStream() << "__finalize_";
6399 if (shouldMangleDeclName(D))
6400 Mangler.mangle(D);
6401 else
6402 Mangler.getStream() << D->getName();
6403}
6404
6405void ItaniumMangleContextImpl::mangleSEHFilterExpression(
6406 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
6407 CXXNameMangler Mangler(*this, Out);
6408 Mangler.getStream() << "__filt_";
6409 if (shouldMangleDeclName(EnclosingDecl))
6410 Mangler.mangle(EnclosingDecl);
6411 else
6412 Mangler.getStream() << EnclosingDecl->getName();
6413}
6414
6415void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
6416 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
6417 CXXNameMangler Mangler(*this, Out);
6418 Mangler.getStream() << "__fin_";
6419 if (shouldMangleDeclName(EnclosingDecl))
6420 Mangler.mangle(EnclosingDecl);
6421 else
6422 Mangler.getStream() << EnclosingDecl->getName();
6423}
6424
6425void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
6426 raw_ostream &Out) {
6427 // <special-name> ::= TH <object name>
6428 CXXNameMangler Mangler(*this, Out);
6429 Mangler.getStream() << "_ZTH";
6430 Mangler.mangleName(D);
6431}
6432
6433void
6434ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
6435 raw_ostream &Out) {
6436 // <special-name> ::= TW <object name>
6437 CXXNameMangler Mangler(*this, Out);
6438 Mangler.getStream() << "_ZTW";
6439 Mangler.mangleName(D);
6440}
6441
6442void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
6443 unsigned ManglingNumber,
6444 raw_ostream &Out) {
6445 // We match the GCC mangling here.
6446 // <special-name> ::= GR <object name>
6447 CXXNameMangler Mangler(*this, Out);
6448 Mangler.getStream() << "_ZGR";
6449 Mangler.mangleName(D);
6450 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!")(static_cast <bool> (ManglingNumber > 0 && "Reference temporary mangling number is zero!"
) ? void (0) : __assert_fail ("ManglingNumber > 0 && \"Reference temporary mangling number is zero!\""
, "clang/lib/AST/ItaniumMangle.cpp", 6450, __extension__ __PRETTY_FUNCTION__
))
;
6451 Mangler.mangleSeqID(ManglingNumber - 1);
6452}
6453
6454void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
6455 raw_ostream &Out) {
6456 // <special-name> ::= TV <type> # virtual table
6457 CXXNameMangler Mangler(*this, Out);
6458 Mangler.getStream() << "_ZTV";
6459 Mangler.mangleNameOrStandardSubstitution(RD);
6460}
6461
6462void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
6463 raw_ostream &Out) {
6464 // <special-name> ::= TT <type> # VTT structure
6465 CXXNameMangler Mangler(*this, Out);
6466 Mangler.getStream() << "_ZTT";
6467 Mangler.mangleNameOrStandardSubstitution(RD);
6468}
6469
6470void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
6471 int64_t Offset,
6472 const CXXRecordDecl *Type,
6473 raw_ostream &Out) {
6474 // <special-name> ::= TC <type> <offset number> _ <base type>
6475 CXXNameMangler Mangler(*this, Out);
6476 Mangler.getStream() << "_ZTC";
6477 Mangler.mangleNameOrStandardSubstitution(RD);
6478 Mangler.getStream() << Offset;
6479 Mangler.getStream() << '_';
6480 Mangler.mangleNameOrStandardSubstitution(Type);
6481}
6482
6483void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
6484 // <special-name> ::= TI <type> # typeinfo structure
6485 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers")(static_cast <bool> (!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"
) ? void (0) : __assert_fail ("!Ty.hasQualifiers() && \"RTTI info cannot have top-level qualifiers\""
, "clang/lib/AST/ItaniumMangle.cpp", 6485, __extension__ __PRETTY_FUNCTION__
))
;
6486 CXXNameMangler Mangler(*this, Out);
6487 Mangler.getStream() << "_ZTI";
6488 Mangler.mangleType(Ty);
6489}
6490
6491void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
6492 raw_ostream &Out) {
6493 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
6494 CXXNameMangler Mangler(*this, Out);
6495 Mangler.getStream() << "_ZTS";
6496 Mangler.mangleType(Ty);
6497}
6498
6499void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
6500 mangleCXXRTTIName(Ty, Out);
6501}
6502
6503void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
6504 llvm_unreachable("Can't mangle string literals")::llvm::llvm_unreachable_internal("Can't mangle string literals"
, "clang/lib/AST/ItaniumMangle.cpp", 6504)
;
6505}
6506
6507void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
6508 raw_ostream &Out) {
6509 CXXNameMangler Mangler(*this, Out);
6510 Mangler.mangleLambdaSig(Lambda);
6511}
6512
6513ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
6514 DiagnosticsEngine &Diags) {
6515 return new ItaniumMangleContextImpl(
6516 Context, Diags,
6517 [](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> {
6518 return llvm::None;
6519 });
6520}
6521
6522ItaniumMangleContext *
6523ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
6524 DiscriminatorOverrideTy DiscriminatorOverride) {
6525 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride);
6526}