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