clang 20.0.0git
ItaniumMangle.cpp
Go to the documentation of this file.
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
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.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"
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>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(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>(decl);
57 return (fn ? getStructor(fn) : decl);
58}
59
60static bool isLambda(const NamedDecl *ND) {
61 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(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;
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;
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;
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>(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, 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(ND);
161 discriminator = ++Discriminator[std::make_pair(DC, 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>(LambdaContextDecl);
178 const FunctionDecl *Func =
179 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
180
181 if (Func) {
182 unsigned DefaultArgNo =
183 Func->getNumParams() - Parm->getFunctionScopeIndex();
184 Name += llvm::utostr(DefaultArgNo);
185 Name += "_";
186 }
187
188 if (LambdaManglingNumber)
189 LambdaId = LambdaManglingNumber;
190 else
191 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
192
193 Name += llvm::utostr(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(cast<Decl>(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>(ND->getCanonicalDecl());
307 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(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>(ND)) {
312 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 }
316 // Don't emit abi tags for namespaces.
317 return;
318 }
319 }
320
321 AbiTagList TagList;
322 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
323 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
324 AbiTag->tags().end());
325 TagList.insert(TagList.end(), AbiTag->tags().begin(),
326 AbiTag->tags().end());
327 }
328
329 if (AdditionalAbiTags) {
330 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
331 AdditionalAbiTags->end());
332 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
333 AdditionalAbiTags->end());
334 }
335
336 llvm::sort(TagList);
337 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
338
339 writeSortedUniqueAbiTags(Out, TagList);
340 }
341
342 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
343 void setUsedAbiTags(const AbiTagList &AbiTags) {
344 UsedAbiTags = AbiTags;
345 }
346
347 const AbiTagList &getEmittedAbiTags() const {
348 return EmittedAbiTags;
349 }
350
351 const AbiTagList &getSortedUniqueUsedAbiTags() {
352 llvm::sort(UsedAbiTags);
353 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
354 UsedAbiTags.end());
355 return UsedAbiTags;
356 }
357
358 private:
359 //! All abi tags used implicitly or explicitly.
360 AbiTagList UsedAbiTags;
361 //! All explicit abi tags (i.e. not from namespace).
362 AbiTagList EmittedAbiTags;
363
364 AbiTagState *&LinkHead;
365 AbiTagState *Parent = nullptr;
366
367 void pop() {
368 assert(LinkHead == this &&
369 "abi tag link head must point to us on destruction");
370 if (Parent) {
371 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
372 UsedAbiTags.begin(), UsedAbiTags.end());
373 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
374 EmittedAbiTags.begin(),
375 EmittedAbiTags.end());
376 }
377 LinkHead = Parent;
378 }
379
380 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
381 for (const auto &Tag : AbiTags) {
382 EmittedAbiTags.push_back(Tag);
383 Out << "B";
384 Out << Tag.size();
385 Out << Tag;
386 }
387 }
388 };
389
390 AbiTagState *AbiTags = nullptr;
391 AbiTagState AbiTagsRoot;
392
393 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
394 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
395
396 ASTContext &getASTContext() const { return Context.getASTContext(); }
397
398 bool isCompatibleWith(LangOptions::ClangABI Ver) {
399 return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
400 }
401
402 bool isStd(const NamespaceDecl *NS);
403 bool isStdNamespace(const DeclContext *DC);
404
405 const RecordDecl *GetLocalClassDecl(const Decl *D);
406 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
407 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
408 llvm::StringRef Name, bool HasAllocator);
409
410public:
411 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
412 const NamedDecl *D = nullptr, bool NullOut_ = false)
413 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
414 AbiTagsRoot(AbiTags) {
415 // These can't be mangled without a ctor type or dtor type.
416 assert(!D || (!isa<CXXDestructorDecl>(D) &&
417 !isa<CXXConstructorDecl>(D)));
418 }
419 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
421 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
422 AbiTagsRoot(AbiTags) {}
423 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
425 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
426 AbiTagsRoot(AbiTags) {}
427
428 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
429 bool NormalizeIntegers_)
430 : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
431 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
432 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
433 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
434 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
435 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
436 Substitutions(Outer.Substitutions),
437 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
438
439 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
440 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
441 NullOut = true;
442 }
443
444 struct WithTemplateDepthOffset { unsigned Offset; };
445 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
446 WithTemplateDepthOffset Offset)
447 : CXXNameMangler(C, Out) {
448 TemplateDepthOffset = Offset.Offset;
449 }
450
451 raw_ostream &getStream() { return Out; }
452
453 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
454 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
455
456 void mangle(GlobalDecl GD);
457 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
458 void mangleNumber(const llvm::APSInt &I);
459 void mangleNumber(int64_t Number);
460 void mangleFloat(const llvm::APFloat &F);
461 void mangleFunctionEncoding(GlobalDecl GD);
462 void mangleSeqID(unsigned SeqID);
463 void mangleName(GlobalDecl GD);
464 void mangleType(QualType T);
465 void mangleCXXRecordDecl(const CXXRecordDecl *Record);
466 void mangleLambdaSig(const CXXRecordDecl *Lambda);
467 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
468 void mangleVendorQualifier(StringRef Name);
469 void mangleVendorType(StringRef Name);
470
471private:
472
473 bool mangleSubstitution(const NamedDecl *ND);
474 bool mangleSubstitution(NestedNameSpecifier *NNS);
475 bool mangleSubstitution(QualType T);
476 bool mangleSubstitution(TemplateName Template);
477 bool mangleSubstitution(uintptr_t Ptr);
478
479 void mangleExistingSubstitution(TemplateName name);
480
481 bool mangleStandardSubstitution(const NamedDecl *ND);
482
483 void addSubstitution(const NamedDecl *ND) {
484 ND = cast<NamedDecl>(ND->getCanonicalDecl());
485
486 addSubstitution(reinterpret_cast<uintptr_t>(ND));
487 }
488 void addSubstitution(NestedNameSpecifier *NNS) {
489 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
490
491 addSubstitution(reinterpret_cast<uintptr_t>(NNS));
492 }
493 void addSubstitution(QualType T);
494 void addSubstitution(TemplateName Template);
495 void addSubstitution(uintptr_t Ptr);
496 // Destructive copy substitutions from other mangler.
497 void extendSubstitutions(CXXNameMangler* Other);
498
499 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
500 bool recursive = false);
501 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
502 DeclarationName name,
503 const TemplateArgumentLoc *TemplateArgs,
504 unsigned NumTemplateArgs,
505 unsigned KnownArity = UnknownArity);
506
507 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
508
509 void mangleNameWithAbiTags(GlobalDecl GD,
510 const AbiTagList *AdditionalAbiTags);
511 void mangleModuleName(const NamedDecl *ND);
512 void mangleTemplateName(const TemplateDecl *TD,
514 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
515 const AbiTagList *AdditionalAbiTags) {
516 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
517 UnknownArity, AdditionalAbiTags);
518 }
519 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
520 const DeclContext *DC, unsigned KnownArity,
521 const AbiTagList *AdditionalAbiTags);
522 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
523 const AbiTagList *AdditionalAbiTags);
524 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
525 const AbiTagList *AdditionalAbiTags);
526 void mangleSourceName(const IdentifierInfo *II);
527 void mangleRegCallName(const IdentifierInfo *II);
528 void mangleDeviceStubName(const IdentifierInfo *II);
529 void mangleSourceNameWithAbiTags(
530 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
531 void mangleLocalName(GlobalDecl GD,
532 const AbiTagList *AdditionalAbiTags);
533 void mangleBlockForPrefix(const BlockDecl *Block);
534 void mangleUnqualifiedBlock(const BlockDecl *Block);
535 void mangleTemplateParamDecl(const NamedDecl *Decl);
536 void mangleTemplateParameterList(const TemplateParameterList *Params);
537 void mangleTypeConstraint(const ConceptDecl *Concept,
539 void mangleTypeConstraint(const TypeConstraint *Constraint);
540 void mangleRequiresClause(const Expr *RequiresClause);
541 void mangleLambda(const CXXRecordDecl *Lambda);
542 void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
543 const AbiTagList *AdditionalAbiTags,
544 bool NoFunction=false);
545 void mangleNestedName(const TemplateDecl *TD,
547 void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
548 const NamedDecl *PrefixND,
549 const AbiTagList *AdditionalAbiTags);
550 void manglePrefix(NestedNameSpecifier *qualifier);
551 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
552 void manglePrefix(QualType type);
553 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
554 void mangleTemplatePrefix(TemplateName Template);
555 const NamedDecl *getClosurePrefix(const Decl *ND);
556 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
557 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
558 StringRef Prefix = "");
559 void mangleOperatorName(DeclarationName Name, unsigned Arity);
560 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
561 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
562 void mangleRefQualifier(RefQualifierKind RefQualifier);
563
564 void mangleObjCMethodName(const ObjCMethodDecl *MD);
565
566 // Declare manglers for every type class.
567#define ABSTRACT_TYPE(CLASS, PARENT)
568#define NON_CANONICAL_TYPE(CLASS, PARENT)
569#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
570#include "clang/AST/TypeNodes.inc"
571
572 void mangleType(const TagType*);
573 void mangleType(TemplateName);
574 static StringRef getCallingConvQualifierName(CallingConv CC);
575 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
576 void mangleExtFunctionInfo(const FunctionType *T);
577 void mangleSMEAttrs(unsigned SMEAttrs);
578 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
579 const FunctionDecl *FD = nullptr);
580 void mangleNeonVectorType(const VectorType *T);
581 void mangleNeonVectorType(const DependentVectorType *T);
582 void mangleAArch64NeonVectorType(const VectorType *T);
583 void mangleAArch64NeonVectorType(const DependentVectorType *T);
584 void mangleAArch64FixedSveVectorType(const VectorType *T);
585 void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
586 void mangleRISCVFixedRVVVectorType(const VectorType *T);
587 void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
588
589 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
590 void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
591 void mangleFixedPointLiteral();
592 void mangleNullPointer(QualType T);
593
594 void mangleMemberExprBase(const Expr *base, bool isArrow);
595 void mangleMemberExpr(const Expr *base, bool isArrow,
596 NestedNameSpecifier *qualifier,
597 NamedDecl *firstQualifierLookup,
598 DeclarationName name,
599 const TemplateArgumentLoc *TemplateArgs,
600 unsigned NumTemplateArgs,
601 unsigned knownArity);
602 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
603 void mangleInitListElements(const InitListExpr *InitList);
604 void mangleRequirement(SourceLocation RequiresExprLoc,
605 const concepts::Requirement *Req);
606 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
607 bool AsTemplateArg = false);
608 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
609 void mangleCXXDtorType(CXXDtorType T);
610
611 struct TemplateArgManglingInfo;
612 void mangleTemplateArgs(TemplateName TN,
613 const TemplateArgumentLoc *TemplateArgs,
614 unsigned NumTemplateArgs);
615 void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
616 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
617 void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
619 void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
620 void mangleTemplateArgExpr(const Expr *E);
621 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
622 bool NeedExactType = false);
623
624 void mangleTemplateParameter(unsigned Depth, unsigned Index);
625
626 void mangleFunctionParam(const ParmVarDecl *parm);
627
628 void writeAbiTags(const NamedDecl *ND,
629 const AbiTagList *AdditionalAbiTags);
630
631 // Returns sorted unique list of ABI tags.
632 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
633 // Returns sorted unique list of ABI tags.
634 AbiTagList makeVariableTypeTags(const VarDecl *VD);
635};
636
637}
638
639NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
640 if (!StdNamespace) {
641 StdNamespace = NamespaceDecl::Create(
642 getASTContext(), getASTContext().getTranslationUnitDecl(),
643 /*Inline=*/false, SourceLocation(), SourceLocation(),
644 &getASTContext().Idents.get("std"),
645 /*PrevDecl=*/nullptr, /*Nested=*/false);
646 StdNamespace->setImplicit();
647 }
648 return StdNamespace;
649}
650
651/// Retrieve the declaration context that should be used when mangling the given
652/// declaration.
653const DeclContext *
654ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
655 // The ABI assumes that lambda closure types that occur within
656 // default arguments live in the context of the function. However, due to
657 // the way in which Clang parses and creates function declarations, this is
658 // not the case: the lambda closure type ends up living in the context
659 // where the function itself resides, because the function declaration itself
660 // had not yet been created. Fix the context here.
661 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
662 if (RD->isLambda())
663 if (ParmVarDecl *ContextParam =
664 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
665 return ContextParam->getDeclContext();
666 }
667
668 // Perform the same check for block literals.
669 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
670 if (ParmVarDecl *ContextParam =
671 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
672 return ContextParam->getDeclContext();
673 }
674
675 // On ARM and AArch64, the va_list tag is always mangled as if in the std
676 // namespace. We do not represent va_list as actually being in the std
677 // namespace in C because this would result in incorrect debug info in C,
678 // among other things. It is important for both languages to have the same
679 // mangling in order for -fsanitize=cfi-icall to work.
680 if (D == getASTContext().getVaListTagDecl()) {
681 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
682 if (T.isARM() || T.isThumb() || T.isAArch64())
683 return getStdNamespace();
684 }
685
686 const DeclContext *DC = D->getDeclContext();
687 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
688 isa<OMPDeclareMapperDecl>(DC)) {
689 return getEffectiveDeclContext(cast<Decl>(DC));
690 }
691
692 if (const auto *VD = dyn_cast<VarDecl>(D))
693 if (VD->isExternC())
694 return getASTContext().getTranslationUnitDecl();
695
696 if (const auto *FD = getASTContext().getLangOpts().getClangABICompat() >
697 LangOptions::ClangABI::Ver19
698 ? D->getAsFunction()
699 : dyn_cast<FunctionDecl>(D)) {
700 if (FD->isExternC())
701 return getASTContext().getTranslationUnitDecl();
702 // Member-like constrained friends are mangled as if they were members of
703 // the enclosing class.
704 if (FD->isMemberLikeConstrainedFriend() &&
705 getASTContext().getLangOpts().getClangABICompat() >
706 LangOptions::ClangABI::Ver17)
708 }
709
710 return DC->getRedeclContext();
711}
712
713bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
714 if (ND && ND->getFormalLinkage() == Linkage::Internal &&
715 !ND->isExternallyVisible() &&
716 getEffectiveDeclContext(ND)->isFileContext() &&
718 return true;
719 return false;
720}
721
722// Check if this Function Decl needs a unique internal linkage name.
723bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
724 const NamedDecl *ND) {
725 if (!NeedsUniqueInternalLinkageNames || !ND)
726 return false;
727
728 const auto *FD = dyn_cast<FunctionDecl>(ND);
729 if (!FD)
730 return false;
731
732 // For C functions without prototypes, return false as their
733 // names should not be mangled.
734 if (!FD->getType()->getAs<FunctionProtoType>())
735 return false;
736
737 if (isInternalLinkageDecl(ND))
738 return true;
739
740 return false;
741}
742
743bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
744 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
745 LanguageLinkage L = FD->getLanguageLinkage();
746 // Overloadable functions need mangling.
747 if (FD->hasAttr<OverloadableAttr>())
748 return true;
749
750 // "main" is not mangled.
751 if (FD->isMain())
752 return false;
753
754 // The Windows ABI expects that we would never mangle "typical"
755 // user-defined entry points regardless of visibility or freestanding-ness.
756 //
757 // N.B. This is distinct from asking about "main". "main" has a lot of
758 // special rules associated with it in the standard while these
759 // user-defined entry points are outside of the purview of the standard.
760 // For example, there can be only one definition for "main" in a standards
761 // compliant program; however nothing forbids the existence of wmain and
762 // WinMain in the same translation unit.
763 if (FD->isMSVCRTEntryPoint())
764 return false;
765
766 // C++ functions and those whose names are not a simple identifier need
767 // mangling.
768 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
769 return true;
770
771 // C functions are not mangled.
772 if (L == CLanguageLinkage)
773 return false;
774 }
775
776 // Otherwise, no mangling is done outside C++ mode.
777 if (!getASTContext().getLangOpts().CPlusPlus)
778 return false;
779
780 if (const auto *VD = dyn_cast<VarDecl>(D)) {
781 // Decompositions are mangled.
782 if (isa<DecompositionDecl>(VD))
783 return true;
784
785 // C variables are not mangled.
786 if (VD->isExternC())
787 return false;
788
789 // Variables at global scope are not mangled unless they have internal
790 // linkage or are specializations or are attached to a named module.
791 const DeclContext *DC = getEffectiveDeclContext(D);
792 // Check for extern variable declared locally.
793 if (DC->isFunctionOrMethod() && D->hasLinkage())
794 while (!DC->isFileContext())
795 DC = getEffectiveParentContext(DC);
796 if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&
797 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
798 !isa<VarTemplateSpecializationDecl>(VD) &&
800 return false;
801 }
802
803 return true;
804}
805
806void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
807 const AbiTagList *AdditionalAbiTags) {
808 assert(AbiTags && "require AbiTagState");
809 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
810}
811
812void CXXNameMangler::mangleSourceNameWithAbiTags(
813 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
814 mangleSourceName(ND->getIdentifier());
815 writeAbiTags(ND, AdditionalAbiTags);
816}
817
818void CXXNameMangler::mangle(GlobalDecl GD) {
819 // <mangled-name> ::= _Z <encoding>
820 // ::= <data name>
821 // ::= <special-name>
822 Out << "_Z";
823 if (isa<FunctionDecl>(GD.getDecl()))
824 mangleFunctionEncoding(GD);
826 BindingDecl>(GD.getDecl()))
827 mangleName(GD);
828 else if (const IndirectFieldDecl *IFD =
829 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
830 mangleName(IFD->getAnonField());
831 else
832 llvm_unreachable("unexpected kind of global decl");
833}
834
835void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
836 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
837 // <encoding> ::= <function name> <bare-function-type>
838
839 // Don't mangle in the type if this isn't a decl we should typically mangle.
840 if (!Context.shouldMangleDeclName(FD)) {
841 mangleName(GD);
842 return;
843 }
844
845 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
846 if (ReturnTypeAbiTags.empty()) {
847 // There are no tags for return type, the simplest case. Enter the function
848 // parameter scope before mangling the name, because a template using
849 // constrained `auto` can have references to its parameters within its
850 // template argument list:
851 //
852 // template<typename T> void f(T x, C<decltype(x)> auto)
853 // ... is mangled as ...
854 // template<typename T, C<decltype(param 1)> U> void f(T, U)
855 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
856 mangleName(GD);
857 FunctionTypeDepth.pop(Saved);
858 mangleFunctionEncodingBareType(FD);
859 return;
860 }
861
862 // Mangle function name and encoding to temporary buffer.
863 // We have to output name and encoding to the same mangler to get the same
864 // substitution as it will be in final mangling.
865 SmallString<256> FunctionEncodingBuf;
866 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
867 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
868 // Output name of the function.
869 FunctionEncodingMangler.disableDerivedAbiTags();
870
871 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
872 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
873 FunctionTypeDepth.pop(Saved);
874
875 // Remember length of the function name in the buffer.
876 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
877 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
878
879 // Get tags from return type that are not present in function name or
880 // encoding.
881 const AbiTagList &UsedAbiTags =
882 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
883 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
884 AdditionalAbiTags.erase(
885 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
886 UsedAbiTags.begin(), UsedAbiTags.end(),
887 AdditionalAbiTags.begin()),
888 AdditionalAbiTags.end());
889
890 // Output name with implicit tags and function encoding from temporary buffer.
891 Saved = FunctionTypeDepth.push();
892 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
893 FunctionTypeDepth.pop(Saved);
894 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
895
896 // Function encoding could create new substitutions so we have to add
897 // temp mangled substitutions to main mangler.
898 extendSubstitutions(&FunctionEncodingMangler);
899}
900
901void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
902 if (FD->hasAttr<EnableIfAttr>()) {
903 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
904 Out << "Ua9enable_ifI";
905 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
906 E = FD->getAttrs().end();
907 I != E; ++I) {
908 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
909 if (!EIA)
910 continue;
911 if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
912 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
913 // even though <template-arg> should not include an X/E around
914 // <expr-primary>.
915 Out << 'X';
916 mangleExpression(EIA->getCond());
917 Out << 'E';
918 } else {
919 mangleTemplateArgExpr(EIA->getCond());
920 }
921 }
922 Out << 'E';
923 FunctionTypeDepth.pop(Saved);
924 }
925
926 // When mangling an inheriting constructor, the bare function type used is
927 // that of the inherited constructor.
928 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
929 if (auto Inherited = CD->getInheritedConstructor())
930 FD = Inherited.getConstructor();
931
932 // Whether the mangling of a function type includes the return type depends on
933 // the context and the nature of the function. The rules for deciding whether
934 // the return type is included are:
935 //
936 // 1. Template functions (names or types) have return types encoded, with
937 // the exceptions listed below.
938 // 2. Function types not appearing as part of a function name mangling,
939 // e.g. parameters, pointer types, etc., have return type encoded, with the
940 // exceptions listed below.
941 // 3. Non-template function names do not have return types encoded.
942 //
943 // The exceptions mentioned in (1) and (2) above, for which the return type is
944 // never included, are
945 // 1. Constructors.
946 // 2. Destructors.
947 // 3. Conversion operator functions, e.g. operator int.
948 bool MangleReturnType = false;
949 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
950 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
951 isa<CXXConversionDecl>(FD)))
952 MangleReturnType = true;
953
954 // Mangle the type of the primary template.
955 FD = PrimaryTemplate->getTemplatedDecl();
956 }
957
958 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
959 MangleReturnType, FD);
960}
961
962/// Return whether a given namespace is the 'std' namespace.
963bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
964 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
965 return false;
966
967 const IdentifierInfo *II = NS->getFirstDecl()->getIdentifier();
968 return II && II->isStr("std");
969}
970
971// isStdNamespace - Return whether a given decl context is a toplevel 'std'
972// namespace.
973bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
974 if (!DC->isNamespace())
975 return false;
976
977 return isStd(cast<NamespaceDecl>(DC));
978}
979
980static const GlobalDecl
981isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
982 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
983 // Check if we have a function template.
984 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
985 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
986 TemplateArgs = FD->getTemplateSpecializationArgs();
987 return GD.getWithDecl(TD);
988 }
989 }
990
991 // Check if we have a class template.
992 if (const ClassTemplateSpecializationDecl *Spec =
993 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
994 TemplateArgs = &Spec->getTemplateArgs();
995 return GD.getWithDecl(Spec->getSpecializedTemplate());
996 }
997
998 // Check if we have a variable template.
999 if (const VarTemplateSpecializationDecl *Spec =
1000 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
1001 TemplateArgs = &Spec->getTemplateArgs();
1002 return GD.getWithDecl(Spec->getSpecializedTemplate());
1003 }
1004
1005 return GlobalDecl();
1006}
1007
1009 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1010 return TemplateName(const_cast<TemplateDecl*>(TD));
1011}
1012
1013void CXXNameMangler::mangleName(GlobalDecl GD) {
1014 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1015 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1016 // Variables should have implicit tags from its type.
1017 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
1018 if (VariableTypeAbiTags.empty()) {
1019 // Simple case no variable type tags.
1020 mangleNameWithAbiTags(VD, nullptr);
1021 return;
1022 }
1023
1024 // Mangle variable name to null stream to collect tags.
1025 llvm::raw_null_ostream NullOutStream;
1026 CXXNameMangler VariableNameMangler(*this, NullOutStream);
1027 VariableNameMangler.disableDerivedAbiTags();
1028 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
1029
1030 // Get tags from variable type that are not present in its name.
1031 const AbiTagList &UsedAbiTags =
1032 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
1033 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
1034 AdditionalAbiTags.erase(
1035 std::set_difference(VariableTypeAbiTags.begin(),
1036 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
1037 UsedAbiTags.end(), AdditionalAbiTags.begin()),
1038 AdditionalAbiTags.end());
1039
1040 // Output name with implicit tags.
1041 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
1042 } else {
1043 mangleNameWithAbiTags(GD, nullptr);
1044 }
1045}
1046
1047const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
1048 const DeclContext *DC = Context.getEffectiveDeclContext(D);
1049 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1050 if (isLocalContainerContext(DC))
1051 return dyn_cast<RecordDecl>(D);
1052 D = cast<Decl>(DC);
1053 DC = Context.getEffectiveDeclContext(D);
1054 }
1055 return nullptr;
1056}
1057
1058void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1059 const AbiTagList *AdditionalAbiTags) {
1060 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1061 // <name> ::= [<module-name>] <nested-name>
1062 // ::= [<module-name>] <unscoped-name>
1063 // ::= [<module-name>] <unscoped-template-name> <template-args>
1064 // ::= <local-name>
1065 //
1066 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1067 bool IsLambda = isLambda(ND);
1068
1069 // If this is an extern variable declared locally, the relevant DeclContext
1070 // is that of the containing namespace, or the translation unit.
1071 // FIXME: This is a hack; extern variables declared locally should have
1072 // a proper semantic declaration context!
1073 if (isLocalContainerContext(DC) && ND->hasLinkage() && !IsLambda)
1074 while (!DC->isNamespace() && !DC->isTranslationUnit())
1075 DC = Context.getEffectiveParentContext(DC);
1076 else if (GetLocalClassDecl(ND) &&
1077 (!IsLambda || isCompatibleWith(LangOptions::ClangABI::Ver18))) {
1078 mangleLocalName(GD, AdditionalAbiTags);
1079 return;
1080 }
1081
1082 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1083
1084 // Closures can require a nested-name mangling even if they're semantically
1085 // in the global namespace.
1086 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1087 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1088 return;
1089 }
1090
1091 if (isLocalContainerContext(DC)) {
1092 mangleLocalName(GD, AdditionalAbiTags);
1093 return;
1094 }
1095
1096 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1097 // Check if we have a template.
1098 const TemplateArgumentList *TemplateArgs = nullptr;
1099 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1100 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1101 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1102 return;
1103 }
1104
1105 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1106 return;
1107 }
1108
1109 mangleNestedName(GD, DC, AdditionalAbiTags);
1110}
1111
1112void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1113 if (ND->isExternallyVisible())
1114 if (Module *M = ND->getOwningModuleForLinkage())
1115 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1116}
1117
1118// <module-name> ::= <module-subname>
1119// ::= <module-name> <module-subname>
1120// ::= <substitution>
1121// <module-subname> ::= W <source-name>
1122// ::= W P <source-name>
1123void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1124 // <substitution> ::= S <seq-id> _
1125 auto It = ModuleSubstitutions.find(Name);
1126 if (It != ModuleSubstitutions.end()) {
1127 Out << 'S';
1128 mangleSeqID(It->second);
1129 return;
1130 }
1131
1132 // FIXME: Preserve hierarchy in module names rather than flattening
1133 // them to strings; use Module*s as substitution keys.
1134 auto Parts = Name.rsplit('.');
1135 if (Parts.second.empty())
1136 Parts.second = Parts.first;
1137 else {
1138 mangleModuleNamePrefix(Parts.first, IsPartition);
1139 IsPartition = false;
1140 }
1141
1142 Out << 'W';
1143 if (IsPartition)
1144 Out << 'P';
1145 Out << Parts.second.size() << Parts.second;
1146 ModuleSubstitutions.insert({Name, SeqID++});
1147}
1148
1149void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1151 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1152
1153 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1154 mangleUnscopedTemplateName(TD, DC, nullptr);
1155 mangleTemplateArgs(asTemplateName(TD), Args);
1156 } else {
1157 mangleNestedName(TD, Args);
1158 }
1159}
1160
1161void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1162 const AbiTagList *AdditionalAbiTags) {
1163 // <unscoped-name> ::= <unqualified-name>
1164 // ::= St <unqualified-name> # ::std::
1165
1166 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1167 if (isStdNamespace(DC)) {
1168 if (getASTContext().getTargetInfo().getTriple().isOSSolaris()) {
1169 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1170 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND)) {
1171 // Issue #33114: Need non-standard mangling of std::tm etc. for
1172 // Solaris ABI compatibility.
1173 //
1174 // <substitution> ::= tm # ::std::tm, same for the others
1175 if (const IdentifierInfo *II = RD->getIdentifier()) {
1176 StringRef type = II->getName();
1177 if (llvm::is_contained({"div_t", "ldiv_t", "lconv", "tm"}, type)) {
1178 Out << type.size() << type;
1179 return;
1180 }
1181 }
1182 }
1183 }
1184 Out << "St";
1185 }
1186
1187 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1188}
1189
1190void CXXNameMangler::mangleUnscopedTemplateName(
1191 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1192 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1193 // <unscoped-template-name> ::= <unscoped-name>
1194 // ::= <substitution>
1195 if (mangleSubstitution(ND))
1196 return;
1197
1198 // <template-template-param> ::= <template-param>
1199 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1200 assert(!AdditionalAbiTags &&
1201 "template template param cannot have abi tags");
1202 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1203 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1204 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1205 } else {
1206 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1207 AdditionalAbiTags);
1208 }
1209
1210 addSubstitution(ND);
1211}
1212
1213void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1214 // ABI:
1215 // Floating-point literals are encoded using a fixed-length
1216 // lowercase hexadecimal string corresponding to the internal
1217 // representation (IEEE on Itanium), high-order bytes first,
1218 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1219 // on Itanium.
1220 // The 'without leading zeroes' thing seems to be an editorial
1221 // mistake; see the discussion on cxx-abi-dev beginning on
1222 // 2012-01-16.
1223
1224 // Our requirements here are just barely weird enough to justify
1225 // using a custom algorithm instead of post-processing APInt::toString().
1226
1227 llvm::APInt valueBits = f.bitcastToAPInt();
1228 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1229 assert(numCharacters != 0);
1230
1231 // Allocate a buffer of the right number of characters.
1232 SmallVector<char, 20> buffer(numCharacters);
1233
1234 // Fill the buffer left-to-right.
1235 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1236 // The bit-index of the next hex digit.
1237 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1238
1239 // Project out 4 bits starting at 'digitIndex'.
1240 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1241 hexDigit >>= (digitBitIndex % 64);
1242 hexDigit &= 0xF;
1243
1244 // Map that over to a lowercase hex digit.
1245 static const char charForHex[16] = {
1246 '0', '1', '2', '3', '4', '5', '6', '7',
1247 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1248 };
1249 buffer[stringIndex] = charForHex[hexDigit];
1250 }
1251
1252 Out.write(buffer.data(), numCharacters);
1253}
1254
1255void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1256 Out << 'L';
1257 mangleType(T);
1258 mangleFloat(V);
1259 Out << 'E';
1260}
1261
1262void CXXNameMangler::mangleFixedPointLiteral() {
1263 DiagnosticsEngine &Diags = Context.getDiags();
1264 unsigned DiagID = Diags.getCustomDiagID(
1265 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1266 Diags.Report(DiagID);
1267}
1268
1269void CXXNameMangler::mangleNullPointer(QualType T) {
1270 // <expr-primary> ::= L <type> 0 E
1271 Out << 'L';
1272 mangleType(T);
1273 Out << "0E";
1274}
1275
1276void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1277 if (Value.isSigned() && Value.isNegative()) {
1278 Out << 'n';
1279 Value.abs().print(Out, /*signed*/ false);
1280 } else {
1281 Value.print(Out, /*signed*/ false);
1282 }
1283}
1284
1285void CXXNameMangler::mangleNumber(int64_t Number) {
1286 // <number> ::= [n] <non-negative decimal integer>
1287 if (Number < 0) {
1288 Out << 'n';
1289 Number = -Number;
1290 }
1291
1292 Out << Number;
1293}
1294
1295void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1296 // <call-offset> ::= h <nv-offset> _
1297 // ::= v <v-offset> _
1298 // <nv-offset> ::= <offset number> # non-virtual base override
1299 // <v-offset> ::= <offset number> _ <virtual offset number>
1300 // # virtual base override, with vcall offset
1301 if (!Virtual) {
1302 Out << 'h';
1303 mangleNumber(NonVirtual);
1304 Out << '_';
1305 return;
1306 }
1307
1308 Out << 'v';
1309 mangleNumber(NonVirtual);
1310 Out << '_';
1311 mangleNumber(Virtual);
1312 Out << '_';
1313}
1314
1315void CXXNameMangler::manglePrefix(QualType type) {
1316 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1317 if (!mangleSubstitution(QualType(TST, 0))) {
1318 mangleTemplatePrefix(TST->getTemplateName());
1319
1320 // FIXME: GCC does not appear to mangle the template arguments when
1321 // the template in question is a dependent template name. Should we
1322 // emulate that badness?
1323 mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1324 addSubstitution(QualType(TST, 0));
1325 }
1326 } else if (const auto *DTST =
1328 if (!mangleSubstitution(QualType(DTST, 0))) {
1329 TemplateName Template = getASTContext().getDependentTemplateName(
1330 DTST->getQualifier(), DTST->getIdentifier());
1331 mangleTemplatePrefix(Template);
1332
1333 // FIXME: GCC does not appear to mangle the template arguments when
1334 // the template in question is a dependent template name. Should we
1335 // emulate that badness?
1336 mangleTemplateArgs(Template, DTST->template_arguments());
1337 addSubstitution(QualType(DTST, 0));
1338 }
1339 } else {
1340 // We use the QualType mangle type variant here because it handles
1341 // substitutions.
1342 mangleType(type);
1343 }
1344}
1345
1346/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1347///
1348/// \param recursive - true if this is being called recursively,
1349/// i.e. if there is more prefix "to the right".
1350void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1351 bool recursive) {
1352
1353 // x, ::x
1354 // <unresolved-name> ::= [gs] <base-unresolved-name>
1355
1356 // T::x / decltype(p)::x
1357 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1358
1359 // T::N::x /decltype(p)::N::x
1360 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1361 // <base-unresolved-name>
1362
1363 // A::x, N::y, A<T>::z; "gs" means leading "::"
1364 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1365 // <base-unresolved-name>
1366
1367 switch (qualifier->getKind()) {
1369 Out << "gs";
1370
1371 // We want an 'sr' unless this is the entire NNS.
1372 if (recursive)
1373 Out << "sr";
1374
1375 // We never want an 'E' here.
1376 return;
1377
1379 llvm_unreachable("Can't mangle __super specifier");
1380
1382 if (qualifier->getPrefix())
1383 mangleUnresolvedPrefix(qualifier->getPrefix(),
1384 /*recursive*/ true);
1385 else
1386 Out << "sr";
1387 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1388 break;
1390 if (qualifier->getPrefix())
1391 mangleUnresolvedPrefix(qualifier->getPrefix(),
1392 /*recursive*/ true);
1393 else
1394 Out << "sr";
1395 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1396 break;
1397
1400 const Type *type = qualifier->getAsType();
1401
1402 // We only want to use an unresolved-type encoding if this is one of:
1403 // - a decltype
1404 // - a template type parameter
1405 // - a template template parameter with arguments
1406 // In all of these cases, we should have no prefix.
1407 if (qualifier->getPrefix()) {
1408 mangleUnresolvedPrefix(qualifier->getPrefix(),
1409 /*recursive*/ true);
1410 } else {
1411 // Otherwise, all the cases want this.
1412 Out << "sr";
1413 }
1414
1415 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1416 return;
1417
1418 break;
1419 }
1420
1422 // Member expressions can have these without prefixes.
1423 if (qualifier->getPrefix())
1424 mangleUnresolvedPrefix(qualifier->getPrefix(),
1425 /*recursive*/ true);
1426 else
1427 Out << "sr";
1428
1429 mangleSourceName(qualifier->getAsIdentifier());
1430 // An Identifier has no type information, so we can't emit abi tags for it.
1431 break;
1432 }
1433
1434 // If this was the innermost part of the NNS, and we fell out to
1435 // here, append an 'E'.
1436 if (!recursive)
1437 Out << 'E';
1438}
1439
1440/// Mangle an unresolved-name, which is generally used for names which
1441/// weren't resolved to specific entities.
1442void CXXNameMangler::mangleUnresolvedName(
1443 NestedNameSpecifier *qualifier, DeclarationName name,
1444 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1445 unsigned knownArity) {
1446 if (qualifier) mangleUnresolvedPrefix(qualifier);
1447 switch (name.getNameKind()) {
1448 // <base-unresolved-name> ::= <simple-id>
1450 mangleSourceName(name.getAsIdentifierInfo());
1451 break;
1452 // <base-unresolved-name> ::= dn <destructor-name>
1454 Out << "dn";
1455 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1456 break;
1457 // <base-unresolved-name> ::= on <operator-name>
1461 Out << "on";
1462 mangleOperatorName(name, knownArity);
1463 break;
1465 llvm_unreachable("Can't mangle a constructor name!");
1467 llvm_unreachable("Can't mangle a using directive name!");
1469 llvm_unreachable("Can't mangle a deduction guide name!");
1473 llvm_unreachable("Can't mangle Objective-C selector names here!");
1474 }
1475
1476 // The <simple-id> and on <operator-name> productions end in an optional
1477 // <template-args>.
1478 if (TemplateArgs)
1479 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1480}
1481
1482void CXXNameMangler::mangleUnqualifiedName(
1483 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1484 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1485 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1486 // <unqualified-name> ::= [<module-name>] [F] <operator-name>
1487 // ::= <ctor-dtor-name>
1488 // ::= [<module-name>] [F] <source-name>
1489 // ::= [<module-name>] DC <source-name>* E
1490
1491 if (ND && DC && DC->isFileContext())
1492 mangleModuleName(ND);
1493
1494 // A member-like constrained friend is mangled with a leading 'F'.
1495 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1496 auto *FD = dyn_cast<FunctionDecl>(ND);
1497 auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
1498 if ((FD && FD->isMemberLikeConstrainedFriend()) ||
1499 (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1500 if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
1501 Out << 'F';
1502 }
1503
1504 unsigned Arity = KnownArity;
1505 switch (Name.getNameKind()) {
1507 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1508
1509 // We mangle decomposition declarations as the names of their bindings.
1510 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1511 // FIXME: Non-standard mangling for decomposition declarations:
1512 //
1513 // <unqualified-name> ::= DC <source-name>* E
1514 //
1515 // Proposed on cxx-abi-dev on 2016-08-12
1516 Out << "DC";
1517 for (auto *BD : DD->bindings())
1518 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1519 Out << 'E';
1520 writeAbiTags(ND, AdditionalAbiTags);
1521 break;
1522 }
1523
1524 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1525 // We follow MSVC in mangling GUID declarations as if they were variables
1526 // with a particular reserved name. Continue the pretense here.
1527 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1528 llvm::raw_svector_ostream GUIDOS(GUID);
1529 Context.mangleMSGuidDecl(GD, GUIDOS);
1530 Out << GUID.size() << GUID;
1531 break;
1532 }
1533
1534 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1535 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1536 Out << "TA";
1537 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1538 TPO->getValue(), /*TopLevel=*/true);
1539 break;
1540 }
1541
1542 if (II) {
1543 // Match GCC's naming convention for internal linkage symbols, for
1544 // symbols that are not actually visible outside of this TU. GCC
1545 // distinguishes between internal and external linkage symbols in
1546 // its mangling, to support cases like this that were valid C++ prior
1547 // to DR426:
1548 //
1549 // void test() { extern void foo(); }
1550 // static void foo();
1551 //
1552 // Don't bother with the L marker for names in anonymous namespaces; the
1553 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1554 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1555 // implying internal linkage.
1556 if (Context.isInternalLinkageDecl(ND))
1557 Out << 'L';
1558
1559 bool IsRegCall = FD &&
1560 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1562 bool IsDeviceStub =
1563 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1564 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1565 if (IsDeviceStub)
1566 mangleDeviceStubName(II);
1567 else if (IsRegCall)
1568 mangleRegCallName(II);
1569 else
1570 mangleSourceName(II);
1571
1572 writeAbiTags(ND, AdditionalAbiTags);
1573 break;
1574 }
1575
1576 // Otherwise, an anonymous entity. We must have a declaration.
1577 assert(ND && "mangling empty name without declaration");
1578
1579 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1580 if (NS->isAnonymousNamespace()) {
1581 // This is how gcc mangles these names.
1582 Out << "12_GLOBAL__N_1";
1583 break;
1584 }
1585 }
1586
1587 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1588 // We must have an anonymous union or struct declaration.
1589 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1590
1591 // Itanium C++ ABI 5.1.2:
1592 //
1593 // For the purposes of mangling, the name of an anonymous union is
1594 // considered to be the name of the first named data member found by a
1595 // pre-order, depth-first, declaration-order walk of the data members of
1596 // the anonymous union. If there is no such data member (i.e., if all of
1597 // the data members in the union are unnamed), then there is no way for
1598 // a program to refer to the anonymous union, and there is therefore no
1599 // need to mangle its name.
1600 assert(RD->isAnonymousStructOrUnion()
1601 && "Expected anonymous struct or union!");
1602 const FieldDecl *FD = RD->findFirstNamedDataMember();
1603
1604 // It's actually possible for various reasons for us to get here
1605 // with an empty anonymous struct / union. Fortunately, it
1606 // doesn't really matter what name we generate.
1607 if (!FD) break;
1608 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1609
1610 mangleSourceName(FD->getIdentifier());
1611 // Not emitting abi tags: internal name anyway.
1612 break;
1613 }
1614
1615 // Class extensions have no name as a category, and it's possible
1616 // for them to be the semantic parent of certain declarations
1617 // (primarily, tag decls defined within declarations). Such
1618 // declarations will always have internal linkage, so the name
1619 // doesn't really matter, but we shouldn't crash on them. For
1620 // safety, just handle all ObjC containers here.
1621 if (isa<ObjCContainerDecl>(ND))
1622 break;
1623
1624 // We must have an anonymous struct.
1625 const TagDecl *TD = cast<TagDecl>(ND);
1626 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1627 assert(TD->getDeclContext() == D->getDeclContext() &&
1628 "Typedef should not be in another decl context!");
1629 assert(D->getDeclName().getAsIdentifierInfo() &&
1630 "Typedef was not named!");
1631 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1632 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1633 // Explicit abi tags are still possible; take from underlying type, not
1634 // from typedef.
1635 writeAbiTags(TD, nullptr);
1636 break;
1637 }
1638
1639 // <unnamed-type-name> ::= <closure-type-name>
1640 //
1641 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1642 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1643 // # Parameter types or 'v' for 'void'.
1644 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1645 std::optional<unsigned> DeviceNumber =
1646 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1647
1648 // If we have a device-number via the discriminator, use that to mangle
1649 // the lambda, otherwise use the typical lambda-mangling-number. In either
1650 // case, a '0' should be mangled as a normal unnamed class instead of as a
1651 // lambda.
1652 if (Record->isLambda() &&
1653 ((DeviceNumber && *DeviceNumber > 0) ||
1654 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1655 assert(!AdditionalAbiTags &&
1656 "Lambda type cannot have additional abi tags");
1657 mangleLambda(Record);
1658 break;
1659 }
1660 }
1661
1662 if (TD->isExternallyVisible()) {
1663 unsigned UnnamedMangle =
1664 getASTContext().getManglingNumber(TD, Context.isAux());
1665 Out << "Ut";
1666 if (UnnamedMangle > 1)
1667 Out << UnnamedMangle - 2;
1668 Out << '_';
1669 writeAbiTags(TD, AdditionalAbiTags);
1670 break;
1671 }
1672
1673 // Get a unique id for the anonymous struct. If it is not a real output
1674 // ID doesn't matter so use fake one.
1675 unsigned AnonStructId =
1676 NullOut ? 0
1677 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1678
1679 // Mangle it as a source name in the form
1680 // [n] $_<id>
1681 // where n is the length of the string.
1682 SmallString<8> Str;
1683 Str += "$_";
1684 Str += llvm::utostr(AnonStructId);
1685
1686 Out << Str.size();
1687 Out << Str;
1688 break;
1689 }
1690
1694 llvm_unreachable("Can't mangle Objective-C selector names here!");
1695
1697 const CXXRecordDecl *InheritedFrom = nullptr;
1698 TemplateName InheritedTemplateName;
1699 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1700 if (auto Inherited =
1701 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1702 InheritedFrom = Inherited.getConstructor()->getParent();
1703 InheritedTemplateName =
1704 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1705 InheritedTemplateArgs =
1706 Inherited.getConstructor()->getTemplateSpecializationArgs();
1707 }
1708
1709 if (ND == Structor)
1710 // If the named decl is the C++ constructor we're mangling, use the type
1711 // we were given.
1712 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1713 else
1714 // Otherwise, use the complete constructor name. This is relevant if a
1715 // class with a constructor is declared within a constructor.
1716 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1717
1718 // FIXME: The template arguments are part of the enclosing prefix or
1719 // nested-name, but it's more convenient to mangle them here.
1720 if (InheritedTemplateArgs)
1721 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1722
1723 writeAbiTags(ND, AdditionalAbiTags);
1724 break;
1725 }
1726
1728 if (ND == Structor)
1729 // If the named decl is the C++ destructor we're mangling, use the type we
1730 // were given.
1731 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1732 else
1733 // Otherwise, use the complete destructor name. This is relevant if a
1734 // class with a destructor is declared within a destructor.
1735 mangleCXXDtorType(Dtor_Complete);
1736 assert(ND);
1737 writeAbiTags(ND, AdditionalAbiTags);
1738 break;
1739
1741 if (ND && Arity == UnknownArity) {
1742 Arity = cast<FunctionDecl>(ND)->getNumParams();
1743
1744 // If we have a member function, we need to include the 'this' pointer.
1745 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1746 if (MD->isImplicitObjectMemberFunction())
1747 Arity++;
1748 }
1749 [[fallthrough]];
1752 mangleOperatorName(Name, Arity);
1753 writeAbiTags(ND, AdditionalAbiTags);
1754 break;
1755
1757 llvm_unreachable("Can't mangle a deduction guide name!");
1758
1760 llvm_unreachable("Can't mangle a using directive name!");
1761 }
1762}
1763
1764void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1765 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1766 // <number> ::= [n] <non-negative decimal integer>
1767 // <identifier> ::= <unqualified source code identifier>
1768 if (getASTContext().getLangOpts().RegCall4)
1769 Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1770 << II->getName();
1771 else
1772 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1773 << II->getName();
1774}
1775
1776void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1777 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1778 // <number> ::= [n] <non-negative decimal integer>
1779 // <identifier> ::= <unqualified source code identifier>
1780 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1781 << II->getName();
1782}
1783
1784void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1785 // <source-name> ::= <positive length number> <identifier>
1786 // <number> ::= [n] <non-negative decimal integer>
1787 // <identifier> ::= <unqualified source code identifier>
1788 Out << II->getLength() << II->getName();
1789}
1790
1791void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1792 const DeclContext *DC,
1793 const AbiTagList *AdditionalAbiTags,
1794 bool NoFunction) {
1795 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1796 // <nested-name>
1797 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1798 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1799 // <template-args> E
1800
1801 Out << 'N';
1802 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1803 Qualifiers MethodQuals = Method->getMethodQualifiers();
1804 // We do not consider restrict a distinguishing attribute for overloading
1805 // purposes so we must not mangle it.
1806 if (Method->isExplicitObjectMemberFunction())
1807 Out << 'H';
1808 MethodQuals.removeRestrict();
1809 mangleQualifiers(MethodQuals);
1810 mangleRefQualifier(Method->getRefQualifier());
1811 }
1812
1813 // Check if we have a template.
1814 const TemplateArgumentList *TemplateArgs = nullptr;
1815 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1816 mangleTemplatePrefix(TD, NoFunction);
1817 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1818 } else {
1819 manglePrefix(DC, NoFunction);
1820 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1821 }
1822
1823 Out << 'E';
1824}
1825void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1827 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1828
1829 Out << 'N';
1830
1831 mangleTemplatePrefix(TD);
1832 mangleTemplateArgs(asTemplateName(TD), Args);
1833
1834 Out << 'E';
1835}
1836
1837void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1838 GlobalDecl GD, const NamedDecl *PrefixND,
1839 const AbiTagList *AdditionalAbiTags) {
1840 // A <closure-prefix> represents a variable or field, not a regular
1841 // DeclContext, so needs special handling. In this case we're mangling a
1842 // limited form of <nested-name>:
1843 //
1844 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1845
1846 Out << 'N';
1847
1848 mangleClosurePrefix(PrefixND);
1849 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1850
1851 Out << 'E';
1852}
1853
1855 GlobalDecl GD;
1856 // The Itanium spec says:
1857 // For entities in constructors and destructors, the mangling of the
1858 // complete object constructor or destructor is used as the base function
1859 // name, i.e. the C1 or D1 version.
1860 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1861 GD = GlobalDecl(CD, Ctor_Complete);
1862 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1863 GD = GlobalDecl(DD, Dtor_Complete);
1864 else
1865 GD = GlobalDecl(cast<FunctionDecl>(DC));
1866 return GD;
1867}
1868
1869void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1870 const AbiTagList *AdditionalAbiTags) {
1871 const Decl *D = GD.getDecl();
1872 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1873 // := Z <function encoding> E s [<discriminator>]
1874 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1875 // _ <entity name>
1876 // <discriminator> := _ <non-negative number>
1877 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1878 const RecordDecl *RD = GetLocalClassDecl(D);
1879 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1880
1881 Out << 'Z';
1882
1883 {
1884 AbiTagState LocalAbiTags(AbiTags);
1885
1886 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1887 mangleObjCMethodName(MD);
1888 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1889 mangleBlockForPrefix(BD);
1890 else
1891 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1892
1893 // Implicit ABI tags (from namespace) are not available in the following
1894 // entity; reset to actually emitted tags, which are available.
1895 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1896 }
1897
1898 Out << 'E';
1899
1900 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1901 // be a bug that is fixed in trunk.
1902
1903 if (RD) {
1904 // The parameter number is omitted for the last parameter, 0 for the
1905 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1906 // <entity name> will of course contain a <closure-type-name>: Its
1907 // numbering will be local to the particular argument in which it appears
1908 // -- other default arguments do not affect its encoding.
1909 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1910 if (CXXRD && CXXRD->isLambda()) {
1911 if (const ParmVarDecl *Parm
1912 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1913 if (const FunctionDecl *Func
1914 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1915 Out << 'd';
1916 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1917 if (Num > 1)
1918 mangleNumber(Num - 2);
1919 Out << '_';
1920 }
1921 }
1922 }
1923
1924 // Mangle the name relative to the closest enclosing function.
1925 // equality ok because RD derived from ND above
1926 if (D == RD) {
1927 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1928 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1929 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1930 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1931 else
1932 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1933 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1934 mangleUnqualifiedBlock(BD);
1935 } else {
1936 const NamedDecl *ND = cast<NamedDecl>(D);
1937 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1938 AdditionalAbiTags, true /*NoFunction*/);
1939 }
1940 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1941 // Mangle a block in a default parameter; see above explanation for
1942 // lambdas.
1943 if (const ParmVarDecl *Parm
1944 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1945 if (const FunctionDecl *Func
1946 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1947 Out << 'd';
1948 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1949 if (Num > 1)
1950 mangleNumber(Num - 2);
1951 Out << '_';
1952 }
1953 }
1954
1955 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1956 mangleUnqualifiedBlock(BD);
1957 } else {
1958 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1959 }
1960
1961 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1962 unsigned disc;
1963 if (Context.getNextDiscriminator(ND, disc)) {
1964 if (disc < 10)
1965 Out << '_' << disc;
1966 else
1967 Out << "__" << disc << '_';
1968 }
1969 }
1970}
1971
1972void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1973 if (GetLocalClassDecl(Block)) {
1974 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1975 return;
1976 }
1977 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1978 if (isLocalContainerContext(DC)) {
1979 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1980 return;
1981 }
1982 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1983 mangleClosurePrefix(PrefixND);
1984 else
1985 manglePrefix(DC);
1986 mangleUnqualifiedBlock(Block);
1987}
1988
1989void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1990 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1991 // <data-member-prefix> now, with no substitutions and no <template-args>.
1992 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1993 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1994 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1995 Context->getDeclContext()->isRecord()) {
1996 const auto *ND = cast<NamedDecl>(Context);
1997 if (ND->getIdentifier()) {
1998 mangleSourceNameWithAbiTags(ND);
1999 Out << 'M';
2000 }
2001 }
2002 }
2003
2004 // If we have a block mangling number, use it.
2005 unsigned Number = Block->getBlockManglingNumber();
2006 // Otherwise, just make up a number. It doesn't matter what it is because
2007 // the symbol in question isn't externally visible.
2008 if (!Number)
2009 Number = Context.getBlockId(Block, false);
2010 else {
2011 // Stored mangling numbers are 1-based.
2012 --Number;
2013 }
2014 Out << "Ub";
2015 if (Number > 0)
2016 Out << Number - 1;
2017 Out << '_';
2018}
2019
2020// <template-param-decl>
2021// ::= Ty # template type parameter
2022// ::= Tk <concept name> [<template-args>] # constrained type parameter
2023// ::= Tn <type> # template non-type parameter
2024// ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2025// # template template parameter
2026// ::= Tp <template-param-decl> # template parameter pack
2027void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2028 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2029 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2030 if (Ty->isParameterPack())
2031 Out << "Tp";
2032 const TypeConstraint *Constraint = Ty->getTypeConstraint();
2033 if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2034 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2035 Out << "Tk";
2036 mangleTypeConstraint(Constraint);
2037 } else {
2038 Out << "Ty";
2039 }
2040 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2041 if (Tn->isExpandedParameterPack()) {
2042 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2043 Out << "Tn";
2044 mangleType(Tn->getExpansionType(I));
2045 }
2046 } else {
2047 QualType T = Tn->getType();
2048 if (Tn->isParameterPack()) {
2049 Out << "Tp";
2050 if (auto *PackExpansion = T->getAs<PackExpansionType>())
2051 T = PackExpansion->getPattern();
2052 }
2053 Out << "Tn";
2054 mangleType(T);
2055 }
2056 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2057 if (Tt->isExpandedParameterPack()) {
2058 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2059 ++I)
2060 mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2061 } else {
2062 if (Tt->isParameterPack())
2063 Out << "Tp";
2064 mangleTemplateParameterList(Tt->getTemplateParameters());
2065 }
2066 }
2067}
2068
2069void CXXNameMangler::mangleTemplateParameterList(
2070 const TemplateParameterList *Params) {
2071 Out << "Tt";
2072 for (auto *Param : *Params)
2073 mangleTemplateParamDecl(Param);
2074 mangleRequiresClause(Params->getRequiresClause());
2075 Out << "E";
2076}
2077
2078void CXXNameMangler::mangleTypeConstraint(
2079 const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
2080 const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
2081 if (!Arguments.empty())
2082 mangleTemplateName(Concept, Arguments);
2083 else if (DC->isTranslationUnit() || isStdNamespace(DC))
2084 mangleUnscopedName(Concept, DC, nullptr);
2085 else
2086 mangleNestedName(Concept, DC, nullptr);
2087}
2088
2089void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2091 if (Constraint->getTemplateArgsAsWritten()) {
2092 for (const TemplateArgumentLoc &ArgLoc :
2093 Constraint->getTemplateArgsAsWritten()->arguments())
2094 Args.push_back(ArgLoc.getArgument());
2095 }
2096 return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
2097}
2098
2099void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2100 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2101 if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2102 Out << 'Q';
2103 mangleExpression(RequiresClause);
2104 }
2105}
2106
2107void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2108 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2109 // <data-member-prefix> now, with no substitutions.
2110 if (Decl *Context = Lambda->getLambdaContextDecl()) {
2111 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2112 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
2113 !isa<ParmVarDecl>(Context)) {
2114 if (const IdentifierInfo *Name
2115 = cast<NamedDecl>(Context)->getIdentifier()) {
2116 mangleSourceName(Name);
2117 const TemplateArgumentList *TemplateArgs = nullptr;
2118 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2119 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2120 Out << 'M';
2121 }
2122 }
2123 }
2124
2125 Out << "Ul";
2126 mangleLambdaSig(Lambda);
2127 Out << "E";
2128
2129 // The number is omitted for the first closure type with a given
2130 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2131 // (in lexical order) with that same <lambda-sig> and context.
2132 //
2133 // The AST keeps track of the number for us.
2134 //
2135 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2136 // and host-side compilations, an extra device mangle context may be created
2137 // if the host-side CXX ABI has different numbering for lambda. In such case,
2138 // if the mangle context is that device-side one, use the device-side lambda
2139 // mangling number for this lambda.
2140 std::optional<unsigned> DeviceNumber =
2141 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2142 unsigned Number =
2143 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2144
2145 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2146 if (Number > 1)
2147 mangleNumber(Number - 2);
2148 Out << '_';
2149}
2150
2151void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2152 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2153 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2154 mangleTemplateParamDecl(D);
2155
2156 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2157 if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2158 mangleRequiresClause(TPL->getRequiresClause());
2159
2160 auto *Proto =
2162 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2163 Lambda->getLambdaStaticInvoker());
2164}
2165
2166void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2167 switch (qualifier->getKind()) {
2169 // nothing
2170 return;
2171
2173 llvm_unreachable("Can't mangle __super specifier");
2174
2176 mangleName(qualifier->getAsNamespace());
2177 return;
2178
2180 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2181 return;
2182
2185 manglePrefix(QualType(qualifier->getAsType(), 0));
2186 return;
2187
2189 // Clang 14 and before did not consider this substitutable.
2190 bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
2191 if (!Clang14Compat && mangleSubstitution(qualifier))
2192 return;
2193
2194 // Member expressions can have these without prefixes, but that
2195 // should end up in mangleUnresolvedPrefix instead.
2196 assert(qualifier->getPrefix());
2197 manglePrefix(qualifier->getPrefix());
2198
2199 mangleSourceName(qualifier->getAsIdentifier());
2200
2201 if (!Clang14Compat)
2202 addSubstitution(qualifier);
2203 return;
2204 }
2205
2206 llvm_unreachable("unexpected nested name specifier");
2207}
2208
2209void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2210 // <prefix> ::= <prefix> <unqualified-name>
2211 // ::= <template-prefix> <template-args>
2212 // ::= <closure-prefix>
2213 // ::= <template-param>
2214 // ::= # empty
2215 // ::= <substitution>
2216
2217 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2218
2219 if (DC->isTranslationUnit())
2220 return;
2221
2222 if (NoFunction && isLocalContainerContext(DC))
2223 return;
2224
2225 const NamedDecl *ND = cast<NamedDecl>(DC);
2226 if (mangleSubstitution(ND))
2227 return;
2228
2229 // Check if we have a template-prefix or a closure-prefix.
2230 const TemplateArgumentList *TemplateArgs = nullptr;
2231 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2232 mangleTemplatePrefix(TD);
2233 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2234 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2235 mangleClosurePrefix(PrefixND, NoFunction);
2236 mangleUnqualifiedName(ND, nullptr, nullptr);
2237 } else {
2238 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2239 manglePrefix(DC, NoFunction);
2240 mangleUnqualifiedName(ND, DC, nullptr);
2241 }
2242
2243 addSubstitution(ND);
2244}
2245
2246void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2247 // <template-prefix> ::= <prefix> <template unqualified-name>
2248 // ::= <template-param>
2249 // ::= <substitution>
2250 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2251 return mangleTemplatePrefix(TD);
2252
2254 assert(Dependent && "unexpected template name kind");
2255
2256 // Clang 11 and before mangled the substitution for a dependent template name
2257 // after already having emitted (a substitution for) the prefix.
2258 bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2259 if (!Clang11Compat && mangleSubstitution(Template))
2260 return;
2261
2262 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2263 manglePrefix(Qualifier);
2264
2265 if (Clang11Compat && mangleSubstitution(Template))
2266 return;
2267
2268 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2269 mangleSourceName(Id);
2270 else
2271 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2272
2273 addSubstitution(Template);
2274}
2275
2276void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2277 bool NoFunction) {
2278 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2279 // <template-prefix> ::= <prefix> <template unqualified-name>
2280 // ::= <template-param>
2281 // ::= <substitution>
2282 // <template-template-param> ::= <template-param>
2283 // <substitution>
2284
2285 if (mangleSubstitution(ND))
2286 return;
2287
2288 // <template-template-param> ::= <template-param>
2289 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2290 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2291 } else {
2292 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2293 manglePrefix(DC, NoFunction);
2294 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2295 mangleUnqualifiedName(GD, DC, nullptr);
2296 else
2297 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2298 nullptr);
2299 }
2300
2301 addSubstitution(ND);
2302}
2303
2304const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2305 if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2306 return nullptr;
2307
2308 const NamedDecl *Context = nullptr;
2309 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2310 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2311 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2312 if (RD->isLambda())
2313 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2314 }
2315 if (!Context)
2316 return nullptr;
2317
2318 // Only lambdas within the initializer of a non-local variable or non-static
2319 // data member get a <closure-prefix>.
2320 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2321 isa<FieldDecl>(Context))
2322 return Context;
2323
2324 return nullptr;
2325}
2326
2327void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2328 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2329 // ::= <template-prefix> <template-args> M
2330 if (mangleSubstitution(ND))
2331 return;
2332
2333 const TemplateArgumentList *TemplateArgs = nullptr;
2334 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2335 mangleTemplatePrefix(TD, NoFunction);
2336 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2337 } else {
2338 const auto *DC = Context.getEffectiveDeclContext(ND);
2339 manglePrefix(DC, NoFunction);
2340 mangleUnqualifiedName(ND, DC, nullptr);
2341 }
2342
2343 Out << 'M';
2344
2345 addSubstitution(ND);
2346}
2347
2348/// Mangles a template name under the production <type>. Required for
2349/// template template arguments.
2350/// <type> ::= <class-enum-type>
2351/// ::= <template-param>
2352/// ::= <substitution>
2353void CXXNameMangler::mangleType(TemplateName TN) {
2354 if (mangleSubstitution(TN))
2355 return;
2356
2357 TemplateDecl *TD = nullptr;
2358
2359 switch (TN.getKind()) {
2363 TD = TN.getAsTemplateDecl();
2364 goto HaveDecl;
2365
2366 HaveDecl:
2367 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2368 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2369 else
2370 mangleName(TD);
2371 break;
2372
2375 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2376
2379 assert(Dependent->isIdentifier());
2380
2381 // <class-enum-type> ::= <name>
2382 // <name> ::= <nested-name>
2383 mangleUnresolvedPrefix(Dependent->getQualifier());
2384 mangleSourceName(Dependent->getIdentifier());
2385 break;
2386 }
2387
2389 // Substituted template parameters are mangled as the substituted
2390 // template. This will check for the substitution twice, which is
2391 // fine, but we have to return early so that we don't try to *add*
2392 // the substitution twice.
2395 mangleType(subst->getReplacement());
2396 return;
2397 }
2398
2400 // FIXME: not clear how to mangle this!
2401 // template <template <class> class T...> class A {
2402 // template <template <class> class U...> void foo(B<T,U> x...);
2403 // };
2404 Out << "_SUBSTPACK_";
2405 break;
2406 }
2408 llvm_unreachable("Unexpected DeducedTemplate");
2409 }
2410
2411 addSubstitution(TN);
2412}
2413
2414bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2415 StringRef Prefix) {
2416 // Only certain other types are valid as prefixes; enumerate them.
2417 switch (Ty->getTypeClass()) {
2418 case Type::Builtin:
2419 case Type::Complex:
2420 case Type::Adjusted:
2421 case Type::Decayed:
2422 case Type::ArrayParameter:
2423 case Type::Pointer:
2424 case Type::BlockPointer:
2425 case Type::LValueReference:
2426 case Type::RValueReference:
2427 case Type::MemberPointer:
2428 case Type::ConstantArray:
2429 case Type::IncompleteArray:
2430 case Type::VariableArray:
2431 case Type::DependentSizedArray:
2432 case Type::DependentAddressSpace:
2433 case Type::DependentVector:
2434 case Type::DependentSizedExtVector:
2435 case Type::Vector:
2436 case Type::ExtVector:
2437 case Type::ConstantMatrix:
2438 case Type::DependentSizedMatrix:
2439 case Type::FunctionProto:
2440 case Type::FunctionNoProto:
2441 case Type::Paren:
2442 case Type::Attributed:
2443 case Type::BTFTagAttributed:
2444 case Type::HLSLAttributedResource:
2445 case Type::Auto:
2446 case Type::DeducedTemplateSpecialization:
2447 case Type::PackExpansion:
2448 case Type::ObjCObject:
2449 case Type::ObjCInterface:
2450 case Type::ObjCObjectPointer:
2451 case Type::ObjCTypeParam:
2452 case Type::Atomic:
2453 case Type::Pipe:
2454 case Type::MacroQualified:
2455 case Type::BitInt:
2456 case Type::DependentBitInt:
2457 case Type::CountAttributed:
2458 llvm_unreachable("type is illegal as a nested name specifier");
2459
2460 case Type::SubstTemplateTypeParmPack:
2461 // FIXME: not clear how to mangle this!
2462 // template <class T...> class A {
2463 // template <class U...> void foo(decltype(T::foo(U())) x...);
2464 // };
2465 Out << "_SUBSTPACK_";
2466 break;
2467
2468 // <unresolved-type> ::= <template-param>
2469 // ::= <decltype>
2470 // ::= <template-template-param> <template-args>
2471 // (this last is not official yet)
2472 case Type::TypeOfExpr:
2473 case Type::TypeOf:
2474 case Type::Decltype:
2475 case Type::PackIndexing:
2476 case Type::TemplateTypeParm:
2477 case Type::UnaryTransform:
2478 case Type::SubstTemplateTypeParm:
2479 unresolvedType:
2480 // Some callers want a prefix before the mangled type.
2481 Out << Prefix;
2482
2483 // This seems to do everything we want. It's not really
2484 // sanctioned for a substituted template parameter, though.
2485 mangleType(Ty);
2486
2487 // We never want to print 'E' directly after an unresolved-type,
2488 // so we return directly.
2489 return true;
2490
2491 case Type::Typedef:
2492 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2493 break;
2494
2495 case Type::UnresolvedUsing:
2496 mangleSourceNameWithAbiTags(
2497 cast<UnresolvedUsingType>(Ty)->getDecl());
2498 break;
2499
2500 case Type::Enum:
2501 case Type::Record:
2502 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2503 break;
2504
2505 case Type::TemplateSpecialization: {
2506 const TemplateSpecializationType *TST =
2507 cast<TemplateSpecializationType>(Ty);
2508 TemplateName TN = TST->getTemplateName();
2509 switch (TN.getKind()) {
2513
2514 // If the base is a template template parameter, this is an
2515 // unresolved type.
2516 assert(TD && "no template for template specialization type");
2517 if (isa<TemplateTemplateParmDecl>(TD))
2518 goto unresolvedType;
2519
2520 mangleSourceNameWithAbiTags(TD);
2521 break;
2522 }
2523
2528 llvm_unreachable("invalid base for a template specialization type");
2529
2533 mangleExistingSubstitution(subst->getReplacement());
2534 break;
2535 }
2536
2538 // FIXME: not clear how to mangle this!
2539 // template <template <class U> class T...> class A {
2540 // template <class U...> void foo(decltype(T<U>::foo) x...);
2541 // };
2542 Out << "_SUBSTPACK_";
2543 break;
2544 }
2547 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2548 mangleSourceNameWithAbiTags(TD);
2549 break;
2550 }
2551 }
2552
2553 // Note: we don't pass in the template name here. We are mangling the
2554 // original source-level template arguments, so we shouldn't consider
2555 // conversions to the corresponding template parameter.
2556 // FIXME: Other compilers mangle partially-resolved template arguments in
2557 // unresolved-qualifier-levels.
2558 mangleTemplateArgs(TemplateName(), TST->template_arguments());
2559 break;
2560 }
2561
2562 case Type::InjectedClassName:
2563 mangleSourceNameWithAbiTags(
2564 cast<InjectedClassNameType>(Ty)->getDecl());
2565 break;
2566
2567 case Type::DependentName:
2568 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2569 break;
2570
2571 case Type::DependentTemplateSpecialization: {
2573 cast<DependentTemplateSpecializationType>(Ty);
2574 TemplateName Template = getASTContext().getDependentTemplateName(
2575 DTST->getQualifier(), DTST->getIdentifier());
2576 mangleSourceName(DTST->getIdentifier());
2577 mangleTemplateArgs(Template, DTST->template_arguments());
2578 break;
2579 }
2580
2581 case Type::Using:
2582 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2583 Prefix);
2584 case Type::Elaborated:
2585 return mangleUnresolvedTypeOrSimpleId(
2586 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2587 }
2588
2589 return false;
2590}
2591
2592void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2593 switch (Name.getNameKind()) {
2602 llvm_unreachable("Not an operator name");
2603
2605 // <operator-name> ::= cv <type> # (cast)
2606 Out << "cv";
2607 mangleType(Name.getCXXNameType());
2608 break;
2609
2611 Out << "li";
2612 mangleSourceName(Name.getCXXLiteralIdentifier());
2613 return;
2614
2616 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2617 break;
2618 }
2619}
2620
2621void
2622CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2623 switch (OO) {
2624 // <operator-name> ::= nw # new
2625 case OO_New: Out << "nw"; break;
2626 // ::= na # new[]
2627 case OO_Array_New: Out << "na"; break;
2628 // ::= dl # delete
2629 case OO_Delete: Out << "dl"; break;
2630 // ::= da # delete[]
2631 case OO_Array_Delete: Out << "da"; break;
2632 // ::= ps # + (unary)
2633 // ::= pl # + (binary or unknown)
2634 case OO_Plus:
2635 Out << (Arity == 1? "ps" : "pl"); break;
2636 // ::= ng # - (unary)
2637 // ::= mi # - (binary or unknown)
2638 case OO_Minus:
2639 Out << (Arity == 1? "ng" : "mi"); break;
2640 // ::= ad # & (unary)
2641 // ::= an # & (binary or unknown)
2642 case OO_Amp:
2643 Out << (Arity == 1? "ad" : "an"); break;
2644 // ::= de # * (unary)
2645 // ::= ml # * (binary or unknown)
2646 case OO_Star:
2647 // Use binary when unknown.
2648 Out << (Arity == 1? "de" : "ml"); break;
2649 // ::= co # ~
2650 case OO_Tilde: Out << "co"; break;
2651 // ::= dv # /
2652 case OO_Slash: Out << "dv"; break;
2653 // ::= rm # %
2654 case OO_Percent: Out << "rm"; break;
2655 // ::= or # |
2656 case OO_Pipe: Out << "or"; break;
2657 // ::= eo # ^
2658 case OO_Caret: Out << "eo"; break;
2659 // ::= aS # =
2660 case OO_Equal: Out << "aS"; break;
2661 // ::= pL # +=
2662 case OO_PlusEqual: Out << "pL"; break;
2663 // ::= mI # -=
2664 case OO_MinusEqual: Out << "mI"; break;
2665 // ::= mL # *=
2666 case OO_StarEqual: Out << "mL"; break;
2667 // ::= dV # /=
2668 case OO_SlashEqual: Out << "dV"; break;
2669 // ::= rM # %=
2670 case OO_PercentEqual: Out << "rM"; break;
2671 // ::= aN # &=
2672 case OO_AmpEqual: Out << "aN"; break;
2673 // ::= oR # |=
2674 case OO_PipeEqual: Out << "oR"; break;
2675 // ::= eO # ^=
2676 case OO_CaretEqual: Out << "eO"; break;
2677 // ::= ls # <<
2678 case OO_LessLess: Out << "ls"; break;
2679 // ::= rs # >>
2680 case OO_GreaterGreater: Out << "rs"; break;
2681 // ::= lS # <<=
2682 case OO_LessLessEqual: Out << "lS"; break;
2683 // ::= rS # >>=
2684 case OO_GreaterGreaterEqual: Out << "rS"; break;
2685 // ::= eq # ==
2686 case OO_EqualEqual: Out << "eq"; break;
2687 // ::= ne # !=
2688 case OO_ExclaimEqual: Out << "ne"; break;
2689 // ::= lt # <
2690 case OO_Less: Out << "lt"; break;
2691 // ::= gt # >
2692 case OO_Greater: Out << "gt"; break;
2693 // ::= le # <=
2694 case OO_LessEqual: Out << "le"; break;
2695 // ::= ge # >=
2696 case OO_GreaterEqual: Out << "ge"; break;
2697 // ::= nt # !
2698 case OO_Exclaim: Out << "nt"; break;
2699 // ::= aa # &&
2700 case OO_AmpAmp: Out << "aa"; break;
2701 // ::= oo # ||
2702 case OO_PipePipe: Out << "oo"; break;
2703 // ::= pp # ++
2704 case OO_PlusPlus: Out << "pp"; break;
2705 // ::= mm # --
2706 case OO_MinusMinus: Out << "mm"; break;
2707 // ::= cm # ,
2708 case OO_Comma: Out << "cm"; break;
2709 // ::= pm # ->*
2710 case OO_ArrowStar: Out << "pm"; break;
2711 // ::= pt # ->
2712 case OO_Arrow: Out << "pt"; break;
2713 // ::= cl # ()
2714 case OO_Call: Out << "cl"; break;
2715 // ::= ix # []
2716 case OO_Subscript: Out << "ix"; break;
2717
2718 // ::= qu # ?
2719 // The conditional operator can't be overloaded, but we still handle it when
2720 // mangling expressions.
2721 case OO_Conditional: Out << "qu"; break;
2722 // Proposal on cxx-abi-dev, 2015-10-21.
2723 // ::= aw # co_await
2724 case OO_Coawait: Out << "aw"; break;
2725 // Proposed in cxx-abi github issue 43.
2726 // ::= ss # <=>
2727 case OO_Spaceship: Out << "ss"; break;
2728
2729 case OO_None:
2731 llvm_unreachable("Not an overloaded operator");
2732 }
2733}
2734
2735void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2736 // Vendor qualifiers come first and if they are order-insensitive they must
2737 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2738
2739 // <type> ::= U <addrspace-expr>
2740 if (DAST) {
2741 Out << "U2ASI";
2742 mangleExpression(DAST->getAddrSpaceExpr());
2743 Out << "E";
2744 }
2745
2746 // Address space qualifiers start with an ordinary letter.
2747 if (Quals.hasAddressSpace()) {
2748 // Address space extension:
2749 //
2750 // <type> ::= U <target-addrspace>
2751 // <type> ::= U <OpenCL-addrspace>
2752 // <type> ::= U <CUDA-addrspace>
2753
2754 SmallString<64> ASString;
2755 LangAS AS = Quals.getAddressSpace();
2756
2757 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2758 // <target-addrspace> ::= "AS" <address-space-number>
2759 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2760 if (TargetAS != 0 ||
2761 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2762 ASString = "AS" + llvm::utostr(TargetAS);
2763 } else {
2764 switch (AS) {
2765 default: llvm_unreachable("Not a language specific address space");
2766 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2767 // "private"| "generic" | "device" |
2768 // "host" ]
2769 case LangAS::opencl_global:
2770 ASString = "CLglobal";
2771 break;
2772 case LangAS::opencl_global_device:
2773 ASString = "CLdevice";
2774 break;
2775 case LangAS::opencl_global_host:
2776 ASString = "CLhost";
2777 break;
2778 case LangAS::opencl_local:
2779 ASString = "CLlocal";
2780 break;
2781 case LangAS::opencl_constant:
2782 ASString = "CLconstant";
2783 break;
2784 case LangAS::opencl_private:
2785 ASString = "CLprivate";
2786 break;
2787 case LangAS::opencl_generic:
2788 ASString = "CLgeneric";
2789 break;
2790 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2791 // "device" | "host" ]
2792 case LangAS::sycl_global:
2793 ASString = "SYglobal";
2794 break;
2795 case LangAS::sycl_global_device:
2796 ASString = "SYdevice";
2797 break;
2798 case LangAS::sycl_global_host:
2799 ASString = "SYhost";
2800 break;
2801 case LangAS::sycl_local:
2802 ASString = "SYlocal";
2803 break;
2804 case LangAS::sycl_private:
2805 ASString = "SYprivate";
2806 break;
2807 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2808 case LangAS::cuda_device:
2809 ASString = "CUdevice";
2810 break;
2811 case LangAS::cuda_constant:
2812 ASString = "CUconstant";
2813 break;
2814 case LangAS::cuda_shared:
2815 ASString = "CUshared";
2816 break;
2817 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2818 case LangAS::ptr32_sptr:
2819 ASString = "ptr32_sptr";
2820 break;
2821 case LangAS::ptr32_uptr:
2822 // For z/OS, there are no special mangling rules applied to the ptr32
2823 // qualifier. Ex: void foo(int * __ptr32 p) -> _Z3f2Pi. The mangling for
2824 // "p" is treated the same as a regular integer pointer.
2825 if (!getASTContext().getTargetInfo().getTriple().isOSzOS())
2826 ASString = "ptr32_uptr";
2827 break;
2828 case LangAS::ptr64:
2829 ASString = "ptr64";
2830 break;
2831 }
2832 }
2833 if (!ASString.empty())
2834 mangleVendorQualifier(ASString);
2835 }
2836
2837 // The ARC ownership qualifiers start with underscores.
2838 // Objective-C ARC Extension:
2839 //
2840 // <type> ::= U "__strong"
2841 // <type> ::= U "__weak"
2842 // <type> ::= U "__autoreleasing"
2843 //
2844 // Note: we emit __weak first to preserve the order as
2845 // required by the Itanium ABI.
2847 mangleVendorQualifier("__weak");
2848
2849 // __unaligned (from -fms-extensions)
2850 if (Quals.hasUnaligned())
2851 mangleVendorQualifier("__unaligned");
2852
2853 // Remaining ARC ownership qualifiers.
2854 switch (Quals.getObjCLifetime()) {
2856 break;
2857
2859 // Do nothing as we already handled this case above.
2860 break;
2861
2863 mangleVendorQualifier("__strong");
2864 break;
2865
2867 mangleVendorQualifier("__autoreleasing");
2868 break;
2869
2871 // The __unsafe_unretained qualifier is *not* mangled, so that
2872 // __unsafe_unretained types in ARC produce the same manglings as the
2873 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2874 // better ABI compatibility.
2875 //
2876 // It's safe to do this because unqualified 'id' won't show up
2877 // in any type signatures that need to be mangled.
2878 break;
2879 }
2880
2881 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2882 if (Quals.hasRestrict())
2883 Out << 'r';
2884 if (Quals.hasVolatile())
2885 Out << 'V';
2886 if (Quals.hasConst())
2887 Out << 'K';
2888}
2889
2890void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2891 Out << 'U' << name.size() << name;
2892}
2893
2894void CXXNameMangler::mangleVendorType(StringRef name) {
2895 Out << 'u' << name.size() << name;
2896}
2897
2898void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2899 // <ref-qualifier> ::= R # lvalue reference
2900 // ::= O # rvalue-reference
2901 switch (RefQualifier) {
2902 case RQ_None:
2903 break;
2904
2905 case RQ_LValue:
2906 Out << 'R';
2907 break;
2908
2909 case RQ_RValue:
2910 Out << 'O';
2911 break;
2912 }
2913}
2914
2915void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2916 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2917}
2918
2919static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2920 ASTContext &Ctx) {
2921 if (Quals)
2922 return true;
2923 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2924 return true;
2925 if (Ty->isOpenCLSpecificType())
2926 return true;
2927 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2928 if (Ty->isSVESizelessBuiltinType() &&
2929 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2930 return true;
2931 if (Ty->isBuiltinType())
2932 return false;
2933 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2934 // substitution candidates.
2935 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2936 isa<AutoType>(Ty))
2937 return false;
2938 // A placeholder type for class template deduction is substitutable with
2939 // its corresponding template name; this is handled specially when mangling
2940 // the type.
2941 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2942 if (DeducedTST->getDeducedType().isNull())
2943 return false;
2944 return true;
2945}
2946
2947void CXXNameMangler::mangleType(QualType T) {
2948 // If our type is instantiation-dependent but not dependent, we mangle
2949 // it as it was written in the source, removing any top-level sugar.
2950 // Otherwise, use the canonical type.
2951 //
2952 // FIXME: This is an approximation of the instantiation-dependent name
2953 // mangling rules, since we should really be using the type as written and
2954 // augmented via semantic analysis (i.e., with implicit conversions and
2955 // default template arguments) for any instantiation-dependent type.
2956 // Unfortunately, that requires several changes to our AST:
2957 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2958 // uniqued, so that we can handle substitutions properly
2959 // - Default template arguments will need to be represented in the
2960 // TemplateSpecializationType, since they need to be mangled even though
2961 // they aren't written.
2962 // - Conversions on non-type template arguments need to be expressed, since
2963 // they can affect the mangling of sizeof/alignof.
2964 //
2965 // FIXME: This is wrong when mapping to the canonical type for a dependent
2966 // type discards instantiation-dependent portions of the type, such as for:
2967 //
2968 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2969 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2970 //
2971 // It's also wrong in the opposite direction when instantiation-dependent,
2972 // canonically-equivalent types differ in some irrelevant portion of inner
2973 // type sugar. In such cases, we fail to form correct substitutions, eg:
2974 //
2975 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2976 //
2977 // We should instead canonicalize the non-instantiation-dependent parts,
2978 // regardless of whether the type as a whole is dependent or instantiation
2979 // dependent.
2981 T = T.getCanonicalType();
2982 else {
2983 // Desugar any types that are purely sugar.
2984 do {
2985 // Don't desugar through template specialization types that aren't
2986 // type aliases. We need to mangle the template arguments as written.
2987 if (const TemplateSpecializationType *TST
2988 = dyn_cast<TemplateSpecializationType>(T))
2989 if (!TST->isTypeAlias())
2990 break;
2991
2992 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2993 // instantation-dependent qualifiers. See
2994 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2995
2996 QualType Desugared
2997 = T.getSingleStepDesugaredType(Context.getASTContext());
2998 if (Desugared == T)
2999 break;
3000
3001 T = Desugared;
3002 } while (true);
3003 }
3004 SplitQualType split = T.split();
3005 Qualifiers quals = split.Quals;
3006 const Type *ty = split.Ty;
3007
3008 bool isSubstitutable =
3009 isTypeSubstitutable(quals, ty, Context.getASTContext());
3010 if (isSubstitutable && mangleSubstitution(T))
3011 return;
3012
3013 // If we're mangling a qualified array type, push the qualifiers to
3014 // the element type.
3015 if (quals && isa<ArrayType>(T)) {
3016 ty = Context.getASTContext().getAsArrayType(T);
3017 quals = Qualifiers();
3018
3019 // Note that we don't update T: we want to add the
3020 // substitution at the original type.
3021 }
3022
3023 if (quals || ty->isDependentAddressSpaceType()) {
3024 if (const DependentAddressSpaceType *DAST =
3025 dyn_cast<DependentAddressSpaceType>(ty)) {
3026 SplitQualType splitDAST = DAST->getPointeeType().split();
3027 mangleQualifiers(splitDAST.Quals, DAST);
3028 mangleType(QualType(splitDAST.Ty, 0));
3029 } else {
3030 mangleQualifiers(quals);
3031
3032 // Recurse: even if the qualified type isn't yet substitutable,
3033 // the unqualified type might be.
3034 mangleType(QualType(ty, 0));
3035 }
3036 } else {
3037 switch (ty->getTypeClass()) {
3038#define ABSTRACT_TYPE(CLASS, PARENT)
3039#define NON_CANONICAL_TYPE(CLASS, PARENT) \
3040 case Type::CLASS: \
3041 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3042 return;
3043#define TYPE(CLASS, PARENT) \
3044 case Type::CLASS: \
3045 mangleType(static_cast<const CLASS##Type*>(ty)); \
3046 break;
3047#include "clang/AST/TypeNodes.inc"
3048 }
3049 }
3050
3051 // Add the substitution.
3052 if (isSubstitutable)
3053 addSubstitution(T);
3054}
3055
3056void CXXNameMangler::mangleCXXRecordDecl(const CXXRecordDecl *Record) {
3057 if (mangleSubstitution(Record))
3058 return;
3059 mangleName(Record);
3060 if (isCompatibleWith(LangOptions::ClangABI::Ver19))
3061 return;
3062 addSubstitution(Record);
3063}
3064
3065void CXXNameMangler::mangleType(const BuiltinType *T) {
3066 // <type> ::= <builtin-type>
3067 // <builtin-type> ::= v # void
3068 // ::= w # wchar_t
3069 // ::= b # bool
3070 // ::= c # char
3071 // ::= a # signed char
3072 // ::= h # unsigned char
3073 // ::= s # short
3074 // ::= t # unsigned short
3075 // ::= i # int
3076 // ::= j # unsigned int
3077 // ::= l # long
3078 // ::= m # unsigned long
3079 // ::= x # long long, __int64
3080 // ::= y # unsigned long long, __int64
3081 // ::= n # __int128
3082 // ::= o # unsigned __int128
3083 // ::= f # float
3084 // ::= d # double
3085 // ::= e # long double, __float80
3086 // ::= g # __float128
3087 // ::= g # __ibm128
3088 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3089 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3090 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3091 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3092 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3093 // ::= Di # char32_t
3094 // ::= Ds # char16_t
3095 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3096 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum
3097 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract
3098 // ::= u <source-name> # vendor extended type
3099 //
3100 // <fixed-point-size>
3101 // ::= s # short
3102 // ::= t # unsigned short
3103 // ::= i # plain
3104 // ::= j # unsigned
3105 // ::= l # long
3106 // ::= m # unsigned long
3107 std::string type_name;
3108 // Normalize integer types as vendor extended types:
3109 // u<length>i<type size>
3110 // u<length>u<type size>
3111 if (NormalizeIntegers && T->isInteger()) {
3112 if (T->isSignedInteger()) {
3113 switch (getASTContext().getTypeSize(T)) {
3114 case 8:
3115 // Pick a representative for each integer size in the substitution
3116 // dictionary. (Its actual defined size is not relevant.)
3117 if (mangleSubstitution(BuiltinType::SChar))
3118 break;
3119 Out << "u2i8";
3120 addSubstitution(BuiltinType::SChar);
3121 break;
3122 case 16:
3123 if (mangleSubstitution(BuiltinType::Short))
3124 break;
3125 Out << "u3i16";
3126 addSubstitution(BuiltinType::Short);
3127 break;
3128 case 32:
3129 if (mangleSubstitution(BuiltinType::Int))
3130 break;
3131 Out << "u3i32";
3132 addSubstitution(BuiltinType::Int);
3133 break;
3134 case 64:
3135 if (mangleSubstitution(BuiltinType::Long))
3136 break;
3137 Out << "u3i64";
3138 addSubstitution(BuiltinType::Long);
3139 break;
3140 case 128:
3141 if (mangleSubstitution(BuiltinType::Int128))
3142 break;
3143 Out << "u4i128";
3144 addSubstitution(BuiltinType::Int128);
3145 break;
3146 default:
3147 llvm_unreachable("Unknown integer size for normalization");
3148 }
3149 } else {
3150 switch (getASTContext().getTypeSize(T)) {
3151 case 8:
3152 if (mangleSubstitution(BuiltinType::UChar))
3153 break;
3154 Out << "u2u8";
3155 addSubstitution(BuiltinType::UChar);
3156 break;
3157 case 16:
3158 if (mangleSubstitution(BuiltinType::UShort))
3159 break;
3160 Out << "u3u16";
3161 addSubstitution(BuiltinType::UShort);
3162 break;
3163 case 32:
3164 if (mangleSubstitution(BuiltinType::UInt))
3165 break;
3166 Out << "u3u32";
3167 addSubstitution(BuiltinType::UInt);
3168 break;
3169 case 64:
3170 if (mangleSubstitution(BuiltinType::ULong))
3171 break;
3172 Out << "u3u64";
3173 addSubstitution(BuiltinType::ULong);
3174 break;
3175 case 128:
3176 if (mangleSubstitution(BuiltinType::UInt128))
3177 break;
3178 Out << "u4u128";
3179 addSubstitution(BuiltinType::UInt128);
3180 break;
3181 default:
3182 llvm_unreachable("Unknown integer size for normalization");
3183 }
3184 }
3185 return;
3186 }
3187 switch (T->getKind()) {
3188 case BuiltinType::Void:
3189 Out << 'v';
3190 break;
3191 case BuiltinType::Bool:
3192 Out << 'b';
3193 break;
3194 case BuiltinType::Char_U:
3195 case BuiltinType::Char_S:
3196 Out << 'c';
3197 break;
3198 case BuiltinType::UChar:
3199 Out << 'h';
3200 break;
3201 case BuiltinType::UShort:
3202 Out << 't';
3203 break;
3204 case BuiltinType::UInt:
3205 Out << 'j';
3206 break;
3207 case BuiltinType::ULong:
3208 Out << 'm';
3209 break;
3210 case BuiltinType::ULongLong:
3211 Out << 'y';
3212 break;
3213 case BuiltinType::UInt128:
3214 Out << 'o';
3215 break;
3216 case BuiltinType::SChar:
3217 Out << 'a';
3218 break;
3219 case BuiltinType::WChar_S:
3220 case BuiltinType::WChar_U:
3221 Out << 'w';
3222 break;
3223 case BuiltinType::Char8:
3224 Out << "Du";
3225 break;
3226 case BuiltinType::Char16:
3227 Out << "Ds";
3228 break;
3229 case BuiltinType::Char32:
3230 Out << "Di";
3231 break;
3232 case BuiltinType::Short:
3233 Out << 's';
3234 break;
3235 case BuiltinType::Int:
3236 Out << 'i';
3237 break;
3238 case BuiltinType::Long:
3239 Out << 'l';
3240 break;
3241 case BuiltinType::LongLong:
3242 Out << 'x';
3243 break;
3244 case BuiltinType::Int128:
3245 Out << 'n';
3246 break;
3247 case BuiltinType::Float16:
3248 Out << "DF16_";
3249 break;
3250 case BuiltinType::ShortAccum:
3251 Out << "DAs";
3252 break;
3253 case BuiltinType::Accum:
3254 Out << "DAi";
3255 break;
3256 case BuiltinType::LongAccum:
3257 Out << "DAl";
3258 break;
3259 case BuiltinType::UShortAccum:
3260 Out << "DAt";
3261 break;
3262 case BuiltinType::UAccum:
3263 Out << "DAj";
3264 break;
3265 case BuiltinType::ULongAccum:
3266 Out << "DAm";
3267 break;
3268 case BuiltinType::ShortFract:
3269 Out << "DRs";
3270 break;
3271 case BuiltinType::Fract:
3272 Out << "DRi";
3273 break;
3274 case BuiltinType::LongFract:
3275 Out << "DRl";
3276 break;
3277 case BuiltinType::UShortFract:
3278 Out << "DRt";
3279 break;
3280 case BuiltinType::UFract:
3281 Out << "DRj";
3282 break;
3283 case BuiltinType::ULongFract:
3284 Out << "DRm";
3285 break;
3286 case BuiltinType::SatShortAccum:
3287 Out << "DSDAs";
3288 break;
3289 case BuiltinType::SatAccum:
3290 Out << "DSDAi";
3291 break;
3292 case BuiltinType::SatLongAccum:
3293 Out << "DSDAl";
3294 break;
3295 case BuiltinType::SatUShortAccum:
3296 Out << "DSDAt";
3297 break;
3298 case BuiltinType::SatUAccum:
3299 Out << "DSDAj";
3300 break;
3301 case BuiltinType::SatULongAccum:
3302 Out << "DSDAm";
3303 break;
3304 case BuiltinType::SatShortFract:
3305 Out << "DSDRs";
3306 break;
3307 case BuiltinType::SatFract:
3308 Out << "DSDRi";
3309 break;
3310 case BuiltinType::SatLongFract:
3311 Out << "DSDRl";
3312 break;
3313 case BuiltinType::SatUShortFract:
3314 Out << "DSDRt";
3315 break;
3316 case BuiltinType::SatUFract:
3317 Out << "DSDRj";
3318 break;
3319 case BuiltinType::SatULongFract:
3320 Out << "DSDRm";
3321 break;
3322 case BuiltinType::Half:
3323 Out << "Dh";
3324 break;
3325 case BuiltinType::Float:
3326 Out << 'f';
3327 break;
3328 case BuiltinType::Double:
3329 Out << 'd';
3330 break;
3331 case BuiltinType::LongDouble: {
3332 const TargetInfo *TI =
3333 getASTContext().getLangOpts().OpenMP &&
3334 getASTContext().getLangOpts().OpenMPIsTargetDevice
3335 ? getASTContext().getAuxTargetInfo()
3336 : &getASTContext().getTargetInfo();
3337 Out << TI->getLongDoubleMangling();
3338 break;
3339 }
3340 case BuiltinType::Float128: {
3341 const TargetInfo *TI =
3342 getASTContext().getLangOpts().OpenMP &&
3343 getASTContext().getLangOpts().OpenMPIsTargetDevice
3344 ? getASTContext().getAuxTargetInfo()
3345 : &getASTContext().getTargetInfo();
3346 Out << TI->getFloat128Mangling();
3347 break;
3348 }
3349 case BuiltinType::BFloat16: {
3350 const TargetInfo *TI =
3351 ((getASTContext().getLangOpts().OpenMP &&
3352 getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3353 getASTContext().getLangOpts().SYCLIsDevice)
3354 ? getASTContext().getAuxTargetInfo()
3355 : &getASTContext().getTargetInfo();
3356 Out << TI->getBFloat16Mangling();
3357 break;
3358 }
3359 case BuiltinType::Ibm128: {
3360 const TargetInfo *TI = &getASTContext().getTargetInfo();
3361 Out << TI->getIbm128Mangling();
3362 break;
3363 }
3364 case BuiltinType::NullPtr:
3365 Out << "Dn";
3366 break;
3367
3368#define BUILTIN_TYPE(Id, SingletonId)
3369#define PLACEHOLDER_TYPE(Id, SingletonId) \
3370 case BuiltinType::Id:
3371#include "clang/AST/BuiltinTypes.def"
3372 case BuiltinType::Dependent:
3373 if (!NullOut)
3374 llvm_unreachable("mangling a placeholder type");
3375 break;
3376 case BuiltinType::ObjCId:
3377 Out << "11objc_object";
3378 break;
3379 case BuiltinType::ObjCClass:
3380 Out << "10objc_class";
3381 break;
3382 case BuiltinType::ObjCSel:
3383 Out << "13objc_selector";
3384 break;
3385#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3386 case BuiltinType::Id: \
3387 type_name = "ocl_" #ImgType "_" #Suffix; \
3388 Out << type_name.size() << type_name; \
3389 break;
3390#include "clang/Basic/OpenCLImageTypes.def"
3391 case BuiltinType::OCLSampler:
3392 Out << "11ocl_sampler";
3393 break;
3394 case BuiltinType::OCLEvent:
3395 Out << "9ocl_event";
3396 break;
3397 case BuiltinType::OCLClkEvent:
3398 Out << "12ocl_clkevent";
3399 break;
3400 case BuiltinType::OCLQueue:
3401 Out << "9ocl_queue";
3402 break;
3403 case BuiltinType::OCLReserveID:
3404 Out << "13ocl_reserveid";
3405 break;
3406#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3407 case BuiltinType::Id: \
3408 type_name = "ocl_" #ExtType; \
3409 Out << type_name.size() << type_name; \
3410 break;
3411#include "clang/Basic/OpenCLExtensionTypes.def"
3412 // The SVE types are effectively target-specific. The mangling scheme
3413 // is defined in the appendices to the Procedure Call Standard for the
3414 // Arm Architecture.
3415#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
3416 case BuiltinType::Id: \
3417 if (T->getKind() == BuiltinType::SveBFloat16 && \
3418 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3419 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3420 mangleVendorType("__SVBFloat16_t"); \
3421 } else { \
3422 type_name = MangledName; \
3423 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3424 } \
3425 break;
3426#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
3427 case BuiltinType::Id: \
3428 type_name = MangledName; \
3429 Out << (type_name == Name ? "u" : "") << type_name.size() << type_name; \
3430 break;
3431#define SVE_OPAQUE_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 AARCH64_VECTOR_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#include "clang/Basic/AArch64SVEACLETypes.def"
3442#define PPC_VECTOR_TYPE(Name, Id, Size) \
3443 case BuiltinType::Id: \
3444 mangleVendorType(#Name); \
3445 break;
3446#include "clang/Basic/PPCTypes.def"
3447 // TODO: Check the mangling scheme for RISC-V V.
3448#define RVV_TYPE(Name, Id, SingletonId) \
3449 case BuiltinType::Id: \
3450 mangleVendorType(Name); \
3451 break;
3452#include "clang/Basic/RISCVVTypes.def"
3453#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3454 case BuiltinType::Id: \
3455 mangleVendorType(MangledName); \
3456 break;
3457#include "clang/Basic/WebAssemblyReferenceTypes.def"
3458#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3459 case BuiltinType::Id: \
3460 mangleVendorType(Name); \
3461 break;
3462#include "clang/Basic/AMDGPUTypes.def"
3463#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3464 case BuiltinType::Id: \
3465 mangleVendorType(#Name); \
3466 break;
3467#include "clang/Basic/HLSLIntangibleTypes.def"
3468 }
3469}
3470
3471StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3472 switch (CC) {
3473 case CC_C:
3474 return "";
3475
3476 case CC_X86VectorCall:
3477 case CC_X86Pascal:
3478 case CC_X86RegCall:
3479 case CC_AAPCS:
3480 case CC_AAPCS_VFP:
3482 case CC_AArch64SVEPCS:
3484 case CC_IntelOclBicc:
3485 case CC_SpirFunction:
3486 case CC_OpenCLKernel:
3487 case CC_PreserveMost:
3488 case CC_PreserveAll:
3489 case CC_M68kRTD:
3490 case CC_PreserveNone:
3491 case CC_RISCVVectorCall:
3492 // FIXME: we should be mangling all of the above.
3493 return "";
3494
3495 case CC_X86ThisCall:
3496 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3497 // used explicitly. At this point, we don't have that much information in
3498 // the AST, since clang tends to bake the convention into the canonical
3499 // function type. thiscall only rarely used explicitly, so don't mangle it
3500 // for now.
3501 return "";
3502
3503 case CC_X86StdCall:
3504 return "stdcall";
3505 case CC_X86FastCall:
3506 return "fastcall";
3507 case CC_X86_64SysV:
3508 return "sysv_abi";
3509 case CC_Win64:
3510 return "ms_abi";
3511 case CC_Swift:
3512 return "swiftcall";
3513 case CC_SwiftAsync:
3514 return "swiftasynccall";
3515 }
3516 llvm_unreachable("bad calling convention");
3517}
3518
3519void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3520 // Fast path.
3522 return;
3523
3524 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3525 // This will get more complicated in the future if we mangle other
3526 // things here; but for now, since we mangle ns_returns_retained as
3527 // a qualifier on the result type, we can get away with this:
3528 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3529 if (!CCQualifier.empty())
3530 mangleVendorQualifier(CCQualifier);
3531
3532 // FIXME: regparm
3533 // FIXME: noreturn
3534}
3535
3536enum class AAPCSBitmaskSME : unsigned {
3537 ArmStreamingBit = 1 << 0,
3539 ArmAgnosticSMEZAStateBit = 1 << 2,
3540 ZA_Shift = 3,
3541 ZT0_Shift = 6,
3542 NoState = 0b000,
3543 ArmIn = 0b001,
3544 ArmOut = 0b010,
3545 ArmInOut = 0b011,
3546 ArmPreserves = 0b100,
3548};
3549
3550static AAPCSBitmaskSME encodeAAPCSZAState(unsigned SMEAttrs) {
3551 switch (SMEAttrs) {
3562 default:
3563 llvm_unreachable("Unrecognised SME attribute");
3564 }
3565}
3566
3567// The mangling scheme for function types which have SME attributes is
3568// implemented as a "pseudo" template:
3569//
3570// '__SME_ATTRS<<normal_function_type>, <sme_state>>'
3571//
3572// Combining the function type with a bitmask representing the streaming and ZA
3573// properties of the function's interface.
3574//
3575// Mangling of SME keywords is described in more detail in the AArch64 ACLE:
3576// https://github.com/ARM-software/acle/blob/main/main/acle.md#c-mangling-of-sme-keywords
3577//
3578void CXXNameMangler::mangleSMEAttrs(unsigned SMEAttrs) {
3579 if (!SMEAttrs)
3580 return;
3581
3582 AAPCSBitmaskSME Bitmask = AAPCSBitmaskSME(0);
3585 else if (SMEAttrs & FunctionType::SME_PStateSMCompatibleMask)
3587
3588 // TODO: Must represent __arm_agnostic("sme_za_state")
3589
3592
3595
3596 Out << "Lj" << static_cast<unsigned>(Bitmask) << "EE";
3597}
3598
3599void
3600CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3601 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3602
3603 // Note that these are *not* substitution candidates. Demanglers might
3604 // have trouble with this if the parameter type is fully substituted.
3605
3606 switch (PI.getABI()) {
3607 case ParameterABI::Ordinary:
3608 break;
3609
3610 // HLSL parameter mangling.
3611 case ParameterABI::HLSLOut:
3612 case ParameterABI::HLSLInOut:
3613 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3614 break;
3615
3616 // All of these start with "swift", so they come before "ns_consumed".
3617 case ParameterABI::SwiftContext:
3618 case ParameterABI::SwiftAsyncContext:
3619 case ParameterABI::SwiftErrorResult:
3620 case ParameterABI::SwiftIndirectResult:
3621 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3622 break;
3623 }
3624
3625 if (PI.isConsumed())
3626 mangleVendorQualifier("ns_consumed");
3627
3628 if (PI.isNoEscape())
3629 mangleVendorQualifier("noescape");
3630}
3631
3632// <type> ::= <function-type>
3633// <function-type> ::= [<CV-qualifiers>] F [Y]
3634// <bare-function-type> [<ref-qualifier>] E
3635void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3636 unsigned SMEAttrs = T->getAArch64SMEAttributes();
3637
3638 if (SMEAttrs)
3639 Out << "11__SME_ATTRSI";
3640
3641 mangleExtFunctionInfo(T);
3642
3643 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3644 // e.g. "const" in "int (A::*)() const".
3645 mangleQualifiers(T->getMethodQuals());
3646
3647 // Mangle instantiation-dependent exception-specification, if present,
3648 // per cxx-abi-dev proposal on 2016-10-11.
3651 Out << "DO";
3652 mangleExpression(T->getNoexceptExpr());
3653 Out << "E";
3654 } else {
3655 assert(T->getExceptionSpecType() == EST_Dynamic);
3656 Out << "Dw";
3657 for (auto ExceptTy : T->exceptions())
3658 mangleType(ExceptTy);
3659 Out << "E";
3660 }
3661 } else if (T->isNothrow()) {
3662 Out << "Do";
3663 }
3664
3665 Out << 'F';
3666
3667 // FIXME: We don't have enough information in the AST to produce the 'Y'
3668 // encoding for extern "C" function types.
3669 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3670
3671 // Mangle the ref-qualifier, if present.
3672 mangleRefQualifier(T->getRefQualifier());
3673
3674 Out << 'E';
3675
3676 mangleSMEAttrs(SMEAttrs);
3677}
3678
3679void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3680 // Function types without prototypes can arise when mangling a function type
3681 // within an overloadable function in C. We mangle these as the absence of any
3682 // parameter types (not even an empty parameter list).
3683 Out << 'F';
3684
3685 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3686
3687 FunctionTypeDepth.enterResultType();
3688 mangleType(T->getReturnType());
3689 FunctionTypeDepth.leaveResultType();
3690
3691 FunctionTypeDepth.pop(saved);
3692 Out << 'E';
3693}
3694
3695void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3696 bool MangleReturnType,
3697 const FunctionDecl *FD) {
3698 // Record that we're in a function type. See mangleFunctionParam
3699 // for details on what we're trying to achieve here.
3700 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3701
3702 // <bare-function-type> ::= <signature type>+
3703 if (MangleReturnType) {
3704 FunctionTypeDepth.enterResultType();
3705
3706 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3707 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3708 mangleVendorQualifier("ns_returns_retained");
3709
3710 // Mangle the return type without any direct ARC ownership qualifiers.
3711 QualType ReturnTy = Proto->getReturnType();
3712 if (ReturnTy.getObjCLifetime()) {
3713 auto SplitReturnTy = ReturnTy.split();
3714 SplitReturnTy.Quals.removeObjCLifetime();
3715 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3716 }
3717 mangleType(ReturnTy);
3718
3719 FunctionTypeDepth.leaveResultType();
3720 }
3721
3722 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3723 // <builtin-type> ::= v # void
3724 Out << 'v';
3725 } else {
3726 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3727 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3728 // Mangle extended parameter info as order-sensitive qualifiers here.
3729 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3730 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3731 }
3732
3733 // Mangle the type.
3734 QualType ParamTy = Proto->getParamType(I);
3735 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3736
3737 if (FD) {
3738 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3739 // Attr can only take 1 character, so we can hardcode the length
3740 // below.
3741 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3742 if (Attr->isDynamic())
3743 Out << "U25pass_dynamic_object_size" << Attr->getType();
3744 else
3745 Out << "U17pass_object_size" << Attr->getType();
3746 }
3747 }
3748 }
3749
3750 // <builtin-type> ::= z # ellipsis
3751 if (Proto->isVariadic())
3752 Out << 'z';
3753 }
3754
3755 if (FD) {
3756 FunctionTypeDepth.enterResultType();
3757 mangleRequiresClause(FD->getTrailingRequiresClause());
3758 }
3759
3760 FunctionTypeDepth.pop(saved);
3761}
3762
3763// <type> ::= <class-enum-type>
3764// <class-enum-type> ::= <name>
3765void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3766 mangleName(T->getDecl());
3767}
3768
3769// <type> ::= <class-enum-type>
3770// <class-enum-type> ::= <name>
3771void CXXNameMangler::mangleType(const EnumType *T) {
3772 mangleType(static_cast<const TagType*>(T));
3773}
3774void CXXNameMangler::mangleType(const RecordType *T) {
3775 mangleType(static_cast<const TagType*>(T));
3776}
3777void CXXNameMangler::mangleType(const TagType *T) {
3778 mangleName(T->getDecl());
3779}
3780
3781// <type> ::= <array-type>
3782// <array-type> ::= A <positive dimension number> _ <element type>
3783// ::= A [<dimension expression>] _ <element type>
3784void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3785 Out << 'A' << T->getSize() << '_';
3786 mangleType(T->getElementType());
3787}
3788void CXXNameMangler::mangleType(const VariableArrayType *T) {
3789 Out << 'A';
3790 // decayed vla types (size 0) will just be skipped.
3791 if (T->getSizeExpr())
3792 mangleExpression(T->getSizeExpr());
3793 Out << '_';
3794 mangleType(T->getElementType());
3795}
3796void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3797 Out << 'A';
3798 // A DependentSizedArrayType might not have size expression as below
3799 //
3800 // template<int ...N> int arr[] = {N...};
3801 if (T->getSizeExpr())
3802 mangleExpression(T->getSizeExpr());
3803 Out << '_';
3804 mangleType(T->getElementType());
3805}
3806void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3807 Out << "A_";
3808 mangleType(T->getElementType());
3809}
3810
3811// <type> ::= <pointer-to-member-type>
3812// <pointer-to-member-type> ::= M <class type> <member type>
3813void CXXNameMangler::mangleType(const MemberPointerType *T) {
3814 Out << 'M';
3815 mangleType(QualType(T->getClass(), 0));
3816 QualType PointeeType = T->getPointeeType();
3817 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3818 mangleType(FPT);
3819
3820 // Itanium C++ ABI 5.1.8:
3821 //
3822 // The type of a non-static member function is considered to be different,
3823 // for the purposes of substitution, from the type of a namespace-scope or
3824 // static member function whose type appears similar. The types of two
3825 // non-static member functions are considered to be different, for the
3826 // purposes of substitution, if the functions are members of different
3827 // classes. In other words, for the purposes of substitution, the class of
3828 // which the function is a member is considered part of the type of
3829 // function.
3830
3831 // Given that we already substitute member function pointers as a
3832 // whole, the net effect of this rule is just to unconditionally
3833 // suppress substitution on the function type in a member pointer.
3834 // We increment the SeqID here to emulate adding an entry to the
3835 // substitution table.
3836 ++SeqID;
3837 } else
3838 mangleType(PointeeType);
3839}
3840
3841// <type> ::= <template-param>
3842void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3843 mangleTemplateParameter(T->getDepth(), T->getIndex());
3844}
3845
3846// <type> ::= <template-param>
3847void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3848 // FIXME: not clear how to mangle this!
3849 // template <class T...> class A {
3850 // template <class U...> void foo(T(*)(U) x...);
3851 // };
3852 Out << "_SUBSTPACK_";
3853}
3854
3855// <type> ::= P <type> # pointer-to
3856void CXXNameMangler::mangleType(const PointerType *T) {
3857 Out << 'P';
3858 mangleType(T->getPointeeType());
3859}
3860void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3861 Out << 'P';
3862 mangleType(T->getPointeeType());
3863}
3864
3865// <type> ::= R <type> # reference-to
3866void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3867 Out << 'R';
3868 mangleType(T->getPointeeType());
3869}
3870
3871// <type> ::= O <type> # rvalue reference-to (C++0x)
3872void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3873 Out << 'O';
3874 mangleType(T->getPointeeType());
3875}
3876
3877// <type> ::= C <type> # complex pair (C 2000)
3878void CXXNameMangler::mangleType(const ComplexType *T) {
3879 Out << 'C';
3880 mangleType(T->getElementType());
3881}
3882
3883// ARM's ABI for Neon vector types specifies that they should be mangled as
3884// if they are structs (to match ARM's initial implementation). The
3885// vector type must be one of the special types predefined by ARM.
3886void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3887 QualType EltType = T->getElementType();
3888 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3889 const char *EltName = nullptr;
3890 if (T->getVectorKind() == VectorKind::NeonPoly) {
3891 switch (cast<BuiltinType>(EltType)->getKind()) {
3892 case BuiltinType::SChar:
3893 case BuiltinType::UChar:
3894 EltName = "poly8_t";
3895 break;
3896 case BuiltinType::Short:
3897 case BuiltinType::UShort:
3898 EltName = "poly16_t";
3899 break;
3900 case BuiltinType::LongLong:
3901 case BuiltinType::ULongLong:
3902 EltName = "poly64_t";
3903 break;
3904 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3905 }
3906 } else {
3907 switch (cast<BuiltinType>(EltType)->getKind()) {
3908 case BuiltinType::SChar: EltName = "int8_t"; break;
3909 case BuiltinType::UChar: EltName = "uint8_t"; break;
3910 case BuiltinType::Short: EltName = "int16_t"; break;
3911 case BuiltinType::UShort: EltName = "uint16_t"; break;
3912 case BuiltinType::Int: EltName = "int32_t"; break;
3913 case BuiltinType::UInt: EltName = "uint32_t"; break;
3914 case BuiltinType::LongLong: EltName = "int64_t"; break;
3915 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3916 case BuiltinType::Double: EltName = "float64_t"; break;
3917 case BuiltinType::Float: EltName = "float32_t"; break;
3918 case BuiltinType::Half: EltName = "float16_t"; break;
3919 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3920 default:
3921 llvm_unreachable("unexpected Neon vector element type");
3922 }
3923 }
3924 const char *BaseName = nullptr;
3925 unsigned BitSize = (T->getNumElements() *
3926 getASTContext().getTypeSize(EltType));
3927 if (BitSize == 64)
3928 BaseName = "__simd64_";
3929 else {
3930 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3931 BaseName = "__simd128_";
3932 }
3933 Out << strlen(BaseName) + strlen(EltName);
3934 Out << BaseName << EltName;
3935}
3936
3937void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3938 DiagnosticsEngine &Diags = Context.getDiags();
3939 unsigned DiagID = Diags.getCustomDiagID(
3941 "cannot mangle this dependent neon vector type yet");
3942 Diags.Report(T->getAttributeLoc(), DiagID);
3943}
3944
3945static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3946 switch (EltType->getKind()) {
3947 case BuiltinType::SChar:
3948 return "Int8";
3949 case BuiltinType::Short:
3950 return "Int16";
3951 case BuiltinType::Int:
3952 return "Int32";
3953 case BuiltinType::Long:
3954 case BuiltinType::LongLong:
3955 return "Int64";
3956 case BuiltinType::UChar:
3957 return "Uint8";
3958 case BuiltinType::UShort:
3959 return "Uint16";
3960 case BuiltinType::UInt:
3961 return "Uint32";
3962 case BuiltinType::ULong:
3963 case BuiltinType::ULongLong:
3964 return "Uint64";
3965 case BuiltinType::Half:
3966 return "Float16";
3967 case BuiltinType::Float:
3968 return "Float32";
3969 case BuiltinType::Double:
3970 return "Float64";
3971 case BuiltinType::BFloat16:
3972 return "Bfloat16";
3973 default:
3974 llvm_unreachable("Unexpected vector element base type");
3975 }
3976}
3977
3978// AArch64's ABI for Neon vector types specifies that they should be mangled as
3979// the equivalent internal name. The vector type must be one of the special
3980// types predefined by ARM.
3981void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3982 QualType EltType = T->getElementType();
3983 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3984 unsigned BitSize =
3985 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3986 (void)BitSize; // Silence warning.
3987
3988 assert((BitSize == 64 || BitSize == 128) &&
3989 "Neon vector type not 64 or 128 bits");
3990
3991 StringRef EltName;
3992 if (T->getVectorKind() == VectorKind::NeonPoly) {
3993 switch (cast<BuiltinType>(EltType)->getKind()) {
3994 case BuiltinType::UChar:
3995 EltName = "Poly8";
3996 break;
3997 case BuiltinType::UShort:
3998 EltName = "Poly16";
3999 break;
4000 case BuiltinType::ULong:
4001 case BuiltinType::ULongLong:
4002 EltName = "Poly64";
4003 break;
4004 default:
4005 llvm_unreachable("unexpected Neon polynomial vector element type");
4006 }
4007 } else
4008 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
4009
4010 std::string TypeName =
4011 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
4012 Out << TypeName.length() << TypeName;
4013}
4014void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
4015 DiagnosticsEngine &Diags = Context.getDiags();
4016 unsigned DiagID = Diags.getCustomDiagID(
4018 "cannot mangle this dependent neon vector type yet");
4019 Diags.Report(T->getAttributeLoc(), DiagID);
4020}
4021
4022// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
4023// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
4024// type as the sizeless variants.
4025//
4026// The mangling scheme for VLS types is implemented as a "pseudo" template:
4027//
4028// '__SVE_VLS<<type>, <vector length>>'
4029//
4030// Combining the existing SVE type and a specific vector length (in bits).
4031// For example:
4032//
4033// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
4034//
4035// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
4036//
4037// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
4038//
4039// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
4040//
4041// The latest ACLE specification (00bet5) does not contain details of this
4042// mangling scheme, it will be specified in the next revision. The mangling
4043// scheme is otherwise defined in the appendices to the Procedure Call Standard
4044// for the Arm Architecture, see
4045// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
4046void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
4047 assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
4048 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
4049 "expected fixed-length SVE vector!");
4050
4051 QualType EltType = T->getElementType();
4052 assert(EltType->isBuiltinType() &&
4053 "expected builtin type for fixed-length SVE vector!");
4054
4055 StringRef TypeName;
4056 switch (cast<BuiltinType>(EltType)->getKind()) {
4057 case BuiltinType::SChar:
4058 TypeName = "__SVInt8_t";
4059 break;
4060 case BuiltinType::UChar: {
4061 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
4062 TypeName = "__SVUint8_t";
4063 else
4064 TypeName = "__SVBool_t";
4065 break;
4066 }
4067 case BuiltinType::Short:
4068 TypeName = "__SVInt16_t";
4069 break;
4070 case BuiltinType::UShort:
4071 TypeName = "__SVUint16_t";
4072 break;
4073 case BuiltinType::Int:
4074 TypeName = "__SVInt32_t";
4075 break;
4076 case BuiltinType::UInt:
4077 TypeName = "__SVUint32_t";
4078 break;
4079 case BuiltinType::Long:
4080 TypeName = "__SVInt64_t";
4081 break;
4082 case BuiltinType::ULong:
4083 TypeName = "__SVUint64_t";
4084 break;
4085 case BuiltinType::Half:
4086 TypeName = "__SVFloat16_t";
4087 break;
4088 case BuiltinType::Float:
4089 TypeName = "__SVFloat32_t";
4090 break;
4091 case BuiltinType::Double:
4092 TypeName = "__SVFloat64_t";
4093 break;
4094 case BuiltinType::BFloat16:
4095 TypeName = "__SVBfloat16_t";
4096 break;
4097 default:
4098 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
4099 }
4100
4101 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4102
4103 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
4104 VecSizeInBits *= 8;
4105
4106 Out << "9__SVE_VLSI";
4107 mangleVendorType(TypeName);
4108 Out << "Lj" << VecSizeInBits << "EE";
4109}
4110
4111void CXXNameMangler::mangleAArch64FixedSveVectorType(
4112 const DependentVectorType *T) {
4113 DiagnosticsEngine &Diags = Context.getDiags();
4114 unsigned DiagID = Diags.getCustomDiagID(
4116 "cannot mangle this dependent fixed-length SVE vector type yet");
4117 Diags.Report(T->getAttributeLoc(), DiagID);
4118}
4119
4120void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
4121 assert((T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4122 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4123 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4124 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4125 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) &&
4126 "expected fixed-length RVV vector!");
4127
4128 QualType EltType = T->getElementType();
4129 assert(EltType->isBuiltinType() &&
4130 "expected builtin type for fixed-length RVV vector!");
4131
4132 SmallString<20> TypeNameStr;
4133 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4134 TypeNameOS << "__rvv_";
4135 switch (cast<BuiltinType>(EltType)->getKind()) {
4136 case BuiltinType::SChar:
4137 TypeNameOS << "int8";
4138 break;
4139 case BuiltinType::UChar:
4140 if (T->getVectorKind() == VectorKind::RVVFixedLengthData)
4141 TypeNameOS << "uint8";
4142 else
4143 TypeNameOS << "bool";
4144 break;
4145 case BuiltinType::Short:
4146 TypeNameOS << "int16";
4147 break;
4148 case BuiltinType::UShort:
4149 TypeNameOS << "uint16";
4150 break;
4151 case BuiltinType::Int:
4152 TypeNameOS << "int32";
4153 break;
4154 case BuiltinType::UInt:
4155 TypeNameOS << "uint32";
4156 break;
4157 case BuiltinType::Long:
4158 TypeNameOS << "int64";
4159 break;
4160 case BuiltinType::ULong:
4161 TypeNameOS << "uint64";
4162 break;
4163 case BuiltinType::Float16:
4164 TypeNameOS << "float16";
4165 break;
4166 case BuiltinType::Float:
4167 TypeNameOS << "float32";
4168 break;
4169 case BuiltinType::Double:
4170 TypeNameOS << "float64";
4171 break;
4172 default:
4173 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4174 }
4175
4176 unsigned VecSizeInBits;
4177 switch (T->getVectorKind()) {
4178 case VectorKind::RVVFixedLengthMask_1:
4179 VecSizeInBits = 1;
4180 break;
4181 case VectorKind::RVVFixedLengthMask_2:
4182 VecSizeInBits = 2;
4183 break;
4184 case VectorKind::RVVFixedLengthMask_4:
4185 VecSizeInBits = 4;
4186 break;
4187 default:
4188 VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4189 break;
4190 }
4191
4192 // Apend the LMUL suffix.
4193 auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4194 getASTContext().getLangOpts());
4195 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4196
4197 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4198 TypeNameOS << 'm';
4199 if (VecSizeInBits >= VLen)
4200 TypeNameOS << (VecSizeInBits / VLen);
4201 else
4202 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4203 } else {
4204 TypeNameOS << (VLen / VecSizeInBits);
4205 }
4206 TypeNameOS << "_t";
4207
4208 Out << "9__RVV_VLSI";
4209 mangleVendorType(TypeNameStr);
4210 Out << "Lj" << VecSizeInBits << "EE";
4211}
4212
4213void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4214 const DependentVectorType *T) {
4215 DiagnosticsEngine &Diags = Context.getDiags();
4216 unsigned DiagID = Diags.getCustomDiagID(
4218 "cannot mangle this dependent fixed-length RVV vector type yet");
4219 Diags.Report(T->getAttributeLoc(), DiagID);
4220}
4221
4222// GNU extension: vector types
4223// <type> ::= <vector-type>
4224// <vector-type> ::= Dv <positive dimension number> _
4225// <extended element type>
4226// ::= Dv [<dimension expression>] _ <element type>
4227// <extended element type> ::= <element type>
4228// ::= p # AltiVec vector pixel
4229// ::= b # Altivec vector bool
4230void CXXNameMangler::mangleType(const VectorType *T) {
4231 if ((T->getVectorKind() == VectorKind::Neon ||
4232 T->getVectorKind() == VectorKind::NeonPoly)) {
4233 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4234 llvm::Triple::ArchType Arch =
4235 getASTContext().getTargetInfo().getTriple().getArch();
4236 if ((Arch == llvm::Triple::aarch64 ||
4237 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4238 mangleAArch64NeonVectorType(T);
4239 else
4240 mangleNeonVectorType(T);
4241 return;
4242 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4243 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4244 mangleAArch64FixedSveVectorType(T);
4245 return;
4246 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData ||
4247 T->getVectorKind() == VectorKind::RVVFixedLengthMask ||
4248 T->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
4249 T->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
4250 T->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
4251 mangleRISCVFixedRVVVectorType(T);
4252 return;
4253 }
4254 Out << "Dv" << T->getNumElements() << '_';
4255 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4256 Out << 'p';
4257 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4258 Out << 'b';
4259 else
4260 mangleType(T->getElementType());
4261}
4262
4263void CXXNameMangler::mangleType(const DependentVectorType *T) {
4264 if ((T->getVectorKind() == VectorKind::Neon ||
4265 T->getVectorKind() == VectorKind::NeonPoly)) {
4266 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4267 llvm::Triple::ArchType Arch =
4268 getASTContext().getTargetInfo().getTriple().getArch();
4269 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4270 !Target.isOSDarwin())
4271 mangleAArch64NeonVectorType(T);
4272 else
4273 mangleNeonVectorType(T);
4274 return;
4275 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4276 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4277 mangleAArch64FixedSveVectorType(T);
4278 return;
4279 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4280 mangleRISCVFixedRVVVectorType(T);
4281 return;
4282 }
4283
4284 Out << "Dv";
4285 mangleExpression(T->getSizeExpr());
4286 Out << '_';
4287 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4288 Out << 'p';
4289 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4290 Out << 'b';
4291 else
4292 mangleType(T->getElementType());
4293}
4294
4295void CXXNameMangler::mangleType(const ExtVectorType *T) {
4296 mangleType(static_cast<const VectorType*>(T));
4297}
4298void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4299 Out << "Dv";
4300 mangleExpression(T->getSizeExpr());
4301 Out << '_';
4302 mangleType(T->getElementType());
4303}
4304
4305void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4306 // Mangle matrix types as a vendor extended type:
4307 // u<Len>matrix_typeI<Rows><Columns><element type>E
4308
4309 mangleVendorType("matrix_type");
4310
4311 Out << "I";
4312 auto &ASTCtx = getASTContext();
4313 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4314 llvm::APSInt Rows(BitWidth);
4315 Rows = T->getNumRows();
4316 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4317 llvm::APSInt Columns(BitWidth);
4318 Columns = T->getNumColumns();
4319 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4320 mangleType(T->getElementType());
4321 Out << "E";
4322}
4323
4324void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4325 // Mangle matrix types as a vendor extended type:
4326 // u<Len>matrix_typeI<row expr><column expr><element type>E
4327 mangleVendorType("matrix_type");
4328
4329 Out << "I";
4330 mangleTemplateArgExpr(T->getRowExpr());
4331 mangleTemplateArgExpr(T->getColumnExpr());
4332 mangleType(T->getElementType());
4333 Out << "E";
4334}
4335
4336void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4337 SplitQualType split = T->getPointeeType().split();
4338 mangleQualifiers(split.Quals, T);
4339 mangleType(QualType(split.Ty, 0));
4340}
4341
4342void CXXNameMangler::mangleType(const PackExpansionType *T) {
4343 // <type> ::= Dp <type> # pack expansion (C++0x)
4344 Out << "Dp";
4345 mangleType(T->getPattern());
4346}
4347
4348void CXXNameMangler::mangleType(const PackIndexingType *T) {
4349 if (!T->hasSelectedType())
4350 mangleType(T->getPattern());
4351 else
4352 mangleType(T->getSelectedType());
4353}
4354
4355void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4356 mangleSourceName(T->getDecl()->getIdentifier());
4357}
4358
4359void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4360 // Treat __kindof as a vendor extended type qualifier.
4361 if (T->isKindOfType())
4362 Out << "U8__kindof";
4363
4364 if (!T->qual_empty()) {
4365 // Mangle protocol qualifiers.
4366 SmallString<64> QualStr;
4367 llvm::raw_svector_ostream QualOS(QualStr);
4368 QualOS << "objcproto";
4369 for (const auto *I : T->quals()) {
4370 StringRef name = I->getName();
4371 QualOS << name.size() << name;
4372 }
4373 mangleVendorQualifier(QualStr);
4374 }
4375
4376 mangleType(T->getBaseType());
4377
4378 if (T->isSpecialized()) {
4379 // Mangle type arguments as I <type>+ E
4380 Out << 'I';
4381 for (auto typeArg : T->getTypeArgs())
4382 mangleType(typeArg);
4383 Out << 'E';
4384 }
4385}
4386
4387void CXXNameMangler::mangleType(const BlockPointerType *T) {
4388 Out << "U13block_pointer";
4389 mangleType(T->getPointeeType());
4390}
4391
4392void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4393 // Mangle injected class name types as if the user had written the
4394 // specialization out fully. It may not actually be possible to see
4395 // this mangling, though.
4396 mangleType(T->getInjectedSpecializationType());
4397}
4398
4399void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4400 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4401 mangleTemplateName(TD, T->template_arguments());
4402 } else {
4403 if (mangleSubstitution(QualType(T, 0)))
4404 return;
4405
4406 mangleTemplatePrefix(T->getTemplateName());
4407
4408 // FIXME: GCC does not appear to mangle the template arguments when
4409 // the template in question is a dependent template name. Should we
4410 // emulate that badness?
4411 mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4412 addSubstitution(QualType(T, 0));
4413 }
4414}
4415
4416void CXXNameMangler::mangleType(const DependentNameType *T) {
4417 // Proposal by cxx-abi-dev, 2014-03-26
4418 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4419 // # dependent elaborated type specifier using
4420 // # 'typename'
4421 // ::= Ts <name> # dependent elaborated type specifier using
4422 // # 'struct' or 'class'
4423 // ::= Tu <name> # dependent elaborated type specifier using
4424 // # 'union'
4425 // ::= Te <name> # dependent elaborated type specifier using
4426 // # 'enum'
4427 switch (T->getKeyword()) {
4428 case ElaboratedTypeKeyword::None:
4429 case ElaboratedTypeKeyword::Typename:
4430 break;
4431 case ElaboratedTypeKeyword::Struct:
4432 case ElaboratedTypeKeyword::Class:
4433 case ElaboratedTypeKeyword::Interface:
4434 Out << "Ts";
4435 break;
4436 case ElaboratedTypeKeyword::Union:
4437 Out << "Tu";
4438 break;
4439 case ElaboratedTypeKeyword::Enum:
4440 Out << "Te";
4441 break;
4442 }
4443 // Typename types are always nested
4444 Out << 'N';
4445 manglePrefix(T->getQualifier());
4446 mangleSourceName(T->getIdentifier());
4447 Out << 'E';
4448}
4449
4450void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4451 // Dependently-scoped template types are nested if they have a prefix.
4452 Out << 'N';
4453
4454 // TODO: avoid making this TemplateName.
4455 TemplateName Prefix =
4456 getASTContext().getDependentTemplateName(T->getQualifier(),
4457 T->getIdentifier());
4458 mangleTemplatePrefix(Prefix);
4459
4460 // FIXME: GCC does not appear to mangle the template arguments when
4461 // the template in question is a dependent template name. Should we
4462 // emulate that badness?
4463 mangleTemplateArgs(Prefix, T->template_arguments());
4464 Out << 'E';
4465}
4466
4467void CXXNameMangler::mangleType(const TypeOfType *T) {
4468 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4469 // "extension with parameters" mangling.
4470 Out << "u6typeof";
4471}
4472
4473void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4474 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4475 // "extension with parameters" mangling.
4476 Out << "u6typeof";
4477}
4478
4479void CXXNameMangler::mangleType(const DecltypeType *T) {
4480 Expr *E = T->getUnderlyingExpr();
4481
4482 // type ::= Dt <expression> E # decltype of an id-expression
4483 // # or class member access
4484 // ::= DT <expression> E # decltype of an expression
4485
4486 // This purports to be an exhaustive list of id-expressions and
4487 // class member accesses. Note that we do not ignore parentheses;
4488 // parentheses change the semantics of decltype for these
4489 // expressions (and cause the mangler to use the other form).
4490 if (isa<DeclRefExpr>(E) ||
4491 isa<MemberExpr>(E) ||
4492 isa<UnresolvedLookupExpr>(E) ||
4493 isa<DependentScopeDeclRefExpr>(E) ||
4494 isa<CXXDependentScopeMemberExpr>(E) ||
4495 isa<UnresolvedMemberExpr>(E))
4496 Out << "Dt";
4497 else
4498 Out << "DT";
4499 mangleExpression(E);
4500 Out << 'E';
4501}
4502
4503void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4504 // If this is dependent, we need to record that. If not, we simply
4505 // mangle it as the underlying type since they are equivalent.
4506 if (T->isDependentType()) {
4507 StringRef BuiltinName;
4508 switch (T->getUTTKind()) {
4509#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4510 case UnaryTransformType::Enum: \
4511 BuiltinName = "__" #Trait; \
4512 break;
4513#include "clang/Basic/TransformTypeTraits.def"
4514 }
4515 mangleVendorType(BuiltinName);
4516 }
4517
4518 Out << "I";
4519 mangleType(T->getBaseType());
4520 Out << "E";
4521}
4522
4523void CXXNameMangler::mangleType(const AutoType *T) {
4524 assert(T->getDeducedType().isNull() &&
4525 "Deduced AutoType shouldn't be handled here!");
4526 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4527 "shouldn't need to mangle __auto_type!");
4528 // <builtin-type> ::= Da # auto
4529 // ::= Dc # decltype(auto)
4530 // ::= Dk # constrained auto
4531 // ::= DK # constrained decltype(auto)
4532 if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4533 Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4534 mangleTypeConstraint(T->getTypeConstraintConcept(),
4535 T->getTypeConstraintArguments());
4536 } else {
4537 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4538 }
4539}
4540
4541void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4542 QualType Deduced = T->getDeducedType();
4543 if (!Deduced.isNull())
4544 return mangleType(Deduced);
4545
4546 TemplateName TN = T->getTemplateName();
4547 assert(TN.getAsTemplateDecl() &&
4548 "shouldn't form deduced TST unless we know we have a template");
4549 mangleType(TN);
4550}
4551
4552void CXXNameMangler::mangleType(const AtomicType *T) {
4553 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4554 // (Until there's a standardized mangling...)
4555 Out << "U7_Atomic";
4556 mangleType(T->getValueType());
4557}
4558
4559void CXXNameMangler::mangleType(const PipeType *T) {
4560 // Pipe type mangling rules are described in SPIR 2.0 specification
4561 // A.1 Data types and A.3 Summary of changes
4562 // <type> ::= 8ocl_pipe
4563 Out << "8ocl_pipe";
4564}
4565
4566void CXXNameMangler::mangleType(const BitIntType *T) {
4567 // 5.1.5.2 Builtin types
4568 // <type> ::= DB <number | instantiation-dependent expression> _
4569 // ::= DU <number | instantiation-dependent expression> _
4570 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4571}
4572
4573void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4574 // 5.1.5.2 Builtin types
4575 // <type> ::= DB <number | instantiation-dependent expression> _
4576 // ::= DU <number | instantiation-dependent expression> _
4577 Out << "D" << (T->isUnsigned() ? "U" : "B");
4578 mangleExpression(T->getNumBitsExpr());
4579 Out << "_";
4580}
4581
4582void CXXNameMangler::mangleType(const ArrayParameterType *T) {
4583 mangleType(cast<ConstantArrayType>(T));
4584}
4585
4586void CXXNameMangler::mangleType(const HLSLAttributedResourceType *T) {
4587 llvm::SmallString<64> Str("_Res");
4588 const HLSLAttributedResourceType::Attributes &Attrs = T->getAttrs();
4589 // map resource class to HLSL virtual register letter
4590 switch (Attrs.ResourceClass) {
4591 case llvm::dxil::ResourceClass::UAV:
4592 Str += "_u";
4593 break;
4594 case llvm::dxil::ResourceClass::SRV:
4595 Str += "_t";
4596 break;
4597 case llvm::dxil::ResourceClass::CBuffer:
4598 Str += "_b";
4599 break;
4600 case llvm::dxil::ResourceClass::Sampler:
4601 Str += "_s";
4602 break;
4603 }
4604 if (Attrs.IsROV)
4605 Str += "_ROV";
4606 if (Attrs.RawBuffer)
4607 Str += "_Raw";
4608 if (T->hasContainedType())
4609 Str += "_CT";
4610 mangleVendorQualifier(Str);
4611
4612 if (T->hasContainedType()) {
4613 mangleType(T->getContainedType());
4614 }
4615 mangleType(T->getWrappedType());
4616}
4617
4618void CXXNameMangler::mangleIntegerLiteral(QualType T,
4619 const llvm::APSInt &Value) {
4620 // <expr-primary> ::= L <type> <value number> E # integer literal
4621 Out << 'L';
4622
4623 mangleType(T);
4624 if (T->isBooleanType()) {
4625 // Boolean values are encoded as 0/1.
4626 Out << (Value.getBoolValue() ? '1' : '0');
4627 } else {
4628 mangleNumber(Value);
4629 }
4630 Out << 'E';
4631
4632}
4633
4634void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4635 // Ignore member expressions involving anonymous unions.
4636 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4637 if (!RT->getDecl()->isAnonymousStructOrUnion())
4638 break;
4639 const auto *ME = dyn_cast<MemberExpr>(Base);
4640 if (!ME)
4641 break;
4642 Base = ME->getBase();
4643 IsArrow = ME->isArrow();
4644 }
4645
4646 if (Base->isImplicitCXXThis()) {
4647 // Note: GCC mangles member expressions to the implicit 'this' as
4648 // *this., whereas we represent them as this->. The Itanium C++ ABI
4649 // does not specify anything here, so we follow GCC.
4650 Out << "dtdefpT";
4651 } else {
4652 Out << (IsArrow ? "pt" : "dt");
4653 mangleExpression(Base);
4654 }
4655}
4656
4657/// Mangles a member expression.
4658void CXXNameMangler::mangleMemberExpr(const Expr *base,
4659 bool isArrow,
4660 NestedNameSpecifier *qualifier,
4661 NamedDecl *firstQualifierLookup,
4662 DeclarationName member,
4663 const TemplateArgumentLoc *TemplateArgs,
4664 unsigned NumTemplateArgs,
4665 unsigned arity) {
4666 // <expression> ::= dt <expression> <unresolved-name>
4667 // ::= pt <expression> <unresolved-name>
4668 if (base)
4669 mangleMemberExprBase(base, isArrow);
4670 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4671}
4672
4673/// Look at the callee of the given call expression and determine if
4674/// it's a parenthesized id-expression which would have triggered ADL
4675/// otherwise.
4676static bool isParenthesizedADLCallee(const CallExpr *call) {
4677 const Expr *callee = call->getCallee();
4678 const Expr *fn = callee->IgnoreParens();
4679
4680 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4681 // too, but for those to appear in the callee, it would have to be
4682 // parenthesized.
4683 if (callee == fn) return false;
4684
4685 // Must be an unresolved lookup.
4686 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4687 if (!lookup) return false;
4688
4689 assert(!lookup->requiresADL());
4690
4691 // Must be an unqualified lookup.
4692 if (lookup->getQualifier()) return false;
4693
4694 // Must not have found a class member. Note that if one is a class
4695 // member, they're all class members.
4696 if (lookup->getNumDecls() > 0 &&
4697 (*lookup->decls_begin())->isCXXClassMember())
4698 return false;
4699
4700 // Otherwise, ADL would have been triggered.
4701 return true;
4702}
4703
4704void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4705 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4706 Out << CastEncoding;
4707 mangleType(ECE->getType());
4708 mangleExpression(ECE->getSubExpr());
4709}
4710
4711void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4712 if (auto *Syntactic = InitList->getSyntacticForm())
4713 InitList = Syntactic;
4714 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4715 mangleExpression(InitList->getInit(i));
4716}
4717
4718void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4719 const concepts::Requirement *Req) {
4721
4722 // TODO: We can't mangle the result of a failed substitution. It's not clear
4723 // whether we should be mangling the original form prior to any substitution
4724 // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4725 auto HandleSubstitutionFailure =
4726 [&](SourceLocation Loc) {
4727 DiagnosticsEngine &Diags = Context.getDiags();
4728 unsigned DiagID = Diags.getCustomDiagID(
4729 DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4730 "containing a substitution failure");
4731 Diags.Report(Loc, DiagID);
4732 Out << 'F';
4733 };
4734
4735 switch (Req->getKind()) {
4736 case Requirement::RK_Type: {
4737 const auto *TR = cast<concepts::TypeRequirement>(Req);
4738 if (TR->isSubstitutionFailure())
4739 return HandleSubstitutionFailure(
4740 TR->getSubstitutionDiagnostic()->DiagLoc);
4741
4742 Out << 'T';
4743 mangleType(TR->getType()->getType());
4744 break;
4745 }
4746
4747 case Requirement::RK_Simple:
4748 case Requirement::RK_Compound: {
4749 const auto *ER = cast<concepts::ExprRequirement>(Req);
4750 if (ER->isExprSubstitutionFailure())
4751 return HandleSubstitutionFailure(
4752 ER->getExprSubstitutionDiagnostic()->DiagLoc);
4753
4754 Out << 'X';
4755 mangleExpression(ER->getExpr());
4756
4757 if (ER->hasNoexceptRequirement())
4758 Out << 'N';
4759
4760 if (!ER->getReturnTypeRequirement().isEmpty()) {
4761 if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4762 return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4763 .getSubstitutionDiagnostic()
4764 ->DiagLoc);
4765
4766 Out << 'R';
4767 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4768 }
4769 break;
4770 }
4771
4772 case Requirement::RK_Nested:
4773 const auto *NR = cast<concepts::NestedRequirement>(Req);
4774 if (NR->hasInvalidConstraint()) {
4775 // FIXME: NestedRequirement should track the location of its requires
4776 // keyword.
4777 return HandleSubstitutionFailure(RequiresExprLoc);
4778 }
4779
4780 Out << 'Q';
4781 mangleExpression(NR->getConstraintExpr());
4782 break;
4783 }
4784}
4785
4786void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4787 bool AsTemplateArg) {
4788 // <expression> ::= <unary operator-name> <expression>
4789 // ::= <binary operator-name> <expression> <expression>
4790 // ::= <trinary operator-name> <expression> <expression> <expression>
4791 // ::= cv <type> expression # conversion with one argument
4792 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4793 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4794 // ::= sc <type> <expression> # static_cast<type> (expression)
4795 // ::= cc <type> <expression> # const_cast<type> (expression)
4796 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4797 // ::= st <type> # sizeof (a type)
4798 // ::= at <type> # alignof (a type)
4799 // ::= <template-param>
4800 // ::= <function-param>
4801 // ::= fpT # 'this' expression (part of <function-param>)
4802 // ::= sr <type> <unqualified-name> # dependent name
4803 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4804 // ::= ds <expression> <expression> # expr.*expr
4805 // ::= sZ <template-param> # size of a parameter pack
4806 // ::= sZ <function-param> # size of a function parameter pack
4807 // ::= u <source-name> <template-arg>* E # vendor extended expression
4808 // ::= <expr-primary>
4809 // <expr-primary> ::= L <type> <value number> E # integer literal
4810 // ::= L <type> <value float> E # floating literal
4811 // ::= L <type> <string type> E # string literal
4812 // ::= L <nullptr type> E # nullptr literal "LDnE"
4813 // ::= L <pointer type> 0 E # null pointer template argument
4814 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4815 // ::= L <mangled-name> E # external name
4816 QualType ImplicitlyConvertedToType;
4817
4818 // A top-level expression that's not <expr-primary> needs to be wrapped in
4819 // X...E in a template arg.
4820 bool IsPrimaryExpr = true;
4821 auto NotPrimaryExpr = [&] {
4822 if (AsTemplateArg && IsPrimaryExpr)
4823 Out << 'X';
4824 IsPrimaryExpr = false;
4825 };
4826
4827 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4828 switch (D->getKind()) {
4829 default:
4830 // <expr-primary> ::= L <mangled-name> E # external name
4831 Out << 'L';
4832 mangle(D);
4833 Out << 'E';
4834 break;
4835
4836 case Decl::ParmVar:
4837 NotPrimaryExpr();
4838 mangleFunctionParam(cast<ParmVarDecl>(D));
4839 break;
4840
4841 case Decl::EnumConstant: {
4842 // <expr-primary>
4843 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4844 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4845 break;
4846 }
4847
4848 case Decl::NonTypeTemplateParm:
4849 NotPrimaryExpr();
4850 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4851 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4852 break;
4853 }
4854 };
4855
4856 // 'goto recurse' is used when handling a simple "unwrapping" node which
4857 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4858 // to be preserved.
4859recurse:
4860 switch (E->getStmtClass()) {
4861 case Expr::NoStmtClass:
4862#define ABSTRACT_STMT(Type)
4863#define EXPR(Type, Base)
4864#define STMT(Type, Base) \
4865 case Expr::Type##Class:
4866#include "clang/AST/StmtNodes.inc"
4867 // fallthrough
4868
4869 // These all can only appear in local or variable-initialization
4870 // contexts and so should never appear in a mangling.
4871 case Expr::AddrLabelExprClass:
4872 case Expr::DesignatedInitUpdateExprClass:
4873 case Expr::ImplicitValueInitExprClass:
4874 case Expr::ArrayInitLoopExprClass:
4875 case Expr::ArrayInitIndexExprClass:
4876 case Expr::NoInitExprClass:
4877 case Expr::ParenListExprClass:
4878 case Expr::MSPropertyRefExprClass:
4879 case Expr::MSPropertySubscriptExprClass:
4880 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4881 case Expr::RecoveryExprClass:
4882 case Expr::ArraySectionExprClass:
4883 case Expr::OMPArrayShapingExprClass:
4884 case Expr::OMPIteratorExprClass:
4885 case Expr::CXXInheritedCtorInitExprClass:
4886 case Expr::CXXParenListInitExprClass:
4887 case Expr::PackIndexingExprClass:
4888 llvm_unreachable("unexpected statement kind");
4889
4890 case Expr::ConstantExprClass:
4891 E = cast<ConstantExpr>(E)->getSubExpr();
4892 goto recurse;
4893
4894 // FIXME: invent manglings for all these.
4895 case Expr::BlockExprClass:
4896 case Expr::ChooseExprClass:
4897 case Expr::CompoundLiteralExprClass:
4898 case Expr::ExtVectorElementExprClass:
4899 case Expr::GenericSelectionExprClass:
4900 case Expr::ObjCEncodeExprClass:
4901 case Expr::ObjCIsaExprClass:
4902 case Expr::ObjCIvarRefExprClass:
4903 case Expr::ObjCMessageExprClass:
4904 case Expr::ObjCPropertyRefExprClass:
4905 case Expr::ObjCProtocolExprClass:
4906 case Expr::ObjCSelectorExprClass:
4907 case Expr::ObjCStringLiteralClass:
4908 case Expr::ObjCBoxedExprClass:
4909 case Expr::ObjCArrayLiteralClass:
4910 case Expr::ObjCDictionaryLiteralClass:
4911 case Expr::ObjCSubscriptRefExprClass:
4912 case Expr::ObjCIndirectCopyRestoreExprClass:
4913 case Expr::ObjCAvailabilityCheckExprClass:
4914 case Expr::OffsetOfExprClass:
4915 case Expr::PredefinedExprClass:
4916 case Expr::ShuffleVectorExprClass:
4917 case Expr::ConvertVectorExprClass:
4918 case Expr::StmtExprClass:
4919 case Expr::ArrayTypeTraitExprClass:
4920 case Expr::ExpressionTraitExprClass:
4921 case Expr::VAArgExprClass:
4922 case Expr::CUDAKernelCallExprClass:
4923 case Expr::AsTypeExprClass:
4924 case Expr::PseudoObjectExprClass:
4925 case Expr::AtomicExprClass:
4926 case Expr::SourceLocExprClass:
4927 case Expr::EmbedExprClass:
4928 case Expr::BuiltinBitCastExprClass:
4929 {
4930 NotPrimaryExpr();
4931 if (!NullOut) {
4932 // As bad as this diagnostic is, it's better than crashing.
4933 DiagnosticsEngine &Diags = Context.getDiags();
4934 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4935 "cannot yet mangle expression type %0");
4936 Diags.Report(E->getExprLoc(), DiagID)
4937 << E->getStmtClassName() << E->getSourceRange();
4938 return;
4939 }
4940 break;
4941 }
4942
4943 case Expr::CXXUuidofExprClass: {
4944 NotPrimaryExpr();
4945 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4946 // As of clang 12, uuidof uses the vendor extended expression
4947 // mangling. Previously, it used a special-cased nonstandard extension.
4948 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4949 Out << "u8__uuidof";
4950 if (UE->isTypeOperand())
4951 mangleType(UE->getTypeOperand(Context.getASTContext()));
4952 else
4953 mangleTemplateArgExpr(UE->getExprOperand());
4954 Out << 'E';
4955 } else {
4956 if (UE->isTypeOperand()) {
4957 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4958 Out << "u8__uuidoft";
4959 mangleType(UuidT);
4960 } else {
4961 Expr *UuidExp = UE->getExprOperand();
4962 Out << "u8__uuidofz";
4963 mangleExpression(UuidExp);
4964 }
4965 }
4966 break;
4967 }
4968
4969 // Even gcc-4.5 doesn't mangle this.
4970 case Expr::BinaryConditionalOperatorClass: {
4971 NotPrimaryExpr();
4972 DiagnosticsEngine &Diags = Context.getDiags();
4973 unsigned DiagID =
4975 "?: operator with omitted middle operand cannot be mangled");
4976 Diags.Report(E->getExprLoc(), DiagID)
4977 << E->getStmtClassName() << E->getSourceRange();
4978 return;
4979 }
4980
4981 // These are used for internal purposes and cannot be meaningfully mangled.
4982 case Expr::OpaqueValueExprClass:
4983 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4984
4985 case Expr::InitListExprClass: {
4986 NotPrimaryExpr();
4987 Out << "il";
4988 mangleInitListElements(cast<InitListExpr>(E));
4989 Out << "E";
4990 break;
4991 }
4992
4993 case Expr::DesignatedInitExprClass: {
4994 NotPrimaryExpr();
4995 auto *DIE = cast<DesignatedInitExpr>(E);
4996 for (const auto &Designator : DIE->designators()) {
4998 Out << "di";
4999 mangleSourceName(Designator.getFieldName());
5000 } else if (Designator.isArrayDesignator()) {
5001 Out << "dx";
5002 mangleExpression(DIE->getArrayIndex(Designator));
5003 } else {
5005 "unknown designator kind");
5006 Out << "dX";
5007 mangleExpression(DIE->getArrayRangeStart(Designator));
5008 mangleExpression(DIE->getArrayRangeEnd(Designator));
5009 }
5010 }
5011 mangleExpression(DIE->getInit());
5012 break;
5013 }
5014
5015 case Expr::CXXDefaultArgExprClass:
5016 E = cast<CXXDefaultArgExpr>(E)->getExpr();
5017 goto recurse;
5018
5019 case Expr::CXXDefaultInitExprClass:
5020 E = cast<CXXDefaultInitExpr>(E)->getExpr();
5021 goto recurse;
5022
5023 case Expr::CXXStdInitializerListExprClass:
5024 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
5025 goto recurse;
5026
5027 case Expr::SubstNonTypeTemplateParmExprClass: {
5028 // Mangle a substituted parameter the same way we mangle the template
5029 // argument.
5030 auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E);
5031 if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) {
5032 // Pull out the constant value and mangle it as a template argument.
5033 QualType ParamType = SNTTPE->getParameterType(Context.getASTContext());
5034 assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue");
5035 mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false,
5036 /*NeedExactType=*/true);
5037 break;
5038 }
5039 // The remaining cases all happen to be substituted with expressions that
5040 // mangle the same as a corresponding template argument anyway.
5041 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
5042 goto recurse;
5043 }
5044
5045 case Expr::UserDefinedLiteralClass:
5046 // We follow g++'s approach of mangling a UDL as a call to the literal
5047 // operator.
5048 case Expr::CXXMemberCallExprClass: // fallthrough
5049 case Expr::CallExprClass: {
5050 NotPrimaryExpr();
5051 const CallExpr *CE = cast<CallExpr>(E);
5052
5053 // <expression> ::= cp <simple-id> <expression>* E
5054 // We use this mangling only when the call would use ADL except
5055 // for being parenthesized. Per discussion with David
5056 // Vandervoorde, 2011.04.25.
5057 if (isParenthesizedADLCallee(CE)) {
5058 Out << "cp";
5059 // The callee here is a parenthesized UnresolvedLookupExpr with
5060 // no qualifier and should always get mangled as a <simple-id>
5061 // anyway.
5062
5063 // <expression> ::= cl <expression>* E
5064 } else {
5065 Out << "cl";
5066 }
5067
5068 unsigned CallArity = CE->getNumArgs();
5069 for (const Expr *Arg : CE->arguments())
5070 if (isa<PackExpansionExpr>(Arg))
5071 CallArity = UnknownArity;
5072
5073 mangleExpression(CE->getCallee(), CallArity);
5074 for (const Expr *Arg : CE->arguments())
5075 mangleExpression(Arg);
5076 Out << 'E';
5077 break;
5078 }
5079
5080 case Expr::CXXNewExprClass: {
5081 NotPrimaryExpr();
5082 const CXXNewExpr *New = cast<CXXNewExpr>(E);
5083 if (New->isGlobalNew()) Out << "gs";
5084 Out << (New->isArray() ? "na" : "nw");
5086 E = New->placement_arg_end(); I != E; ++I)
5087 mangleExpression(*I);
5088 Out << '_';
5089 mangleType(New->getAllocatedType());
5090 if (New->hasInitializer()) {
5091 if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces)
5092 Out << "il";
5093 else
5094 Out << "pi";
5095 const Expr *Init = New->getInitializer();
5096 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
5097 // Directly inline the initializers.
5098 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
5099 E = CCE->arg_end();
5100 I != E; ++I)
5101 mangleExpression(*I);
5102 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
5103 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
5104 mangleExpression(PLE->getExpr(i));
5105 } else if (New->getInitializationStyle() ==
5106 CXXNewInitializationStyle::Braces &&
5107 isa<InitListExpr>(Init)) {
5108 // Only take InitListExprs apart for list-initialization.
5109 mangleInitListElements(cast<InitListExpr>(Init));
5110 } else
5111 mangleExpression(Init);
5112 }
5113 Out << 'E';
5114 break;
5115 }
5116
5117 case Expr::CXXPseudoDestructorExprClass: {
5118 NotPrimaryExpr();
5119 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
5120 if (const Expr *Base = PDE->getBase())
5121 mangleMemberExprBase(Base, PDE->isArrow());
5122 NestedNameSpecifier *Qualifier = PDE->getQualifier();
5123 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
5124 if (Qualifier) {
5125 mangleUnresolvedPrefix(Qualifier,
5126 /*recursive=*/true);
5127 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
5128 Out << 'E';
5129 } else {
5130 Out << "sr";
5131 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
5132 Out << 'E';
5133 }
5134 } else if (Qualifier) {
5135 mangleUnresolvedPrefix(Qualifier);
5136 }
5137 // <base-unresolved-name> ::= dn <destructor-name>
5138 Out << "dn";
5139 QualType DestroyedType = PDE->getDestroyedType();
5140 mangleUnresolvedTypeOrSimpleId(DestroyedType);
5141 break;
5142 }
5143
5144 case Expr::MemberExprClass: {
5145 NotPrimaryExpr();
5146 const MemberExpr *ME = cast<MemberExpr>(E);
5147 mangleMemberExpr(ME->getBase(), ME->isArrow(),
5148 ME->getQualifier(), nullptr,
5149 ME->getMemberDecl()->getDeclName(),
5151 Arity);
5152 break;
5153 }
5154
5155 case Expr::UnresolvedMemberExprClass: {
5156 NotPrimaryExpr();
5157 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
5158 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5159 ME->isArrow(), ME->getQualifier(), nullptr,
5160 ME->getMemberName(),
5162 Arity);
5163 break;
5164 }
5165
5166 case Expr::CXXDependentScopeMemberExprClass: {
5167 NotPrimaryExpr();
5169 = cast<CXXDependentScopeMemberExpr>(E);
5170 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
5171 ME->isArrow(), ME->getQualifier(),
5173 ME->getMember(),
5175 Arity);
5176 break;
5177 }
5178
5179 case Expr::UnresolvedLookupExprClass: {
5180 NotPrimaryExpr();
5181 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
5182 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
5183 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
5184 Arity);
5185 break;
5186 }
5187
5188 case Expr::CXXUnresolvedConstructExprClass: {
5189 NotPrimaryExpr();
5190 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
5191 unsigned N = CE->getNumArgs();
5192
5193 if (CE->isListInitialization()) {
5194 assert(N == 1 && "unexpected form for list initialization");
5195 auto *IL = cast<InitListExpr>(CE->getArg(0));
5196 Out << "tl";
5197 mangleType(CE->getType());
5198 mangleInitListElements(IL);
5199 Out << "E";
5200 break;
5201 }
5202
5203 Out << "cv";
5204 mangleType(CE->getType());
5205 if (N != 1) Out << '_';
5206 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
5207 if (N != 1) Out << 'E';
5208 break;
5209 }
5210
5211 case Expr::CXXConstructExprClass: {
5212 // An implicit cast is silent, thus may contain <expr-primary>.
5213 const auto *CE = cast<CXXConstructExpr>(E);
5214 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5215 assert(
5216 CE->getNumArgs() >= 1 &&
5217 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5218 "implicit CXXConstructExpr must have one argument");
5219 E = cast<CXXConstructExpr>(E)->getArg(0);
5220 goto recurse;
5221 }
5222 NotPrimaryExpr();
5223 Out << "il";
5224 for (auto *E : CE->arguments())
5225 mangleExpression(E);
5226 Out << "E";
5227 break;
5228 }
5229
5230 case Expr::CXXTemporaryObjectExprClass: {
5231 NotPrimaryExpr();
5232 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5233 unsigned N = CE->getNumArgs();
5234 bool List = CE->isListInitialization();
5235
5236 if (List)
5237 Out << "tl";
5238 else
5239 Out << "cv";
5240 mangleType(CE->getType());
5241 if (!List && N != 1)
5242 Out << '_';
5243 if (CE->isStdInitListInitialization()) {
5244 // We implicitly created a std::initializer_list<T> for the first argument
5245 // of a constructor of type U in an expression of the form U{a, b, c}.
5246 // Strip all the semantic gunk off the initializer list.
5247 auto *SILE =
5248 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
5249 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5250 mangleInitListElements(ILE);
5251 } else {
5252 for (auto *E : CE->arguments())
5253 mangleExpression(E);
5254 }
5255 if (List || N != 1)
5256 Out << 'E';
5257 break;
5258 }
5259
5260 case Expr::CXXScalarValueInitExprClass:
5261 NotPrimaryExpr();
5262 Out << "cv";
5263 mangleType(E->getType());
5264 Out << "_E";
5265 break;
5266
5267 case Expr::CXXNoexceptExprClass:
5268 NotPrimaryExpr();
5269 Out << "nx";
5270 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5271 break;
5272
5273 case Expr::UnaryExprOrTypeTraitExprClass: {
5274 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5275 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5276
5277 if (!SAE->isInstantiationDependent()) {
5278 // Itanium C++ ABI:
5279 // If the operand of a sizeof or alignof operator is not
5280 // instantiation-dependent it is encoded as an integer literal
5281 // reflecting the result of the operator.
5282 //
5283 // If the result of the operator is implicitly converted to a known
5284 // integer type, that type is used for the literal; otherwise, the type
5285 // of std::size_t or std::ptrdiff_t is used.
5286 //
5287 // FIXME: We still include the operand in the profile in this case. This
5288 // can lead to mangling collisions between function templates that we
5289 // consider to be different.
5290 QualType T = (ImplicitlyConvertedToType.isNull() ||
5291 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5292 : ImplicitlyConvertedToType;
5293 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5294 mangleIntegerLiteral(T, V);
5295 break;
5296 }
5297
5298 NotPrimaryExpr(); // But otherwise, they are not.
5299
5300 auto MangleAlignofSizeofArg = [&] {
5301 if (SAE->isArgumentType()) {
5302 Out << 't';
5303 mangleType(SAE->getArgumentType());
5304 } else {
5305 Out << 'z';
5306 mangleExpression(SAE->getArgumentExpr());
5307 }
5308 };
5309
5310 switch(SAE->getKind()) {
5311 case UETT_SizeOf:
5312 Out << 's';
5313 MangleAlignofSizeofArg();
5314 break;
5315 case UETT_PreferredAlignOf:
5316 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5317 // have acted differently since Clang 8, but were previously mangled the
5318 // same.)
5319 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5320 Out << "u11__alignof__";
5321 if (SAE->isArgumentType())
5322 mangleType(SAE->getArgumentType());
5323 else
5324 mangleTemplateArgExpr(SAE->getArgumentExpr());
5325 Out << 'E';
5326 break;
5327 }
5328 [[fallthrough]];
5329 case UETT_AlignOf:
5330 Out << 'a';
5331 MangleAlignofSizeofArg();
5332 break;
5333 case UETT_DataSizeOf: {
5334 DiagnosticsEngine &Diags = Context.getDiags();
5335 unsigned DiagID =
5337 "cannot yet mangle __datasizeof expression");
5338 Diags.Report(DiagID);
5339 return;
5340 }
5341 case UETT_PtrAuthTypeDiscriminator: {
5342 DiagnosticsEngine &Diags = Context.getDiags();
5343 unsigned DiagID = Diags.getCustomDiagID(
5345 "cannot yet mangle __builtin_ptrauth_type_discriminator expression");
5346 Diags.Report(E->getExprLoc(), DiagID);
5347 return;
5348 }
5349 case UETT_VecStep: {
5350 DiagnosticsEngine &Diags = Context.getDiags();
5351 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
5352 "cannot yet mangle vec_step expression");
5353 Diags.Report(DiagID);
5354 return;
5355 }
5356 case UETT_OpenMPRequiredSimdAlign: {
5357 DiagnosticsEngine &Diags = Context.getDiags();
5358 unsigned DiagID = Diags.getCustomDiagID(
5360 "cannot yet mangle __builtin_omp_required_simd_align expression");
5361 Diags.Report(DiagID);
5362 return;
5363 }
5364 case UETT_VectorElements: {
5365 DiagnosticsEngine &Diags = Context.getDiags();
5366 unsigned DiagID = Diags.getCustomDiagID(
5368 "cannot yet mangle __builtin_vectorelements expression");
5369 Diags.Report(DiagID);
5370 return;
5371 }
5372 }
5373 break;
5374 }
5375
5376 case Expr::TypeTraitExprClass: {
5377 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5378 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5379 NotPrimaryExpr();
5380 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5381 mangleVendorType(Spelling);
5382 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5383 mangleType(TSI->getType());
5384 }
5385 Out << 'E';
5386 break;
5387 }
5388
5389 case Expr::CXXThrowExprClass: {
5390 NotPrimaryExpr();
5391 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5392 // <expression> ::= tw <expression> # throw expression
5393 // ::= tr # rethrow
5394 if (TE->getSubExpr()) {
5395 Out << "tw";
5396 mangleExpression(TE->getSubExpr());
5397 } else {
5398 Out << "tr";
5399 }
5400 break;
5401 }
5402
5403 case Expr::CXXTypeidExprClass: {
5404 NotPrimaryExpr();
5405 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5406 // <expression> ::= ti <type> # typeid (type)
5407 // ::= te <expression> # typeid (expression)
5408 if (TIE->isTypeOperand()) {
5409 Out << "ti";
5410 mangleType(TIE->getTypeOperand(Context.getASTContext()));
5411 } else {
5412 Out << "te";
5413 mangleExpression(TIE->getExprOperand());
5414 }
5415 break;
5416 }
5417
5418 case Expr::CXXDeleteExprClass: {
5419 NotPrimaryExpr();
5420 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5421 // <expression> ::= [gs] dl <expression> # [::] delete expr
5422 // ::= [gs] da <expression> # [::] delete [] expr
5423 if (DE->isGlobalDelete()) Out << "gs";
5424 Out << (DE->isArrayForm() ? "da" : "dl");
5425 mangleExpression(DE->getArgument());
5426 break;
5427 }
5428
5429 case Expr::UnaryOperatorClass: {
5430 NotPrimaryExpr();
5431 const UnaryOperator *UO = cast<UnaryOperator>(E);
5432 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5433 /*Arity=*/1);
5434 mangleExpression(UO->getSubExpr());
5435 break;
5436 }
5437
5438 case Expr::ArraySubscriptExprClass: {
5439 NotPrimaryExpr();
5440 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5441
5442 // Array subscript is treated as a syntactically weird form of
5443 // binary operator.
5444 Out << "ix";
5445 mangleExpression(AE->getLHS());
5446 mangleExpression(AE->getRHS());
5447 break;
5448 }
5449
5450 case Expr::MatrixSubscriptExprClass: {
5451 NotPrimaryExpr();
5452 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5453 Out << "ixix";
5454 mangleExpression(ME->getBase());
5455 mangleExpression(ME->getRowIdx());
5456 mangleExpression(ME->getColumnIdx());
5457 break;
5458 }
5459
5460 case Expr::CompoundAssignOperatorClass: // fallthrough
5461 case Expr::BinaryOperatorClass: {
5462 NotPrimaryExpr();
5463 const BinaryOperator *BO = cast<BinaryOperator>(E);
5464 if (BO->getOpcode() == BO_PtrMemD)
5465 Out << "ds";
5466 else
5467 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5468 /*Arity=*/2);
5469 mangleExpression(BO->getLHS());
5470 mangleExpression(BO->getRHS());
5471 break;
5472 }
5473
5474 case Expr::CXXRewrittenBinaryOperatorClass: {
5475 NotPrimaryExpr();
5476 // The mangled form represents the original syntax.
5478 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5479 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5480 /*Arity=*/2);
5481 mangleExpression(Decomposed.LHS);
5482 mangleExpression(Decomposed.RHS);
5483 break;
5484 }
5485
5486 case Expr::ConditionalOperatorClass: {
5487 NotPrimaryExpr();
5488 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5489 mangleOperatorName(OO_Conditional, /*Arity=*/3);
5490 mangleExpression(CO->getCond());
5491 mangleExpression(CO->getLHS(), Arity);
5492 mangleExpression(CO->getRHS(), Arity);
5493 break;
5494 }
5495
5496 case Expr::ImplicitCastExprClass: {
5497 ImplicitlyConvertedToType = E->getType();
5498 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5499 goto recurse;
5500 }
5501
5502 case Expr::ObjCBridgedCastExprClass: {
5503 NotPrimaryExpr();
5504 // Mangle ownership casts as a vendor extended operator __bridge,
5505 // __bridge_transfer, or __bridge_retain.
5506 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5507 Out << "v1U" << Kind.size() << Kind;
5508 mangleCastExpression(E, "cv");
5509 break;
5510 }
5511
5512 case Expr::CStyleCastExprClass:
5513 NotPrimaryExpr();
5514 mangleCastExpression(E, "cv");
5515 break;
5516
5517 case Expr::CXXFunctionalCastExprClass: {
5518 NotPrimaryExpr();
5519 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5520 // FIXME: Add isImplicit to CXXConstructExpr.
5521 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5522 if (CCE->getParenOrBraceRange().isInvalid())
5523 Sub = CCE->getArg(0)->IgnoreImplicit();
5524 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5525 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5526 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5527 Out << "tl";
5528 mangleType(E->getType());
5529 mangleInitListElements(IL);
5530 Out << "E";
5531 } else {
5532 mangleCastExpression(E, "cv");
5533 }
5534 break;
5535 }
5536
5537 case Expr::CXXStaticCastExprClass:
5538 NotPrimaryExpr();
5539 mangleCastExpression(E, "sc");
5540 break;
5541 case Expr::CXXDynamicCastExprClass:
5542 NotPrimaryExpr();
5543 mangleCastExpression(E, "dc");
5544 break;
5545 case Expr::CXXReinterpretCastExprClass:
5546 NotPrimaryExpr();
5547 mangleCastExpression(E, "rc");
5548 break;
5549 case Expr::CXXConstCastExprClass:
5550 NotPrimaryExpr();
5551 mangleCastExpression(E, "cc");
5552 break;
5553 case Expr::CXXAddrspaceCastExprClass:
5554 NotPrimaryExpr();
5555 mangleCastExpression(E, "ac");
5556 break;
5557
5558 case Expr::CXXOperatorCallExprClass: {
5559 NotPrimaryExpr();
5560 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5561 unsigned NumArgs = CE->getNumArgs();
5562 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5563 // (the enclosing MemberExpr covers the syntactic portion).
5564 if (CE->getOperator() != OO_Arrow)
5565 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5566 // Mangle the arguments.
5567 for (unsigned i = 0; i != NumArgs; ++i)
5568 mangleExpression(CE->getArg(i));
5569 break;
5570 }
5571
5572 case Expr::ParenExprClass:
5573 E = cast<ParenExpr>(E)->getSubExpr();
5574 goto recurse;
5575
5576 case Expr::ConceptSpecializationExprClass: {
5577 auto *CSE = cast<ConceptSpecializationExpr>(E);
5578 if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5579 // Clang 17 and before mangled concept-ids as if they resolved to an
5580 // entity, meaning that references to enclosing template arguments don't
5581 // work.
5582 Out << "L_Z";
5583 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5584 Out << 'E';
5585 break;
5586 }
5587 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5588 NotPrimaryExpr();
5589 mangleUnresolvedName(
5590 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5591 CSE->getConceptNameInfo().getName(),
5592 CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5593 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5594 break;
5595 }
5596
5597 case Expr::RequiresExprClass: {
5598 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5599 auto *RE = cast<RequiresExpr>(E);
5600 // This is a primary-expression in the C++ grammar, but does not have an
5601 // <expr-primary> mangling (starting with 'L').
5602 NotPrimaryExpr();
5603 if (RE->getLParenLoc().isValid()) {
5604 Out << "rQ";
5605 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5606 if (RE->getLocalParameters().empty()) {
5607 Out << 'v';
5608 } else {
5609 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5610 mangleType(Context.getASTContext().getSignatureParameterType(
5611 Param->getType()));
5612 }
5613 }
5614 Out << '_';
5615
5616 // The rest of the mangling is in the immediate scope of the parameters.
5617 FunctionTypeDepth.enterResultType();
5618 for (const concepts::Requirement *Req : RE->getRequirements())
5619 mangleRequirement(RE->getExprLoc(), Req);
5620 FunctionTypeDepth.pop(saved);
5621 Out << 'E';
5622 } else {
5623 Out << "rq";
5624 for (const concepts::Requirement *Req : RE->getRequirements())
5625 mangleRequirement(RE->getExprLoc(), Req);
5626 Out << 'E';
5627 }
5628 break;
5629 }
5630
5631 case Expr::DeclRefExprClass:
5632 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5633 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5634 break;
5635
5636 case Expr::SubstNonTypeTemplateParmPackExprClass:
5637 NotPrimaryExpr();
5638 // FIXME: not clear how to mangle this!
5639 // template <unsigned N...> class A {
5640 // template <class U...> void foo(U (&x)[N]...);
5641 // };
5642 Out << "_SUBSTPACK_";
5643 break;
5644
5645 case Expr::FunctionParmPackExprClass: {
5646 NotPrimaryExpr();
5647 // FIXME: not clear how to mangle this!
5648 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5649 Out << "v110_SUBSTPACK";
5650 MangleDeclRefExpr(FPPE->getParameterPack());
5651 break;
5652 }
5653
5654 case Expr::DependentScopeDeclRefExprClass: {
5655 NotPrimaryExpr();
5656 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5657 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5658 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5659 Arity);
5660 break;
5661 }
5662
5663 case Expr::CXXBindTemporaryExprClass:
5664 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5665 goto recurse;
5666
5667 case Expr::ExprWithCleanupsClass:
5668 E = cast<ExprWithCleanups>(E)->getSubExpr();
5669 goto recurse;
5670
5671 case Expr::FloatingLiteralClass: {
5672 // <expr-primary>
5673 const FloatingLiteral *FL = cast<FloatingLiteral>(E);