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