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)->getNumParamsIncludingThis();
1772 [[fallthrough]];
1773 case DeclarationName::CXXConversionFunctionName:
1774 case DeclarationName::CXXLiteralOperatorName:
1775 mangleOperatorName(Name, Arity);
1776 writeAbiTags(ND, AdditionalAbiTags);
1777 break;
1778
1779 case DeclarationName::CXXDeductionGuideName:
1780 llvm_unreachable("Can't mangle a deduction guide name!");
1781
1782 case DeclarationName::CXXUsingDirective:
1783 llvm_unreachable("Can't mangle a using directive name!");
1784 }
1785}
1786
1787void CXXNameMangler::mangleConstructorName(
1788 const CXXConstructorDecl *CCD, ArrayRef<StringRef> AdditionalAbiTags) {
1789 const CXXRecordDecl *InheritedFrom = nullptr;
1790 TemplateName InheritedTemplateName;
1791 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1792 if (const auto Inherited = CCD->getInheritedConstructor()) {
1793 InheritedFrom = Inherited.getConstructor()->getParent();
1794 InheritedTemplateName =
1795 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1796 InheritedTemplateArgs =
1797 Inherited.getConstructor()->getTemplateSpecializationArgs();
1798 }
1799
1800 if (CCD == Structor)
1801 // If the named decl is the C++ constructor we're mangling, use the type
1802 // we were given.
1803 mangleCXXCtorType(T: static_cast<CXXCtorType>(StructorType), InheritedFrom);
1804 else
1805 // Otherwise, use the complete constructor name. This is relevant if a
1806 // class with a constructor is declared within a constructor.
1807 mangleCXXCtorType(T: Ctor_Complete, InheritedFrom);
1808
1809 // FIXME: The template arguments are part of the enclosing prefix or
1810 // nested-name, but it's more convenient to mangle them here.
1811 if (InheritedTemplateArgs)
1812 mangleTemplateArgs(TN: InheritedTemplateName, AL: *InheritedTemplateArgs);
1813
1814 writeAbiTags(ND: CCD, AdditionalAbiTags);
1815}
1816
1817void CXXNameMangler::mangleDestructorName(
1818 const CXXDestructorDecl *CDD, ArrayRef<StringRef> AdditionalAbiTags) {
1819 if (CDD == Structor)
1820 // If the named decl is the C++ destructor we're mangling, use the type we
1821 // were given.
1822 mangleCXXDtorType(T: static_cast<CXXDtorType>(StructorType));
1823 else
1824 // Otherwise, use the complete destructor name. This is relevant if a
1825 // class with a destructor is declared within a destructor.
1826 mangleCXXDtorType(T: Dtor_Complete);
1827 assert(CDD);
1828 writeAbiTags(ND: CDD, AdditionalAbiTags);
1829}
1830
1831void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1832 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1833 // <number> ::= [n] <non-negative decimal integer>
1834 // <identifier> ::= <unqualified source code identifier>
1835 if (getASTContext().getLangOpts().RegCall4)
1836 Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1837 << II->getName();
1838 else
1839 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1840 << II->getName();
1841}
1842
1843void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1844 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1845 // <number> ::= [n] <non-negative decimal integer>
1846 // <identifier> ::= <unqualified source code identifier>
1847 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1848 << II->getName();
1849}
1850
1851void CXXNameMangler::mangleOCLDeviceStubName(const IdentifierInfo *II) {
1852 // <source-name> ::= <positive length number> __clang_ocl_kern_imp_
1853 // <identifier> <number> ::= [n] <non-negative decimal integer> <identifier>
1854 // ::= <unqualified source code identifier>
1855 StringRef OCLDeviceStubNamePrefix = "__clang_ocl_kern_imp_";
1856 Out << II->getLength() + OCLDeviceStubNamePrefix.size()
1857 << OCLDeviceStubNamePrefix << II->getName();
1858}
1859
1860void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1861 // <source-name> ::= <positive length number> <identifier>
1862 // <number> ::= [n] <non-negative decimal integer>
1863 // <identifier> ::= <unqualified source code identifier>
1864 Out << II->getLength() << II->getName();
1865}
1866
1867void CXXNameMangler::mangleNestedName(GlobalDecl GD, const DeclContext *DC,
1868 ArrayRef<StringRef> AdditionalAbiTags,
1869 bool NoFunction) {
1870 const NamedDecl *ND = cast<NamedDecl>(Val: GD.getDecl());
1871 // <nested-name>
1872 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1873 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1874 // <template-args> E
1875
1876 Out << 'N';
1877 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: ND)) {
1878 Qualifiers MethodQuals = Method->getMethodQualifiers();
1879 // We do not consider restrict a distinguishing attribute for overloading
1880 // purposes so we must not mangle it.
1881 if (Method->isExplicitObjectMemberFunction())
1882 Out << 'H';
1883 MethodQuals.removeRestrict();
1884 mangleQualifiers(Quals: MethodQuals);
1885 mangleRefQualifier(RefQualifier: Method->getRefQualifier());
1886 }
1887
1888 // Check if we have a template.
1889 const TemplateArgumentList *TemplateArgs = nullptr;
1890 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1891 mangleTemplatePrefix(GD: TD, NoFunction);
1892 mangleTemplateArgs(TN: asTemplateName(GD: TD), AL: *TemplateArgs);
1893 } else {
1894 manglePrefix(DC, NoFunction);
1895 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1896 }
1897
1898 Out << 'E';
1899}
1900void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1901 ArrayRef<TemplateArgument> Args) {
1902 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1903
1904 Out << 'N';
1905
1906 mangleTemplatePrefix(GD: TD);
1907 mangleTemplateArgs(TN: asTemplateName(GD: TD), Args);
1908
1909 Out << 'E';
1910}
1911
1912void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1913 GlobalDecl GD, const NamedDecl *PrefixND,
1914 ArrayRef<StringRef> AdditionalAbiTags, bool NoFunction) {
1915 // A <closure-prefix> represents a variable or field, not a regular
1916 // DeclContext, so needs special handling. In this case we're mangling a
1917 // limited form of <nested-name>:
1918 //
1919 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1920
1921 Out << 'N';
1922
1923 mangleClosurePrefix(ND: PrefixND, NoFunction);
1924 mangleUnqualifiedName(GD, DC: nullptr, AdditionalAbiTags);
1925
1926 Out << 'E';
1927}
1928
1929static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1930 GlobalDecl GD;
1931 // The Itanium spec says:
1932 // For entities in constructors and destructors, the mangling of the
1933 // complete object constructor or destructor is used as the base function
1934 // name, i.e. the C1 or D1 version.
1935 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: DC))
1936 GD = GlobalDecl(CD, Ctor_Complete);
1937 else if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: DC))
1938 GD = GlobalDecl(DD, Dtor_Complete);
1939 else if (DC->isExpansionStmt())
1940 GD = getParentOfLocalEntity(DC: DC->getEnclosingNonExpansionStatementContext());
1941 else
1942 GD = GlobalDecl(cast<FunctionDecl>(Val: DC));
1943 return GD;
1944}
1945
1946void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1947 ArrayRef<StringRef> AdditionalAbiTags) {
1948 const Decl *D = GD.getDecl();
1949 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1950 // := Z <function encoding> E s [<discriminator>]
1951 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1952 // _ <entity name>
1953 // <discriminator> := _ <non-negative number>
1954 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1955 const RecordDecl *RD = GetLocalClassDecl(D);
1956 const DeclContext *DC = Context.getEffectiveDeclContext(D: RD ? RD : D);
1957
1958 Out << 'Z';
1959
1960 {
1961 AbiTagState LocalAbiTags(AbiTags);
1962
1963 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: DC)) {
1964 mangleObjCMethodName(MD);
1965 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(Val: DC)) {
1966 mangleBlockForPrefix(Block: BD);
1967 } else if (const auto *TLSD = dyn_cast<TopLevelStmtDecl>(Val: DC)) {
1968 mangleTopLevelStmtEncoding(D: TLSD);
1969 } else {
1970 mangleFunctionEncoding(GD: getParentOfLocalEntity(DC));
1971 }
1972
1973 // Implicit ABI tags (from namespace) are not available in the following
1974 // entity; reset to actually emitted tags, which are available.
1975 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1976 }
1977
1978 Out << 'E';
1979
1980 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1981 // be a bug that is fixed in trunk.
1982
1983 if (RD) {
1984 // The parameter number is omitted for the last parameter, 0 for the
1985 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1986 // <entity name> will of course contain a <closure-type-name>: Its
1987 // numbering will be local to the particular argument in which it appears
1988 // -- other default arguments do not affect its encoding.
1989 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD);
1990 if (CXXRD && CXXRD->isLambda()) {
1991 if (const ParmVarDecl *Parm
1992 = dyn_cast_or_null<ParmVarDecl>(Val: CXXRD->getLambdaContextDecl())) {
1993 if (const FunctionDecl *Func
1994 = dyn_cast<FunctionDecl>(Val: Parm->getDeclContext())) {
1995 Out << 'd';
1996 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1997 if (Num > 1)
1998 mangleNumber(Number: Num - 2);
1999 Out << '_';
2000 }
2001 }
2002 }
2003
2004 // Mangle the name relative to the closest enclosing function.
2005 // equality ok because RD derived from ND above
2006 if (D == RD) {
2007 mangleUnqualifiedName(GD: RD, DC, AdditionalAbiTags);
2008 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(Val: D)) {
2009 if (const NamedDecl *PrefixND = getClosurePrefix(ND: BD))
2010 mangleClosurePrefix(ND: PrefixND, NoFunction: true /*NoFunction*/);
2011 else
2012 manglePrefix(DC: Context.getEffectiveDeclContext(D: BD), NoFunction: true /*NoFunction*/);
2013 assert(AdditionalAbiTags.empty() &&
2014 "Block cannot have additional abi tags");
2015 mangleUnqualifiedBlock(Block: BD);
2016 } else {
2017 const NamedDecl *ND = cast<NamedDecl>(Val: D);
2018 const NamedDecl *PrefixND = getClosurePrefix(ND);
2019 if (PrefixND && !isCompatibleWith(Ver: LangOptions::ClangABI::Ver18))
2020 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags,
2021 /*NoFunction=*/true);
2022 else
2023 mangleNestedName(GD, DC: Context.getEffectiveDeclContext(D: ND),
2024 AdditionalAbiTags, /*NoFunction=*/true);
2025 }
2026 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(Val: D)) {
2027 // Mangle a block in a default parameter; see above explanation for
2028 // lambdas.
2029 if (const ParmVarDecl *Parm
2030 = dyn_cast_or_null<ParmVarDecl>(Val: BD->getBlockManglingContextDecl())) {
2031 if (const FunctionDecl *Func
2032 = dyn_cast<FunctionDecl>(Val: Parm->getDeclContext())) {
2033 Out << 'd';
2034 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
2035 if (Num > 1)
2036 mangleNumber(Number: Num - 2);
2037 Out << '_';
2038 }
2039 }
2040
2041 assert(AdditionalAbiTags.empty() &&
2042 "Block cannot have additional abi tags");
2043 mangleUnqualifiedBlock(Block: BD);
2044 } else {
2045 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
2046 }
2047
2048 if (const NamedDecl *ND = dyn_cast<NamedDecl>(Val: RD ? RD : D)) {
2049 unsigned disc;
2050 if (Context.getNextDiscriminator(ND, disc)) {
2051 if (disc < 10)
2052 Out << '_' << disc;
2053 else
2054 Out << "__" << disc << '_';
2055 }
2056 }
2057}
2058
2059void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
2060 if (GetLocalClassDecl(D: Block)) {
2061 mangleLocalName(GD: Block);
2062 return;
2063 }
2064 const DeclContext *DC = Context.getEffectiveDeclContext(D: Block);
2065 if (isLocalContainerContext(DC)) {
2066 mangleLocalName(GD: Block);
2067 return;
2068 }
2069 if (const NamedDecl *PrefixND = getClosurePrefix(ND: Block))
2070 mangleClosurePrefix(ND: PrefixND);
2071 else
2072 manglePrefix(DC);
2073 mangleUnqualifiedBlock(Block);
2074}
2075
2076void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
2077 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2078 // <data-member-prefix> now, with no substitutions and no <template-args>.
2079 if (Decl *Context = Block->getBlockManglingContextDecl();
2080 Context && isCompatibleWith(Ver: LangOptions::ClangABI::Ver12) &&
2081 (isa<VarDecl>(Val: Context) || isa<FieldDecl>(Val: Context)) &&
2082 Context->getDeclContext()->isRecord()) {
2083 const auto *ND = cast<NamedDecl>(Val: Context);
2084 if (ND->getIdentifier()) {
2085 mangleSourceNameWithAbiTags(ND);
2086 Out << 'M';
2087 }
2088 }
2089
2090 // If we have a block mangling number, use it.
2091 unsigned Number = Block->getBlockManglingNumber();
2092 // Otherwise, just make up a number. It doesn't matter what it is because
2093 // the symbol in question isn't externally visible.
2094 if (!Number)
2095 Number = Context.getBlockId(BD: Block, Local: false);
2096 else {
2097 // Stored mangling numbers are 1-based.
2098 --Number;
2099 }
2100 Out << "Ub";
2101 if (Number > 0)
2102 Out << Number - 1;
2103 Out << '_';
2104}
2105
2106void CXXNameMangler::mangleTopLevelStmtEncoding(const TopLevelStmtDecl *D) {
2107 // Numbered internal function, like Ub_ for blocks: locals get <local-name>s.
2108 SmallString<16> Name("__stmt__");
2109 Name += llvm::utostr(X: D->getOrdinal());
2110 Out << 'L' << Name.size() << Name << 'v';
2111}
2112
2113// <template-param-decl>
2114// ::= Ty # template type parameter
2115// ::= Tk <concept name> [<template-args>] # constrained type parameter
2116// ::= Tn <type> # template non-type parameter
2117// ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2118// # template template parameter
2119// ::= Tp <template-param-decl> # template parameter pack
2120void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2121 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2122 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Val: Decl)) {
2123 if (Ty->isParameterPack())
2124 Out << "Tp";
2125 const TypeConstraint *Constraint = Ty->getTypeConstraint();
2126 if (Constraint && !isCompatibleWith(Ver: LangOptions::ClangABI::Ver17)) {
2127 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2128 Out << "Tk";
2129 mangleTypeConstraint(Constraint);
2130 } else {
2131 Out << "Ty";
2132 }
2133 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Val: Decl)) {
2134 if (Tn->isExpandedParameterPack()) {
2135 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2136 Out << "Tn";
2137 mangleType(T: Tn->getExpansionType(I));
2138 }
2139 } else {
2140 QualType T = Tn->getType();
2141 if (Tn->isParameterPack()) {
2142 Out << "Tp";
2143 if (auto *PackExpansion = T->getAs<PackExpansionType>())
2144 T = PackExpansion->getPattern();
2145 }
2146 Out << "Tn";
2147 mangleType(T);
2148 }
2149 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Val: Decl)) {
2150 if (Tt->isExpandedParameterPack()) {
2151 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2152 ++I)
2153 mangleTemplateParameterList(Params: Tt->getExpansionTemplateParameters(I));
2154 } else {
2155 if (Tt->isParameterPack())
2156 Out << "Tp";
2157 mangleTemplateParameterList(Params: Tt->getTemplateParameters());
2158 }
2159 }
2160}
2161
2162void CXXNameMangler::mangleTemplateParameterList(
2163 const TemplateParameterList *Params) {
2164 Out << "Tt";
2165 for (auto *Param : *Params)
2166 mangleTemplateParamDecl(Decl: Param);
2167 mangleRequiresClause(RequiresClause: Params->getRequiresClause());
2168 Out << "E";
2169}
2170
2171void CXXNameMangler::mangleTypeConstraint(
2172 TemplateName Concept, ArrayRef<TemplateArgument> Arguments) {
2173 const TemplateDecl *TD = Concept.getAsTemplateDecl();
2174 if (!TD) {
2175 DiagnoseUnsupportedPackIndexTemplateName();
2176 return;
2177 }
2178 const DeclContext *DC = Context.getEffectiveDeclContext(D: TD);
2179 if (!Arguments.empty())
2180 mangleTemplateName(TD, Args: Arguments);
2181 else if (DC->isTranslationUnit() || isStdNamespace(DC))
2182 mangleUnscopedName(GD: TD, DC);
2183 else
2184 mangleNestedName(GD: TD, DC);
2185}
2186
2187void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2188 llvm::SmallVector<TemplateArgument, 8> Args;
2189 if (Constraint->getTemplateArgsAsWritten()) {
2190 for (const TemplateArgumentLoc &ArgLoc :
2191 Constraint->getTemplateArgsAsWritten()->arguments())
2192 Args.push_back(Elt: ArgLoc.getArgument());
2193 }
2194 return mangleTypeConstraint(Concept: Constraint->getNamedConcept(), Arguments: Args);
2195}
2196
2197void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2198 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2199 if (RequiresClause && !isCompatibleWith(Ver: LangOptions::ClangABI::Ver17)) {
2200 Out << 'Q';
2201 mangleExpression(E: RequiresClause);
2202 }
2203}
2204
2205void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2206 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2207 // <data-member-prefix> now, with no substitutions.
2208 if (Decl *Context = Lambda->getLambdaContextDecl();
2209 Context && isCompatibleWith(Ver: LangOptions::ClangABI::Ver12) &&
2210 (isa<VarDecl>(Val: Context) || isa<FieldDecl>(Val: Context)) &&
2211 !isa<ParmVarDecl>(Val: Context)) {
2212 if (const IdentifierInfo *Name =
2213 cast<NamedDecl>(Val: Context)->getIdentifier()) {
2214 mangleSourceName(II: Name);
2215 const TemplateArgumentList *TemplateArgs = nullptr;
2216 if (GlobalDecl TD = isTemplate(GD: cast<NamedDecl>(Val: Context), TemplateArgs))
2217 mangleTemplateArgs(TN: asTemplateName(GD: TD), AL: *TemplateArgs);
2218 Out << 'M';
2219 }
2220 }
2221
2222 Out << "Ul";
2223 mangleLambdaSig(Lambda);
2224 Out << "E";
2225
2226 // The number is omitted for the first closure type with a given
2227 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2228 // (in lexical order) with that same <lambda-sig> and context.
2229 //
2230 // The AST keeps track of the number for us.
2231 //
2232 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2233 // and host-side compilations, an extra device mangle context may be created
2234 // if the host-side CXX ABI has different numbering for lambda. In such case,
2235 // if the mangle context is that device-side one, use the device-side lambda
2236 // mangling number for this lambda.
2237 UnsignedOrNone DeviceNumber =
2238 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2239 unsigned Number =
2240 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2241
2242 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2243 if (Number > 1)
2244 mangleNumber(Number: Number - 2);
2245 Out << '_';
2246}
2247
2248void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2249 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2250 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2251 mangleTemplateParamDecl(Decl: D);
2252
2253 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2254 if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2255 mangleRequiresClause(RequiresClause: TPL->getRequiresClause());
2256
2257 auto *Proto =
2258 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2259 mangleBareFunctionType(T: Proto, /*MangleReturnType=*/false,
2260 FD: Lambda->getLambdaStaticInvoker());
2261}
2262
2263void CXXNameMangler::manglePrefix(NestedNameSpecifier Qualifier) {
2264 switch (Qualifier.getKind()) {
2265 case NestedNameSpecifier::Kind::Null:
2266 case NestedNameSpecifier::Kind::Global:
2267 // nothing
2268 return;
2269
2270 case NestedNameSpecifier::Kind::MicrosoftSuper:
2271 llvm_unreachable("Can't mangle __super specifier");
2272
2273 case NestedNameSpecifier::Kind::Namespace:
2274 mangleName(GD: Qualifier.getAsNamespaceAndPrefix().Namespace->getNamespace());
2275 return;
2276
2277 case NestedNameSpecifier::Kind::Type:
2278 manglePrefix(type: QualType(Qualifier.getAsType(), 0));
2279 return;
2280 }
2281
2282 llvm_unreachable("unexpected nested name specifier");
2283}
2284
2285void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2286 // <prefix> ::= <prefix> <unqualified-name>
2287 // ::= <template-prefix> <template-args>
2288 // ::= <closure-prefix>
2289 // ::= <template-param>
2290 // ::= # empty
2291 // ::= <substitution>
2292
2293 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2294
2295 if (DC->isTranslationUnit())
2296 return;
2297
2298 if (NoFunction && isLocalContainerContext(DC))
2299 return;
2300
2301 if (DC->isExpansionStmt())
2302 return;
2303
2304 const NamedDecl *ND = cast<NamedDecl>(Val: DC);
2305 if (mangleSubstitution(ND))
2306 return;
2307
2308 // Constructors and destructors can't be represented as a plain GlobalDecl,
2309 // and prefix mangling only needs their spelling.
2310 if (isa<CXXConstructorDecl>(Val: ND)) {
2311 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: ND);
2312 const TemplateDecl *TD = FD->getPrimaryTemplate()) {
2313 mangleTemplatePrefix(GD: TD);
2314 mangleTemplateArgs(TN: asTemplateName(GD: TD),
2315 AL: *FD->getTemplateSpecializationArgs());
2316 } else {
2317 manglePrefix(DC: Context.getEffectiveDeclContext(D: ND), NoFunction);
2318 mangleConstructorName(CCD: cast<CXXConstructorDecl>(Val: ND));
2319 }
2320 addSubstitution(ND);
2321 return;
2322 }
2323
2324 if (isa<CXXDestructorDecl>(Val: ND)) {
2325 manglePrefix(DC: Context.getEffectiveDeclContext(D: ND), NoFunction);
2326 mangleDestructorName(CDD: cast<CXXDestructorDecl>(Val: ND));
2327 addSubstitution(ND);
2328 return;
2329 }
2330
2331 // Check if we have a template-prefix or a closure-prefix.
2332 const TemplateArgumentList *TemplateArgs = nullptr;
2333 if (GlobalDecl TD = isTemplate(GD: ND, TemplateArgs)) {
2334 mangleTemplatePrefix(GD: TD);
2335 mangleTemplateArgs(TN: asTemplateName(GD: TD), AL: *TemplateArgs);
2336 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2337 mangleClosurePrefix(ND: PrefixND, NoFunction);
2338 mangleUnqualifiedName(GD: ND, DC: nullptr);
2339 } else {
2340 const DeclContext *DC = Context.getEffectiveDeclContext(D: ND);
2341 manglePrefix(DC, NoFunction);
2342 mangleUnqualifiedName(GD: ND, DC);
2343 }
2344
2345 addSubstitution(ND);
2346}
2347
2348void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2349 // <template-prefix> ::= <prefix> <template unqualified-name>
2350 // ::= <template-param>
2351 // ::= <substitution>
2352 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2353 return mangleTemplatePrefix(GD: TD);
2354
2355 if (Template.getAsPackIndexingTemplate()) {
2356 DiagnoseUnsupportedPackIndexTemplateName();
2357 return;
2358 }
2359
2360 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2361 assert(Dependent && "unexpected template name kind");
2362
2363 // Clang 11 and before mangled the substitution for a dependent template name
2364 // after already having emitted (a substitution for) the prefix.
2365 bool Clang11Compat = isCompatibleWith(Ver: LangOptions::ClangABI::Ver11);
2366 if (!Clang11Compat && mangleSubstitution(Template))
2367 return;
2368
2369 manglePrefix(Qualifier: Dependent->getQualifier());
2370
2371 if (Clang11Compat && mangleSubstitution(Template))
2372 return;
2373
2374 if (IdentifierOrOverloadedOperator Name = Dependent->getName();
2375 const IdentifierInfo *Id = Name.getIdentifier())
2376 mangleSourceName(II: Id);
2377 else
2378 mangleOperatorName(OO: Name.getOperator(), Arity: UnknownArity);
2379
2380 addSubstitution(Template);
2381}
2382
2383void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2384 bool NoFunction) {
2385 const TemplateDecl *ND = cast<TemplateDecl>(Val: GD.getDecl());
2386 // <template-prefix> ::= <prefix> <template unqualified-name>
2387 // ::= <template-param>
2388 // ::= <substitution>
2389 // <template-template-param> ::= <template-param>
2390 // <substitution>
2391
2392 if (mangleSubstitution(ND))
2393 return;
2394
2395 // <template-template-param> ::= <template-param>
2396 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: ND)) {
2397 mangleTemplateParameter(Depth: TTP->getDepth(), Index: TTP->getIndex());
2398 } else {
2399 const DeclContext *DC = Context.getEffectiveDeclContext(D: ND);
2400 manglePrefix(DC, NoFunction);
2401 if (isa<BuiltinTemplateDecl>(Val: ND) || isa<ConceptDecl>(Val: ND))
2402 mangleUnqualifiedName(GD, DC);
2403 else
2404 mangleUnqualifiedName(GD: GD.getWithDecl(D: ND->getTemplatedDecl()), DC);
2405 }
2406
2407 addSubstitution(ND);
2408}
2409
2410const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2411 if (isCompatibleWith(Ver: LangOptions::ClangABI::Ver12))
2412 return nullptr;
2413
2414 const NamedDecl *Context = nullptr;
2415 if (auto *Block = dyn_cast<BlockDecl>(Val: ND)) {
2416 Context = dyn_cast_or_null<NamedDecl>(Val: Block->getBlockManglingContextDecl());
2417 } else if (auto *VD = dyn_cast<VarDecl>(Val: ND)) {
2418 if (const CXXRecordDecl *Lambda = getLambdaForInitCapture(VD))
2419 Context = dyn_cast_or_null<NamedDecl>(Val: Lambda->getLambdaContextDecl());
2420 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) {
2421 if (RD->isLambda())
2422 Context = dyn_cast_or_null<NamedDecl>(Val: RD->getLambdaContextDecl());
2423 }
2424 if (!Context)
2425 return nullptr;
2426
2427 // Only entities associated with lambdas within the initializer of a
2428 // non-local variable or non-static data member get a <closure-prefix>.
2429 if ((isa<VarDecl>(Val: Context) && cast<VarDecl>(Val: Context)->hasGlobalStorage()) ||
2430 isa<FieldDecl>(Val: Context))
2431 return Context;
2432
2433 return nullptr;
2434}
2435
2436void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2437 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2438 // ::= <template-prefix> <template-args> M
2439 if (mangleSubstitution(ND))
2440 return;
2441
2442 const TemplateArgumentList *TemplateArgs = nullptr;
2443 if (GlobalDecl TD = isTemplate(GD: ND, TemplateArgs)) {
2444 mangleTemplatePrefix(GD: TD, NoFunction);
2445 mangleTemplateArgs(TN: asTemplateName(GD: TD), AL: *TemplateArgs);
2446 } else {
2447 const auto *DC = Context.getEffectiveDeclContext(D: ND);
2448 manglePrefix(DC, NoFunction);
2449 mangleUnqualifiedName(GD: ND, DC);
2450 }
2451
2452 Out << 'M';
2453
2454 addSubstitution(ND);
2455}
2456
2457/// Mangles a template name under the production <type>. Required for
2458/// template template arguments.
2459/// <type> ::= <class-enum-type>
2460/// ::= <template-param>
2461/// ::= <substitution>
2462void CXXNameMangler::mangleType(TemplateName TN) {
2463 if (mangleSubstitution(Template: TN))
2464 return;
2465
2466 TemplateDecl *TD = nullptr;
2467
2468 switch (TN.getKind()) {
2469 case TemplateName::QualifiedTemplate:
2470 case TemplateName::UsingTemplate:
2471 case TemplateName::Template:
2472 TD = TN.getAsTemplateDecl();
2473 goto HaveDecl;
2474
2475 HaveDecl:
2476 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TD))
2477 mangleTemplateParameter(Depth: TTP->getDepth(), Index: TTP->getIndex());
2478 else
2479 mangleName(GD: TD);
2480 break;
2481
2482 case TemplateName::OverloadedTemplate:
2483 case TemplateName::AssumedTemplate:
2484 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2485
2486 case TemplateName::DependentTemplate: {
2487 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2488 const IdentifierInfo *II = Dependent->getName().getIdentifier();
2489 assert(II);
2490
2491 // <class-enum-type> ::= <name>
2492 // <name> ::= <nested-name>
2493 mangleUnresolvedPrefix(Qualifier: Dependent->getQualifier());
2494 mangleSourceName(II);
2495 break;
2496 }
2497
2498 case TemplateName::SubstTemplateTemplateParm: {
2499 // Substituted template parameters are mangled as the substituted
2500 // template. This will check for the substitution twice, which is
2501 // fine, but we have to return early so that we don't try to *add*
2502 // the substitution twice.
2503 SubstTemplateTemplateParmStorage *subst
2504 = TN.getAsSubstTemplateTemplateParm();
2505 mangleType(TN: subst->getReplacement());
2506 return;
2507 }
2508
2509 case TemplateName::SubstTemplateTemplateParmPack: {
2510 // FIXME: not clear how to mangle this!
2511 // template <template <class> class T...> class A {
2512 // template <template <class> class U...> void foo(B<T,U> x...);
2513 // };
2514 Out << "_SUBSTPACK_";
2515 break;
2516 }
2517
2518 case TemplateName::PackIndexingTemplate:
2519 DiagnoseUnsupportedPackIndexTemplateName();
2520 return;
2521
2522 case TemplateName::DeducedTemplate:
2523 llvm_unreachable("Unexpected DeducedTemplate");
2524 }
2525
2526 addSubstitution(Template: TN);
2527}
2528
2529bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2530 StringRef Prefix) {
2531 // Only certain other types are valid as prefixes; enumerate them.
2532 switch (Ty->getTypeClass()) {
2533 case Type::Builtin:
2534 case Type::Complex:
2535 case Type::Adjusted:
2536 case Type::Decayed:
2537 case Type::ArrayParameter:
2538 case Type::Pointer:
2539 case Type::BlockPointer:
2540 case Type::LValueReference:
2541 case Type::RValueReference:
2542 case Type::MemberPointer:
2543 case Type::ConstantArray:
2544 case Type::IncompleteArray:
2545 case Type::VariableArray:
2546 case Type::DependentSizedArray:
2547 case Type::DependentAddressSpace:
2548 case Type::DependentVector:
2549 case Type::DependentSizedExtVector:
2550 case Type::Vector:
2551 case Type::ExtVector:
2552 case Type::ConstantMatrix:
2553 case Type::DependentSizedMatrix:
2554 case Type::FunctionProto:
2555 case Type::FunctionNoProto:
2556 case Type::Paren:
2557 case Type::Attributed:
2558 case Type::BTFTagAttributed:
2559 case Type::OverflowBehavior:
2560 case Type::HLSLAttributedResource:
2561 case Type::HLSLInlineSpirv:
2562 case Type::Auto:
2563 case Type::DeducedTemplateSpecialization:
2564 case Type::PackExpansion:
2565 case Type::ObjCObject:
2566 case Type::ObjCInterface:
2567 case Type::ObjCObjectPointer:
2568 case Type::ObjCTypeParam:
2569 case Type::Atomic:
2570 case Type::Pipe:
2571 case Type::MacroQualified:
2572 case Type::BitInt:
2573 case Type::DependentBitInt:
2574 case Type::CountAttributed:
2575 case Type::LateParsedAttr:
2576 llvm_unreachable("type is illegal as a nested name specifier");
2577
2578 case Type::SubstBuiltinTemplatePack:
2579 // FIXME: not clear how to mangle this!
2580 // template <class T...> class A {
2581 // template <class U...> void foo(__builtin_dedup_pack<T...>(*)(U) x...);
2582 // };
2583 Out << "_SUBSTBUILTINPACK_";
2584 break;
2585 case Type::SubstTemplateTypeParmPack:
2586 // FIXME: not clear how to mangle this!
2587 // template <class T...> class A {
2588 // template <class U...> void foo(decltype(T::foo(U())) x...);
2589 // };
2590 Out << "_SUBSTPACK_";
2591 break;
2592
2593 // <unresolved-type> ::= <template-param>
2594 // ::= <decltype>
2595 // ::= <template-template-param> <template-args>
2596 // (this last is not official yet)
2597 case Type::TypeOfExpr:
2598 case Type::TypeOf:
2599 case Type::Decltype:
2600 case Type::PackIndexing:
2601 case Type::TemplateTypeParm:
2602 case Type::UnaryTransform:
2603 unresolvedType:
2604 // Some callers want a prefix before the mangled type.
2605 Out << Prefix;
2606
2607 // This seems to do everything we want. It's not really
2608 // sanctioned for a substituted template parameter, though.
2609 mangleType(T: Ty);
2610
2611 // We never want to print 'E' directly after an unresolved-type,
2612 // so we return directly.
2613 return true;
2614
2615 case Type::SubstTemplateTypeParm: {
2616 auto *ST = cast<SubstTemplateTypeParmType>(Val&: Ty);
2617 // If this was replaced from a type alias, this is not substituted
2618 // from an outer template parameter, so it's not an unresolved-type.
2619 if (auto *TD = dyn_cast<TemplateDecl>(Val: ST->getAssociatedDecl());
2620 TD && TD->isTypeAlias())
2621 return mangleUnresolvedTypeOrSimpleId(Ty: ST->getReplacementType(), Prefix);
2622 goto unresolvedType;
2623 }
2624
2625 case Type::Typedef:
2626 mangleSourceNameWithAbiTags(ND: cast<TypedefType>(Val&: Ty)->getDecl());
2627 break;
2628
2629 case Type::PredefinedSugar:
2630 mangleType(T: cast<PredefinedSugarType>(Val&: Ty)->desugar());
2631 break;
2632
2633 case Type::UnresolvedUsing:
2634 mangleSourceNameWithAbiTags(
2635 ND: cast<UnresolvedUsingType>(Val&: Ty)->getDecl());
2636 break;
2637
2638 case Type::Enum:
2639 case Type::Record:
2640 mangleSourceNameWithAbiTags(
2641 ND: cast<TagType>(Val&: Ty)->getDecl()->getDefinitionOrSelf());
2642 break;
2643
2644 case Type::TemplateSpecialization: {
2645 const TemplateSpecializationType *TST =
2646 cast<TemplateSpecializationType>(Val&: Ty);
2647 TemplateName TN = TST->getTemplateName();
2648 switch (TN.getKind()) {
2649 case TemplateName::Template:
2650 case TemplateName::QualifiedTemplate: {
2651 TemplateDecl *TD = TN.getAsTemplateDecl();
2652
2653 // If the base is a template template parameter, this is an
2654 // unresolved type.
2655 assert(TD && "no template for template specialization type");
2656 if (isa<TemplateTemplateParmDecl>(Val: TD))
2657 goto unresolvedType;
2658
2659 mangleSourceNameWithAbiTags(ND: TD);
2660 break;
2661 }
2662 case TemplateName::DependentTemplate: {
2663 const DependentTemplateStorage *S = TN.getAsDependentTemplateName();
2664 mangleSourceName(II: S->getName().getIdentifier());
2665 break;
2666 }
2667
2668 case TemplateName::OverloadedTemplate:
2669 case TemplateName::AssumedTemplate:
2670 case TemplateName::DeducedTemplate:
2671 llvm_unreachable("invalid base for a template specialization type");
2672
2673 case TemplateName::SubstTemplateTemplateParm: {
2674 SubstTemplateTemplateParmStorage *subst =
2675 TN.getAsSubstTemplateTemplateParm();
2676 mangleExistingSubstitution(name: subst->getReplacement());
2677 break;
2678 }
2679
2680 case TemplateName::SubstTemplateTemplateParmPack: {
2681 // FIXME: not clear how to mangle this!
2682 // template <template <class U> class T...> class A {
2683 // template <class U...> void foo(decltype(T<U>::foo) x...);
2684 // };
2685 Out << "_SUBSTPACK_";
2686 break;
2687 }
2688
2689 case TemplateName::PackIndexingTemplate:
2690 DiagnoseUnsupportedPackIndexTemplateName();
2691 return false;
2692
2693 case TemplateName::UsingTemplate: {
2694 TemplateDecl *TD = TN.getAsTemplateDecl();
2695 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2696 mangleSourceNameWithAbiTags(ND: TD);
2697 break;
2698 }
2699 }
2700
2701 // Note: we don't pass in the template name here. We are mangling the
2702 // original source-level template arguments, so we shouldn't consider
2703 // conversions to the corresponding template parameter.
2704 // FIXME: Other compilers mangle partially-resolved template arguments in
2705 // unresolved-qualifier-levels.
2706 mangleTemplateArgs(TN: TemplateName(), Args: TST->template_arguments());
2707 break;
2708 }
2709
2710 case Type::InjectedClassName:
2711 mangleSourceNameWithAbiTags(
2712 ND: cast<InjectedClassNameType>(Val&: Ty)->getDecl()->getDefinitionOrSelf());
2713 break;
2714
2715 case Type::DependentName:
2716 mangleSourceName(II: cast<DependentNameType>(Val&: Ty)->getIdentifier());
2717 break;
2718
2719 case Type::Using:
2720 return mangleUnresolvedTypeOrSimpleId(Ty: cast<UsingType>(Val&: Ty)->desugar(),
2721 Prefix);
2722 }
2723
2724 return false;
2725}
2726
2727void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2728 switch (Name.getNameKind()) {
2729 case DeclarationName::CXXConstructorName:
2730 case DeclarationName::CXXDestructorName:
2731 case DeclarationName::CXXDeductionGuideName:
2732 case DeclarationName::CXXUsingDirective:
2733 case DeclarationName::Identifier:
2734 case DeclarationName::ObjCMultiArgSelector:
2735 case DeclarationName::ObjCOneArgSelector:
2736 case DeclarationName::ObjCZeroArgSelector:
2737 llvm_unreachable("Not an operator name");
2738
2739 case DeclarationName::CXXConversionFunctionName:
2740 // <operator-name> ::= cv <type> # (cast)
2741 Out << "cv";
2742 mangleType(T: Name.getCXXNameType());
2743 break;
2744
2745 case DeclarationName::CXXLiteralOperatorName:
2746 Out << "li";
2747 mangleSourceName(II: Name.getCXXLiteralIdentifier());
2748 return;
2749
2750 case DeclarationName::CXXOperatorName:
2751 mangleOperatorName(OO: Name.getCXXOverloadedOperator(), Arity);
2752 break;
2753 }
2754}
2755
2756void
2757CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2758 switch (OO) {
2759 // <operator-name> ::= nw # new
2760 case OO_New: Out << "nw"; break;
2761 // ::= na # new[]
2762 case OO_Array_New: Out << "na"; break;
2763 // ::= dl # delete
2764 case OO_Delete: Out << "dl"; break;
2765 // ::= da # delete[]
2766 case OO_Array_Delete: Out << "da"; break;
2767 // ::= ps # + (unary)
2768 // ::= pl # + (binary or unknown)
2769 case OO_Plus:
2770 Out << (Arity == 1? "ps" : "pl"); break;
2771 // ::= ng # - (unary)
2772 // ::= mi # - (binary or unknown)
2773 case OO_Minus:
2774 Out << (Arity == 1? "ng" : "mi"); break;
2775 // ::= ad # & (unary)
2776 // ::= an # & (binary or unknown)
2777 case OO_Amp:
2778 Out << (Arity == 1? "ad" : "an"); break;
2779 // ::= de # * (unary)
2780 // ::= ml # * (binary or unknown)
2781 case OO_Star:
2782 // Use binary when unknown.
2783 Out << (Arity == 1? "de" : "ml"); break;
2784 // ::= co # ~
2785 case OO_Tilde: Out << "co"; break;
2786 // ::= dv # /
2787 case OO_Slash: Out << "dv"; break;
2788 // ::= rm # %
2789 case OO_Percent: Out << "rm"; break;
2790 // ::= or # |
2791 case OO_Pipe: Out << "or"; break;
2792 // ::= eo # ^
2793 case OO_Caret: Out << "eo"; break;
2794 // ::= aS # =
2795 case OO_Equal: Out << "aS"; break;
2796 // ::= pL # +=
2797 case OO_PlusEqual: Out << "pL"; break;
2798 // ::= mI # -=
2799 case OO_MinusEqual: Out << "mI"; break;
2800 // ::= mL # *=
2801 case OO_StarEqual: Out << "mL"; break;
2802 // ::= dV # /=
2803 case OO_SlashEqual: Out << "dV"; break;
2804 // ::= rM # %=
2805 case OO_PercentEqual: Out << "rM"; break;
2806 // ::= aN # &=
2807 case OO_AmpEqual: Out << "aN"; break;
2808 // ::= oR # |=
2809 case OO_PipeEqual: Out << "oR"; break;
2810 // ::= eO # ^=
2811 case OO_CaretEqual: Out << "eO"; break;
2812 // ::= ls # <<
2813 case OO_LessLess: Out << "ls"; break;
2814 // ::= rs # >>
2815 case OO_GreaterGreater: Out << "rs"; break;
2816 // ::= lS # <<=
2817 case OO_LessLessEqual: Out << "lS"; break;
2818 // ::= rS # >>=
2819 case OO_GreaterGreaterEqual: Out << "rS"; break;
2820 // ::= eq # ==
2821 case OO_EqualEqual: Out << "eq"; break;
2822 // ::= ne # !=
2823 case OO_ExclaimEqual: Out << "ne"; break;
2824 // ::= lt # <
2825 case OO_Less: Out << "lt"; break;
2826 // ::= gt # >
2827 case OO_Greater: Out << "gt"; break;
2828 // ::= le # <=
2829 case OO_LessEqual: Out << "le"; break;
2830 // ::= ge # >=
2831 case OO_GreaterEqual: Out << "ge"; break;
2832 // ::= nt # !
2833 case OO_Exclaim: Out << "nt"; break;
2834 // ::= aa # &&
2835 case OO_AmpAmp: Out << "aa"; break;
2836 // ::= oo # ||
2837 case OO_PipePipe: Out << "oo"; break;
2838 // ::= pp # ++
2839 case OO_PlusPlus: Out << "pp"; break;
2840 // ::= mm # --
2841 case OO_MinusMinus: Out << "mm"; break;
2842 // ::= cm # ,
2843 case OO_Comma: Out << "cm"; break;
2844 // ::= pm # ->*
2845 case OO_ArrowStar: Out << "pm"; break;
2846 // ::= pt # ->
2847 case OO_Arrow: Out << "pt"; break;
2848 // ::= cl # ()
2849 case OO_Call: Out << "cl"; break;
2850 // ::= ix # []
2851 case OO_Subscript: Out << "ix"; break;
2852
2853 // ::= qu # ?
2854 // The conditional operator can't be overloaded, but we still handle it when
2855 // mangling expressions.
2856 case OO_Conditional: Out << "qu"; break;
2857 // Proposal on cxx-abi-dev, 2015-10-21.
2858 // ::= aw # co_await
2859 case OO_Coawait: Out << "aw"; break;
2860 // Proposed in cxx-abi github issue 43.
2861 // ::= ss # <=>
2862 case OO_Spaceship: Out << "ss"; break;
2863
2864 case OO_None:
2865 case NUM_OVERLOADED_OPERATORS:
2866 llvm_unreachable("Not an overloaded operator");
2867 }
2868}
2869
2870void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2871 // Vendor qualifiers come first and if they are order-insensitive they must
2872 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2873
2874 // <type> ::= U <addrspace-expr>
2875 if (DAST) {
2876 Out << "U2ASI";
2877 mangleExpression(E: DAST->getAddrSpaceExpr());
2878 Out << "E";
2879 }
2880
2881 // Address space qualifiers start with an ordinary letter.
2882 if (Quals.hasAddressSpace()) {
2883 // Address space extension:
2884 //
2885 // <type> ::= U <target-addrspace>
2886 // <type> ::= U <OpenCL-addrspace>
2887 // <type> ::= U <CUDA-addrspace>
2888
2889 SmallString<64> ASString;
2890 LangAS AS = Quals.getAddressSpace();
2891
2892 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2893 // <target-addrspace> ::= "AS" <address-space-number>
2894 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2895 if (TargetAS != 0 ||
2896 Context.getASTContext().getTargetAddressSpace(AS: LangAS::Default) != 0)
2897 ASString = "AS" + llvm::utostr(X: TargetAS);
2898 } else {
2899 switch (AS) {
2900 default: llvm_unreachable("Not a language specific address space");
2901 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2902 // "private"| "generic" | "device" |
2903 // "host" ]
2904 case LangAS::opencl_global:
2905 ASString = "CLglobal";
2906 break;
2907 case LangAS::opencl_global_device:
2908 ASString = "CLdevice";
2909 break;
2910 case LangAS::opencl_global_host:
2911 ASString = "CLhost";
2912 break;
2913 case LangAS::opencl_local:
2914 ASString = "CLlocal";
2915 break;
2916 case LangAS::opencl_constant:
2917 ASString = "CLconstant";
2918 break;
2919 case LangAS::opencl_private:
2920 ASString = "CLprivate";
2921 break;
2922 case LangAS::opencl_generic:
2923 ASString = "CLgeneric";
2924 break;
2925 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2926 // "generic" | "constant" | "device" | "host"
2927 // ]
2928 case LangAS::sycl_global:
2929 ASString = "SYglobal";
2930 break;
2931 case LangAS::sycl_global_device:
2932 ASString = "SYdevice";
2933 break;
2934 case LangAS::sycl_global_host:
2935 ASString = "SYhost";
2936 break;
2937 case LangAS::sycl_local:
2938 ASString = "SYlocal";
2939 break;
2940 case LangAS::sycl_private:
2941 ASString = "SYprivate";
2942 break;
2943 case LangAS::sycl_generic:
2944 ASString = "SYgeneric";
2945 break;
2946 case LangAS::sycl_constant:
2947 ASString = "SYconstant";
2948 break;
2949 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2950 case LangAS::cuda_device:
2951 ASString = "CUdevice";
2952 break;
2953 case LangAS::cuda_constant:
2954 ASString = "CUconstant";
2955 break;
2956 case LangAS::cuda_shared:
2957 ASString = "CUshared";
2958 break;
2959 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2960 case LangAS::ptr32_sptr:
2961 ASString = "ptr32_sptr";
2962 break;
2963 case LangAS::ptr32_uptr:
2964 // For z/OS, there are no special mangling rules applied to the ptr32
2965 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2966 // "p" is treated the same as a regular integer pointer.
2967 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2968 ASString = "ptr32_uptr";
2969 break;
2970 case LangAS::ptr64:
2971 ASString = "ptr64";
2972 break;
2973 }
2974 }
2975 if (!ASString.empty())
2976 mangleVendorQualifier(Name: ASString);
2977 }
2978
2979 // The ARC ownership qualifiers start with underscores.
2980 // Objective-C ARC Extension:
2981 //
2982 // <type> ::= U "__strong"
2983 // <type> ::= U "__weak"
2984 // <type> ::= U "__autoreleasing"
2985 //
2986 // Note: we emit __weak first to preserve the order as
2987 // required by the Itanium ABI.
2988 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2989 mangleVendorQualifier(Name: "__weak");
2990
2991 // __unaligned (from -fms-extensions)
2992 if (Quals.hasUnaligned())
2993 mangleVendorQualifier(Name: "__unaligned");
2994
2995 // __ptrauth. Note that this is parameterized.
2996 if (PointerAuthQualifier PtrAuth = Quals.getPointerAuth()) {
2997 mangleVendorQualifier(Name: "__ptrauth");
2998 // For now, since we only allow non-dependent arguments, we can just
2999 // inline the mangling of those arguments as literals. We treat the
3000 // key and extra-discriminator arguments as 'unsigned int' and the
3001 // address-discriminated argument as 'bool'.
3002 Out << "I"
3003 "Lj"
3004 << PtrAuth.getKey()
3005 << "E"
3006 "Lb"
3007 << unsigned(PtrAuth.isAddressDiscriminated())
3008 << "E"
3009 "Lj"
3010 << PtrAuth.getExtraDiscriminator()
3011 << "E"
3012 "E";
3013 }
3014
3015 // Remaining ARC ownership qualifiers.
3016 switch (Quals.getObjCLifetime()) {
3017 case Qualifiers::OCL_None:
3018 break;
3019
3020 case Qualifiers::OCL_Weak:
3021 // Do nothing as we already handled this case above.
3022 break;
3023
3024 case Qualifiers::OCL_Strong:
3025 mangleVendorQualifier(Name: "__strong");
3026 break;
3027
3028 case Qualifiers::OCL_Autoreleasing:
3029 mangleVendorQualifier(Name: "__autoreleasing");
3030 break;
3031
3032 case Qualifiers::OCL_ExplicitNone:
3033 // The __unsafe_unretained qualifier is *not* mangled, so that
3034 // __unsafe_unretained types in ARC produce the same manglings as the
3035 // equivalent (but, naturally, unqualified) types in non-ARC, providing
3036 // better ABI compatibility.
3037 //
3038 // It's safe to do this because unqualified 'id' won't show up
3039 // in any type signatures that need to be mangled.
3040 break;
3041 }
3042
3043 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
3044 if (Quals.hasRestrict())
3045 Out << 'r';
3046 if (Quals.hasVolatile())
3047 Out << 'V';
3048 if (Quals.hasConst())
3049 Out << 'K';
3050}
3051
3052void CXXNameMangler::mangleVendorQualifier(StringRef name) {
3053 Out << 'U' << name.size() << name;
3054}
3055
3056void CXXNameMangler::mangleVendorType(StringRef name) {
3057 Out << 'u' << name.size() << name;
3058}
3059
3060void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
3061 // <ref-qualifier> ::= R # lvalue reference
3062 // ::= O # rvalue-reference
3063 switch (RefQualifier) {
3064 case RQ_None:
3065 break;
3066
3067 case RQ_LValue:
3068 Out << 'R';
3069 break;
3070
3071 case RQ_RValue:
3072 Out << 'O';
3073 break;
3074 }
3075}
3076
3077void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
3078 Context.mangleObjCMethodNameAsSourceName(MD, Out);
3079}
3080
3081static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
3082 ASTContext &Ctx) {
3083 if (Quals)
3084 return true;
3085 if (Ty->isSpecificBuiltinType(K: BuiltinType::ObjCSel))
3086 return true;
3087 if (Ty->isOpenCLSpecificType())
3088 return true;
3089 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
3090 if (Ty->isSVESizelessBuiltinType() &&
3091 !Ctx.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver17))
3092 return true;
3093 if (Ty->isBuiltinType())
3094 return false;
3095 // Through to Clang 6.0, we accidentally treated undeduced auto types as
3096 // substitution candidates.
3097 if (!Ctx.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver6) &&
3098 isa<AutoType>(Val: Ty))
3099 return false;
3100 // A placeholder type for class template deduction is substitutable with
3101 // its corresponding template name; this is handled specially when mangling
3102 // the type.
3103 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
3104 if (DeducedTST->getDeducedType().isNull())
3105 return false;
3106 return true;
3107}
3108
3109void CXXNameMangler::mangleType(QualType T) {
3110 // If our type is instantiation-dependent but not dependent, we mangle
3111 // it as it was written in the source, removing any top-level sugar.
3112 // Otherwise, use the canonical type.
3113 //
3114 // FIXME: This is an approximation of the instantiation-dependent name
3115 // mangling rules, since we should really be using the type as written and
3116 // augmented via semantic analysis (i.e., with implicit conversions and
3117 // default template arguments) for any instantiation-dependent type.
3118 // Unfortunately, that requires several changes to our AST:
3119 // - Instantiation-dependent TemplateSpecializationTypes will need to be
3120 // uniqued, so that we can handle substitutions properly
3121 // - Default template arguments will need to be represented in the
3122 // TemplateSpecializationType, since they need to be mangled even though
3123 // they aren't written.
3124 // - Conversions on non-type template arguments need to be expressed, since
3125 // they can affect the mangling of sizeof/alignof.
3126 //
3127 // FIXME: This is wrong when mapping to the canonical type for a dependent
3128 // type discards instantiation-dependent portions of the type, such as for:
3129 //
3130 // template<typename T, int N> void f(T (&)[sizeof(N)]);
3131 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
3132 //
3133 // It's also wrong in the opposite direction when instantiation-dependent,
3134 // canonically-equivalent types differ in some irrelevant portion of inner
3135 // type sugar. In such cases, we fail to form correct substitutions, eg:
3136 //
3137 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
3138 //
3139 // We should instead canonicalize the non-instantiation-dependent parts,
3140 // regardless of whether the type as a whole is dependent or instantiation
3141 // dependent.
3142 if (!T->isInstantiationDependentType() || T->isDependentType())
3143 T = T.getCanonicalType();
3144 else {
3145 // Desugar any types that are purely sugar.
3146 do {
3147 // Don't desugar through template specialization types that aren't
3148 // type aliases. We need to mangle the template arguments as written.
3149 if (const TemplateSpecializationType *TST
3150 = dyn_cast<TemplateSpecializationType>(Val&: T))
3151 if (!TST->isTypeAlias())
3152 break;
3153
3154 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
3155 // instantation-dependent qualifiers. See
3156 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
3157
3158 QualType Desugared
3159 = T.getSingleStepDesugaredType(Context: Context.getASTContext());
3160 if (Desugared == T)
3161 break;
3162
3163 T = Desugared;
3164 } while (true);
3165 }
3166 auto [ty, quals] = T.split();
3167
3168 bool isSubstitutable =
3169 isTypeSubstitutable(Quals: quals, Ty: ty, Ctx&: Context.getASTContext());
3170 if (isSubstitutable && mangleSubstitution(T))
3171 return;
3172
3173 // If we're mangling a qualified array type, push the qualifiers to
3174 // the element type.
3175 if (quals && isa<ArrayType>(Val: T)) {
3176 ty = Context.getASTContext().getAsArrayType(T);
3177 quals = Qualifiers();
3178
3179 // Note that we don't update T: we want to add the
3180 // substitution at the original type.
3181 }
3182
3183 if (quals || ty->isDependentAddressSpaceType()) {
3184 if (const DependentAddressSpaceType *DAST =
3185 dyn_cast<DependentAddressSpaceType>(Val: ty)) {
3186 auto [Ty, Quals] = DAST->getPointeeType().split();
3187 mangleQualifiers(Quals, DAST);
3188 mangleType(T: QualType(Ty, 0));
3189 } else {
3190 mangleQualifiers(Quals: quals);
3191
3192 // Recurse: even if the qualified type isn't yet substitutable,
3193 // the unqualified type might be.
3194 mangleType(T: QualType(ty, 0));
3195 }
3196 } else {
3197 switch (ty->getTypeClass()) {
3198#define ABSTRACT_TYPE(CLASS, PARENT)
3199#define NON_CANONICAL_TYPE(CLASS, PARENT) \
3200 case Type::CLASS: \
3201 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3202 return;
3203#define TYPE(CLASS, PARENT) \
3204 case Type::CLASS: \
3205 mangleType(static_cast<const CLASS##Type*>(ty)); \
3206 break;
3207#include "clang/AST/TypeNodes.inc"
3208 }
3209 }
3210
3211 // Add the substitution.
3212 if (isSubstitutable)
3213 addSubstitution(T);
3214}
3215
3216void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl *Record,
3217 bool SuppressSubstitution) {
3218 if (mangleSubstitution(ND: Record))
3219 return;
3220 mangleName(GD: Record);
3221 if (SuppressSubstitution)
3222 return;
3223 addSubstitution(ND: Record);
3224}
3225
3226void CXXNameMangler::mangleType(const BuiltinType *T) {
3227 // <type> ::= <builtin-type>
3228 // <builtin-type> ::= v # void
3229 // ::= w # wchar_t
3230 // ::= b # bool
3231 // ::= c # char
3232 // ::= a # signed char
3233 // ::= h # unsigned char
3234 // ::= s # short
3235 // ::= t # unsigned short
3236 // ::= i # int
3237 // ::= j # unsigned int
3238 // ::= l # long
3239 // ::= m # unsigned long
3240 // ::= x # long long, __int64
3241 // ::= y # unsigned long long, __int64
3242 // ::= n # __int128
3243 // ::= o # unsigned __int128
3244 // ::= f # float
3245 // ::= d # double
3246 // ::= e # long double, __float80
3247 // ::= g # __float128
3248 // ::= g # __ibm128
3249 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3250 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3251 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3252 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3253 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point
3254 // type _FloatN (N bits);
3255 // ::= Di # char32_t
3256 // ::= Ds # char16_t
3257 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3258 // ::= Dm # std::meta::info (i.e., decltype(^^int))
3259 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3260 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3261 // ::= u <source-name> # vendor extended type
3262 //
3263 // <fixed-point-size>
3264 // ::= s # short
3265 // ::= t # unsigned short
3266 // ::= i # plain
3267 // ::= j # unsigned
3268 // ::= l # long
3269 // ::= m # unsigned long
3270 std::string type_name;
3271 // Normalize integer types as vendor extended types:
3272 // u<length>i<type size>
3273 // u<length>u<type size>
3274 if (NormalizeIntegers && T->isInteger()) {
3275 if (T->isSignedInteger()) {
3276 switch (getASTContext().getTypeSize(T)) {
3277 case 8:
3278 // Pick a representative for each integer size in the substitution
3279 // dictionary. (Its actual defined size is not relevant.)
3280 if (mangleSubstitution(Ptr: BuiltinType::SChar))
3281 break;
3282 Out << "u2i8";
3283 addSubstitution(Ptr: BuiltinType::SChar);
3284 break;
3285 case 16:
3286 if (mangleSubstitution(Ptr: BuiltinType::Short))
3287 break;
3288 Out << "u3i16";
3289 addSubstitution(Ptr: BuiltinType::Short);
3290 break;
3291 case 32:
3292 if (mangleSubstitution(Ptr: BuiltinType::Int))
3293 break;
3294 Out << "u3i32";
3295 addSubstitution(Ptr: BuiltinType::Int);
3296 break;
3297 case 64:
3298 if (mangleSubstitution(Ptr: BuiltinType::Long))
3299 break;
3300 Out << "u3i64";
3301 addSubstitution(Ptr: BuiltinType::Long);
3302 break;
3303 case 128:
3304 if (mangleSubstitution(Ptr: BuiltinType::Int128))
3305 break;
3306 Out << "u4i128";
3307 addSubstitution(Ptr: BuiltinType::Int128);
3308 break;
3309 default:
3310 llvm_unreachable("Unknown integer size for normalization");
3311 }
3312 } else {
3313 switch (getASTContext().getTypeSize(T)) {
3314 case 8:
3315 if (mangleSubstitution(Ptr: BuiltinType::UChar))
3316 break;
3317 Out << "u2u8";
3318 addSubstitution(Ptr: BuiltinType::UChar);
3319 break;
3320 case 16:
3321 if (mangleSubstitution(Ptr: BuiltinType::UShort))
3322 break;
3323 Out << "u3u16";
3324 addSubstitution(Ptr: BuiltinType::UShort);
3325 break;
3326 case 32:
3327 if (mangleSubstitution(Ptr: BuiltinType::UInt))
3328 break;
3329 Out << "u3u32";
3330 addSubstitution(Ptr: BuiltinType::UInt);
3331 break;
3332 case 64:
3333 if (mangleSubstitution(Ptr: BuiltinType::ULong))
3334 break;
3335 Out << "u3u64";
3336 addSubstitution(Ptr: BuiltinType::ULong);
3337 break;
3338 case 128:
3339 if (mangleSubstitution(Ptr: BuiltinType::UInt128))
3340 break;
3341 Out << "u4u128";
3342 addSubstitution(Ptr: BuiltinType::UInt128);
3343 break;
3344 default:
3345 llvm_unreachable("Unknown integer size for normalization");
3346 }
3347 }
3348 return;
3349 }
3350 switch (T->getKind()) {
3351 case BuiltinType::Void:
3352 Out << 'v';
3353 break;
3354 case BuiltinType::Bool:
3355 Out << 'b';
3356 break;
3357 case BuiltinType::Char_U:
3358 case BuiltinType::Char_S:
3359 Out << 'c';
3360 break;
3361 case BuiltinType::UChar:
3362 Out << 'h';
3363 break;
3364 case BuiltinType::UShort:
3365 Out << 't';
3366 break;
3367 case BuiltinType::UInt:
3368 Out << 'j';
3369 break;
3370 case BuiltinType::ULong:
3371 Out << 'm';
3372 break;
3373 case BuiltinType::ULongLong:
3374 Out << 'y';
3375 break;
3376 case BuiltinType::UInt128:
3377 Out << 'o';
3378 break;
3379 case BuiltinType::SChar:
3380 Out << 'a';
3381 break;
3382 case BuiltinType::WChar_S:
3383 case BuiltinType::WChar_U:
3384 Out << 'w';
3385 break;
3386 case BuiltinType::Char8:
3387 Out << "Du";
3388 break;
3389 case BuiltinType::Char16:
3390 Out << "Ds";
3391 break;
3392 case BuiltinType::Char32:
3393 Out << "Di";
3394 break;
3395 case BuiltinType::Short:
3396 Out << 's';
3397 break;
3398 case BuiltinType::Int:
3399 Out << 'i';
3400 break;
3401 case BuiltinType::Long:
3402 Out << 'l';
3403 break;
3404 case BuiltinType::LongLong:
3405 Out << 'x';
3406 break;
3407 case BuiltinType::Int128:
3408 Out << 'n';
3409 break;
3410 case BuiltinType::Float16:
3411 Out << "DF16_";
3412 break;
3413 case BuiltinType::ShortAccum:
3414 Out << "DAs";
3415 break;
3416 case BuiltinType::Accum:
3417 Out << "DAi";
3418 break;
3419 case BuiltinType::LongAccum:
3420 Out << "DAl";
3421 break;
3422 case BuiltinType::UShortAccum:
3423 Out << "DAt";
3424 break;
3425 case BuiltinType::UAccum:
3426 Out << "DAj";
3427 break;
3428 case BuiltinType::ULongAccum:
3429 Out << "DAm";
3430 break;
3431 case BuiltinType::ShortFract:
3432 Out << "DRs";
3433 break;
3434 case BuiltinType::Fract:
3435 Out << "DRi";
3436 break;
3437 case BuiltinType::LongFract:
3438 Out << "DRl";
3439 break;
3440 case BuiltinType::UShortFract:
3441 Out << "DRt";
3442 break;
3443 case BuiltinType::UFract:
3444 Out << "DRj";
3445 break;
3446 case BuiltinType::ULongFract:
3447 Out << "DRm";
3448 break;
3449 case BuiltinType::SatShortAccum:
3450 Out << "DSDAs";
3451 break;
3452 case BuiltinType::SatAccum:
3453 Out << "DSDAi";
3454 break;
3455 case BuiltinType::SatLongAccum:
3456 Out << "DSDAl";
3457 break;
3458 case BuiltinType::SatUShortAccum:
3459 Out << "DSDAt";
3460 break;
3461 case BuiltinType::SatUAccum:
3462 Out << "DSDAj";
3463 break;
3464 case BuiltinType::SatULongAccum:
3465 Out << "DSDAm";
3466 break;
3467 case BuiltinType::SatShortFract:
3468 Out << "DSDRs";
3469 break;
3470 case BuiltinType::SatFract:
3471 Out << "DSDRi";
3472 break;
3473 case BuiltinType::SatLongFract:
3474 Out << "DSDRl";
3475 break;
3476 case BuiltinType::SatUShortFract:
3477 Out << "DSDRt";
3478 break;
3479 case BuiltinType::SatUFract:
3480 Out << "DSDRj";
3481 break;
3482 case BuiltinType::SatULongFract:
3483 Out << "DSDRm";
3484 break;
3485 case BuiltinType::Half:
3486 Out << "Dh";
3487 break;
3488 case BuiltinType::Float:
3489 Out << 'f';
3490 break;
3491 case BuiltinType::Double:
3492 Out << 'd';
3493 break;
3494 case BuiltinType::LongDouble: {
3495 const TargetInfo *TI =
3496 getASTContext().getLangOpts().OpenMP &&
3497 getASTContext().getLangOpts().OpenMPIsTargetDevice
3498 ? getASTContext().getAuxTargetInfo()
3499 : &getASTContext().getTargetInfo();
3500 Out << TI->getLongDoubleMangling();
3501 break;
3502 }
3503 case BuiltinType::Float128: {
3504 const TargetInfo *TI =
3505 getASTContext().getLangOpts().OpenMP &&
3506 getASTContext().getLangOpts().OpenMPIsTargetDevice
3507 ? getASTContext().getAuxTargetInfo()
3508 : &getASTContext().getTargetInfo();
3509 Out << TI->getFloat128Mangling();
3510 break;
3511 }
3512 case BuiltinType::BFloat16: {
3513 const TargetInfo *TI =
3514 ((getASTContext().getLangOpts().OpenMP &&
3515 getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3516 getASTContext().getLangOpts().SYCLIsDevice)
3517 ? getASTContext().getAuxTargetInfo()
3518 : &getASTContext().getTargetInfo();
3519 Out << TI->getBFloat16Mangling();
3520 break;
3521 }
3522 case BuiltinType::Ibm128: {
3523 const TargetInfo *TI = &getASTContext().getTargetInfo();
3524 Out << TI->getIbm128Mangling();
3525 break;
3526 }
3527 case BuiltinType::MetaInfo:
3528 // https://github.com/itanium-cxx-abi/cxx-abi/issues/208
3529 Out << "Dm";
3530 break;
3531 case BuiltinType::NullPtr:
3532 Out << "Dn";
3533 break;
3534
3535#define BUILTIN_TYPE(Id, SingletonId)
3536#define PLACEHOLDER_TYPE(Id, SingletonId) \
3537 case BuiltinType::Id:
3538#include "clang/AST/BuiltinTypes.def"
3539 case BuiltinType::Dependent:
3540 if (!NullOut)
3541 llvm_unreachable("mangling a placeholder type");
3542 break;
3543 case BuiltinType::ObjCId:
3544 Out << "11objc_object";
3545 break;
3546 case BuiltinType::ObjCClass:
3547 Out << "10objc_class";
3548 break;
3549 case BuiltinType::ObjCSel:
3550 Out << "13objc_selector";
3551 break;
3552#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3553 case BuiltinType::Id: \
3554 type_name = "ocl_" #ImgType "_" #Suffix; \
3555 Out << type_name.size() << type_name; \
3556 break;
3557#include "clang/Basic/OpenCLImageTypes.def"
3558 case BuiltinType::OCLSampler:
3559 Out << "11ocl_sampler";
3560 break;
3561 case BuiltinType::OCLEvent:
3562 Out << "9ocl_event";
3563 break;
3564 case BuiltinType::OCLClkEvent:
3565 Out << "12ocl_clkevent";
3566 break;
3567 case BuiltinType::OCLQueue:
3568 Out << "9ocl_queue";
3569 break;
3570 case BuiltinType::OCLReserveID:
3571 Out << "13ocl_reserveid";
3572 break;
3573#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3574 case BuiltinType::Id: \
3575 type_name = "ocl_" #ExtType; \
3576 Out << type_name.size() << type_name; \
3577 break;
3578#include "clang/Basic/OpenCLExtensionTypes.def"
3579 // The SVE types are effectively target-specific. The mangling scheme
3580 // is defined in the appendices to the Procedure Call Standard for the
3581 // Arm Architecture.
3582#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
3583 case BuiltinType::Id: \
3584 if (T->getKind() == BuiltinType::SveBFloat16 && \
3585 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3586 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3587 mangleVendorType("__SVBFloat16_t"); \
3588 } else { \
3589 type_name = #MangledName; \
3590 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3591 } \
3592 break;
3593#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
3594 case BuiltinType::Id: \
3595 type_name = #MangledName; \
3596 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3597 break;
3598#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
3599 case BuiltinType::Id: \
3600 type_name = #MangledName; \
3601 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3602 break;
3603#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
3604 case BuiltinType::Id: \
3605 type_name = #MangledName; \
3606 Out << (type_name == #Name ? "u" : "") << type_name.size() << type_name; \
3607 break;
3608#include "clang/Basic/AArch64ACLETypes.def"
3609#define PPC_VECTOR_TYPE(Name, Id, Size) \
3610 case BuiltinType::Id: \
3611 mangleVendorType(#Name); \
3612 break;
3613#include "clang/Basic/PPCTypes.def"
3614 // TODO: Check the mangling scheme for RISC-V V.
3615#define RVV_TYPE(Name, Id, SingletonId) \
3616 case BuiltinType::Id: \
3617 mangleVendorType(Name); \
3618 break;
3619#include "clang/Basic/RISCVVTypes.def"
3620#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3621 case BuiltinType::Id: \
3622 mangleVendorType(MangledName); \
3623 break;
3624#include "clang/Basic/WebAssemblyReferenceTypes.def"
3625#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3626 case BuiltinType::Id: \
3627 mangleVendorType(Name); \
3628 break;
3629#include "clang/Basic/AMDGPUTypes.def"
3630#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3631 case BuiltinType::Id: \
3632 mangleVendorType(#Name); \
3633 break;
3634#include "clang/Basic/HLSLIntangibleTypes.def"
3635#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3636 case BuiltinType::Id: \
3637 mangleVendorType(#Name); \
3638 break;
3639#include "clang/Basic/HLSLPackedTypes.def"
3640#define SPIRV_TYPE(Name, Id, SingletonId) \
3641 case BuiltinType::Id: \
3642 mangleVendorType(Name); \
3643 break;
3644#include "clang/Basic/SPIRVTypes.def"
3645 }
3646}
3647
3648StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3649 switch (CC) {
3650 case CC_C:
3651 return "";
3652
3653 case CC_X86VectorCall:
3654 case CC_X86Pascal:
3655 case CC_X86RegCall:
3656 case CC_AAPCS:
3657 case CC_AAPCS_VFP:
3658 case CC_AArch64VectorCall:
3659 case CC_AArch64SVEPCS:
3660 case CC_IntelOclBicc:
3661 case CC_DeviceKernel:
3662 case CC_PreserveMost:
3663 case CC_PreserveAll:
3664 case CC_M68kRTD:
3665 case CC_PreserveNone:
3666 case CC_RISCVVectorCall:
3667#define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN:
3668 CC_VLS_CASE(32)
3669 CC_VLS_CASE(64)
3670 CC_VLS_CASE(128)
3671 CC_VLS_CASE(256)
3672 CC_VLS_CASE(512)
3673 CC_VLS_CASE(1024)
3674 CC_VLS_CASE(2048)
3675 CC_VLS_CASE(4096)
3676 CC_VLS_CASE(8192)
3677 CC_VLS_CASE(16384)
3678 CC_VLS_CASE(32768)
3679 CC_VLS_CASE(65536)
3680#undef CC_VLS_CASE
3681 // FIXME: we should be mangling all of the above.
3682 return "";
3683
3684 case CC_X86ThisCall:
3685 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3686 // used explicitly. At this point, we don't have that much information in
3687 // the AST, since clang tends to bake the convention into the canonical
3688 // function type. thiscall only rarely used explicitly, so don't mangle it
3689 // for now.
3690 return "";
3691
3692 case CC_X86StdCall:
3693 return "stdcall";
3694 case CC_X86FastCall:
3695 return "fastcall";
3696 case CC_X86_64SysV:
3697 return "sysv_abi";
3698 case CC_Win64:
3699 return "ms_abi";
3700 case CC_Swift:
3701 return "swiftcall";
3702 case CC_SwiftAsync:
3703 return "swiftasynccall";
3704 }
3705 llvm_unreachable("bad calling convention");
3706}
3707
3708void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3709 // Fast path.
3710 if (T->getExtInfo() == FunctionType::ExtInfo())
3711 return;
3712
3713 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3714 // This will get more complicated in the future if we mangle other
3715 // things here; but for now, since we mangle ns_returns_retained as
3716 // a qualifier on the result type, we can get away with this:
3717 StringRef CCQualifier = getCallingConvQualifierName(CC: T->getExtInfo().getCC());
3718 if (!CCQualifier.empty())
3719 mangleVendorQualifier(name: CCQualifier);
3720
3721 // FIXME: regparm
3722 // FIXME: noreturn
3723}
3724
3725enum class AAPCSBitmaskSME : unsigned {
3726 ArmStreamingBit = 1 << 0,
3727 ArmStreamingCompatibleBit = 1 << 1,
3728 ArmAgnosticSMEZAStateBit = 1 << 2,
3729 ZA_Shift = 3,
3730 ZT0_Shift = 6,
3731 NoState = 0b000,
3732 ArmIn = 0b001,
3733 ArmOut = 0b010,
3734 ArmInOut = 0b011,
3735 ArmPreserves = 0b100,
3736 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ArmPreserves << ZT0_Shift)
3737};
3738
3739static AAPCSBitmaskSME encodeAAPCSZAState(unsigned SMEAttrs) {
3740 switch (SMEAttrs) {
3741 case FunctionType::ARM_None:
3742 return AAPCSBitmaskSME::NoState;
3743 case FunctionType::ARM_In:
3744 return AAPCSBitmaskSME::ArmIn;
3745 case FunctionType::ARM_Out:
3746 return AAPCSBitmaskSME::ArmOut;
3747 case FunctionType::ARM_InOut:
3748 return AAPCSBitmaskSME::ArmInOut;
3749 case FunctionType::ARM_Preserves:
3750 return AAPCSBitmaskSME::ArmPreserves;
3751 default:
3752 llvm_unreachable("Unrecognised SME attribute");
3753 }
3754}
3755
3756// The mangling scheme for function types which have SME attributes is
3757// implemented as a "pseudo" template:
3758//
3759// '__SME_ATTRS<<normal_function_type>, <sme_state>>'
3760//
3761// Combining the function type with a bitmask representing the streaming and ZA
3762// properties of the function's interface.
3763//
3764// Mangling of SME keywords is described in more detail in the AArch64 ACLE:
3765// https://github.com/ARM-software/acle/blob/main/main/acle.md#c-mangling-of-sme-keywords
3766//
3767void CXXNameMangler::mangleSMEAttrs(unsigned SMEAttrs) {
3768 if (!SMEAttrs)
3769 return;
3770
3771 AAPCSBitmaskSME Bitmask = AAPCSBitmaskSME(0);
3772 if (SMEAttrs & FunctionType::SME_PStateSMEnabledMask)
3773 Bitmask |= AAPCSBitmaskSME::ArmStreamingBit;
3774 else if (SMEAttrs & FunctionType::SME_PStateSMCompatibleMask)
3775 Bitmask |= AAPCSBitmaskSME::ArmStreamingCompatibleBit;
3776
3777 if (SMEAttrs & FunctionType::SME_AgnosticZAStateMask)
3778 Bitmask |= AAPCSBitmaskSME::ArmAgnosticSMEZAStateBit;
3779 else {
3780 Bitmask |= encodeAAPCSZAState(SMEAttrs: FunctionType::getArmZAState(AttrBits: SMEAttrs))
3781 << AAPCSBitmaskSME::ZA_Shift;
3782
3783 Bitmask |= encodeAAPCSZAState(SMEAttrs: FunctionType::getArmZT0State(AttrBits: SMEAttrs))
3784 << AAPCSBitmaskSME::ZT0_Shift;
3785 }
3786
3787 Out << "Lj" << static_cast<unsigned>(Bitmask) << "EE";
3788}
3789
3790void
3791CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3792 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3793
3794 // Note that these are *not* substitution candidates. Demanglers might
3795 // have trouble with this if the parameter type is fully substituted.
3796
3797 switch (PI.getABI()) {
3798 case ParameterABI::Ordinary:
3799 break;
3800
3801 // HLSL parameter mangling.
3802 case ParameterABI::HLSLOut:
3803 case ParameterABI::HLSLInOut:
3804 mangleVendorQualifier(name: getParameterABISpelling(kind: PI.getABI()));
3805 break;
3806
3807 // All of these start with "swift", so they come before "ns_consumed".
3808 case ParameterABI::SwiftContext:
3809 case ParameterABI::SwiftAsyncContext:
3810 case ParameterABI::SwiftErrorResult:
3811 case ParameterABI::SwiftIndirectResult:
3812 mangleVendorQualifier(name: getParameterABISpelling(kind: PI.getABI()));
3813 break;
3814 }
3815
3816 if (PI.isConsumed())
3817 mangleVendorQualifier(name: "ns_consumed");
3818
3819 if (PI.isNoEscape())
3820 mangleVendorQualifier(name: "noescape");
3821}
3822
3823// <type> ::= <function-type>
3824// <function-type> ::= [<CV-qualifiers>] F [Y]
3825// <bare-function-type> [<ref-qualifier>] E
3826void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3827 unsigned SMEAttrs = T->getAArch64SMEAttributes();
3828
3829 if (SMEAttrs)
3830 Out << "11__SME_ATTRSI";
3831
3832 mangleExtFunctionInfo(T);
3833
3834 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3835 // e.g. "const" in "int (A::*)() const".
3836 mangleQualifiers(Quals: T->getMethodQuals());
3837
3838 // Mangle instantiation-dependent exception-specification, if present,
3839 // per cxx-abi-dev proposal on 2016-10-11.
3840 if (T->hasInstantiationDependentExceptionSpec()) {
3841 if (isComputedNoexcept(ESpecType: T->getExceptionSpecType())) {
3842 Out << "DO";
3843 mangleExpression(E: T->getNoexceptExpr());
3844 Out << "E";
3845 } else {
3846 assert(T->getExceptionSpecType() == EST_Dynamic);
3847 Out << "Dw";
3848 for (auto ExceptTy : T->exceptions())
3849 mangleType(T: ExceptTy);
3850 Out << "E";
3851 }
3852 } else if (T->isNothrow()) {
3853 Out << "Do";
3854 }
3855
3856 Out << 'F';
3857
3858 // FIXME: We don't have enough information in the AST to produce the 'Y'
3859 // encoding for extern "C" function types.
3860 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3861
3862 // Mangle the ref-qualifier, if present.
3863 mangleRefQualifier(RefQualifier: T->getRefQualifier());
3864
3865 Out << 'E';
3866
3867 mangleSMEAttrs(SMEAttrs);
3868}
3869
3870void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3871 // Function types without prototypes can arise when mangling a function type
3872 // within an overloadable function in C. We mangle these as the absence of any
3873 // parameter types (not even an empty parameter list).
3874 Out << 'F';
3875
3876 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3877
3878 FunctionTypeDepth.enterFunctionDeclSuffix();
3879 mangleType(T: T->getReturnType());
3880 FunctionTypeDepth.leaveFunctionDeclSuffix();
3881
3882 FunctionTypeDepth.pop(Saved: saved);
3883 Out << 'E';
3884}
3885
3886void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3887 bool MangleReturnType,
3888 const FunctionDecl *FD) {
3889 // Record that we're in a function type. See mangleFunctionParam
3890 // for details on what we're trying to achieve here.
3891 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3892
3893 // <bare-function-type> ::= <signature type>+
3894 if (MangleReturnType) {
3895 FunctionTypeDepth.enterFunctionDeclSuffix();
3896
3897 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3898 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3899 mangleVendorQualifier(name: "ns_returns_retained");
3900
3901 // Mangle the return type without any direct ARC ownership qualifiers.
3902 QualType ReturnTy = Proto->getReturnType();
3903 if (ReturnTy.getObjCLifetime()) {
3904 auto SplitReturnTy = ReturnTy.split();
3905 SplitReturnTy.Quals.removeObjCLifetime();
3906 ReturnTy = getASTContext().getQualifiedType(split: SplitReturnTy);
3907 }
3908 mangleType(T: ReturnTy);
3909
3910 FunctionTypeDepth.leaveFunctionDeclSuffix();
3911 }
3912
3913 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3914 // <builtin-type> ::= v # void
3915 Out << 'v';
3916 } else {
3917 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3918 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3919 // Mangle extended parameter info as order-sensitive qualifiers here.
3920 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3921 mangleExtParameterInfo(PI: Proto->getExtParameterInfo(I));
3922 }
3923
3924 // Mangle the type.
3925 QualType ParamTy = Proto->getParamType(i: I);
3926 mangleType(T: Context.getASTContext().getSignatureParameterType(T: ParamTy));
3927
3928 if (FD) {
3929 if (auto *Attr = FD->getParamDecl(i: I)->getAttr<PassObjectSizeAttr>()) {
3930 // Attr can only take 1 character, so we can hardcode the length
3931 // below.
3932 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3933 if (Attr->isDynamic())
3934 Out << "U25pass_dynamic_object_size" << Attr->getType();
3935 else
3936 Out << "U17pass_object_size" << Attr->getType();
3937 }
3938 }
3939 }
3940
3941 // <builtin-type> ::= z # ellipsis
3942 if (Proto->isVariadic())
3943 Out << 'z';
3944 }
3945
3946 if (FD) {
3947 FunctionTypeDepth.enterFunctionDeclSuffix();
3948 mangleRequiresClause(RequiresClause: FD->getTrailingRequiresClause().ConstraintExpr);
3949 }
3950
3951 FunctionTypeDepth.pop(Saved: saved);
3952}
3953
3954// <type> ::= <class-enum-type>
3955// <class-enum-type> ::= <name>
3956void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3957 mangleName(GD: T->getDecl());
3958}
3959
3960// <type> ::= <class-enum-type>
3961// <class-enum-type> ::= <name>
3962void CXXNameMangler::mangleType(const EnumType *T) {
3963 mangleType(static_cast<const TagType*>(T));
3964}
3965void CXXNameMangler::mangleType(const RecordType *T) {
3966 mangleType(static_cast<const TagType*>(T));
3967}
3968void CXXNameMangler::mangleType(const TagType *T) {
3969 mangleName(GD: T->getDecl()->getDefinitionOrSelf());
3970}
3971
3972// <type> ::= <array-type>
3973// <array-type> ::= A <positive dimension number> _ <element type>
3974// ::= A [<dimension expression>] _ <element type>
3975void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3976 Out << 'A' << T->getSize() << '_';
3977 mangleType(T: T->getElementType());
3978}
3979void CXXNameMangler::mangleType(const VariableArrayType *T) {
3980 Out << 'A';
3981 // decayed vla types (size 0) will just be skipped.
3982 if (T->getSizeExpr())
3983 mangleExpression(E: T->getSizeExpr());
3984 Out << '_';
3985 mangleType(T: T->getElementType());
3986}
3987void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3988 Out << 'A';
3989 // A DependentSizedArrayType might not have size expression as below
3990 //
3991 // template<int ...N> int arr[] = {N...};
3992 if (T->getSizeExpr())
3993 mangleExpression(E: T->getSizeExpr());
3994 Out << '_';
3995 mangleType(T: T->getElementType());
3996}
3997void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3998 Out << "A_";
3999 mangleType(T: T->getElementType());
4000}
4001
4002// <type> ::= <pointer-to-member-type>
4003// <pointer-to-member-type> ::= M <class type> <member type>
4004void CXXNameMangler::mangleType(const MemberPointerType *T) {
4005 Out << 'M';
4006 if (auto *RD = T->getMostRecentCXXRecordDecl())
4007 mangleCXXRecordDecl(Record: RD);
4008 else
4009 mangleType(T: QualType(T->getQualifier().getAsType(), 0));
4010 QualType PointeeType = T->getPointeeType();
4011 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Val&: PointeeType)) {
4012 mangleType(T: FPT);
4013
4014 // Itanium C++ ABI 5.1.8:
4015 //
4016 // The type of a non-static member function is considered to be different,
4017 // for the purposes of substitution, from the type of a namespace-scope or
4018 // static member function whose type appears similar. The types of two
4019 // non-static member functions are considered to be different, for the
4020 // purposes of substitution, if the functions are members of different
4021 // classes. In other words, for the purposes of substitution, the class of
4022 // which the function is a member is considered part of the type of
4023 // function.
4024
4025 // Given that we already substitute member function pointers as a
4026 // whole, the net effect of this rule is just to unconditionally
4027 // suppress substitution on the function type in a member pointer.
4028 // We increment the SeqID here to emulate adding an entry to the
4029 // substitution table.
4030 ++SeqID;
4031 } else
4032 mangleType(T: PointeeType);
4033}
4034
4035// <type> ::= <template-param>
4036void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
4037 mangleTemplateParameter(Depth: T->getDepth(), Index: T->getIndex());
4038}
4039
4040// <type> ::= <template-param>
4041void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
4042 // FIXME: not clear how to mangle this!
4043 // template <class T...> class A {
4044 // template <class U...> void foo(T(*)(U) x...);
4045 // };
4046 Out << "_SUBSTPACK_";
4047}
4048
4049void CXXNameMangler::mangleType(const SubstBuiltinTemplatePackType *T) {
4050 // FIXME: not clear how to mangle this!
4051 // template <class T...> class A {
4052 // template <class U...> void foo(__builtin_dedup_pack<T...>(*)(U) x...);
4053 // };
4054 Out << "_SUBSTBUILTINPACK_";
4055}
4056
4057// <type> ::= P <type> # pointer-to
4058void CXXNameMangler::mangleType(const PointerType *T) {
4059 Out << 'P';
4060 mangleType(T: T->getPointeeType());
4061}
4062void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
4063 Out << 'P';
4064 mangleType(T: T->getPointeeType());
4065}
4066
4067// <type> ::= R <type> # reference-to
4068void CXXNameMangler::mangleType(const LValueReferenceType *T) {
4069 Out << 'R';
4070 mangleType(T: T->getPointeeType());
4071}
4072
4073// <type> ::= O <type> # rvalue reference-to (C++0x)
4074void CXXNameMangler::mangleType(const RValueReferenceType *T) {
4075 Out << 'O';
4076 mangleType(T: T->getPointeeType());
4077}
4078
4079// <type> ::= C <type> # complex pair (C 2000)
4080void CXXNameMangler::mangleType(const ComplexType *T) {
4081 Out << 'C';
4082 mangleType(T: T->getElementType());
4083}
4084
4085// ARM's ABI for Neon vector types specifies that they should be mangled as
4086// if they are structs (to match ARM's initial implementation). The
4087// vector type must be one of the special types predefined by ARM.
4088void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
4089 QualType EltType = T->getElementType();
4090 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
4091 const char *EltName = nullptr;
4092 if (T->getVectorKind() == VectorKind::NeonPoly) {
4093 switch (cast<BuiltinType>(Val&: EltType)->getKind()) {
4094 case BuiltinType::SChar:
4095 case BuiltinType::UChar:
4096 EltName = "poly8_t";
4097 break;
4098 case BuiltinType::Short:
4099 case BuiltinType::UShort:
4100 EltName = "poly16_t";
4101 break;
4102 case BuiltinType::LongLong:
4103 case BuiltinType::ULongLong:
4104 EltName = "poly64_t";
4105 break;
4106 default: llvm_unreachable("unexpected Neon polynomial vector element type");
4107 }
4108 } else {
4109 switch (cast<BuiltinType>(Val&: EltType)->getKind()) {
4110 case BuiltinType::SChar: EltName = "int8_t"; break;
4111 case BuiltinType::UChar: EltName = "uint8_t"; break;
4112 case BuiltinType::Short: EltName = "int16_t"; break;
4113 case BuiltinType::UShort: EltName = "uint16_t"; break;
4114 case BuiltinType::Int: EltName = "int32_t"; break;
4115 case BuiltinType::UInt: EltName = "uint32_t"; break;
4116 case BuiltinType::LongLong: EltName = "int64_t"; break;
4117 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
4118 case BuiltinType::Double: EltName = "float64_t"; break;
4119 case BuiltinType::Float: EltName = "float32_t"; break;
4120 case BuiltinType::Half: EltName = "float16_t"; break;
4121 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
4122 case BuiltinType::MFloat8:
4123 EltName = "mfloat8_t";
4124 break;
4125 default:
4126 llvm_unreachable("unexpected Neon vector element type");
4127 }
4128 }
4129 const char *BaseName = nullptr;
4130 unsigned BitSize = (T->getNumElements() *
4131 getASTContext().getTypeSize(T: EltType));
4132 if (BitSize == 64)
4133 BaseName = "__simd64_";
4134 else {
4135 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
4136 BaseName = "__simd128_";
4137 }
4138 Out << strlen(s: BaseName) + strlen(s: EltName);
4139 Out << BaseName << EltName;
4140}
4141
4142void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
4143 DiagnosticsEngine &Diags = Context.getDiags();
4144 Diags.Report(Loc: T->getAttributeLoc(), DiagID: diag::err_unsupported_itanium_mangling)
4145 << UnsupportedItaniumManglingKind::DependentNeonVector;
4146}
4147
4148static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
4149 switch (EltType->getKind()) {
4150 case BuiltinType::SChar:
4151 return "Int8";
4152 case BuiltinType::Short:
4153 return "Int16";
4154 case BuiltinType::Int:
4155 return "Int32";
4156 case BuiltinType::Long:
4157 case BuiltinType::LongLong:
4158 return "Int64";
4159 case BuiltinType::UChar:
4160 return "Uint8";
4161 case BuiltinType::UShort:
4162 return "Uint16";
4163 case BuiltinType::UInt:
4164 return "Uint32";
4165 case BuiltinType::ULong:
4166 case BuiltinType::ULongLong:
4167 return "Uint64";
4168 case BuiltinType::Half:
4169 return "Float16";
4170 case BuiltinType::Float:
4171 return "Float32";
4172 case BuiltinType::Double:
4173 return "Float64";
4174 case BuiltinType::BFloat16:
4175 return "Bfloat16";
4176 case BuiltinType::MFloat8:
4177 return "Mfloat8";
4178 default:
4179 llvm_unreachable("Unexpected vector element base type");
4180 }
4181}
4182
4183// AArch64's ABI for Neon vector types specifies that they should be mangled as
4184// the equivalent internal name. The vector type must be one of the special
4185// types predefined by ARM.
4186void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
4187 QualType EltType = T->getElementType();
4188 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
4189 unsigned BitSize =
4190 (T->getNumElements() * getASTContext().getTypeSize(T: EltType));
4191 (void)BitSize; // Silence warning.
4192
4193 assert((BitSize == 64 || BitSize == 128) &&
4194 "Neon vector type not 64 or 128 bits");
4195
4196 StringRef EltName;
4197 if (T->getVectorKind() == VectorKind::NeonPoly) {
4198 switch (cast<BuiltinType>(Val&: EltType)->getKind()) {
4199 case BuiltinType::UChar:
4200 EltName = "Poly8";
4201 break;
4202 case BuiltinType::UShort:
4203 EltName = "Poly16";
4204 break;
4205 case BuiltinType::ULong:
4206 case BuiltinType::ULongLong:
4207 EltName = "Poly64";
4208 break;
4209 default:
4210 llvm_unreachable("unexpected Neon polynomial vector element type");
4211 }
4212 } else
4213 EltName = mangleAArch64VectorBase(EltType: cast<BuiltinType>(Val&: EltType));
4214
4215 std::string TypeName =
4216 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
4217 Out << TypeName.length() << TypeName;
4218}
4219void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
4220 DiagnosticsEngine &Diags = Context.getDiags();
4221 Diags.Report(Loc: T->getAttributeLoc(), DiagID: diag::err_unsupported_itanium_mangling)
4222 << UnsupportedItaniumManglingKind::DependentNeonVector;
4223}
4224
4225// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
4226// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
4227// type as the sizeless variants.
4228//
4229// The mangling scheme for VLS types is implemented as a "pseudo" template:
4230//
4231// '__SVE_VLS<<type>, <vector length>>'
4232//
4233// Combining the existing SVE type and a specific vector length (in bits).
4234// For example:
4235//
4236// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
4237//
4238// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
4239//
4240// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
4241//
4242// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
4243//
4244// The latest ACLE specification (00bet5) does not contain details of this
4245// mangling scheme, it will be specified in the next revision. The mangling
4246// scheme is otherwise defined in the appendices to the Procedure Call Standard
4247// for the Arm Architecture, see
4248// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
4249void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
4250 assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
4251 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
4252 "expected fixed-length SVE vector!");
4253
4254 QualType EltType = T->getElementType();
4255 assert(EltType->isBuiltinType() &&
4256 "expected builtin type for fixed-length SVE vector!");
4257
4258 StringRef TypeName;
4259 switch (cast<BuiltinType>(Val&: EltType)->getKind()) {
4260 case BuiltinType::SChar:
4261 TypeName = "__SVInt8_t";
4262 break;
4263 case BuiltinType::UChar: {
4264 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
4265 TypeName = "__SVUint8_t";
4266 else
4267 TypeName = "__SVBool_t";
4268 break;
4269 }
4270 case BuiltinType::Short:
4271 TypeName = "__SVInt16_t";
4272 break;
4273 case BuiltinType::UShort:
4274 TypeName = "__SVUint16_t";
4275 break;
4276 case BuiltinType::Int:
4277 TypeName = "__SVInt32_t";
4278 break;
4279 case BuiltinType::UInt:
4280 TypeName = "__SVUint32_t";
4281 break;
4282 case BuiltinType::Long:
4283 TypeName = "__SVInt64_t";
4284 break;
4285 case BuiltinType::ULong:
4286 TypeName = "__SVUint64_t";
4287 break;
4288 case BuiltinType::Half:
4289 TypeName = "__SVFloat16_t";
4290 break;
4291 case BuiltinType::Float:
4292 TypeName = "__SVFloat32_t";
4293 break;
4294 case BuiltinType::Double:
4295 TypeName = "__SVFloat64_t";
4296 break;
4297 case BuiltinType::BFloat16:
4298 TypeName = "__SVBfloat16_t";
4299 break;
4300 default:
4301 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4302 }
4303
4304 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4305
4306 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4307 VecSizeInBits *= 8;
4308
4309 Out << "9__SVE_VLSI";
4310 mangleVendorType(name: TypeName);
4311 Out << "Lj" << VecSizeInBits << "EE";
4312}
4313
4314void CXXNameMangler::mangleAArch64FixedSveVectorType(
4315 const DependentVectorType *T) {
4316 DiagnosticsEngine &Diags = Context.getDiags();
4317 Diags.Report(Loc: T->getAttributeLoc(), DiagID: diag::err_unsupported_itanium_mangling)
4318 << UnsupportedItaniumManglingKind::DependentFixedLengthSVEVector;
4319}
4320
4321void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4322 assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4323 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4324 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4325 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4326 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&
4327 "expected fixed-length RVV vector!");
4328
4329 QualType EltType = T->getElementType();
4330 assert(EltType->isBuiltinType() &&
4331 "expected builtin type for fixed-length RVV vector!");
4332
4333 SmallString<20> TypeNameStr;
4334 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4335 TypeNameOS << "__rvv_";
4336 switch (cast<BuiltinType>(Val&: EltType)->getKind()) {
4337 case BuiltinType::SChar:
4338 TypeNameOS << "int8";
4339 break;
4340 case BuiltinType::UChar:
4341 if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4342 TypeNameOS << "uint8";
4343 else
4344 TypeNameOS << "bool";
4345 break;
4346 case BuiltinType::Short:
4347 TypeNameOS << "int16";
4348 break;
4349 case BuiltinType::UShort:
4350 TypeNameOS << "uint16";
4351 break;
4352 case BuiltinType::Int:
4353 TypeNameOS << "int32";
4354 break;
4355 case BuiltinType::UInt:
4356 TypeNameOS << "uint32";
4357 break;
4358 case BuiltinType::Long:
4359 case BuiltinType::LongLong:
4360 TypeNameOS << "int64";
4361 break;
4362 case BuiltinType::ULong:
4363 case BuiltinType::ULongLong:
4364 TypeNameOS << "uint64";
4365 break;
4366 case BuiltinType::Float16:
4367 TypeNameOS << "float16";
4368 break;
4369 case BuiltinType::Float:
4370 TypeNameOS << "float32";
4371 break;
4372 case BuiltinType::Double:
4373 TypeNameOS << "float64";
4374 break;
4375 case BuiltinType::BFloat16:
4376 TypeNameOS << "bfloat16";
4377 break;
4378 default:
4379 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4380 }
4381
4382 unsigned VecSizeInBits;
4383 switch (T->getVectorKind()) {
4384 case VectorKind::RVVFixedLengthMask_1:
4385 VecSizeInBits = 1;
4386 break;
4387 case VectorKind::RVVFixedLengthMask_2:
4388 VecSizeInBits = 2;
4389 break;
4390 case VectorKind::RVVFixedLengthMask_4:
4391 VecSizeInBits = 4;
4392 break;
4393 default:
4394 VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4395 break;
4396 }
4397
4398 // Apend the LMUL suffix.
4399 auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4400 LangOpts: getASTContext().getLangOpts(),
4401 Mode: TargetInfo::ArmStreamingKind::NotStreaming);
4402 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4403
4404 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4405 TypeNameOS << 'm';
4406 if (VecSizeInBits >= VLen)
4407 TypeNameOS << (VecSizeInBits / VLen);
4408 else
4409 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4410 } else {
4411 TypeNameOS << (VLen / VecSizeInBits);
4412 }
4413 TypeNameOS << "_t";
4414
4415 Out << "9__RVV_VLSI";
4416 mangleVendorType(name: TypeNameStr);
4417 Out << "Lj" << VecSizeInBits << "EE";
4418}
4419
4420void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4421 const DependentVectorType *T) {
4422 DiagnosticsEngine &Diags = Context.getDiags();
4423 Diags.Report(Loc: T->getAttributeLoc(), DiagID: diag::err_unsupported_itanium_mangling)
4424 << UnsupportedItaniumManglingKind::DependentFixedLengthRVVVectorType;
4425}
4426
4427// GNU extension: vector types
4428// <type> ::= <vector-type>
4429// <vector-type> ::= Dv <positive dimension number> _
4430// <extended element type>
4431// ::= Dv [<dimension expression>] _ <element type>
4432// <extended element type> ::= <element type>
4433// ::= p # AltiVec vector pixel
4434// ::= b # Altivec vector bool
4435void CXXNameMangler::mangleType(const VectorType *T) {
4436 if ((T->getVectorKind() == VectorKind::Neon ||
4437 T->getVectorKind() == VectorKind::NeonPoly)) {
4438 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4439 llvm::Triple::ArchType Arch =
4440 getASTContext().getTargetInfo().getTriple().getArch();
4441 if ((Arch == llvm::Triple::aarch64 ||
4442 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4443 mangleAArch64NeonVectorType(T);
4444 else
4445 mangleNeonVectorType(T);
4446 return;
4447 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4448 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4449 mangleAArch64FixedSveVectorType(T);
4450 return;
4451 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4452 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4453 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4454 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4455 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
4456 mangleRISCVFixedRVVVectorType(T);
4457 return;
4458 }
4459 Out << "Dv" << T->getNumElements() << '_';
4460 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4461 Out << 'p';
4462 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4463 Out << 'b';
4464 else
4465 mangleType(T: T->getElementType());
4466}
4467
4468void CXXNameMangler::mangleType(const DependentVectorType *T) {
4469 if ((T->getVectorKind() == VectorKind::Neon ||
4470 T->getVectorKind() == VectorKind::NeonPoly)) {
4471 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4472 llvm::Triple::ArchType Arch =
4473 getASTContext().getTargetInfo().getTriple().getArch();
4474 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4475 !Target.isOSDarwin())
4476 mangleAArch64NeonVectorType(T);
4477 else
4478 mangleNeonVectorType(T);
4479 return;
4480 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4481 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4482 mangleAArch64FixedSveVectorType(T);
4483 return;
4484 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4485 mangleRISCVFixedRVVVectorType(T);
4486 return;
4487 }
4488
4489 Out << "Dv";
4490 mangleExpression(E: T->getSizeExpr());
4491 Out << '_';
4492 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4493 Out << 'p';
4494 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4495 Out << 'b';
4496 else
4497 mangleType(T: T->getElementType());
4498}
4499
4500void CXXNameMangler::mangleType(const ExtVectorType *T) {
4501 mangleType(T: static_cast<const VectorType*>(T));
4502}
4503void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4504 Out << "Dv";
4505 mangleExpression(E: T->getSizeExpr());
4506 Out << '_';
4507 mangleType(T: T->getElementType());
4508}
4509
4510void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4511 // Mangle matrix types as a vendor extended type:
4512 // u<Len>matrix_typeI<Rows><Columns><element type>E
4513
4514 mangleVendorType(name: "matrix_type");
4515
4516 Out << "I";
4517 auto &ASTCtx = getASTContext();
4518 unsigned BitWidth = ASTCtx.getTypeSize(T: ASTCtx.getSizeType());
4519 llvm::APSInt Rows(BitWidth);
4520 Rows = T->getNumRows();
4521 mangleIntegerLiteral(T: ASTCtx.getSizeType(), Value: Rows);
4522 llvm::APSInt Columns(BitWidth);
4523 Columns = T->getNumColumns();
4524 mangleIntegerLiteral(T: ASTCtx.getSizeType(), Value: Columns);
4525 mangleType(T: T->getElementType());
4526 Out << "E";
4527}
4528
4529void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4530 // Mangle matrix types as a vendor extended type:
4531 // u<Len>matrix_typeI<row expr><column expr><element type>E
4532 mangleVendorType(name: "matrix_type");
4533
4534 Out << "I";
4535 mangleTemplateArgExpr(E: T->getRowExpr());
4536 mangleTemplateArgExpr(E: T->getColumnExpr());
4537 mangleType(T: T->getElementType());
4538 Out << "E";
4539}
4540
4541void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4542 SplitQualType split = T->getPointeeType().split();
4543 mangleQualifiers(Quals: split.Quals, DAST: T);
4544 mangleType(T: QualType(split.Ty, 0));
4545}
4546
4547void CXXNameMangler::mangleType(const PackExpansionType *T) {
4548 // <type> ::= Dp <type> # pack expansion (C++0x)
4549 Out << "Dp";
4550 mangleType(T: T->getPattern());
4551}
4552
4553void CXXNameMangler::mangleType(const PackIndexingType *T) {
4554 // <type> ::= Dy <type> <expression> # pack indexing type (C++23)
4555 Out << "Dy";
4556 mangleType(T: T->getPattern());
4557 mangleExpression(E: T->getIndexExpr());
4558}
4559
4560void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4561 mangleSourceName(II: T->getDecl()->getIdentifier());
4562}
4563
4564void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4565 // Treat __kindof as a vendor extended type qualifier.
4566 if (T->isKindOfType())
4567 Out << "U8__kindof";
4568
4569 if (!T->qual_empty()) {
4570 // Mangle protocol qualifiers.
4571 SmallString<64> QualStr;
4572 llvm::raw_svector_ostream QualOS(QualStr);
4573 QualOS << "objcproto";
4574 for (const auto *I : T->quals()) {
4575 StringRef name = I->getName();
4576 QualOS << name.size() << name;
4577 }
4578 mangleVendorQualifier(name: QualStr);
4579 }
4580
4581 mangleType(T: T->getBaseType());
4582
4583 if (T->isSpecialized()) {
4584 // Mangle type arguments as I <type>+ E
4585 Out << 'I';
4586 for (auto typeArg : T->getTypeArgs())
4587 mangleType(T: typeArg);
4588 Out << 'E';
4589 }
4590}
4591
4592void CXXNameMangler::mangleType(const BlockPointerType *T) {
4593 Out << "U13block_pointer";
4594 mangleType(T: T->getPointeeType());
4595}
4596
4597void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4598 // Mangle injected class name types as if the user had written the
4599 // specialization out fully. It may not actually be possible to see
4600 // this mangling, though.
4601 mangleType(
4602 T: T->getDecl()->getCanonicalTemplateSpecializationType(Ctx: getASTContext()));
4603}
4604
4605void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4606 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4607 mangleTemplateName(TD, Args: T->template_arguments());
4608 } else {
4609 Out << 'N';
4610 mangleTemplatePrefix(Template: T->getTemplateName());
4611
4612 // FIXME: GCC does not appear to mangle the template arguments when
4613 // the template in question is a dependent template name. Should we
4614 // emulate that badness?
4615 mangleTemplateArgs(TN: T->getTemplateName(), Args: T->template_arguments());
4616 Out << 'E';
4617 }
4618}
4619
4620void CXXNameMangler::mangleType(const DependentNameType *T) {
4621 // Proposal by cxx-abi-dev, 2014-03-26
4622 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4623 // # dependent elaborated type specifier using
4624 // # 'typename'
4625 // ::= Ts <name> # dependent elaborated type specifier using
4626 // # 'struct' or 'class'
4627 // ::= Tu <name> # dependent elaborated type specifier using
4628 // # 'union'
4629 // ::= Te <name> # dependent elaborated type specifier using
4630 // # 'enum'
4631 switch (T->getKeyword()) {
4632 case ElaboratedTypeKeyword::None:
4633 case ElaboratedTypeKeyword::Typename:
4634 break;
4635 case ElaboratedTypeKeyword::Struct:
4636 case ElaboratedTypeKeyword::Class:
4637 case ElaboratedTypeKeyword::Interface:
4638 Out << "Ts";
4639 break;
4640 case ElaboratedTypeKeyword::Union:
4641 Out << "Tu";
4642 break;
4643 case ElaboratedTypeKeyword::Enum:
4644 Out << "Te";
4645 break;
4646 }
4647 // Typename types are always nested
4648 Out << 'N';
4649 manglePrefix(Qualifier: T->getQualifier());
4650 mangleSourceName(II: T->getIdentifier());
4651 Out << 'E';
4652}
4653
4654void CXXNameMangler::mangleType(const TypeOfType *T) {
4655 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4656 // "extension with parameters" mangling.
4657 Out << "u6typeof";
4658}
4659
4660void CXXNameMangler::mangleType(const TypeOfExprType *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 DecltypeType *T) {
4667 Expr *E = T->getUnderlyingExpr();
4668
4669 // type ::= Dt <expression> E # decltype of an id-expression
4670 // # or class member access
4671 // ::= DT <expression> E # decltype of an expression
4672
4673 // This purports to be an exhaustive list of id-expressions and
4674 // class member accesses. Note that we do not ignore parentheses;
4675 // parentheses change the semantics of decltype for these
4676 // expressions (and cause the mangler to use the other form).
4677 if (isa<DeclRefExpr>(Val: E) ||
4678 isa<MemberExpr>(Val: E) ||
4679 isa<UnresolvedLookupExpr>(Val: E) ||
4680 isa<DependentScopeDeclRefExpr>(Val: E) ||
4681 isa<CXXDependentScopeMemberExpr>(Val: E) ||
4682 isa<UnresolvedMemberExpr>(Val: E))
4683 Out << "Dt";
4684 else
4685 Out << "DT";
4686 mangleExpression(E);
4687 Out << 'E';
4688}
4689
4690void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4691 // If this is dependent, we need to record that. If not, we simply
4692 // mangle it as the underlying type since they are equivalent.
4693 if (T->isDependentType()) {
4694 StringRef BuiltinName;
4695 switch (T->getUTTKind()) {
4696#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4697 case UnaryTransformType::Enum: \
4698 BuiltinName = "__" #Trait; \
4699 break;
4700#include "clang/Basic/BuiltinTraits.inc"
4701 }
4702 mangleVendorType(name: BuiltinName);
4703 }
4704
4705 Out << "I";
4706 mangleType(T: T->getBaseType());
4707 Out << "E";
4708}
4709
4710void CXXNameMangler::mangleType(const AutoType *T) {
4711 assert(T->getDeducedType().isNull() &&
4712 "Deduced AutoType shouldn't be handled here!");
4713 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4714 "shouldn't need to mangle __auto_type!");
4715 // <builtin-type> ::= Da # auto
4716 // ::= Dc # decltype(auto)
4717 // ::= Dk # constrained auto
4718 // ::= DK # constrained decltype(auto)
4719 if (T->isConstrained() && !isCompatibleWith(Ver: LangOptions::ClangABI::Ver17)) {
4720 Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4721 mangleTypeConstraint(Concept: T->getTypeConstraintConcept(),
4722 Arguments: T->getTypeConstraintArguments());
4723 } else {
4724 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4725 }
4726}
4727
4728void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4729 QualType Deduced = T->getDeducedType();
4730 if (!Deduced.isNull())
4731 return mangleType(T: Deduced);
4732
4733 TemplateName TN = T->getTemplateName();
4734 assert(TN.getAsTemplateDecl() &&
4735 "shouldn't form deduced TST unless we know we have a template");
4736 mangleType(TN);
4737}
4738
4739void CXXNameMangler::mangleType(const AtomicType *T) {
4740 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4741 // (Until there's a standardized mangling...)
4742 Out << "U7_Atomic";
4743 mangleType(T: T->getValueType());
4744}
4745
4746void CXXNameMangler::mangleType(const PipeType *T) {
4747 // Pipe type mangling rules are described in SPIR 2.0 specification
4748 // A.1 Data types and A.3 Summary of changes
4749 // <type> ::= 8ocl_pipe
4750 Out << "8ocl_pipe";
4751}
4752
4753void CXXNameMangler::mangleType(const OverflowBehaviorType *T) {
4754 // Vender-extended type mangling for OverflowBehaviorType
4755 // <type> ::= U <behavior> <underlying_type>
4756 if (T->isWrapKind()) {
4757 Out << "U8ObtWrap_";
4758 } else {
4759 Out << "U8ObtTrap_";
4760 }
4761 mangleType(T: T->getUnderlyingType());
4762}
4763
4764void CXXNameMangler::mangleType(const BitIntType *T) {
4765 // 5.1.5.2 Builtin types
4766 // <type> ::= DB <number | instantiation-dependent expression> _
4767 // ::= DU <number | instantiation-dependent expression> _
4768 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4769}
4770
4771void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4772 // 5.1.5.2 Builtin types
4773 // <type> ::= DB <number | instantiation-dependent expression> _
4774 // ::= DU <number | instantiation-dependent expression> _
4775 Out << "D" << (T->isUnsigned() ? "U" : "B");
4776 mangleExpression(E: T->getNumBitsExpr());
4777 Out << "_";
4778}
4779
4780void CXXNameMangler::mangleType(const ArrayParameterType *T) {
4781 mangleType(T: cast<ConstantArrayType>(Val: T));
4782}
4783
4784void CXXNameMangler::mangleType(const HLSLAttributedResourceType *T) {
4785 llvm::SmallString<64> Str("_Res");
4786 const HLSLAttributedResourceType::Attributes &Attrs = T->getAttrs();
4787 // map resource class to HLSL virtual register letter
4788 switch (Attrs.ResourceClass) {
4789 case llvm::dxil::ResourceClass::UAV:
4790 Str += "_u";
4791 break;
4792 case llvm::dxil::ResourceClass::SRV:
4793 Str += "_t";
4794 break;
4795 case llvm::dxil::ResourceClass::CBuffer:
4796 Str += "_b";
4797 break;
4798 case llvm::dxil::ResourceClass::Sampler:
4799 Str += "_s";
4800 break;
4801 }
4802 if (Attrs.IsROV)
4803 Str += "_ROV";
4804 if (Attrs.RawBuffer)
4805 Str += "_Raw";
4806 if (Attrs.IsCounter)
4807 Str += "_Counter";
4808 if (Attrs.IsArray)
4809 Str += "_Array";
4810 if (Attrs.isMultiSampled())
4811 Str += "_MS";
4812 if (T->hasContainedType())
4813 Str += "_CT";
4814 mangleVendorQualifier(name: Str);
4815
4816 if (T->hasContainedType()) {
4817 mangleType(T: T->getContainedType());
4818 }
4819 mangleType(T: T->getWrappedType());
4820}
4821
4822void CXXNameMangler::mangleType(const HLSLInlineSpirvType *T) {
4823 SmallString<20> TypeNameStr;
4824 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4825
4826 TypeNameOS << "spirv_type";
4827
4828 TypeNameOS << "_" << T->getOpcode();
4829 TypeNameOS << "_" << T->getSize();
4830 TypeNameOS << "_" << T->getAlignment();
4831
4832 mangleVendorType(name: TypeNameStr);
4833
4834 for (auto &Operand : T->getOperands()) {
4835 using SpirvOperandKind = SpirvOperand::SpirvOperandKind;
4836
4837 switch (Operand.getKind()) {
4838 case SpirvOperandKind::ConstantId:
4839 mangleVendorQualifier(name: "_Const");
4840 mangleIntegerLiteral(T: Operand.getResultType(),
4841 Value: llvm::APSInt(Operand.getValue()));
4842 break;
4843 case SpirvOperandKind::Literal:
4844 mangleVendorQualifier(name: "_Lit");
4845 mangleIntegerLiteral(T: Context.getASTContext().IntTy,
4846 Value: llvm::APSInt(Operand.getValue()));
4847 break;
4848 case SpirvOperandKind::TypeId:
4849 mangleVendorQualifier(name: "_Type");
4850 mangleType(T: Operand.getResultType());
4851 break;
4852 default:
4853 llvm_unreachable("Invalid SpirvOperand kind");
4854 break;
4855 }
4856 TypeNameOS << Operand.getKind();
4857 }
4858}
4859
4860void CXXNameMangler::mangleIntegerLiteral(QualType T,
4861 const llvm::APSInt &Value) {
4862 // <expr-primary> ::= L <type> <value number> E # integer literal
4863 Out << 'L';
4864
4865 mangleType(T);
4866 if (T->isBooleanType()) {
4867 // Boolean values are encoded as 0/1.
4868 Out << (Value.getBoolValue() ? '1' : '0');
4869 } else {
4870 mangleNumber(Value);
4871 }
4872 Out << 'E';
4873}
4874
4875void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4876 // Ignore member expressions involving anonymous unions.
4877 while (const auto *RT = Base->getType()->getAsCanonical<RecordType>()) {
4878 if (!RT->getDecl()->isAnonymousStructOrUnion())
4879 break;
4880 const auto *ME = dyn_cast<MemberExpr>(Val: Base);
4881 if (!ME)
4882 break;
4883 Base = ME->getBase();
4884 IsArrow = ME->isArrow();
4885 }
4886
4887 if (Base->isImplicitCXXThis()) {
4888 // Note: GCC mangles member expressions to the implicit 'this' as
4889 // *this., whereas we represent them as this->. The Itanium C++ ABI
4890 // does not specify anything here, so we follow GCC.
4891 Out << "dtdefpT";
4892 } else {
4893 Out << (IsArrow ? "pt" : "dt");
4894 mangleExpression(E: Base);
4895 }
4896}
4897
4898/// Mangles a member expression.
4899void CXXNameMangler::mangleMemberExpr(const Expr *base, bool isArrow,
4900 NestedNameSpecifier Qualifier,
4901 NamedDecl *firstQualifierLookup,
4902 DeclarationName member,
4903 const TemplateArgumentLoc *TemplateArgs,
4904 unsigned NumTemplateArgs,
4905 unsigned arity) {
4906 // <expression> ::= dt <expression> <unresolved-name>
4907 // ::= pt <expression> <unresolved-name>
4908 if (base)
4909 mangleMemberExprBase(Base: base, IsArrow: isArrow);
4910 mangleUnresolvedName(Qualifier, name: member, TemplateArgs, NumTemplateArgs, knownArity: arity);
4911}
4912
4913/// Look at the callee of the given call expression and determine if
4914/// it's a parenthesized id-expression which would have triggered ADL
4915/// otherwise.
4916static bool isParenthesizedADLCallee(const CallExpr *call) {
4917 const Expr *callee = call->getCallee();
4918 const Expr *fn = callee->IgnoreParens();
4919
4920 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4921 // too, but for those to appear in the callee, it would have to be
4922 // parenthesized.
4923 if (callee == fn) return false;
4924
4925 // Must be an unresolved lookup.
4926 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(Val: fn);
4927 if (!lookup) return false;
4928
4929 assert(!lookup->requiresADL());
4930
4931 // Must be an unqualified lookup.
4932 if (lookup->getQualifier()) return false;
4933
4934 // Must not have found a class member. Note that if one is a class
4935 // member, they're all class members.
4936 if (lookup->getNumDecls() > 0 &&
4937 (*lookup->decls_begin())->isCXXClassMember())
4938 return false;
4939
4940 // Otherwise, ADL would have been triggered.
4941 return true;
4942}
4943
4944void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4945 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(Val: E);
4946 Out << CastEncoding;
4947 mangleType(T: ECE->getType());
4948 if (const auto *PLIE = dyn_cast<CXXParenListInitExpr>(Val: ECE->getSubExpr())) {
4949 ArrayRef<Expr *> Inits = PLIE->getUserSpecifiedInitExprs();
4950 assert(Inits.size() == 1 && "cast must have exactly one operand");
4951 mangleExpression(E: Inits.front());
4952 } else {
4953 mangleExpression(E: ECE->getSubExpr());
4954 }
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 auto *PLE = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
5354 for (const Expr *Arg : PLE->getUserSpecifiedInitExprs())
5355 mangleExpression(E: Arg);
5356 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: Init)) {
5357 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
5358 mangleExpression(E: PLE->getExpr(Init: i));
5359 } else if (New->getInitializationStyle() ==
5360 CXXNewInitializationStyle::Braces &&
5361 isa<InitListExpr>(Val: Init)) {
5362 // Only take InitListExprs apart for list-initialization.
5363 mangleInitListElements(InitList: cast<InitListExpr>(Val: Init));
5364 } else
5365 mangleExpression(E: Init);
5366 }
5367 Out << 'E';
5368 break;
5369 }
5370
5371 case Expr::CXXPseudoDestructorExprClass: {
5372 NotPrimaryExpr();
5373 const auto *PDE = cast<CXXPseudoDestructorExpr>(Val: E);
5374 if (const Expr *Base = PDE->getBase())
5375 mangleMemberExprBase(Base, IsArrow: PDE->isArrow());
5376 NestedNameSpecifier Qualifier = PDE->getQualifier();
5377 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
5378 if (Qualifier) {
5379 mangleUnresolvedPrefix(Qualifier,
5380 /*recursive=*/true);
5381 mangleUnresolvedTypeOrSimpleId(Ty: ScopeInfo->getType());
5382 Out << 'E';
5383 } else {
5384 Out << "sr";
5385 if (!mangleUnresolvedTypeOrSimpleId(Ty: ScopeInfo->getType()))
5386 Out << 'E';
5387 }
5388 } else if (Qualifier) {
5389 mangleUnresolvedPrefix(Qualifier);
5390 }
5391 // <base-unresolved-name> ::= dn <destructor-name>
5392 Out << "dn";
5393 QualType DestroyedType = PDE->getDestroyedType();
5394 mangleUnresolvedTypeOrSimpleId(Ty: DestroyedType);
5395 break;
5396 }
5397
5398 case Expr::MemberExprClass: {
5399 NotPrimaryExpr();
5400 const MemberExpr *ME = cast<MemberExpr>(Val: E);
5401 mangleMemberExpr(base: ME->getBase(), isArrow: ME->isArrow(),
5402 Qualifier: ME->getQualifier(), firstQualifierLookup: nullptr,
5403 member: ME->getMemberDecl()->getDeclName(),
5404 TemplateArgs: ME->getTemplateArgs(), NumTemplateArgs: ME->getNumTemplateArgs(),
5405 arity: Arity);
5406 break;
5407 }
5408
5409 case Expr::UnresolvedMemberExprClass: {
5410 NotPrimaryExpr();
5411 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(Val: E);
5412 mangleMemberExpr(base: ME->isImplicitAccess() ? nullptr : ME->getBase(),
5413 isArrow: ME->isArrow(), Qualifier: ME->getQualifier(), firstQualifierLookup: nullptr,
5414 member: ME->getMemberName(),
5415 TemplateArgs: ME->getTemplateArgs(), NumTemplateArgs: ME->getNumTemplateArgs(),
5416 arity: Arity);
5417 break;
5418 }
5419
5420 case Expr::CXXDependentScopeMemberExprClass: {
5421 NotPrimaryExpr();
5422 const CXXDependentScopeMemberExpr *ME
5423 = cast<CXXDependentScopeMemberExpr>(Val: E);
5424 mangleMemberExpr(base: ME->isImplicitAccess() ? nullptr : ME->getBase(),
5425 isArrow: ME->isArrow(), Qualifier: ME->getQualifier(),
5426 firstQualifierLookup: ME->getFirstQualifierFoundInScope(),
5427 member: ME->getMember(),
5428 TemplateArgs: ME->getTemplateArgs(), NumTemplateArgs: ME->getNumTemplateArgs(),
5429 arity: Arity);
5430 break;
5431 }
5432
5433 case Expr::UnresolvedLookupExprClass: {
5434 NotPrimaryExpr();
5435 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(Val: E);
5436 mangleUnresolvedName(Qualifier: ULE->getQualifier(), name: ULE->getName(),
5437 TemplateArgs: ULE->getTemplateArgs(), NumTemplateArgs: ULE->getNumTemplateArgs(),
5438 knownArity: Arity);
5439 break;
5440 }
5441
5442 case Expr::DependentTemplateIdExprClass: {
5443 NotPrimaryExpr();
5444 const auto *DTI = cast<DependentTemplateIdExpr>(Val: E);
5445 if (DTI->getTemplateName().getAsPackIndexingTemplate()) {
5446 DiagnoseUnsupportedPackIndexTemplateName();
5447 break;
5448 }
5449 mangleUnresolvedName(/*NestedNameSpecifier=*/Qualifier: std::nullopt, name: DTI->getName(),
5450 TemplateArgs: DTI->template_arguments().data(),
5451 NumTemplateArgs: DTI->getNumTemplateArgs(), knownArity: Arity);
5452 break;
5453 }
5454
5455 case Expr::CXXUnresolvedConstructExprClass: {
5456 NotPrimaryExpr();
5457 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(Val: E);
5458 unsigned N = CE->getNumArgs();
5459
5460 if (CE->isListInitialization()) {
5461 assert(N == 1 && "unexpected form for list initialization");
5462 auto *IL = cast<InitListExpr>(Val: CE->getArg(I: 0));
5463 Out << "tl";
5464 mangleType(T: CE->getType());
5465 mangleInitListElements(InitList: IL);
5466 Out << "E";
5467 break;
5468 }
5469
5470 Out << "cv";
5471 mangleType(T: CE->getType());
5472 if (N != 1) Out << '_';
5473 for (unsigned I = 0; I != N; ++I) mangleExpression(E: CE->getArg(I));
5474 if (N != 1) Out << 'E';
5475 break;
5476 }
5477
5478 case Expr::CXXConstructExprClass: {
5479 // An implicit cast is silent, thus may contain <expr-primary>.
5480 const auto *CE = cast<CXXConstructExpr>(Val: E);
5481 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5482 assert(
5483 CE->getNumArgs() >= 1 &&
5484 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5485 "implicit CXXConstructExpr must have one argument");
5486 E = cast<CXXConstructExpr>(Val: E)->getArg(Arg: 0);
5487 goto recurse;
5488 }
5489 NotPrimaryExpr();
5490 Out << "il";
5491 for (auto *E : CE->arguments())
5492 mangleExpression(E);
5493 Out << "E";
5494 break;
5495 }
5496
5497 case Expr::CXXTemporaryObjectExprClass: {
5498 NotPrimaryExpr();
5499 const auto *CE = cast<CXXTemporaryObjectExpr>(Val: E);
5500 unsigned N = CE->getNumArgs();
5501 bool List = CE->isListInitialization();
5502
5503 if (List)
5504 Out << "tl";
5505 else
5506 Out << "cv";
5507 mangleType(T: CE->getType());
5508 if (!List && N != 1)
5509 Out << '_';
5510 if (CE->isStdInitListInitialization()) {
5511 // We implicitly created a std::initializer_list<T> for the first argument
5512 // of a constructor of type U in an expression of the form U{a, b, c}.
5513 // Strip all the semantic gunk off the initializer list.
5514 auto *SILE =
5515 cast<CXXStdInitializerListExpr>(Val: CE->getArg(Arg: 0)->IgnoreImplicit());
5516 auto *ILE = cast<InitListExpr>(Val: SILE->getSubExpr()->IgnoreImplicit());
5517 mangleInitListElements(InitList: ILE);
5518 } else {
5519 for (auto *E : CE->arguments())
5520 mangleExpression(E);
5521 }
5522 if (List || N != 1)
5523 Out << 'E';
5524 break;
5525 }
5526
5527 case Expr::CXXScalarValueInitExprClass:
5528 NotPrimaryExpr();
5529 Out << "cv";
5530 mangleType(T: E->getType());
5531 Out << "_E";
5532 break;
5533
5534 case Expr::CXXNoexceptExprClass:
5535 NotPrimaryExpr();
5536 Out << "nx";
5537 mangleExpression(E: cast<CXXNoexceptExpr>(Val: E)->getOperand());
5538 break;
5539
5540 case Expr::UnaryExprOrTypeTraitExprClass: {
5541 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5542 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(Val: E);
5543
5544 if (!SAE->isInstantiationDependent()) {
5545 // Itanium C++ ABI:
5546 // If the operand of a sizeof or alignof operator is not
5547 // instantiation-dependent it is encoded as an integer literal
5548 // reflecting the result of the operator.
5549 //
5550 // If the result of the operator is implicitly converted to a known
5551 // integer type, that type is used for the literal; otherwise, the type
5552 // of std::size_t or std::ptrdiff_t is used.
5553 //
5554 // FIXME: We still include the operand in the profile in this case. This
5555 // can lead to mangling collisions between function templates that we
5556 // consider to be different.
5557 QualType T = (ImplicitlyConvertedToType.isNull() ||
5558 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5559 : ImplicitlyConvertedToType;
5560 llvm::APSInt V = SAE->EvaluateKnownConstInt(Ctx: Context.getASTContext());
5561 mangleIntegerLiteral(T, Value: V);
5562 break;
5563 }
5564
5565 NotPrimaryExpr(); // But otherwise, they are not.
5566
5567 auto MangleAlignofSizeofArg = [&] {
5568 if (SAE->isArgumentType()) {
5569 Out << 't';
5570 mangleType(T: SAE->getArgumentType());
5571 } else {
5572 Out << 'z';
5573 mangleExpression(E: SAE->getArgumentExpr());
5574 }
5575 };
5576
5577 auto MangleExtensionBuiltin = [&](const UnaryExprOrTypeTraitExpr *E,
5578 StringRef Name = {}) {
5579 if (Name.empty())
5580 Name = getTraitSpelling(T: E->getKind());
5581 mangleVendorType(name: Name);
5582 if (SAE->isArgumentType())
5583 mangleType(T: SAE->getArgumentType());
5584 else
5585 mangleTemplateArgExpr(E: SAE->getArgumentExpr());
5586 Out << 'E';
5587 };
5588
5589 switch (SAE->getKind()) {
5590 case UETT_SizeOf:
5591 Out << 's';
5592 MangleAlignofSizeofArg();
5593 break;
5594 case UETT_PreferredAlignOf:
5595 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5596 // have acted differently since Clang 8, but were previously mangled the
5597 // same.)
5598 if (!isCompatibleWith(Ver: LangOptions::ClangABI::Ver11)) {
5599 MangleExtensionBuiltin(SAE, "__alignof__");
5600 break;
5601 }
5602 [[fallthrough]];
5603 case UETT_AlignOf:
5604 Out << 'a';
5605 MangleAlignofSizeofArg();
5606 break;
5607
5608 case UETT_CountOf:
5609 case UETT_VectorElements:
5610 case UETT_OpenMPRequiredSimdAlign:
5611 case UETT_VecStep:
5612 case UETT_PtrAuthTypeDiscriminator:
5613 case UETT_DataSizeOf: {
5614 DiagnosticsEngine &Diags = Context.getDiags();
5615 Diags.Report(Loc: E->getExprLoc(), DiagID: diag::err_unsupported_itanium_expr_mangling)
5616 << getTraitSpelling(T: SAE->getKind());
5617 return;
5618 }
5619 }
5620 break;
5621 }
5622
5623 case Expr::TypeTraitExprClass: {
5624 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5625 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(Val: E);
5626 NotPrimaryExpr();
5627 llvm::StringRef Spelling = getTraitSpelling(T: TTE->getTrait());
5628 mangleVendorType(name: Spelling);
5629 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5630 mangleType(T: TSI->getType());
5631 }
5632 Out << 'E';
5633 break;
5634 }
5635
5636 case Expr::CXXThrowExprClass: {
5637 NotPrimaryExpr();
5638 const CXXThrowExpr *TE = cast<CXXThrowExpr>(Val: E);
5639 // <expression> ::= tw <expression> # throw expression
5640 // ::= tr # rethrow
5641 if (TE->getSubExpr()) {
5642 Out << "tw";
5643 mangleExpression(E: TE->getSubExpr());
5644 } else {
5645 Out << "tr";
5646 }
5647 break;
5648 }
5649
5650 case Expr::CXXTypeidExprClass: {
5651 NotPrimaryExpr();
5652 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(Val: E);
5653 // <expression> ::= ti <type> # typeid (type)
5654 // ::= te <expression> # typeid (expression)
5655 if (TIE->isTypeOperand()) {
5656 Out << "ti";
5657 mangleType(T: TIE->getTypeOperand(Context: Context.getASTContext()));
5658 } else {
5659 Out << "te";
5660 mangleExpression(E: TIE->getExprOperand());
5661 }
5662 break;
5663 }
5664
5665 case Expr::CXXDeleteExprClass: {
5666 NotPrimaryExpr();
5667 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(Val: E);
5668 // <expression> ::= [gs] dl <expression> # [::] delete expr
5669 // ::= [gs] da <expression> # [::] delete [] expr
5670 if (DE->isGlobalDelete()) Out << "gs";
5671 Out << (DE->isArrayForm() ? "da" : "dl");
5672 mangleExpression(E: DE->getArgument());
5673 break;
5674 }
5675
5676 case Expr::UnaryOperatorClass: {
5677 NotPrimaryExpr();
5678 const UnaryOperator *UO = cast<UnaryOperator>(Val: E);
5679 mangleOperatorName(OO: UnaryOperator::getOverloadedOperator(Opc: UO->getOpcode()),
5680 /*Arity=*/1);
5681 mangleExpression(E: UO->getSubExpr());
5682 break;
5683 }
5684
5685 case Expr::ArraySubscriptExprClass: {
5686 NotPrimaryExpr();
5687 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(Val: E);
5688
5689 // Array subscript is treated as a syntactically weird form of
5690 // binary operator.
5691 Out << "ix";
5692 mangleExpression(E: AE->getLHS());
5693 mangleExpression(E: AE->getRHS());
5694 break;
5695 }
5696
5697 case Expr::MatrixSingleSubscriptExprClass: {
5698 NotPrimaryExpr();
5699 const MatrixSingleSubscriptExpr *ME = cast<MatrixSingleSubscriptExpr>(Val: E);
5700 Out << "ix";
5701 mangleExpression(E: ME->getBase());
5702 mangleExpression(E: ME->getRowIdx());
5703 break;
5704 }
5705
5706 case Expr::MatrixSubscriptExprClass: {
5707 NotPrimaryExpr();
5708 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(Val: E);
5709 Out << "ixix";
5710 mangleExpression(E: ME->getBase());
5711 mangleExpression(E: ME->getRowIdx());
5712 mangleExpression(E: ME->getColumnIdx());
5713 break;
5714 }
5715
5716 case Expr::CompoundAssignOperatorClass: // fallthrough
5717 case Expr::BinaryOperatorClass: {
5718 NotPrimaryExpr();
5719 const BinaryOperator *BO = cast<BinaryOperator>(Val: E);
5720 if (BO->getOpcode() == BO_PtrMemD)
5721 Out << "ds";
5722 else
5723 mangleOperatorName(OO: BinaryOperator::getOverloadedOperator(Opc: BO->getOpcode()),
5724 /*Arity=*/2);
5725 mangleExpression(E: BO->getLHS());
5726 mangleExpression(E: BO->getRHS());
5727 break;
5728 }
5729
5730 case Expr::CXXRewrittenBinaryOperatorClass: {
5731 NotPrimaryExpr();
5732 // The mangled form represents the original syntax.
5733 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5734 cast<CXXRewrittenBinaryOperator>(Val: E)->getDecomposedForm();
5735 mangleOperatorName(OO: BinaryOperator::getOverloadedOperator(Opc: Decomposed.Opcode),
5736 /*Arity=*/2);
5737 mangleExpression(E: Decomposed.LHS);
5738 mangleExpression(E: Decomposed.RHS);
5739 break;
5740 }
5741
5742 case Expr::ConditionalOperatorClass: {
5743 NotPrimaryExpr();
5744 const ConditionalOperator *CO = cast<ConditionalOperator>(Val: E);
5745 mangleOperatorName(OO: OO_Conditional, /*Arity=*/3);
5746 mangleExpression(E: CO->getCond());
5747 mangleExpression(E: CO->getLHS(), Arity);
5748 mangleExpression(E: CO->getRHS(), Arity);
5749 break;
5750 }
5751
5752 case Expr::ImplicitCastExprClass: {
5753 ImplicitlyConvertedToType = E->getType();
5754 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
5755 goto recurse;
5756 }
5757
5758 case Expr::ObjCBridgedCastExprClass: {
5759 NotPrimaryExpr();
5760 // Mangle ownership casts as a vendor extended operator __bridge,
5761 // __bridge_transfer, or __bridge_retain.
5762 StringRef Kind = cast<ObjCBridgedCastExpr>(Val: E)->getBridgeKindName();
5763 Out << "v1U" << Kind.size() << Kind;
5764 mangleCastExpression(E, CastEncoding: "cv");
5765 break;
5766 }
5767
5768 case Expr::CStyleCastExprClass:
5769 NotPrimaryExpr();
5770 mangleCastExpression(E, CastEncoding: "cv");
5771 break;
5772
5773 case Expr::CXXFunctionalCastExprClass: {
5774 NotPrimaryExpr();
5775 auto *Sub = cast<ExplicitCastExpr>(Val: E)->getSubExpr()->IgnoreImplicit();
5776 // FIXME: Add isImplicit to CXXConstructExpr.
5777 if (auto *CCE = dyn_cast<CXXConstructExpr>(Val: Sub))
5778 if (CCE->getParenOrBraceRange().isInvalid())
5779 Sub = CCE->getArg(Arg: 0)->IgnoreImplicit();
5780 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Val: Sub))
5781 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5782 if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(Val: Sub)) {
5783 ArrayRef<Expr *> Inits = PLIE->getUserSpecifiedInitExprs();
5784 Out << "cv";
5785 mangleType(T: E->getType());
5786 if (Inits.size() != 1)
5787 Out << '_';
5788 for (const Expr *Init : Inits)
5789 mangleExpression(E: Init);
5790 if (Inits.size() != 1)
5791 Out << 'E';
5792 } else if (auto *IL = dyn_cast<InitListExpr>(Val: Sub)) {
5793 Out << "tl";
5794 mangleType(T: E->getType());
5795 mangleInitListElements(InitList: IL);
5796 Out << "E";
5797 } else {
5798 mangleCastExpression(E, CastEncoding: "cv");
5799 }
5800 break;
5801 }
5802
5803 case Expr::CXXStaticCastExprClass:
5804 NotPrimaryExpr();
5805 mangleCastExpression(E, CastEncoding: "sc");
5806 break;
5807 case Expr::CXXDynamicCastExprClass:
5808 NotPrimaryExpr();
5809 mangleCastExpression(E, CastEncoding: "dc");
5810 break;
5811 case Expr::CXXReinterpretCastExprClass:
5812 NotPrimaryExpr();
5813 mangleCastExpression(E, CastEncoding: "rc");
5814 break;
5815 case Expr::CXXConstCastExprClass:
5816 NotPrimaryExpr();
5817 mangleCastExpression(E, CastEncoding: "cc");
5818 break;
5819 case Expr::CXXAddrspaceCastExprClass:
5820 NotPrimaryExpr();
5821 mangleCastExpression(E, CastEncoding: "ac");
5822 break;
5823
5824 case Expr::CXXOperatorCallExprClass: {
5825 NotPrimaryExpr();
5826 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(Val: E);
5827 unsigned NumArgs = CE->getNumArgs();
5828 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5829 // (the enclosing MemberExpr covers the syntactic portion).
5830 if (CE->getOperator() != OO_Arrow)
5831 mangleOperatorName(OO: CE->getOperator(), /*Arity=*/NumArgs);
5832 // Mangle the arguments.
5833 for (unsigned i = 0; i != NumArgs; ++i)
5834 mangleExpression(E: CE->getArg(Arg: i));
5835 break;
5836 }
5837
5838 case Expr::ParenExprClass:
5839 E = cast<ParenExpr>(Val: E)->getSubExpr();
5840 goto recurse;
5841
5842 case Expr::ConceptSpecializationExprClass: {
5843 auto *CSE = cast<ConceptSpecializationExpr>(Val: E);
5844 if (isCompatibleWith(Ver: LangOptions::ClangABI::Ver17)) {
5845 // Clang 17 and before mangled concept-ids as if they resolved to an
5846 // entity, meaning that references to enclosing template arguments don't
5847 // work.
5848 Out << "L_Z";
5849 mangleTemplateName(TD: CSE->getConceptDecl(), Args: CSE->getTemplateArguments());
5850 Out << 'E';
5851 break;
5852 }
5853 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5854 NotPrimaryExpr();
5855 mangleUnresolvedName(
5856 Qualifier: CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5857 name: CSE->getConceptNameInfo().getName(),
5858 TemplateArgs: CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5859 NumTemplateArgs: CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5860 break;
5861 }
5862
5863 case Expr::RequiresExprClass: {
5864 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5865 auto *RE = cast<RequiresExpr>(Val: E);
5866 // This is a primary-expression in the C++ grammar, but does not have an
5867 // <expr-primary> mangling (starting with 'L').
5868 NotPrimaryExpr();
5869 if (RE->getLParenLoc().isValid()) {
5870 Out << "rQ";
5871 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5872 if (RE->getLocalParameters().empty()) {
5873 Out << 'v';
5874 } else {
5875 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5876 mangleType(T: Context.getASTContext().getSignatureParameterType(
5877 T: Param->getType()));
5878 }
5879 }
5880 Out << '_';
5881
5882 // The rest of the mangling is in the immediate scope of the parameters.
5883 FunctionTypeDepth.enterFunctionDeclSuffix();
5884 for (const concepts::Requirement *Req : RE->getRequirements())
5885 mangleRequirement(RequiresExprLoc: RE->getExprLoc(), Req);
5886 FunctionTypeDepth.pop(Saved: saved);
5887 Out << 'E';
5888 } else {
5889 Out << "rq";
5890 for (const concepts::Requirement *Req : RE->getRequirements())
5891 mangleRequirement(RequiresExprLoc: RE->getExprLoc(), Req);
5892 Out << 'E';
5893 }
5894 break;
5895 }
5896
5897 case Expr::DeclRefExprClass:
5898 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5899 MangleDeclRefExpr(cast<DeclRefExpr>(Val: E)->getDecl());
5900 break;
5901
5902 case Expr::SubstNonTypeTemplateParmPackExprClass:
5903 NotPrimaryExpr();
5904 // FIXME: not clear how to mangle this!
5905 // template <unsigned N...> class A {
5906 // template <class U...> void foo(U (&x)[N]...);
5907 // };
5908 Out << "_SUBSTPACK_";
5909 break;
5910
5911 case Expr::FunctionParmPackExprClass: {
5912 NotPrimaryExpr();
5913 // FIXME: not clear how to mangle this!
5914 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(Val: E);
5915 Out << "v110_SUBSTPACK";
5916 MangleDeclRefExpr(FPPE->getParameterPack());
5917 break;
5918 }
5919
5920 case Expr::DependentScopeDeclRefExprClass: {
5921 NotPrimaryExpr();
5922 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(Val: E);
5923 mangleUnresolvedName(Qualifier: DRE->getQualifier(), name: DRE->getDeclName(),
5924 TemplateArgs: DRE->getTemplateArgs(), NumTemplateArgs: DRE->getNumTemplateArgs(),
5925 knownArity: Arity);
5926 break;
5927 }
5928
5929 case Expr::CXXBindTemporaryExprClass:
5930 E = cast<CXXBindTemporaryExpr>(Val: E)->getSubExpr();
5931 goto recurse;
5932
5933 case Expr::ExprWithCleanupsClass:
5934 E = cast<ExprWithCleanups>(Val: E)->getSubExpr();
5935 goto recurse;
5936
5937 case Expr::FloatingLiteralClass: {
5938 // <expr-primary>
5939 const FloatingLiteral *FL = cast<FloatingLiteral>(Val: E);
5940 mangleFloatLiteral(T: FL->getType(), V: FL->getValue());
5941 break;
5942 }
5943
5944 case Expr::FixedPointLiteralClass:
5945 // Currently unimplemented -- might be <expr-primary> in future?
5946 mangleFixedPointLiteral();
5947 break;
5948
5949 case Expr::CharacterLiteralClass:
5950 // <expr-primary>
5951 Out << 'L';
5952 mangleType(T: E->getType());
5953 Out << cast<CharacterLiteral>(Val: E)->getValue();
5954 Out << 'E';
5955 break;
5956
5957 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5958 case Expr::ObjCBoolLiteralExprClass:
5959 // <expr-primary>
5960 Out << "Lb";
5961 Out << (cast<ObjCBoolLiteralExpr>(Val: E)->getValue() ? '1' : '0');
5962 Out << 'E';
5963 break;
5964
5965 case Expr::CXXBoolLiteralExprClass:
5966 // <expr-primary>
5967 Out << "Lb";
5968 Out << (cast<CXXBoolLiteralExpr>(Val: E)->getValue() ? '1' : '0');
5969 Out << 'E';
5970 break;
5971
5972 case Expr::IntegerLiteralClass: {
5973 // <expr-primary>
5974 llvm::APSInt Value(cast<IntegerLiteral>(Val: E)->getValue());
5975 if (E->getType()->isSignedIntegerType())
5976 Value.setIsSigned(true);
5977 mangleIntegerLiteral(T: E->getType(), Value);
5978 break;
5979 }
5980
5981 case Expr::ImaginaryLiteralClass: {
5982 // <expr-primary>
5983 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(Val: E);
5984 // Mangle as if a complex literal.
5985 // Proposal from David Vandevoorde, 2010.06.30.
5986 Out << 'L';
5987 mangleType(T: E->getType());
5988 if (const FloatingLiteral *Imag =
5989 dyn_cast<FloatingLiteral>(Val: IE->getSubExpr())) {
5990 // Mangle a floating-point zero of the appropriate type.
5991 mangleFloat(f: llvm::APFloat(Imag->getValue().getSemantics()));
5992 Out << '_';
5993 mangleFloat(f: Imag->getValue());
5994 } else {
5995 Out << "0_";
5996 llvm::APSInt Value(cast<IntegerLiteral>(Val: IE->getSubExpr())->getValue());
5997 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5998 Value.setIsSigned(true);
5999 mangleNumber(Value);
6000 }
6001 Out << 'E';
6002 break;
6003 }
6004
6005 case Expr::StringLiteralClass: {
6006 // <expr-primary>
6007 // Revised proposal from David Vandervoorde, 2010.07.15.
6008 Out << 'L';
6009 assert(isa<ConstantArrayType>(E->getType()));
6010 mangleType(T: E->getType());
6011 Out << 'E';
6012 break;
6013 }
6014
6015 case Expr::GNUNullExprClass:
6016 // <expr-primary>
6017 // Mangle as if an integer literal 0.
6018 mangleIntegerLiteral(T: E->getType(), Value: llvm::APSInt(32));
6019 break;
6020
6021 case Expr::CXXNullPtrLiteralExprClass: {
6022 // <expr-primary>
6023 Out << "LDnE";
6024 break;
6025 }
6026
6027 case Expr::LambdaExprClass: {
6028 // A lambda-expression can't appear in the signature of an
6029 // externally-visible declaration, so there's no standard mangling for
6030 // this, but mangling as a literal of the closure type seems reasonable.
6031 Out << "L";
6032 mangleType(T: Context.getASTContext().getCanonicalTagType(
6033 TD: cast<LambdaExpr>(Val: E)->getLambdaClass()));
6034 Out << "E";
6035 break;
6036 }
6037
6038 case Expr::PackExpansionExprClass:
6039 NotPrimaryExpr();
6040 Out << "sp";
6041 mangleExpression(E: cast<PackExpansionExpr>(Val: E)->getPattern());
6042 break;
6043
6044 case Expr::SizeOfPackExprClass: {
6045 NotPrimaryExpr();
6046 auto *SPE = cast<SizeOfPackExpr>(Val: E);
6047 if (SPE->isPartiallySubstituted()) {
6048 Out << "sP";
6049 for (const auto &A : SPE->getPartialArguments())
6050 mangleTemplateArg(A, NeedExactType: false);
6051 Out << "E";
6052 break;
6053 }
6054
6055 Out << "sZ";
6056 mangleReferenceToPack(ND: SPE->getPack());
6057 break;
6058 }
6059
6060 case Expr::MaterializeTemporaryExprClass:
6061 E = cast<MaterializeTemporaryExpr>(Val: E)->getSubExpr();
6062 goto recurse;
6063
6064 case Expr::CXXFoldExprClass: {
6065 NotPrimaryExpr();
6066 auto *FE = cast<CXXFoldExpr>(Val: E);
6067 if (FE->isLeftFold())
6068 Out << (FE->getInit() ? "fL" : "fl");
6069 else
6070 Out << (FE->getInit() ? "fR" : "fr");
6071
6072 if (FE->getOperator() == BO_PtrMemD)
6073 Out << "ds";
6074 else
6075 mangleOperatorName(
6076 OO: BinaryOperator::getOverloadedOperator(Opc: FE->getOperator()),
6077 /*Arity=*/2);
6078
6079 if (FE->getLHS())
6080 mangleExpression(E: FE->getLHS());
6081 if (FE->getRHS())
6082 mangleExpression(E: FE->getRHS());
6083 break;
6084 }
6085
6086 case Expr::PackIndexingExprClass: {
6087 auto *PE = cast<PackIndexingExpr>(Val: E);
6088 NotPrimaryExpr();
6089 Out << "sy";
6090 mangleReferenceToPack(ND: PE->getPackDecl());
6091 mangleExpression(E: PE->getIndexExpr());
6092 break;
6093 }
6094
6095 case Expr::CXXThisExprClass:
6096 NotPrimaryExpr();
6097 Out << "fpT";
6098 break;
6099
6100 case Expr::CoawaitExprClass:
6101 // FIXME: Propose a non-vendor mangling.
6102 NotPrimaryExpr();
6103 Out << "v18co_await";
6104 mangleExpression(E: cast<CoawaitExpr>(Val: E)->getOperand());
6105 break;
6106
6107 case Expr::DependentCoawaitExprClass:
6108 // FIXME: Propose a non-vendor mangling.
6109 NotPrimaryExpr();
6110 Out << "v18co_await";
6111 mangleExpression(E: cast<DependentCoawaitExpr>(Val: E)->getOperand());
6112 break;
6113
6114 case Expr::CoyieldExprClass:
6115 // FIXME: Propose a non-vendor mangling.
6116 NotPrimaryExpr();
6117 Out << "v18co_yield";
6118 mangleExpression(E: cast<CoawaitExpr>(Val: E)->getOperand());
6119 break;
6120 case Expr::SYCLUniqueStableNameExprClass: {
6121 const auto *USN = cast<SYCLUniqueStableNameExpr>(Val: E);
6122 NotPrimaryExpr();
6123
6124 Out << "u33__builtin_sycl_unique_stable_name";
6125 mangleType(T: USN->getTypeSourceInfo()->getType());
6126
6127 Out << "E";
6128 break;
6129 }
6130 case Expr::HLSLOutArgExprClass:
6131 llvm_unreachable(
6132 "cannot mangle hlsl temporary value; mangling wrong thing?");
6133 case Expr::OpenACCAsteriskSizeExprClass: {
6134 // We shouldn't ever be able to get here, but diagnose anyway.
6135 DiagnosticsEngine &Diags = Context.getDiags();
6136 Diags.Report(DiagID: diag::err_unsupported_itanium_mangling)
6137 << UnsupportedItaniumManglingKind::OpenACCAsteriskSizeExpr;
6138 return;
6139 }
6140 }
6141
6142 if (AsTemplateArg && !IsPrimaryExpr)
6143 Out << 'E';
6144}
6145
6146/// Mangle an expression which refers to a parameter variable.
6147///
6148/// <expression> ::= <function-param>
6149/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
6150/// <function-param> ::= fp <top-level CV-qualifiers>
6151/// <parameter-2 non-negative number> _ # L == 0, I > 0
6152/// <function-param> ::= fL <L-1 non-negative number>
6153/// p <top-level CV-qualifiers> _ # L > 0, I == 0
6154/// <function-param> ::= fL <L-1 non-negative number>
6155/// p <top-level CV-qualifiers>
6156/// <I-1 non-negative number> _ # L > 0, I > 0
6157///
6158/// L is the nesting depth of the parameter, defined as 1 if the
6159/// parameter comes from the innermost function prototype scope
6160/// enclosing the current context, 2 if from the next enclosing
6161/// function prototype scope, and so on, with one special case: if
6162/// we've processed the full parameter clause for the innermost
6163/// function type, then L is one less. This definition conveniently
6164/// makes it irrelevant whether a function's result type was written
6165/// trailing or leading, but is otherwise overly complicated; the
6166/// numbering was first designed without considering references to
6167/// parameter in locations other than return types, and then the
6168/// mangling had to be generalized without changing the existing
6169/// manglings.
6170///
6171/// I is the zero-based index of the parameter within its parameter
6172/// declaration clause. Note that the original ABI document describes
6173/// this using 1-based ordinals.
6174void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
6175 unsigned parmDepth = parm->getFunctionScopeDepth();
6176 unsigned parmIndex = parm->getFunctionScopeIndex();
6177
6178 // Compute 'L'.
6179 if (unsigned nestingDepth = FunctionTypeDepth.getNestingDepth(ParmDepth: parmDepth);
6180 nestingDepth == 0) {
6181 Out << "fp";
6182 } else {
6183 Out << "fL" << (nestingDepth - 1) << 'p';
6184 }
6185
6186 // Top-level qualifiers. We don't have to worry about arrays here,
6187 // because parameters declared as arrays should already have been
6188 // transformed to have pointer type. FIXME: apparently these don't
6189 // get mangled if used as an rvalue of a known non-class type?
6190 assert(!parm->getType()->isArrayType()
6191 && "parameter's type is still an array type?");
6192
6193 if (const DependentAddressSpaceType *DAST =
6194 dyn_cast<DependentAddressSpaceType>(Val: parm->getType())) {
6195 mangleQualifiers(Quals: DAST->getPointeeType().getQualifiers(), DAST);
6196 } else {
6197 mangleQualifiers(Quals: parm->getType().getQualifiers());
6198 }
6199
6200 // Parameter index.
6201 if (parmIndex != 0) {
6202 Out << (parmIndex - 1);
6203 }
6204 Out << '_';
6205}
6206
6207void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
6208 const CXXRecordDecl *InheritedFrom) {
6209 // <ctor-dtor-name> ::= C1 # complete object constructor
6210 // ::= C2 # base object constructor
6211 // ::= CI1 <type> # complete inheriting constructor
6212 // ::= CI2 <type> # base inheriting constructor
6213 //
6214 // In addition, C5 is a comdat name with C1 and C2 in it.
6215 // C4 represents a ctor declaration and is used by debuggers to look up
6216 // the various ctor variants.
6217 Out << 'C';
6218 if (InheritedFrom)
6219 Out << 'I';
6220 switch (T) {
6221 case Ctor_Complete:
6222 Out << '1';
6223 break;
6224 case Ctor_Base:
6225 Out << '2';
6226 break;
6227 case Ctor_Unified:
6228 Out << '4';
6229 break;
6230 case Ctor_Comdat:
6231 Out << '5';
6232 break;
6233 case Ctor_DefaultClosure:
6234 case Ctor_CopyingClosure:
6235 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
6236 }
6237 if (InheritedFrom)
6238 mangleName(GD: InheritedFrom);
6239}
6240
6241void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
6242 // <ctor-dtor-name> ::= D0 # deleting destructor
6243 // ::= D1 # complete object destructor
6244 // ::= D2 # base object destructor
6245 //
6246 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
6247 // D4 represents a dtor declaration and is used by debuggers to look up
6248 // the various dtor variants.
6249 switch (T) {
6250 case Dtor_Deleting:
6251 Out << "D0";
6252 break;
6253 case Dtor_Complete:
6254 Out << "D1";
6255 break;
6256 case Dtor_Base:
6257 Out << "D2";
6258 break;
6259 case Dtor_Unified:
6260 Out << "D4";
6261 break;
6262 case Dtor_Comdat:
6263 Out << "D5";
6264 break;
6265 case Dtor_VectorDeleting:
6266 llvm_unreachable("Itanium ABI does not use vector deleting dtors");
6267 }
6268}
6269
6270void CXXNameMangler::mangleReferenceToPack(const NamedDecl *Pack) {
6271 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Pack))
6272 mangleTemplateParameter(Depth: TTP->getDepth(), Index: TTP->getIndex());
6273 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Pack))
6274 mangleTemplateParameter(Depth: NTTP->getDepth(), Index: NTTP->getIndex());
6275 else if (const auto *TempTP = dyn_cast<TemplateTemplateParmDecl>(Val: Pack))
6276 mangleTemplateParameter(Depth: TempTP->getDepth(), Index: TempTP->getIndex());
6277 else
6278 mangleFunctionParam(parm: cast<ParmVarDecl>(Val: Pack));
6279}
6280
6281// Helper to provide ancillary information on a template used to mangle its
6282// arguments.
6283struct CXXNameMangler::TemplateArgManglingInfo {
6284 const CXXNameMangler &Mangler;
6285 TemplateDecl *ResolvedTemplate = nullptr;
6286 bool SeenPackExpansionIntoNonPack = false;
6287 const NamedDecl *UnresolvedExpandedPack = nullptr;
6288
6289 TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
6290 : Mangler(Mangler) {
6291 if (TemplateDecl *TD = TN.getAsTemplateDecl())
6292 ResolvedTemplate = TD;
6293 }
6294
6295 /// Information about how to mangle a template argument.
6296 struct Info {
6297 /// Do we need to mangle the template argument with an exactly correct type?
6298 bool NeedExactType;
6299 /// If we need to prefix the mangling with a mangling of the template
6300 /// parameter, the corresponding parameter.
6301 const NamedDecl *TemplateParameterToMangle;
6302 };
6303
6304 /// Determine whether the resolved template might be overloaded on its
6305 /// template parameter list. If so, the mangling needs to include enough
6306 /// information to reconstruct the template parameter list.
6307 bool isOverloadable() {
6308 // Function templates are generally overloadable. As a special case, a
6309 // member function template of a generic lambda is not overloadable.
6310 if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(Val: ResolvedTemplate)) {
6311 auto *RD = dyn_cast<CXXRecordDecl>(Val: FTD->getDeclContext());
6312 if (!RD || !RD->isGenericLambda())
6313 return true;
6314 }
6315
6316 // All other templates are not overloadable. Partial specializations would
6317 // be, but we never mangle them.
6318 return false;
6319 }
6320
6321 /// Determine whether we need to prefix this <template-arg> mangling with a
6322 /// <template-param-decl>. This happens if the natural template parameter for
6323 /// the argument mangling is not the same as the actual template parameter.
6324 bool needToMangleTemplateParam(const NamedDecl *Param,
6325 const TemplateArgument &Arg) {
6326 // For a template type parameter, the natural parameter is 'typename T'.
6327 // The actual parameter might be constrained.
6328 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
6329 return TTP->hasTypeConstraint();
6330
6331 if (Arg.getKind() == TemplateArgument::Pack) {
6332 // For an empty pack, the natural parameter is `typename...`.
6333 if (Arg.pack_size() == 0)
6334 return true;
6335
6336 // For any other pack, we use the first argument to determine the natural
6337 // template parameter.
6338 return needToMangleTemplateParam(Param, Arg: *Arg.pack_begin());
6339 }
6340
6341 // For a non-type template parameter, the natural parameter is `T V` (for a
6342 // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
6343 // type of the argument, which we require to exactly match. If the actual
6344 // parameter has a deduced or instantiation-dependent type, it is not
6345 // equivalent to the natural parameter.
6346 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
6347 return NTTP->getType()->isInstantiationDependentType() ||
6348 NTTP->getType()->getContainedDeducedType();
6349
6350 // For a template template parameter, the template-head might differ from
6351 // that of the template.
6352 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6353 TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
6354 assert(!ArgTemplateName.getTemplateDeclAndDefaultArgs().second &&
6355 "A DeducedTemplateName shouldn't escape partial ordering");
6356 const TemplateDecl *ArgTemplate =
6357 ArgTemplateName.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6358 if (!ArgTemplate)
6359 return true;
6360
6361 // Mangle the template parameter list of the parameter and argument to see
6362 // if they are the same. We can't use Profile for this, because it can't
6363 // model the depth difference between parameter and argument and might not
6364 // necessarily have the same definition of "identical" that we use here --
6365 // that is, same mangling.
6366 auto MangleTemplateParamListToString =
6367 [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
6368 unsigned DepthOffset) {
6369 llvm::raw_svector_ostream Stream(Buffer);
6370 CXXNameMangler(Mangler.Context, Stream,
6371 WithTemplateDepthOffset{.Offset: DepthOffset})
6372 .mangleTemplateParameterList(Params);
6373 };
6374 llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
6375 MangleTemplateParamListToString(ParamTemplateHead,
6376 TTP->getTemplateParameters(), 0);
6377 // Add the depth of the parameter's template parameter list to all
6378 // parameters appearing in the argument to make the indexes line up
6379 // properly.
6380 MangleTemplateParamListToString(ArgTemplateHead,
6381 ArgTemplate->getTemplateParameters(),
6382 TTP->getTemplateParameters()->getDepth());
6383 return ParamTemplateHead != ArgTemplateHead;
6384 }
6385
6386 /// Determine information about how this template argument should be mangled.
6387 /// This should be called exactly once for each parameter / argument pair, in
6388 /// order.
6389 Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {
6390 // We need correct types when the template-name is unresolved or when it
6391 // names a template that is able to be overloaded.
6392 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
6393 return {.NeedExactType: true, .TemplateParameterToMangle: nullptr};
6394
6395 // Move to the next parameter.
6396 const NamedDecl *Param = UnresolvedExpandedPack;
6397 if (!Param) {
6398 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
6399 "no parameter for argument");
6400 Param = ResolvedTemplate->getTemplateParameters()->getParam(Idx: ParamIdx);
6401
6402 // If we reach a parameter pack whose argument isn't in pack form, that
6403 // means Sema couldn't or didn't figure out which arguments belonged to
6404 // it, because it contains a pack expansion or because Sema bailed out of
6405 // computing parameter / argument correspondence before this point. Track
6406 // the pack as the corresponding parameter for all further template
6407 // arguments until we hit a pack expansion, at which point we don't know
6408 // the correspondence between parameters and arguments at all.
6409 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
6410 UnresolvedExpandedPack = Param;
6411 }
6412 }
6413
6414 // If we encounter a pack argument that is expanded into a non-pack
6415 // parameter, we can no longer track parameter / argument correspondence,
6416 // and need to use exact types from this point onwards.
6417 if (Arg.isPackExpansion() &&
6418 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
6419 SeenPackExpansionIntoNonPack = true;
6420 return {.NeedExactType: true, .TemplateParameterToMangle: nullptr};
6421 }
6422
6423 // We need exact types for arguments of a template that might be overloaded
6424 // on template parameter type.
6425 if (isOverloadable())
6426 return {.NeedExactType: true, .TemplateParameterToMangle: needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
6427
6428 // Otherwise, we only need a correct type if the parameter has a deduced
6429 // type.
6430 //
6431 // Note: for an expanded parameter pack, getType() returns the type prior
6432 // to expansion. We could ask for the expanded type with getExpansionType(),
6433 // but it doesn't matter because substitution and expansion don't affect
6434 // whether a deduced type appears in the type.
6435 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param);
6436 bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
6437 return {.NeedExactType: NeedExactType, .TemplateParameterToMangle: nullptr};
6438 }
6439
6440 /// Determine if we should mangle a requires-clause after the template
6441 /// argument list. If so, returns the expression to mangle.
6442 const Expr *getTrailingRequiresClauseToMangle() {
6443 if (!isOverloadable())
6444 return nullptr;
6445 return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
6446 }
6447};
6448
6449void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6450 const TemplateArgumentLoc *TemplateArgs,
6451 unsigned NumTemplateArgs) {
6452 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6453 Out << 'I';
6454 TemplateArgManglingInfo Info(*this, TN);
6455 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
6456 mangleTemplateArg(Info, Index: i, A: TemplateArgs[i].getArgument());
6457 }
6458 mangleRequiresClause(RequiresClause: Info.getTrailingRequiresClauseToMangle());
6459 Out << 'E';
6460}
6461
6462void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6463 const TemplateArgumentList &AL) {
6464 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6465 Out << 'I';
6466 TemplateArgManglingInfo Info(*this, TN);
6467 for (unsigned i = 0, e = AL.size(); i != e; ++i) {
6468 mangleTemplateArg(Info, Index: i, A: AL[i]);
6469 }
6470 mangleRequiresClause(RequiresClause: Info.getTrailingRequiresClauseToMangle());
6471 Out << 'E';
6472}
6473
6474void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
6475 ArrayRef<TemplateArgument> Args) {
6476 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
6477 Out << 'I';
6478 TemplateArgManglingInfo Info(*this, TN);
6479 for (unsigned i = 0; i != Args.size(); ++i) {
6480 mangleTemplateArg(Info, Index: i, A: Args[i]);
6481 }
6482 mangleRequiresClause(RequiresClause: Info.getTrailingRequiresClauseToMangle());
6483 Out << 'E';
6484}
6485
6486void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
6487 unsigned Index, TemplateArgument A) {
6488 TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(ParamIdx: Index, Arg: A);
6489
6490 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6491 if (ArgInfo.TemplateParameterToMangle &&
6492 !isCompatibleWith(Ver: LangOptions::ClangABI::Ver17)) {
6493 // The template parameter is mangled if the mangling would otherwise be
6494 // ambiguous.
6495 //
6496 // <template-arg> ::= <template-param-decl> <template-arg>
6497 //
6498 // Clang 17 and before did not do this.
6499 mangleTemplateParamDecl(Decl: ArgInfo.TemplateParameterToMangle);
6500 }
6501
6502 mangleTemplateArg(A, NeedExactType: ArgInfo.NeedExactType);
6503}
6504
6505void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
6506 // <template-arg> ::= <type> # type or template
6507 // ::= X <expression> E # expression
6508 // ::= <expr-primary> # simple expressions
6509 // ::= J <template-arg>* E # argument pack
6510 if (!A.isInstantiationDependent() || A.isDependent())
6511 A = Context.getASTContext().getCanonicalTemplateArgument(Arg: A);
6512
6513 switch (A.getKind()) {
6514 case TemplateArgument::Null:
6515 llvm_unreachable("Cannot mangle NULL template argument");
6516
6517 case TemplateArgument::Type:
6518 mangleType(T: A.getAsType());
6519 break;
6520 case TemplateArgument::Template:
6521 // This is mangled as <type>.
6522 mangleType(TN: A.getAsTemplate());
6523 break;
6524 case TemplateArgument::TemplateExpansion:
6525 // <type> ::= Dp <type> # pack expansion (C++0x)
6526 Out << "Dp";
6527 mangleType(TN: A.getAsTemplateOrTemplatePattern());
6528 break;
6529 case TemplateArgument::Expression:
6530 mangleTemplateArgExpr(E: A.getAsExpr());
6531 break;
6532 case TemplateArgument::Integral:
6533 mangleIntegerLiteral(T: A.getIntegralType(), Value: A.getAsIntegral());
6534 break;
6535 case TemplateArgument::Declaration: {
6536 // <expr-primary> ::= L <mangled-name> E # external name
6537 ValueDecl *D = A.getAsDecl();
6538
6539 // Template parameter objects are modeled by reproducing a source form
6540 // produced as if by aggregate initialization.
6541 if (A.getParamTypeForDecl()->isRecordType()) {
6542 auto *TPO = cast<TemplateParamObjectDecl>(Val: D);
6543 mangleValueInTemplateArg(T: TPO->getType().getUnqualifiedType(),
6544 V: TPO->getValue(), /*TopLevel=*/true,
6545 NeedExactType);
6546 break;
6547 }
6548
6549 ASTContext &Ctx = Context.getASTContext();
6550 APValue Value;
6551 if (D->isCXXInstanceMember())
6552 // Simple pointer-to-member with no conversion.
6553 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
6554 else if (D->getType()->isArrayType() &&
6555 Ctx.hasSimilarType(T1: Ctx.getDecayedType(T: D->getType()),
6556 T2: A.getParamTypeForDecl()) &&
6557 !isCompatibleWith(Ver: LangOptions::ClangABI::Ver11))
6558 // Build a value corresponding to this implicit array-to-pointer decay.
6559 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6560 {APValue::LValuePathEntry::ArrayIndex(Index: 0)},
6561 /*OnePastTheEnd=*/false);
6562 else
6563 // Regular pointer or reference to a declaration.
6564 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6565 ArrayRef<APValue::LValuePathEntry>(),
6566 /*OnePastTheEnd=*/false);
6567 mangleValueInTemplateArg(T: A.getParamTypeForDecl(), V: Value, /*TopLevel=*/true,
6568 NeedExactType);
6569 break;
6570 }
6571 case TemplateArgument::NullPtr: {
6572 mangleNullPointer(T: A.getNullPtrType());
6573 break;
6574 }
6575 case TemplateArgument::StructuralValue:
6576 mangleValueInTemplateArg(T: A.getStructuralValueType(),
6577 V: A.getAsStructuralValue(),
6578 /*TopLevel=*/true, NeedExactType);
6579 break;
6580 case TemplateArgument::Pack: {
6581 // <template-arg> ::= J <template-arg>* E
6582 Out << 'J';
6583 for (const auto &P : A.pack_elements())
6584 mangleTemplateArg(A: P, NeedExactType);
6585 Out << 'E';
6586 }
6587 }
6588}
6589
6590void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6591 if (!isCompatibleWith(Ver: LangOptions::ClangABI::Ver11)) {
6592 mangleExpression(E, Arity: UnknownArity, /*AsTemplateArg=*/true);
6593 return;
6594 }
6595
6596 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6597 // correctly in cases where the template argument was
6598 // constructed from an expression rather than an already-evaluated
6599 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6600 // 'Li0E'.
6601 //
6602 // We did special-case DeclRefExpr to attempt to DTRT for that one
6603 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6604 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6605 // the proper 'Xfp_E'.
6606 E = E->IgnoreParenImpCasts();
6607 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
6608 const ValueDecl *D = DRE->getDecl();
6609 if (isa<VarDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
6610 Out << 'L';
6611 mangle(GD: D);
6612 Out << 'E';
6613 return;
6614 }
6615 }
6616 Out << 'X';
6617 mangleExpression(E);
6618 Out << 'E';
6619}
6620
6621/// Determine whether a given value is equivalent to zero-initialization for
6622/// the purpose of discarding a trailing portion of a 'tl' mangling.
6623///
6624/// Note that this is not in general equivalent to determining whether the
6625/// value has an all-zeroes bit pattern.
6626static bool isZeroInitialized(QualType T, const APValue &V) {
6627 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6628 // pathological cases due to using this, but it's a little awkward
6629 // to do this in linear time in general.
6630 switch (V.getKind()) {
6631 case APValue::None:
6632 case APValue::Indeterminate:
6633 case APValue::AddrLabelDiff:
6634 return false;
6635
6636 case APValue::Struct: {
6637 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6638 assert(RD && "unexpected type for record value");
6639 unsigned I = 0;
6640 for (const CXXBaseSpecifier &BS : RD->bases()) {
6641 if (!isZeroInitialized(T: BS.getType(), V: V.getStructBase(i: I)))
6642 return false;
6643 ++I;
6644 }
6645 I = 0;
6646 for (const FieldDecl *FD : RD->fields()) {
6647 if (!FD->isUnnamedBitField() &&
6648 !isZeroInitialized(T: FD->getType(), V: V.getStructField(i: I)))
6649 return false;
6650 ++I;
6651 }
6652 return true;
6653 }
6654
6655 case APValue::Union: {
6656 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6657 assert(RD && "unexpected type for union value");
6658 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6659 for (const FieldDecl *FD : RD->fields()) {
6660 if (!FD->isUnnamedBitField())
6661 return V.getUnionField() && declaresSameEntity(D1: FD, D2: V.getUnionField()) &&
6662 isZeroInitialized(T: FD->getType(), V: V.getUnionValue());
6663 }
6664 // If there are no fields (other than unnamed bitfields), the value is
6665 // necessarily zero-initialized.
6666 return true;
6667 }
6668
6669 case APValue::Array: {
6670 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6671 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6672 if (!isZeroInitialized(T: ElemT, V: V.getArrayInitializedElt(I)))
6673 return false;
6674 return !V.hasArrayFiller() || isZeroInitialized(T: ElemT, V: V.getArrayFiller());
6675 }
6676
6677 case APValue::Vector: {
6678 const VectorType *VT = T->castAs<VectorType>();
6679 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6680 if (!isZeroInitialized(T: VT->getElementType(), V: V.getVectorElt(I)))
6681 return false;
6682 return true;
6683 }
6684
6685 case APValue::Matrix:
6686 llvm_unreachable("Matrix APValues not yet supported");
6687
6688 case APValue::Int:
6689 return !V.getInt();
6690
6691 case APValue::Float:
6692 return V.getFloat().isPosZero();
6693
6694 case APValue::FixedPoint:
6695 return !V.getFixedPoint().getValue();
6696
6697 case APValue::ComplexFloat:
6698 return V.getComplexFloatReal().isPosZero() &&
6699 V.getComplexFloatImag().isPosZero();
6700
6701 case APValue::ComplexInt:
6702 return !V.getComplexIntReal() && !V.getComplexIntImag();
6703
6704 case APValue::LValue:
6705 return V.isNullPointer();
6706
6707 case APValue::MemberPointer:
6708 return !V.getMemberPointerDecl();
6709
6710 case APValue::Reflection:
6711 return !V.getReflectionOpaqueOperand();
6712 }
6713
6714 llvm_unreachable("Unhandled APValue::ValueKind enum");
6715}
6716
6717static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6718 QualType T = LV.getLValueBase().getType();
6719 for (APValue::LValuePathEntry E : LV.getLValuePath()) {
6720 if (const ArrayType *AT = Ctx.getAsArrayType(T))
6721 T = AT->getElementType();
6722 else if (const FieldDecl *FD =
6723 dyn_cast<FieldDecl>(Val: E.getAsBaseOrMember().getPointer()))
6724 T = FD->getType();
6725 else
6726 T = Ctx.getCanonicalTagType(
6727 TD: cast<CXXRecordDecl>(Val: E.getAsBaseOrMember().getPointer()));
6728 }
6729 return T;
6730}
6731
6732static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
6733 DiagnosticsEngine &Diags,
6734 const FieldDecl *FD) {
6735 // According to:
6736 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6737 // For the purposes of mangling, the name of an anonymous union is considered
6738 // to be the name of the first named data member found by a pre-order,
6739 // depth-first, declaration-order walk of the data members of the anonymous
6740 // union.
6741
6742 if (FD->getIdentifier())
6743 return FD->getIdentifier();
6744
6745 // The only cases where the identifer of a FieldDecl would be blank is if the
6746 // field represents an anonymous record type or if it is an unnamed bitfield.
6747 // There is no type to descend into in the case of a bitfield, so we can just
6748 // return nullptr in that case.
6749 if (FD->isBitField())
6750 return nullptr;
6751 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6752
6753 // Consider only the fields in declaration order, searched depth-first. We
6754 // don't care about the active member of the union, as all we are doing is
6755 // looking for a valid name. We also don't check bases, due to guidance from
6756 // the Itanium ABI folks.
6757 for (const FieldDecl *RDField : RD->fields()) {
6758 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, FD: RDField))
6759 return II;
6760 }
6761
6762 // According to the Itanium ABI: If there is no such data member (i.e., if all
6763 // of the data members in the union are unnamed), then there is no way for a
6764 // program to refer to the anonymous union, and there is therefore no need to
6765 // mangle its name. However, we should diagnose this anyway.
6766 Diags.Report(Loc: UnionLoc, DiagID: diag::err_unsupported_itanium_mangling)
6767 << UnsupportedItaniumManglingKind::UnnamedUnionNTTP;
6768
6769 return nullptr;
6770}
6771
6772void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6773 bool TopLevel,
6774 bool NeedExactType) {
6775 // Ignore all top-level cv-qualifiers, to match GCC.
6776 Qualifiers Quals;
6777 T = getASTContext().getUnqualifiedArrayType(T, Quals);
6778
6779 // A top-level expression that's not a primary expression is wrapped in X...E.
6780 bool IsPrimaryExpr = true;
6781 auto NotPrimaryExpr = [&] {
6782 if (TopLevel && IsPrimaryExpr)
6783 Out << 'X';
6784 IsPrimaryExpr = false;
6785 };
6786
6787 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6788 switch (V.getKind()) {
6789 case APValue::None:
6790 case APValue::Indeterminate:
6791 Out << 'L';
6792 mangleType(T);
6793 Out << 'E';
6794 break;
6795
6796 case APValue::AddrLabelDiff:
6797 llvm_unreachable("unexpected value kind in template argument");
6798
6799 case APValue::Struct: {
6800 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6801 assert(RD && "unexpected type for record value");
6802
6803 // Drop trailing zero-initialized elements.
6804 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
6805 while (
6806 !Fields.empty() &&
6807 (Fields.back()->isUnnamedBitField() ||
6808 isZeroInitialized(T: Fields.back()->getType(),
6809 V: V.getStructField(i: Fields.back()->getFieldIndex())))) {
6810 Fields.pop_back();
6811 }
6812 ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
6813 if (Fields.empty()) {
6814 while (!Bases.empty() &&
6815 isZeroInitialized(T: Bases.back().getType(),
6816 V: V.getStructBase(i: Bases.size() - 1)))
6817 Bases = Bases.drop_back();
6818 }
6819
6820 // <expression> ::= tl <type> <braced-expression>* E
6821 NotPrimaryExpr();
6822 Out << "tl";
6823 mangleType(T);
6824 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6825 mangleValueInTemplateArg(T: Bases[I].getType(), V: V.getStructBase(i: I), TopLevel: false);
6826 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
6827 if (Fields[I]->isUnnamedBitField())
6828 continue;
6829 mangleValueInTemplateArg(T: Fields[I]->getType(),
6830 V: V.getStructField(i: Fields[I]->getFieldIndex()),
6831 TopLevel: false);
6832 }
6833 Out << 'E';
6834 break;
6835 }
6836
6837 case APValue::Union: {
6838 assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6839 const FieldDecl *FD = V.getUnionField();
6840
6841 if (!FD) {
6842 Out << 'L';
6843 mangleType(T);
6844 Out << 'E';
6845 break;
6846 }
6847
6848 // <braced-expression> ::= di <field source-name> <braced-expression>
6849 NotPrimaryExpr();
6850 Out << "tl";
6851 mangleType(T);
6852 if (!isZeroInitialized(T, V)) {
6853 Out << "di";
6854 IdentifierInfo *II = (getUnionInitName(
6855 UnionLoc: T->getAsCXXRecordDecl()->getLocation(), Diags&: Context.getDiags(), FD));
6856 if (II)
6857 mangleSourceName(II);
6858 mangleValueInTemplateArg(T: FD->getType(), V: V.getUnionValue(), TopLevel: false);
6859 }
6860 Out << 'E';
6861 break;
6862 }
6863
6864 case APValue::Array: {
6865 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6866
6867 NotPrimaryExpr();
6868 Out << "tl";
6869 mangleType(T);
6870
6871 // Drop trailing zero-initialized elements.
6872 unsigned N = V.getArraySize();
6873 if (!V.hasArrayFiller() || isZeroInitialized(T: ElemT, V: V.getArrayFiller())) {
6874 N = V.getArrayInitializedElts();
6875 while (N && isZeroInitialized(T: ElemT, V: V.getArrayInitializedElt(I: N - 1)))
6876 --N;
6877 }
6878
6879 for (unsigned I = 0; I != N; ++I) {
6880 const APValue &Elem = I < V.getArrayInitializedElts()
6881 ? V.getArrayInitializedElt(I)
6882 : V.getArrayFiller();
6883 mangleValueInTemplateArg(T: ElemT, V: Elem, TopLevel: false);
6884 }
6885 Out << 'E';
6886 break;
6887 }
6888
6889 case APValue::Vector: {
6890 const VectorType *VT = T->castAs<VectorType>();
6891
6892 NotPrimaryExpr();
6893 Out << "tl";
6894 mangleType(T);
6895 unsigned N = V.getVectorLength();
6896 while (N && isZeroInitialized(T: VT->getElementType(), V: V.getVectorElt(I: N - 1)))
6897 --N;
6898 for (unsigned I = 0; I != N; ++I)
6899 mangleValueInTemplateArg(T: VT->getElementType(), V: V.getVectorElt(I), TopLevel: false);
6900 Out << 'E';
6901 break;
6902 }
6903
6904 case APValue::Matrix:
6905 llvm_unreachable("Matrix template argument mangling not yet supported");
6906
6907 case APValue::Int:
6908 mangleIntegerLiteral(T, Value: V.getInt());
6909 break;
6910
6911 case APValue::Float:
6912 mangleFloatLiteral(T, V: V.getFloat());
6913 break;
6914
6915 case APValue::FixedPoint:
6916 mangleFixedPointLiteral();
6917 break;
6918
6919 case APValue::ComplexFloat: {
6920 const ComplexType *CT = T->castAs<ComplexType>();
6921 NotPrimaryExpr();
6922 Out << "tl";
6923 mangleType(T);
6924 if (!V.getComplexFloatReal().isPosZero() ||
6925 !V.getComplexFloatImag().isPosZero())
6926 mangleFloatLiteral(T: CT->getElementType(), V: V.getComplexFloatReal());
6927 if (!V.getComplexFloatImag().isPosZero())
6928 mangleFloatLiteral(T: CT->getElementType(), V: V.getComplexFloatImag());
6929 Out << 'E';
6930 break;
6931 }
6932
6933 case APValue::ComplexInt: {
6934 const ComplexType *CT = T->castAs<ComplexType>();
6935 NotPrimaryExpr();
6936 Out << "tl";
6937 mangleType(T);
6938 if (V.getComplexIntReal().getBoolValue() ||
6939 V.getComplexIntImag().getBoolValue())
6940 mangleIntegerLiteral(T: CT->getElementType(), Value: V.getComplexIntReal());
6941 if (V.getComplexIntImag().getBoolValue())
6942 mangleIntegerLiteral(T: CT->getElementType(), Value: V.getComplexIntImag());
6943 Out << 'E';
6944 break;
6945 }
6946
6947 case APValue::LValue: {
6948 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6949 assert((T->isPointerOrReferenceType()) &&
6950 "unexpected type for LValue template arg");
6951
6952 if (V.isNullPointer()) {
6953 mangleNullPointer(T);
6954 break;
6955 }
6956
6957 APValue::LValueBase B = V.getLValueBase();
6958 if (!B) {
6959 // Non-standard mangling for integer cast to a pointer; this can only
6960 // occur as an extension.
6961 CharUnits Offset = V.getLValueOffset();
6962 if (Offset.isZero()) {
6963 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6964 // a cast, because L <type> 0 E means something else.
6965 NotPrimaryExpr();
6966 Out << "rc";
6967 mangleType(T);
6968 Out << "Li0E";
6969 if (TopLevel)
6970 Out << 'E';
6971 } else {
6972 Out << "L";
6973 mangleType(T);
6974 Out << Offset.getQuantity() << 'E';
6975 }
6976 break;
6977 }
6978
6979 ASTContext &Ctx = Context.getASTContext();
6980
6981 enum { Base, Offset, Path } Kind;
6982 if (!V.hasLValuePath()) {
6983 // Mangle as (T*)((char*)&base + N).
6984 if (T->isReferenceType()) {
6985 NotPrimaryExpr();
6986 Out << "decvP";
6987 mangleType(T: T->getPointeeType());
6988 } else {
6989 NotPrimaryExpr();
6990 Out << "cv";
6991 mangleType(T);
6992 }
6993 Out << "plcvPcad";
6994 Kind = Offset;
6995 } else {
6996 // Clang 11 and before mangled an array subject to array-to-pointer decay
6997 // as if it were the declaration itself.
6998 bool IsArrayToPointerDecayMangledAsDecl = false;
6999 if (TopLevel && isCompatibleWith(Ver: LangOptions::ClangABI::Ver11)) {
7000 QualType BType = B.getType();
7001 IsArrayToPointerDecayMangledAsDecl =
7002 BType->isArrayType() && V.getLValuePath().size() == 1 &&
7003 V.getLValuePath()[0].getAsArrayIndex() == 0 &&
7004 Ctx.hasSimilarType(T1: T, T2: Ctx.getDecayedType(T: BType));
7005 }
7006
7007 if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) &&
7008 !IsArrayToPointerDecayMangledAsDecl) {
7009 NotPrimaryExpr();
7010 // A final conversion to the template parameter's type is usually
7011 // folded into the 'so' mangling, but we can't do that for 'void*'
7012 // parameters without introducing collisions.
7013 if (NeedExactType && T->isVoidPointerType()) {
7014 Out << "cv";
7015 mangleType(T);
7016 }
7017 if (T->isPointerType())
7018 Out << "ad";
7019 Out << "so";
7020 mangleType(T: T->isVoidPointerType()
7021 ? getLValueType(Ctx, LV: V).getUnqualifiedType()
7022 : T->getPointeeType());
7023 Kind = Path;
7024 } else {
7025 if (NeedExactType &&
7026 !Ctx.hasSameType(T1: T->getPointeeType(), T2: getLValueType(Ctx, LV: V)) &&
7027 !isCompatibleWith(Ver: LangOptions::ClangABI::Ver11)) {
7028 NotPrimaryExpr();
7029 Out << "cv";
7030 mangleType(T);
7031 }
7032 if (T->isPointerType()) {
7033 NotPrimaryExpr();
7034 Out << "ad";
7035 }
7036 Kind = Base;
7037 }
7038 }
7039
7040 QualType TypeSoFar = B.getType();
7041 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
7042 Out << 'L';
7043 mangle(GD: VD);
7044 Out << 'E';
7045 } else if (auto *E = B.dyn_cast<const Expr*>()) {
7046 NotPrimaryExpr();
7047 mangleExpression(E);
7048 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
7049 NotPrimaryExpr();
7050 Out << "ti";
7051 mangleType(T: QualType(TI.getType(), 0));
7052 } else {
7053 // We should never see dynamic allocations here.
7054 llvm_unreachable("unexpected lvalue base kind in template argument");
7055 }
7056
7057 switch (Kind) {
7058 case Base:
7059 break;
7060
7061 case Offset:
7062 Out << 'L';
7063 mangleType(T: Ctx.getPointerDiffType());
7064 mangleNumber(Number: V.getLValueOffset().getQuantity());
7065 Out << 'E';
7066 break;
7067
7068 case Path:
7069 // <expression> ::= so <referent type> <expr> [<offset number>]
7070 // <union-selector>* [p] E
7071 if (!V.getLValueOffset().isZero())
7072 mangleNumber(Number: V.getLValueOffset().getQuantity());
7073
7074 // We model a past-the-end array pointer as array indexing with index N,
7075 // not with the "past the end" flag. Compensate for that.
7076 bool OnePastTheEnd = V.isLValueOnePastTheEnd();
7077
7078 for (APValue::LValuePathEntry E : V.getLValuePath()) {
7079 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
7080 if (auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
7081 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
7082 TypeSoFar = AT->getElementType();
7083 } else {
7084 const Decl *D = E.getAsBaseOrMember().getPointer();
7085 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
7086 // <union-selector> ::= _ <number>
7087 if (FD->getParent()->isUnion()) {
7088 Out << '_';
7089 if (FD->getFieldIndex())
7090 Out << (FD->getFieldIndex() - 1);
7091 }
7092 TypeSoFar = FD->getType();
7093 } else {
7094 TypeSoFar = Ctx.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: D));
7095 }
7096 }
7097 }
7098
7099 if (OnePastTheEnd)
7100 Out << 'p';
7101 Out << 'E';
7102 break;
7103 }
7104
7105 break;
7106 }
7107
7108 case APValue::Reflection: {
7109 mangleReflection(Kind: V.getReflectionOperandKind(),
7110 OpaqueOperand: V.getReflectionOpaqueOperand());
7111 break;
7112 }
7113
7114 case APValue::MemberPointer:
7115 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
7116 if (!V.getMemberPointerDecl()) {
7117 mangleNullPointer(T);
7118 break;
7119 }
7120
7121 ASTContext &Ctx = Context.getASTContext();
7122
7123 NotPrimaryExpr();
7124 if (!V.getMemberPointerPath().empty()) {
7125 Out << "mc";
7126 mangleType(T);
7127 } else if (NeedExactType &&
7128 !Ctx.hasSameType(
7129 T1: T->castAs<MemberPointerType>()->getPointeeType(),
7130 T2: V.getMemberPointerDecl()->getType()) &&
7131 !isCompatibleWith(Ver: LangOptions::ClangABI::Ver11)) {
7132 Out << "cv";
7133 mangleType(T);
7134 }
7135 Out << "adL";
7136 mangle(GD: V.getMemberPointerDecl());
7137 Out << 'E';
7138 if (!V.getMemberPointerPath().empty()) {
7139 CharUnits Offset =
7140 Context.getASTContext().getMemberPointerPathAdjustment(MP: V);
7141 if (!Offset.isZero())
7142 mangleNumber(Number: Offset.getQuantity());
7143 Out << 'E';
7144 }
7145 break;
7146 }
7147
7148 if (TopLevel && !IsPrimaryExpr)
7149 Out << 'E';
7150}
7151
7152void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
7153 // <template-param> ::= T_ # first template parameter
7154 // ::= T <parameter-2 non-negative number> _
7155 // ::= TL <L-1 non-negative number> __
7156 // ::= TL <L-1 non-negative number> _
7157 // <parameter-2 non-negative number> _
7158 //
7159 // The latter two manglings are from a proposal here:
7160 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
7161 Out << 'T';
7162 Depth += TemplateDepthOffset;
7163 if (Depth != 0)
7164 Out << 'L' << (Depth - 1) << '_';
7165 if (Index != 0)
7166 Out << (Index - 1);
7167 Out << '_';
7168}
7169
7170void CXXNameMangler::mangleSeqID(unsigned SeqID) {
7171 if (SeqID == 0) {
7172 // Nothing.
7173 } else if (SeqID == 1) {
7174 Out << '0';
7175 } else {
7176 SeqID--;
7177
7178 // <seq-id> is encoded in base-36, using digits and upper case letters.
7179 char Buffer[7]; // log(2**32) / log(36) ~= 7
7180 MutableArrayRef<char> BufferRef(Buffer);
7181 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
7182
7183 for (; SeqID != 0; SeqID /= 36) {
7184 unsigned C = SeqID % 36;
7185 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
7186 }
7187
7188 Out.write(Ptr: I.base(), Size: I - BufferRef.rbegin());
7189 }
7190 Out << '_';
7191}
7192
7193void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
7194 bool result = mangleSubstitution(Template: tname);
7195 assert(result && "no existing substitution for template name");
7196 (void) result;
7197}
7198
7199// <substitution> ::= S <seq-id> _
7200// ::= S_
7201bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
7202 // Try one of the standard substitutions first.
7203 if (mangleStandardSubstitution(ND))
7204 return true;
7205
7206 ND = cast<NamedDecl>(Val: ND->getCanonicalDecl());
7207 return mangleSubstitution(Ptr: reinterpret_cast<uintptr_t>(ND));
7208}
7209
7210/// Determine whether the given type has any qualifiers that are relevant for
7211/// substitutions.
7212static bool hasMangledSubstitutionQualifiers(QualType T) {
7213 Qualifiers Qs = T.getQualifiers();
7214 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
7215}
7216
7217bool CXXNameMangler::mangleSubstitution(QualType T) {
7218 if (!hasMangledSubstitutionQualifiers(T)) {
7219 if (const auto *RD = T->getAsCXXRecordDecl())
7220 return mangleSubstitution(ND: RD);
7221 }
7222
7223 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
7224
7225 return mangleSubstitution(Ptr: TypePtr);
7226}
7227
7228bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
7229 if (TemplateDecl *TD = Template.getAsTemplateDecl())
7230 return mangleSubstitution(ND: TD);
7231
7232 Template = Context.getASTContext().getCanonicalTemplateName(Name: Template);
7233 return mangleSubstitution(
7234 Ptr: reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
7235}
7236
7237bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
7238 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Val: Ptr);
7239 if (I == Substitutions.end())
7240 return false;
7241
7242 unsigned SeqID = I->second;
7243 Out << 'S';
7244 mangleSeqID(SeqID);
7245
7246 return true;
7247}
7248
7249/// Returns whether S is a template specialization of std::Name with a single
7250/// argument of type A.
7251bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
7252 QualType A) {
7253 if (S.isNull())
7254 return false;
7255
7256 const RecordType *RT = S->getAsCanonical<RecordType>();
7257 if (!RT)
7258 return false;
7259
7260 const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
7261 if (!SD || !SD->getIdentifier()->isStr(Str: Name))
7262 return false;
7263
7264 if (!isStdNamespace(DC: Context.getEffectiveDeclContext(D: SD)))
7265 return false;
7266
7267 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
7268 if (TemplateArgs.size() != 1)
7269 return false;
7270
7271 if (TemplateArgs[0].getAsType() != A)
7272 return false;
7273
7274 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
7275 return false;
7276
7277 return true;
7278}
7279
7280/// Returns whether SD is a template specialization std::Name<char,
7281/// std::char_traits<char> [, std::allocator<char>]>
7282/// HasAllocator controls whether the 3rd template argument is needed.
7283bool CXXNameMangler::isStdCharSpecialization(
7284 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
7285 bool HasAllocator) {
7286 if (!SD->getIdentifier()->isStr(Str: Name))
7287 return false;
7288
7289 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
7290 if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
7291 return false;
7292
7293 QualType A = TemplateArgs[0].getAsType();
7294 if (A.isNull())
7295 return false;
7296 // Plain 'char' is named Char_S or Char_U depending on the target ABI.
7297 if (!A->isSpecificBuiltinType(K: BuiltinType::Char_S) &&
7298 !A->isSpecificBuiltinType(K: BuiltinType::Char_U))
7299 return false;
7300
7301 if (!isSpecializedAs(S: TemplateArgs[1].getAsType(), Name: "char_traits", A))
7302 return false;
7303
7304 if (HasAllocator &&
7305 !isSpecializedAs(S: TemplateArgs[2].getAsType(), Name: "allocator", A))
7306 return false;
7307
7308 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
7309 return false;
7310
7311 return true;
7312}
7313
7314bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
7315 // <substitution> ::= St # ::std::
7316 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: ND)) {
7317 if (isStd(NS)) {
7318 Out << "St";
7319 return true;
7320 }
7321 return false;
7322 }
7323
7324 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(Val: ND)) {
7325 if (!isStdNamespace(DC: Context.getEffectiveDeclContext(D: TD)))
7326 return false;
7327
7328 if (TD->getOwningModuleForLinkage())
7329 return false;
7330
7331 // <substitution> ::= Sa # ::std::allocator
7332 if (TD->getIdentifier()->isStr(Str: "allocator")) {
7333 Out << "Sa";
7334 return true;
7335 }
7336
7337 // <<substitution> ::= Sb # ::std::basic_string
7338 if (TD->getIdentifier()->isStr(Str: "basic_string")) {
7339 Out << "Sb";
7340 return true;
7341 }
7342 return false;
7343 }
7344
7345 if (const ClassTemplateSpecializationDecl *SD =
7346 dyn_cast<ClassTemplateSpecializationDecl>(Val: ND)) {
7347 if (!isStdNamespace(DC: Context.getEffectiveDeclContext(D: SD)))
7348 return false;
7349
7350 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
7351 return false;
7352
7353 // <substitution> ::= Ss # ::std::basic_string<char,
7354 // ::std::char_traits<char>,
7355 // ::std::allocator<char> >
7356 if (isStdCharSpecialization(SD, Name: "basic_string", /*HasAllocator=*/true)) {
7357 Out << "Ss";
7358 return true;
7359 }
7360
7361 // <substitution> ::= Si # ::std::basic_istream<char,
7362 // ::std::char_traits<char> >
7363 if (isStdCharSpecialization(SD, Name: "basic_istream", /*HasAllocator=*/false)) {
7364 Out << "Si";
7365 return true;
7366 }
7367
7368 // <substitution> ::= So # ::std::basic_ostream<char,
7369 // ::std::char_traits<char> >
7370 if (isStdCharSpecialization(SD, Name: "basic_ostream", /*HasAllocator=*/false)) {
7371 Out << "So";
7372 return true;
7373 }
7374
7375 // <substitution> ::= Sd # ::std::basic_iostream<char,
7376 // ::std::char_traits<char> >
7377 if (isStdCharSpecialization(SD, Name: "basic_iostream", /*HasAllocator=*/false)) {
7378 Out << "Sd";
7379 return true;
7380 }
7381 return false;
7382 }
7383
7384 return false;
7385}
7386
7387void CXXNameMangler::addSubstitution(QualType T) {
7388 if (!hasMangledSubstitutionQualifiers(T)) {
7389 if (const auto *RD = T->getAsCXXRecordDecl()) {
7390 addSubstitution(ND: RD);
7391 return;
7392 }
7393 }
7394
7395 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
7396 addSubstitution(Ptr: TypePtr);
7397}
7398
7399void CXXNameMangler::addSubstitution(TemplateName Template) {
7400 if (TemplateDecl *TD = Template.getAsTemplateDecl())
7401 return addSubstitution(ND: TD);
7402
7403 Template = Context.getASTContext().getCanonicalTemplateName(Name: Template);
7404 addSubstitution(Ptr: reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
7405}
7406
7407void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
7408 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
7409 Substitutions[Ptr] = SeqID++;
7410}
7411
7412void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
7413 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
7414 if (Other->SeqID > SeqID) {
7415 Substitutions.swap(RHS&: Other->Substitutions);
7416 SeqID = Other->SeqID;
7417 }
7418}
7419
7420CXXNameMangler::AbiTagList
7421CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
7422 // When derived abi tags are disabled there is no need to make any list.
7423 if (DisableDerivedAbiTags)
7424 return AbiTagList();
7425
7426 llvm::raw_null_ostream NullOutStream;
7427 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
7428 TrackReturnTypeTags.disableDerivedAbiTags();
7429
7430 const FunctionProtoType *Proto =
7431 cast<FunctionProtoType>(Val: FD->getType()->getAs<FunctionType>());
7432 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
7433 TrackReturnTypeTags.FunctionTypeDepth.enterFunctionDeclSuffix();
7434 TrackReturnTypeTags.mangleType(T: Proto->getReturnType());
7435 TrackReturnTypeTags.FunctionTypeDepth.leaveFunctionDeclSuffix();
7436 TrackReturnTypeTags.FunctionTypeDepth.pop(Saved: saved);
7437
7438 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7439}
7440
7441CXXNameMangler::AbiTagList
7442CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
7443 // When derived abi tags are disabled there is no need to make any list.
7444 if (DisableDerivedAbiTags)
7445 return AbiTagList();
7446
7447 llvm::raw_null_ostream NullOutStream;
7448 CXXNameMangler TrackVariableType(*this, NullOutStream);
7449 TrackVariableType.disableDerivedAbiTags();
7450
7451 TrackVariableType.mangleType(T: VD->getType());
7452
7453 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
7454}
7455
7456bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
7457 const VarDecl *VD) {
7458 llvm::raw_null_ostream NullOutStream;
7459 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
7460 TrackAbiTags.mangle(GD: VD);
7461 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
7462}
7463
7464/// Mangles the name of the declaration \p GD and emits that name to the given
7465/// output stream \p Out.
7466void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
7467 raw_ostream &Out) {
7468 const NamedDecl *D = cast<NamedDecl>(Val: GD.getDecl());
7469 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
7470 "Invalid mangleName() call, argument is not a variable or function!");
7471
7472 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
7473 getASTContext().getSourceManager(),
7474 "Mangling declaration");
7475
7476 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: D)) {
7477 auto Type = GD.getCtorType();
7478 CXXNameMangler Mangler(*this, Out, CD, Type);
7479 return Mangler.mangle(GD: GlobalDecl(CD, Type));
7480 }
7481
7482 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: D)) {
7483 auto Type = GD.getDtorType();
7484 CXXNameMangler Mangler(*this, Out, DD, Type);
7485 return Mangler.mangle(GD: GlobalDecl(DD, Type));
7486 }
7487
7488 CXXNameMangler Mangler(*this, Out, D);
7489 Mangler.mangle(GD);
7490}
7491
7492void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
7493 raw_ostream &Out) {
7494 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
7495 Mangler.mangle(GD: GlobalDecl(D, Ctor_Comdat));
7496}
7497
7498void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
7499 raw_ostream &Out) {
7500 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
7501 Mangler.mangle(GD: GlobalDecl(D, Dtor_Comdat));
7502}
7503
7504/// Mangles the pointer authentication override attribute for classes
7505/// that have explicit overrides for the vtable authentication schema.
7506///
7507/// The override is mangled as a parameterized vendor extension as follows
7508///
7509/// <type> ::= U "__vtptrauth" I
7510/// <key>
7511/// <addressDiscriminated>
7512/// <extraDiscriminator>
7513/// E
7514///
7515/// The extra discriminator encodes the explicit value derived from the
7516/// override schema, e.g. if the override has specified type based
7517/// discrimination the encoded value will be the discriminator derived from the
7518/// type name.
7519static void mangleOverrideDiscrimination(CXXNameMangler &Mangler,
7520 ASTContext &Context,
7521 const ThunkInfo &Thunk) {
7522 auto &LangOpts = Context.getLangOpts();
7523 const CXXRecordDecl *ThisRD = Thunk.ThisType->getPointeeCXXRecordDecl();
7524 const CXXRecordDecl *PtrauthClassRD =
7525 Context.baseForVTableAuthentication(ThisClass: ThisRD);
7526 unsigned TypedDiscriminator =
7527 Context.getPointerAuthVTablePointerDiscriminator(RD: ThisRD,
7528 /*IsVTTEntry=*/false);
7529 Mangler.mangleVendorQualifier(name: "__vtptrauth");
7530 auto &ManglerStream = Mangler.getStream();
7531 ManglerStream << "I";
7532 if (const auto *ExplicitAuth =
7533 PtrauthClassRD->getAttr<VTablePointerAuthenticationAttr>()) {
7534 ManglerStream << "Lj" << ExplicitAuth->getKey();
7535
7536 if (ExplicitAuth->getAddressDiscrimination() ==
7537 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
7538 ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7539 else
7540 ManglerStream << "Lb"
7541 << (ExplicitAuth->getAddressDiscrimination() ==
7542 VTablePointerAuthenticationAttr::AddressDiscrimination);
7543
7544 switch (ExplicitAuth->getExtraDiscrimination()) {
7545 case VTablePointerAuthenticationAttr::DefaultExtraDiscrimination: {
7546 if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7547 ManglerStream << "Lj" << TypedDiscriminator;
7548 else
7549 ManglerStream << "Lj" << 0;
7550 break;
7551 }
7552 case VTablePointerAuthenticationAttr::TypeDiscrimination:
7553 ManglerStream << "Lj" << TypedDiscriminator;
7554 break;
7555 case VTablePointerAuthenticationAttr::CustomDiscrimination:
7556 ManglerStream << "Lj" << ExplicitAuth->getCustomDiscriminationValue();
7557 break;
7558 case VTablePointerAuthenticationAttr::NoExtraDiscrimination:
7559 ManglerStream << "Lj" << 0;
7560 break;
7561 }
7562 } else {
7563 ManglerStream << "Lj"
7564 << (unsigned)VTablePointerAuthenticationAttr::DefaultKey;
7565 ManglerStream << "Lb" << LangOpts.PointerAuthVTPtrAddressDiscrimination;
7566 if (LangOpts.PointerAuthVTPtrTypeDiscrimination)
7567 ManglerStream << "Lj" << TypedDiscriminator;
7568 else
7569 ManglerStream << "Lj" << 0;
7570 }
7571 ManglerStream << "E";
7572}
7573
7574void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
7575 const ThunkInfo &Thunk,
7576 bool ElideOverrideInfo,
7577 raw_ostream &Out) {
7578 // <special-name> ::= T <call-offset> <base encoding>
7579 // # base is the nominal target function of thunk
7580 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
7581 // # base is the nominal target function of thunk
7582 // # first call-offset is 'this' adjustment
7583 // # second call-offset is result adjustment
7584
7585 assert(!isa<CXXDestructorDecl>(MD) &&
7586 "Use mangleCXXDtor for destructor decls!");
7587 CXXNameMangler Mangler(*this, Out);
7588 Mangler.getStream() << "_ZT";
7589 if (!Thunk.Return.isEmpty())
7590 Mangler.getStream() << 'c';
7591
7592 // Mangle the 'this' pointer adjustment.
7593 Mangler.mangleCallOffset(NonVirtual: Thunk.This.NonVirtual,
7594 Virtual: Thunk.This.Virtual.Itanium.VCallOffsetOffset);
7595
7596 // Mangle the return pointer adjustment if there is one.
7597 if (!Thunk.Return.isEmpty())
7598 Mangler.mangleCallOffset(NonVirtual: Thunk.Return.NonVirtual,
7599 Virtual: Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
7600
7601 Mangler.mangleFunctionEncoding(GD: MD);
7602 if (!ElideOverrideInfo)
7603 mangleOverrideDiscrimination(Mangler, Context&: getASTContext(), Thunk);
7604}
7605
7606void ItaniumMangleContextImpl::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
7607 CXXDtorType Type,
7608 const ThunkInfo &Thunk,
7609 bool ElideOverrideInfo,
7610 raw_ostream &Out) {
7611 // <special-name> ::= T <call-offset> <base encoding>
7612 // # base is the nominal target function of thunk
7613 CXXNameMangler Mangler(*this, Out, DD, Type);
7614 Mangler.getStream() << "_ZT";
7615
7616 auto &ThisAdjustment = Thunk.This;
7617 // Mangle the 'this' pointer adjustment.
7618 Mangler.mangleCallOffset(NonVirtual: ThisAdjustment.NonVirtual,
7619 Virtual: ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
7620
7621 Mangler.mangleFunctionEncoding(GD: GlobalDecl(DD, Type));
7622 if (!ElideOverrideInfo)
7623 mangleOverrideDiscrimination(Mangler, Context&: getASTContext(), Thunk);
7624}
7625
7626/// Returns the mangled name for a guard variable for the passed in VarDecl.
7627void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
7628 raw_ostream &Out) {
7629 // <special-name> ::= GV <object name> # Guard variable for one-time
7630 // # initialization
7631 CXXNameMangler Mangler(*this, Out);
7632 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
7633 // be a bug that is fixed in trunk.
7634 Mangler.getStream() << "_ZGV";
7635 Mangler.mangleName(GD: D);
7636}
7637
7638void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
7639 raw_ostream &Out) {
7640 // These symbols are internal in the Itanium ABI, so the names don't matter.
7641 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
7642 // avoid duplicate symbols.
7643 Out << "__cxx_global_var_init";
7644}
7645
7646void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
7647 raw_ostream &Out) {
7648 // Prefix the mangling of D with __dtor_.
7649 CXXNameMangler Mangler(*this, Out);
7650 Mangler.getStream() << "__dtor_";
7651 if (shouldMangleDeclName(D))
7652 Mangler.mangle(GD: D);
7653 else
7654 Mangler.getStream() << D->getName();
7655}
7656
7657void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
7658 raw_ostream &Out) {
7659 // Clang generates these internal-linkage functions as part of its
7660 // implementation of the XL ABI.
7661 CXXNameMangler Mangler(*this, Out);
7662 Mangler.getStream() << "__finalize_";
7663 if (shouldMangleDeclName(D))
7664 Mangler.mangle(GD: D);
7665 else
7666 Mangler.getStream() << D->getName();
7667}
7668
7669void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7670 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7671 CXXNameMangler Mangler(*this, Out);
7672 Mangler.getStream() << "__filt_";
7673 auto *EnclosingFD = cast<FunctionDecl>(Val: EnclosingDecl.getDecl());
7674 if (shouldMangleDeclName(D: EnclosingFD))
7675 Mangler.mangle(GD: EnclosingDecl);
7676 else
7677 Mangler.getStream() << EnclosingFD->getName();
7678}
7679
7680void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7681 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7682 CXXNameMangler Mangler(*this, Out);
7683 Mangler.getStream() << "__fin_";
7684 auto *EnclosingFD = cast<FunctionDecl>(Val: EnclosingDecl.getDecl());
7685 if (shouldMangleDeclName(D: EnclosingFD))
7686 Mangler.mangle(GD: EnclosingDecl);
7687 else
7688 Mangler.getStream() << EnclosingFD->getName();
7689}
7690
7691void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7692 raw_ostream &Out) {
7693 // <special-name> ::= TH <object name>
7694 CXXNameMangler Mangler(*this, Out);
7695 Mangler.getStream() << "_ZTH";
7696 Mangler.mangleName(GD: D);
7697}
7698
7699void
7700ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7701 raw_ostream &Out) {
7702 // <special-name> ::= TW <object name>
7703 CXXNameMangler Mangler(*this, Out);
7704 Mangler.getStream() << "_ZTW";
7705 Mangler.mangleName(GD: D);
7706}
7707
7708void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
7709 unsigned ManglingNumber,
7710 raw_ostream &Out) {
7711 // We match the GCC mangling here.
7712 // <special-name> ::= GR <object name>
7713 CXXNameMangler Mangler(*this, Out);
7714 Mangler.getStream() << "_ZGR";
7715 Mangler.mangleName(GD: D);
7716 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
7717 Mangler.mangleSeqID(SeqID: ManglingNumber - 1);
7718}
7719
7720void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
7721 raw_ostream &Out) {
7722 // <special-name> ::= TV <type> # virtual table
7723 CXXNameMangler Mangler(*this, Out);
7724 Mangler.getStream() << "_ZTV";
7725 Mangler.mangleCXXRecordDecl(Record: RD);
7726}
7727
7728void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
7729 raw_ostream &Out) {
7730 // <special-name> ::= TT <type> # VTT structure
7731 CXXNameMangler Mangler(*this, Out);
7732 Mangler.getStream() << "_ZTT";
7733 Mangler.mangleCXXRecordDecl(Record: RD);
7734}
7735
7736void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
7737 int64_t Offset,
7738 const CXXRecordDecl *Type,
7739 raw_ostream &Out) {
7740 // <special-name> ::= TC <type> <offset number> _ <base type>
7741 CXXNameMangler Mangler(*this, Out);
7742 Mangler.getStream() << "_ZTC";
7743 // Older versions of clang did not add the record as a substitution candidate
7744 // here.
7745 bool SuppressSubstitution = getASTContext().getLangOpts().isCompatibleWith(
7746 Version: LangOptions::ClangABI::Ver19);
7747 Mangler.mangleCXXRecordDecl(Record: RD, SuppressSubstitution);
7748 Mangler.getStream() << Offset;
7749 Mangler.getStream() << '_';
7750 Mangler.mangleCXXRecordDecl(Record: Type);
7751}
7752
7753void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
7754 // <special-name> ::= TI <type> # typeinfo structure
7755 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7756 CXXNameMangler Mangler(*this, Out);
7757 Mangler.getStream() << "_ZTI";
7758 Mangler.mangleType(T: Ty);
7759}
7760
7761void ItaniumMangleContextImpl::mangleCXXRTTIName(
7762 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7763 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
7764 CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
7765 Mangler.getStream() << "_ZTS";
7766 Mangler.mangleType(T: Ty);
7767}
7768
7769void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7770 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7771 mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
7772}
7773
7774void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
7775 llvm_unreachable("Can't mangle string literals");
7776}
7777
7778void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7779 raw_ostream &Out) {
7780 CXXNameMangler Mangler(*this, Out);
7781 Mangler.mangleLambdaSig(Lambda);
7782}
7783
7784void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7785 raw_ostream &Out) {
7786 // <special-name> ::= GI <module-name> # module initializer function
7787 CXXNameMangler Mangler(*this, Out);
7788 Mangler.getStream() << "_ZGI";
7789 Mangler.mangleModuleNamePrefix(Name: M->getPrimaryModuleInterfaceName());
7790 if (M->isModulePartition()) {
7791 // The partition needs including, as partitions can have them too.
7792 auto Partition = M->Name.find(c: ':');
7793 Mangler.mangleModuleNamePrefix(
7794 Name: StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
7795 /*IsPartition*/ true);
7796 }
7797}
7798
7799ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
7800 DiagnosticsEngine &Diags,
7801 bool IsAux) {
7802 return new ItaniumMangleContextImpl(
7803 Context, Diags,
7804 [](ASTContext &, const NamedDecl *) -> UnsignedOrNone {
7805 return std::nullopt;
7806 },
7807 IsAux);
7808}
7809
7810ItaniumMangleContext *
7811ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
7812 DiscriminatorOverrideTy DiscriminatorOverride,
7813 bool IsAux) {
7814 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7815 IsAux);
7816}
7817