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