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