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