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