[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / AST / ItaniumMangle.cpp
blob261a56c4b666ae560d6bfaa18435861570ab286d
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):
13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
15 //===----------------------------------------------------------------------===//
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/Module.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/Thunk.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/TargetParser/RISCVTargetParser.h"
39 #include <optional>
41 using namespace clang;
43 namespace {
45 static bool isLocalContainerContext(const DeclContext *DC) {
46 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
49 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
50 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
51 return ftd->getTemplatedDecl();
53 return fn;
56 static const NamedDecl *getStructor(const NamedDecl *decl) {
57 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
58 return (fn ? getStructor(fn) : decl);
61 static bool isLambda(const NamedDecl *ND) {
62 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
63 if (!Record)
64 return false;
66 return Record->isLambda();
69 static const unsigned UnknownArity = ~0U;
71 class ItaniumMangleContextImpl : public ItaniumMangleContext {
72 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
73 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
74 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
75 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
76 NamespaceDecl *StdNamespace = nullptr;
78 bool NeedsUniqueInternalLinkageNames = false;
80 public:
81 explicit ItaniumMangleContextImpl(
82 ASTContext &Context, DiagnosticsEngine &Diags,
83 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
84 : ItaniumMangleContext(Context, Diags, IsAux),
85 DiscriminatorOverride(DiscriminatorOverride) {}
87 /// @name Mangler Entry Points
88 /// @{
90 bool shouldMangleCXXName(const NamedDecl *D) override;
91 bool shouldMangleStringLiteral(const StringLiteral *) override {
92 return false;
95 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
96 void needsUniqueInternalLinkageNames() override {
97 NeedsUniqueInternalLinkageNames = true;
100 void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
101 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
102 raw_ostream &) override;
103 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
104 const ThisAdjustment &ThisAdjustment,
105 raw_ostream &) override;
106 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
107 raw_ostream &) override;
108 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
109 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
110 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
111 const CXXRecordDecl *Type, raw_ostream &) override;
112 void mangleCXXRTTI(QualType T, raw_ostream &) override;
113 void mangleCXXRTTIName(QualType T, raw_ostream &,
114 bool NormalizeIntegers) override;
115 void mangleCanonicalTypeName(QualType T, raw_ostream &,
116 bool NormalizeIntegers) override;
118 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
119 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
120 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
121 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
122 void mangleDynamicAtExitDestructor(const VarDecl *D,
123 raw_ostream &Out) override;
124 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
125 void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
126 raw_ostream &Out) override;
127 void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
128 raw_ostream &Out) override;
129 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
130 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
131 raw_ostream &) override;
133 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
135 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
137 void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
139 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
140 // Lambda closure types are already numbered.
141 if (isLambda(ND))
142 return false;
144 // Anonymous tags are already numbered.
145 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
146 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
147 return false;
150 // Use the canonical number for externally visible decls.
151 if (ND->isExternallyVisible()) {
152 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
153 if (discriminator == 1)
154 return false;
155 disc = discriminator - 2;
156 return true;
159 // Make up a reasonable number for internal decls.
160 unsigned &discriminator = Uniquifier[ND];
161 if (!discriminator) {
162 const DeclContext *DC = getEffectiveDeclContext(ND);
163 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
165 if (discriminator == 1)
166 return false;
167 disc = discriminator-2;
168 return true;
171 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
172 // This function matches the one in MicrosoftMangle, which returns
173 // the string that is used in lambda mangled names.
174 assert(Lambda->isLambda() && "RD must be a lambda!");
175 std::string Name("<lambda");
176 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
177 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
178 unsigned LambdaId;
179 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
180 const FunctionDecl *Func =
181 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
183 if (Func) {
184 unsigned DefaultArgNo =
185 Func->getNumParams() - Parm->getFunctionScopeIndex();
186 Name += llvm::utostr(DefaultArgNo);
187 Name += "_";
190 if (LambdaManglingNumber)
191 LambdaId = LambdaManglingNumber;
192 else
193 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
195 Name += llvm::utostr(LambdaId);
196 Name += '>';
197 return Name;
200 DiscriminatorOverrideTy getDiscriminatorOverride() const override {
201 return DiscriminatorOverride;
204 NamespaceDecl *getStdNamespace();
206 const DeclContext *getEffectiveDeclContext(const Decl *D);
207 const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
208 return getEffectiveDeclContext(cast<Decl>(DC));
211 bool isInternalLinkageDecl(const NamedDecl *ND);
213 /// @}
216 /// Manage the mangling of a single name.
217 class CXXNameMangler {
218 ItaniumMangleContextImpl &Context;
219 raw_ostream &Out;
220 /// Normalize integer types for cross-language CFI support with other
221 /// languages that can't represent and encode C/C++ integer types.
222 bool NormalizeIntegers = false;
224 bool NullOut = false;
225 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
226 /// This mode is used when mangler creates another mangler recursively to
227 /// calculate ABI tags for the function return value or the variable type.
228 /// Also it is required to avoid infinite recursion in some cases.
229 bool DisableDerivedAbiTags = false;
231 /// The "structor" is the top-level declaration being mangled, if
232 /// that's not a template specialization; otherwise it's the pattern
233 /// for that specialization.
234 const NamedDecl *Structor;
235 unsigned StructorType = 0;
237 // An offset to add to all template parameter depths while mangling. Used
238 // when mangling a template parameter list to see if it matches a template
239 // template parameter exactly.
240 unsigned TemplateDepthOffset = 0;
242 /// The next substitution sequence number.
243 unsigned SeqID = 0;
245 class FunctionTypeDepthState {
246 unsigned Bits = 0;
248 enum { InResultTypeMask = 1 };
250 public:
251 FunctionTypeDepthState() = default;
253 /// The number of function types we're inside.
254 unsigned getDepth() const {
255 return Bits >> 1;
258 /// True if we're in the return type of the innermost function type.
259 bool isInResultType() const {
260 return Bits & InResultTypeMask;
263 FunctionTypeDepthState push() {
264 FunctionTypeDepthState tmp = *this;
265 Bits = (Bits & ~InResultTypeMask) + 2;
266 return tmp;
269 void enterResultType() {
270 Bits |= InResultTypeMask;
273 void leaveResultType() {
274 Bits &= ~InResultTypeMask;
277 void pop(FunctionTypeDepthState saved) {
278 assert(getDepth() == saved.getDepth() + 1);
279 Bits = saved.Bits;
282 } FunctionTypeDepth;
284 // abi_tag is a gcc attribute, taking one or more strings called "tags".
285 // The goal is to annotate against which version of a library an object was
286 // built and to be able to provide backwards compatibility ("dual abi").
287 // For more information see docs/ItaniumMangleAbiTags.rst.
288 typedef SmallVector<StringRef, 4> AbiTagList;
290 // State to gather all implicit and explicit tags used in a mangled name.
291 // Must always have an instance of this while emitting any name to keep
292 // track.
293 class AbiTagState final {
294 public:
295 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
296 Parent = LinkHead;
297 LinkHead = this;
300 // No copy, no move.
301 AbiTagState(const AbiTagState &) = delete;
302 AbiTagState &operator=(const AbiTagState &) = delete;
304 ~AbiTagState() { pop(); }
306 void write(raw_ostream &Out, const NamedDecl *ND,
307 const AbiTagList *AdditionalAbiTags) {
308 ND = cast<NamedDecl>(ND->getCanonicalDecl());
309 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
310 assert(
311 !AdditionalAbiTags &&
312 "only function and variables need a list of additional abi tags");
313 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
314 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
315 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
318 // Don't emit abi tags for namespaces.
319 return;
323 AbiTagList TagList;
324 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
325 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
326 AbiTag->tags().end());
327 TagList.insert(TagList.end(), AbiTag->tags().begin(),
328 AbiTag->tags().end());
331 if (AdditionalAbiTags) {
332 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
333 AdditionalAbiTags->end());
334 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
335 AdditionalAbiTags->end());
338 llvm::sort(TagList);
339 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
341 writeSortedUniqueAbiTags(Out, TagList);
344 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
345 void setUsedAbiTags(const AbiTagList &AbiTags) {
346 UsedAbiTags = AbiTags;
349 const AbiTagList &getEmittedAbiTags() const {
350 return EmittedAbiTags;
353 const AbiTagList &getSortedUniqueUsedAbiTags() {
354 llvm::sort(UsedAbiTags);
355 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
356 UsedAbiTags.end());
357 return UsedAbiTags;
360 private:
361 //! All abi tags used implicitly or explicitly.
362 AbiTagList UsedAbiTags;
363 //! All explicit abi tags (i.e. not from namespace).
364 AbiTagList EmittedAbiTags;
366 AbiTagState *&LinkHead;
367 AbiTagState *Parent = nullptr;
369 void pop() {
370 assert(LinkHead == this &&
371 "abi tag link head must point to us on destruction");
372 if (Parent) {
373 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
374 UsedAbiTags.begin(), UsedAbiTags.end());
375 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
376 EmittedAbiTags.begin(),
377 EmittedAbiTags.end());
379 LinkHead = Parent;
382 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
383 for (const auto &Tag : AbiTags) {
384 EmittedAbiTags.push_back(Tag);
385 Out << "B";
386 Out << Tag.size();
387 Out << Tag;
392 AbiTagState *AbiTags = nullptr;
393 AbiTagState AbiTagsRoot;
395 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
396 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
398 ASTContext &getASTContext() const { return Context.getASTContext(); }
400 bool isCompatibleWith(LangOptions::ClangABI Ver) {
401 return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
404 bool isStd(const NamespaceDecl *NS);
405 bool isStdNamespace(const DeclContext *DC);
407 const RecordDecl *GetLocalClassDecl(const Decl *D);
408 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
409 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
410 llvm::StringRef Name, bool HasAllocator);
412 public:
413 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
414 const NamedDecl *D = nullptr, bool NullOut_ = false)
415 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
416 AbiTagsRoot(AbiTags) {
417 // These can't be mangled without a ctor type or dtor type.
418 assert(!D || (!isa<CXXDestructorDecl>(D) &&
419 !isa<CXXConstructorDecl>(D)));
421 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
422 const CXXConstructorDecl *D, CXXCtorType Type)
423 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
424 AbiTagsRoot(AbiTags) {}
425 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
426 const CXXDestructorDecl *D, CXXDtorType Type)
427 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
428 AbiTagsRoot(AbiTags) {}
430 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
431 bool NormalizeIntegers_)
432 : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
433 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
434 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
435 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
436 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
437 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
438 Substitutions(Outer.Substitutions),
439 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
441 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
442 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
443 NullOut = true;
446 struct WithTemplateDepthOffset { unsigned Offset; };
447 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
448 WithTemplateDepthOffset Offset)
449 : CXXNameMangler(C, Out) {
450 TemplateDepthOffset = Offset.Offset;
453 raw_ostream &getStream() { return Out; }
455 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
456 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
458 void mangle(GlobalDecl GD);
459 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
460 void mangleNumber(const llvm::APSInt &I);
461 void mangleNumber(int64_t Number);
462 void mangleFloat(const llvm::APFloat &F);
463 void mangleFunctionEncoding(GlobalDecl GD);
464 void mangleSeqID(unsigned SeqID);
465 void mangleName(GlobalDecl GD);
466 void mangleType(QualType T);
467 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
468 void mangleLambdaSig(const CXXRecordDecl *Lambda);
469 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
471 private:
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);
479 void mangleExistingSubstitution(TemplateName name);
481 bool mangleStandardSubstitution(const NamedDecl *ND);
483 void addSubstitution(const NamedDecl *ND) {
484 ND = cast<NamedDecl>(ND->getCanonicalDecl());
486 addSubstitution(reinterpret_cast<uintptr_t>(ND));
488 void addSubstitution(NestedNameSpecifier *NNS) {
489 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
491 addSubstitution(reinterpret_cast<uintptr_t>(NNS));
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);
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);
507 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
509 void mangleNameWithAbiTags(GlobalDecl GD,
510 const AbiTagList *AdditionalAbiTags);
511 void mangleModuleName(const NamedDecl *ND);
512 void mangleTemplateName(const TemplateDecl *TD,
513 ArrayRef<TemplateArgument> Args);
514 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
515 const AbiTagList *AdditionalAbiTags) {
516 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
517 UnknownArity, AdditionalAbiTags);
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,
538 ArrayRef<TemplateArgument> Arguments);
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,
546 ArrayRef<TemplateArgument> Args);
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 mangleVendorQualifier(StringRef qualifier);
562 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
563 void mangleRefQualifier(RefQualifierKind RefQualifier);
565 void mangleObjCMethodName(const ObjCMethodDecl *MD);
567 // Declare manglers for every type class.
568 #define ABSTRACT_TYPE(CLASS, PARENT)
569 #define NON_CANONICAL_TYPE(CLASS, PARENT)
570 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
571 #include "clang/AST/TypeNodes.inc"
573 void mangleType(const TagType*);
574 void mangleType(TemplateName);
575 static StringRef getCallingConvQualifierName(CallingConv CC);
576 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
577 void mangleExtFunctionInfo(const FunctionType *T);
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);
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);
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);
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,
618 TemplateArgument A);
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);
624 void mangleTemplateParameter(unsigned Depth, unsigned Index);
626 void mangleFunctionParam(const ParmVarDecl *parm);
628 void writeAbiTags(const NamedDecl *ND,
629 const AbiTagList *AdditionalAbiTags);
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);
639 NamespaceDecl *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();
648 return StdNamespace;
651 /// Retrieve the declaration context that should be used when mangling the given
652 /// declaration.
653 const DeclContext *
654 ItaniumMangleContextImpl::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();
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();
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();
686 const DeclContext *DC = D->getDeclContext();
687 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
688 isa<OMPDeclareMapperDecl>(DC)) {
689 return getEffectiveDeclContext(cast<Decl>(DC));
692 if (const auto *VD = dyn_cast<VarDecl>(D))
693 if (VD->isExternC())
694 return getASTContext().getTranslationUnitDecl();
696 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
697 if (FD->isExternC())
698 return getASTContext().getTranslationUnitDecl();
699 // Member-like constrained friends are mangled as if they were members of
700 // the enclosing class.
701 if (FD->isMemberLikeConstrainedFriend() &&
702 getASTContext().getLangOpts().getClangABICompat() >
703 LangOptions::ClangABI::Ver17)
704 return D->getLexicalDeclContext()->getRedeclContext();
707 return DC->getRedeclContext();
710 bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
711 if (ND && ND->getFormalLinkage() == InternalLinkage &&
712 !ND->isExternallyVisible() &&
713 getEffectiveDeclContext(ND)->isFileContext() &&
714 !ND->isInAnonymousNamespace())
715 return true;
716 return false;
719 // Check if this Function Decl needs a unique internal linkage name.
720 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
721 const NamedDecl *ND) {
722 if (!NeedsUniqueInternalLinkageNames || !ND)
723 return false;
725 const auto *FD = dyn_cast<FunctionDecl>(ND);
726 if (!FD)
727 return false;
729 // For C functions without prototypes, return false as their
730 // names should not be mangled.
731 if (!FD->getType()->getAs<FunctionProtoType>())
732 return false;
734 if (isInternalLinkageDecl(ND))
735 return true;
737 return false;
740 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
741 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
742 LanguageLinkage L = FD->getLanguageLinkage();
743 // Overloadable functions need mangling.
744 if (FD->hasAttr<OverloadableAttr>())
745 return true;
747 // "main" is not mangled.
748 if (FD->isMain())
749 return false;
751 // The Windows ABI expects that we would never mangle "typical"
752 // user-defined entry points regardless of visibility or freestanding-ness.
754 // N.B. This is distinct from asking about "main". "main" has a lot of
755 // special rules associated with it in the standard while these
756 // user-defined entry points are outside of the purview of the standard.
757 // For example, there can be only one definition for "main" in a standards
758 // compliant program; however nothing forbids the existence of wmain and
759 // WinMain in the same translation unit.
760 if (FD->isMSVCRTEntryPoint())
761 return false;
763 // C++ functions and those whose names are not a simple identifier need
764 // mangling.
765 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
766 return true;
768 // C functions are not mangled.
769 if (L == CLanguageLinkage)
770 return false;
773 // Otherwise, no mangling is done outside C++ mode.
774 if (!getASTContext().getLangOpts().CPlusPlus)
775 return false;
777 if (const auto *VD = dyn_cast<VarDecl>(D)) {
778 // Decompositions are mangled.
779 if (isa<DecompositionDecl>(VD))
780 return true;
782 // C variables are not mangled.
783 if (VD->isExternC())
784 return false;
786 // Variables at global scope are not mangled unless they have internal
787 // linkage or are specializations or are attached to a named module.
788 const DeclContext *DC = getEffectiveDeclContext(D);
789 // Check for extern variable declared locally.
790 if (DC->isFunctionOrMethod() && D->hasLinkage())
791 while (!DC->isFileContext())
792 DC = getEffectiveParentContext(DC);
793 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
794 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
795 !isa<VarTemplateSpecializationDecl>(VD) &&
796 !VD->getOwningModuleForLinkage())
797 return false;
800 return true;
803 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
804 const AbiTagList *AdditionalAbiTags) {
805 assert(AbiTags && "require AbiTagState");
806 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
809 void CXXNameMangler::mangleSourceNameWithAbiTags(
810 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
811 mangleSourceName(ND->getIdentifier());
812 writeAbiTags(ND, AdditionalAbiTags);
815 void CXXNameMangler::mangle(GlobalDecl GD) {
816 // <mangled-name> ::= _Z <encoding>
817 // ::= <data name>
818 // ::= <special-name>
819 Out << "_Z";
820 if (isa<FunctionDecl>(GD.getDecl()))
821 mangleFunctionEncoding(GD);
822 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
823 BindingDecl>(GD.getDecl()))
824 mangleName(GD);
825 else if (const IndirectFieldDecl *IFD =
826 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
827 mangleName(IFD->getAnonField());
828 else
829 llvm_unreachable("unexpected kind of global decl");
832 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
833 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
834 // <encoding> ::= <function name> <bare-function-type>
836 // Don't mangle in the type if this isn't a decl we should typically mangle.
837 if (!Context.shouldMangleDeclName(FD)) {
838 mangleName(GD);
839 return;
842 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
843 if (ReturnTypeAbiTags.empty()) {
844 // There are no tags for return type, the simplest case. Enter the function
845 // parameter scope before mangling the name, because a template using
846 // constrained `auto` can have references to its parameters within its
847 // template argument list:
849 // template<typename T> void f(T x, C<decltype(x)> auto)
850 // ... is mangled as ...
851 // template<typename T, C<decltype(param 1)> U> void f(T, U)
852 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
853 mangleName(GD);
854 FunctionTypeDepth.pop(Saved);
855 mangleFunctionEncodingBareType(FD);
856 return;
859 // Mangle function name and encoding to temporary buffer.
860 // We have to output name and encoding to the same mangler to get the same
861 // substitution as it will be in final mangling.
862 SmallString<256> FunctionEncodingBuf;
863 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
864 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
865 // Output name of the function.
866 FunctionEncodingMangler.disableDerivedAbiTags();
868 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
869 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
870 FunctionTypeDepth.pop(Saved);
872 // Remember length of the function name in the buffer.
873 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
874 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
876 // Get tags from return type that are not present in function name or
877 // encoding.
878 const AbiTagList &UsedAbiTags =
879 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
880 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
881 AdditionalAbiTags.erase(
882 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
883 UsedAbiTags.begin(), UsedAbiTags.end(),
884 AdditionalAbiTags.begin()),
885 AdditionalAbiTags.end());
887 // Output name with implicit tags and function encoding from temporary buffer.
888 Saved = FunctionTypeDepth.push();
889 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
890 FunctionTypeDepth.pop(Saved);
891 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
893 // Function encoding could create new substitutions so we have to add
894 // temp mangled substitutions to main mangler.
895 extendSubstitutions(&FunctionEncodingMangler);
898 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
899 if (FD->hasAttr<EnableIfAttr>()) {
900 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
901 Out << "Ua9enable_ifI";
902 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
903 E = FD->getAttrs().end();
904 I != E; ++I) {
905 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
906 if (!EIA)
907 continue;
908 if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
909 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
910 // even though <template-arg> should not include an X/E around
911 // <expr-primary>.
912 Out << 'X';
913 mangleExpression(EIA->getCond());
914 Out << 'E';
915 } else {
916 mangleTemplateArgExpr(EIA->getCond());
919 Out << 'E';
920 FunctionTypeDepth.pop(Saved);
923 // When mangling an inheriting constructor, the bare function type used is
924 // that of the inherited constructor.
925 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
926 if (auto Inherited = CD->getInheritedConstructor())
927 FD = Inherited.getConstructor();
929 // Whether the mangling of a function type includes the return type depends on
930 // the context and the nature of the function. The rules for deciding whether
931 // the return type is included are:
933 // 1. Template functions (names or types) have return types encoded, with
934 // the exceptions listed below.
935 // 2. Function types not appearing as part of a function name mangling,
936 // e.g. parameters, pointer types, etc., have return type encoded, with the
937 // exceptions listed below.
938 // 3. Non-template function names do not have return types encoded.
940 // The exceptions mentioned in (1) and (2) above, for which the return type is
941 // never included, are
942 // 1. Constructors.
943 // 2. Destructors.
944 // 3. Conversion operator functions, e.g. operator int.
945 bool MangleReturnType = false;
946 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
947 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
948 isa<CXXConversionDecl>(FD)))
949 MangleReturnType = true;
951 // Mangle the type of the primary template.
952 FD = PrimaryTemplate->getTemplatedDecl();
955 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
956 MangleReturnType, FD);
959 /// Return whether a given namespace is the 'std' namespace.
960 bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
961 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
962 return false;
964 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
965 return II && II->isStr("std");
968 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
969 // namespace.
970 bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
971 if (!DC->isNamespace())
972 return false;
974 return isStd(cast<NamespaceDecl>(DC));
977 static const GlobalDecl
978 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
979 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
980 // Check if we have a function template.
981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
982 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
983 TemplateArgs = FD->getTemplateSpecializationArgs();
984 return GD.getWithDecl(TD);
988 // Check if we have a class template.
989 if (const ClassTemplateSpecializationDecl *Spec =
990 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
991 TemplateArgs = &Spec->getTemplateArgs();
992 return GD.getWithDecl(Spec->getSpecializedTemplate());
995 // Check if we have a variable template.
996 if (const VarTemplateSpecializationDecl *Spec =
997 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
998 TemplateArgs = &Spec->getTemplateArgs();
999 return GD.getWithDecl(Spec->getSpecializedTemplate());
1002 return GlobalDecl();
1005 static TemplateName asTemplateName(GlobalDecl GD) {
1006 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1007 return TemplateName(const_cast<TemplateDecl*>(TD));
1010 void CXXNameMangler::mangleName(GlobalDecl GD) {
1011 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1012 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1013 // Variables should have implicit tags from its type.
1014 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
1015 if (VariableTypeAbiTags.empty()) {
1016 // Simple case no variable type tags.
1017 mangleNameWithAbiTags(VD, nullptr);
1018 return;
1021 // Mangle variable name to null stream to collect tags.
1022 llvm::raw_null_ostream NullOutStream;
1023 CXXNameMangler VariableNameMangler(*this, NullOutStream);
1024 VariableNameMangler.disableDerivedAbiTags();
1025 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
1027 // Get tags from variable type that are not present in its name.
1028 const AbiTagList &UsedAbiTags =
1029 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
1030 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
1031 AdditionalAbiTags.erase(
1032 std::set_difference(VariableTypeAbiTags.begin(),
1033 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
1034 UsedAbiTags.end(), AdditionalAbiTags.begin()),
1035 AdditionalAbiTags.end());
1037 // Output name with implicit tags.
1038 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
1039 } else {
1040 mangleNameWithAbiTags(GD, nullptr);
1044 const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
1045 const DeclContext *DC = Context.getEffectiveDeclContext(D);
1046 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1047 if (isLocalContainerContext(DC))
1048 return dyn_cast<RecordDecl>(D);
1049 D = cast<Decl>(DC);
1050 DC = Context.getEffectiveDeclContext(D);
1052 return nullptr;
1055 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1056 const AbiTagList *AdditionalAbiTags) {
1057 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1058 // <name> ::= [<module-name>] <nested-name>
1059 // ::= [<module-name>] <unscoped-name>
1060 // ::= [<module-name>] <unscoped-template-name> <template-args>
1061 // ::= <local-name>
1063 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1065 // If this is an extern variable declared locally, the relevant DeclContext
1066 // is that of the containing namespace, or the translation unit.
1067 // FIXME: This is a hack; extern variables declared locally should have
1068 // a proper semantic declaration context!
1069 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
1070 while (!DC->isNamespace() && !DC->isTranslationUnit())
1071 DC = Context.getEffectiveParentContext(DC);
1072 else if (GetLocalClassDecl(ND)) {
1073 mangleLocalName(GD, AdditionalAbiTags);
1074 return;
1077 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1079 if (isLocalContainerContext(DC)) {
1080 mangleLocalName(GD, AdditionalAbiTags);
1081 return;
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;
1091 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1092 // Check if we have a template.
1093 const TemplateArgumentList *TemplateArgs = nullptr;
1094 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1095 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1096 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1097 return;
1100 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1101 return;
1104 mangleNestedName(GD, DC, AdditionalAbiTags);
1107 void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1108 if (ND->isExternallyVisible())
1109 if (Module *M = ND->getOwningModuleForLinkage())
1110 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1113 // <module-name> ::= <module-subname>
1114 // ::= <module-name> <module-subname>
1115 // ::= <substitution>
1116 // <module-subname> ::= W <source-name>
1117 // ::= W P <source-name>
1118 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1119 // <substitution> ::= S <seq-id> _
1120 auto It = ModuleSubstitutions.find(Name);
1121 if (It != ModuleSubstitutions.end()) {
1122 Out << 'S';
1123 mangleSeqID(It->second);
1124 return;
1127 // FIXME: Preserve hierarchy in module names rather than flattening
1128 // them to strings; use Module*s as substitution keys.
1129 auto Parts = Name.rsplit('.');
1130 if (Parts.second.empty())
1131 Parts.second = Parts.first;
1132 else {
1133 mangleModuleNamePrefix(Parts.first, IsPartition);
1134 IsPartition = false;
1137 Out << 'W';
1138 if (IsPartition)
1139 Out << 'P';
1140 Out << Parts.second.size() << Parts.second;
1141 ModuleSubstitutions.insert({Name, SeqID++});
1144 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1145 ArrayRef<TemplateArgument> Args) {
1146 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1148 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1149 mangleUnscopedTemplateName(TD, DC, nullptr);
1150 mangleTemplateArgs(asTemplateName(TD), Args);
1151 } else {
1152 mangleNestedName(TD, Args);
1156 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1157 const AbiTagList *AdditionalAbiTags) {
1158 // <unscoped-name> ::= <unqualified-name>
1159 // ::= St <unqualified-name> # ::std::
1161 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1162 if (isStdNamespace(DC))
1163 Out << "St";
1165 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1168 void CXXNameMangler::mangleUnscopedTemplateName(
1169 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1170 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1171 // <unscoped-template-name> ::= <unscoped-name>
1172 // ::= <substitution>
1173 if (mangleSubstitution(ND))
1174 return;
1176 // <template-template-param> ::= <template-param>
1177 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1178 assert(!AdditionalAbiTags &&
1179 "template template param cannot have abi tags");
1180 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1181 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1182 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1183 } else {
1184 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1185 AdditionalAbiTags);
1188 addSubstitution(ND);
1191 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1192 // ABI:
1193 // Floating-point literals are encoded using a fixed-length
1194 // lowercase hexadecimal string corresponding to the internal
1195 // representation (IEEE on Itanium), high-order bytes first,
1196 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1197 // on Itanium.
1198 // The 'without leading zeroes' thing seems to be an editorial
1199 // mistake; see the discussion on cxx-abi-dev beginning on
1200 // 2012-01-16.
1202 // Our requirements here are just barely weird enough to justify
1203 // using a custom algorithm instead of post-processing APInt::toString().
1205 llvm::APInt valueBits = f.bitcastToAPInt();
1206 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1207 assert(numCharacters != 0);
1209 // Allocate a buffer of the right number of characters.
1210 SmallVector<char, 20> buffer(numCharacters);
1212 // Fill the buffer left-to-right.
1213 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1214 // The bit-index of the next hex digit.
1215 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1217 // Project out 4 bits starting at 'digitIndex'.
1218 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1219 hexDigit >>= (digitBitIndex % 64);
1220 hexDigit &= 0xF;
1222 // Map that over to a lowercase hex digit.
1223 static const char charForHex[16] = {
1224 '0', '1', '2', '3', '4', '5', '6', '7',
1225 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1227 buffer[stringIndex] = charForHex[hexDigit];
1230 Out.write(buffer.data(), numCharacters);
1233 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1234 Out << 'L';
1235 mangleType(T);
1236 mangleFloat(V);
1237 Out << 'E';
1240 void CXXNameMangler::mangleFixedPointLiteral() {
1241 DiagnosticsEngine &Diags = Context.getDiags();
1242 unsigned DiagID = Diags.getCustomDiagID(
1243 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1244 Diags.Report(DiagID);
1247 void CXXNameMangler::mangleNullPointer(QualType T) {
1248 // <expr-primary> ::= L <type> 0 E
1249 Out << 'L';
1250 mangleType(T);
1251 Out << "0E";
1254 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1255 if (Value.isSigned() && Value.isNegative()) {
1256 Out << 'n';
1257 Value.abs().print(Out, /*signed*/ false);
1258 } else {
1259 Value.print(Out, /*signed*/ false);
1263 void CXXNameMangler::mangleNumber(int64_t Number) {
1264 // <number> ::= [n] <non-negative decimal integer>
1265 if (Number < 0) {
1266 Out << 'n';
1267 Number = -Number;
1270 Out << Number;
1273 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1274 // <call-offset> ::= h <nv-offset> _
1275 // ::= v <v-offset> _
1276 // <nv-offset> ::= <offset number> # non-virtual base override
1277 // <v-offset> ::= <offset number> _ <virtual offset number>
1278 // # virtual base override, with vcall offset
1279 if (!Virtual) {
1280 Out << 'h';
1281 mangleNumber(NonVirtual);
1282 Out << '_';
1283 return;
1286 Out << 'v';
1287 mangleNumber(NonVirtual);
1288 Out << '_';
1289 mangleNumber(Virtual);
1290 Out << '_';
1293 void CXXNameMangler::manglePrefix(QualType type) {
1294 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1295 if (!mangleSubstitution(QualType(TST, 0))) {
1296 mangleTemplatePrefix(TST->getTemplateName());
1298 // FIXME: GCC does not appear to mangle the template arguments when
1299 // the template in question is a dependent template name. Should we
1300 // emulate that badness?
1301 mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1302 addSubstitution(QualType(TST, 0));
1304 } else if (const auto *DTST =
1305 type->getAs<DependentTemplateSpecializationType>()) {
1306 if (!mangleSubstitution(QualType(DTST, 0))) {
1307 TemplateName Template = getASTContext().getDependentTemplateName(
1308 DTST->getQualifier(), DTST->getIdentifier());
1309 mangleTemplatePrefix(Template);
1311 // FIXME: GCC does not appear to mangle the template arguments when
1312 // the template in question is a dependent template name. Should we
1313 // emulate that badness?
1314 mangleTemplateArgs(Template, DTST->template_arguments());
1315 addSubstitution(QualType(DTST, 0));
1317 } else {
1318 // We use the QualType mangle type variant here because it handles
1319 // substitutions.
1320 mangleType(type);
1324 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1326 /// \param recursive - true if this is being called recursively,
1327 /// i.e. if there is more prefix "to the right".
1328 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1329 bool recursive) {
1331 // x, ::x
1332 // <unresolved-name> ::= [gs] <base-unresolved-name>
1334 // T::x / decltype(p)::x
1335 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1337 // T::N::x /decltype(p)::N::x
1338 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1339 // <base-unresolved-name>
1341 // A::x, N::y, A<T>::z; "gs" means leading "::"
1342 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1343 // <base-unresolved-name>
1345 switch (qualifier->getKind()) {
1346 case NestedNameSpecifier::Global:
1347 Out << "gs";
1349 // We want an 'sr' unless this is the entire NNS.
1350 if (recursive)
1351 Out << "sr";
1353 // We never want an 'E' here.
1354 return;
1356 case NestedNameSpecifier::Super:
1357 llvm_unreachable("Can't mangle __super specifier");
1359 case NestedNameSpecifier::Namespace:
1360 if (qualifier->getPrefix())
1361 mangleUnresolvedPrefix(qualifier->getPrefix(),
1362 /*recursive*/ true);
1363 else
1364 Out << "sr";
1365 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1366 break;
1367 case NestedNameSpecifier::NamespaceAlias:
1368 if (qualifier->getPrefix())
1369 mangleUnresolvedPrefix(qualifier->getPrefix(),
1370 /*recursive*/ true);
1371 else
1372 Out << "sr";
1373 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1374 break;
1376 case NestedNameSpecifier::TypeSpec:
1377 case NestedNameSpecifier::TypeSpecWithTemplate: {
1378 const Type *type = qualifier->getAsType();
1380 // We only want to use an unresolved-type encoding if this is one of:
1381 // - a decltype
1382 // - a template type parameter
1383 // - a template template parameter with arguments
1384 // In all of these cases, we should have no prefix.
1385 if (qualifier->getPrefix()) {
1386 mangleUnresolvedPrefix(qualifier->getPrefix(),
1387 /*recursive*/ true);
1388 } else {
1389 // Otherwise, all the cases want this.
1390 Out << "sr";
1393 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1394 return;
1396 break;
1399 case NestedNameSpecifier::Identifier:
1400 // Member expressions can have these without prefixes.
1401 if (qualifier->getPrefix())
1402 mangleUnresolvedPrefix(qualifier->getPrefix(),
1403 /*recursive*/ true);
1404 else
1405 Out << "sr";
1407 mangleSourceName(qualifier->getAsIdentifier());
1408 // An Identifier has no type information, so we can't emit abi tags for it.
1409 break;
1412 // If this was the innermost part of the NNS, and we fell out to
1413 // here, append an 'E'.
1414 if (!recursive)
1415 Out << 'E';
1418 /// Mangle an unresolved-name, which is generally used for names which
1419 /// weren't resolved to specific entities.
1420 void CXXNameMangler::mangleUnresolvedName(
1421 NestedNameSpecifier *qualifier, DeclarationName name,
1422 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1423 unsigned knownArity) {
1424 if (qualifier) mangleUnresolvedPrefix(qualifier);
1425 switch (name.getNameKind()) {
1426 // <base-unresolved-name> ::= <simple-id>
1427 case DeclarationName::Identifier:
1428 mangleSourceName(name.getAsIdentifierInfo());
1429 break;
1430 // <base-unresolved-name> ::= dn <destructor-name>
1431 case DeclarationName::CXXDestructorName:
1432 Out << "dn";
1433 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1434 break;
1435 // <base-unresolved-name> ::= on <operator-name>
1436 case DeclarationName::CXXConversionFunctionName:
1437 case DeclarationName::CXXLiteralOperatorName:
1438 case DeclarationName::CXXOperatorName:
1439 Out << "on";
1440 mangleOperatorName(name, knownArity);
1441 break;
1442 case DeclarationName::CXXConstructorName:
1443 llvm_unreachable("Can't mangle a constructor name!");
1444 case DeclarationName::CXXUsingDirective:
1445 llvm_unreachable("Can't mangle a using directive name!");
1446 case DeclarationName::CXXDeductionGuideName:
1447 llvm_unreachable("Can't mangle a deduction guide name!");
1448 case DeclarationName::ObjCMultiArgSelector:
1449 case DeclarationName::ObjCOneArgSelector:
1450 case DeclarationName::ObjCZeroArgSelector:
1451 llvm_unreachable("Can't mangle Objective-C selector names here!");
1454 // The <simple-id> and on <operator-name> productions end in an optional
1455 // <template-args>.
1456 if (TemplateArgs)
1457 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1460 void CXXNameMangler::mangleUnqualifiedName(
1461 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1462 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1463 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1464 // <unqualified-name> ::= [<module-name>] [F] <operator-name>
1465 // ::= <ctor-dtor-name>
1466 // ::= [<module-name>] [F] <source-name>
1467 // ::= [<module-name>] DC <source-name>* E
1469 if (ND && DC && DC->isFileContext())
1470 mangleModuleName(ND);
1472 // A member-like constrained friend is mangled with a leading 'F'.
1473 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1474 auto *FD = dyn_cast<FunctionDecl>(ND);
1475 auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
1476 if ((FD && FD->isMemberLikeConstrainedFriend()) ||
1477 (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1478 if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
1479 Out << 'F';
1482 unsigned Arity = KnownArity;
1483 switch (Name.getNameKind()) {
1484 case DeclarationName::Identifier: {
1485 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1487 // We mangle decomposition declarations as the names of their bindings.
1488 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1489 // FIXME: Non-standard mangling for decomposition declarations:
1491 // <unqualified-name> ::= DC <source-name>* E
1493 // Proposed on cxx-abi-dev on 2016-08-12
1494 Out << "DC";
1495 for (auto *BD : DD->bindings())
1496 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1497 Out << 'E';
1498 writeAbiTags(ND, AdditionalAbiTags);
1499 break;
1502 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1503 // We follow MSVC in mangling GUID declarations as if they were variables
1504 // with a particular reserved name. Continue the pretense here.
1505 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1506 llvm::raw_svector_ostream GUIDOS(GUID);
1507 Context.mangleMSGuidDecl(GD, GUIDOS);
1508 Out << GUID.size() << GUID;
1509 break;
1512 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1513 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1514 Out << "TA";
1515 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1516 TPO->getValue(), /*TopLevel=*/true);
1517 break;
1520 if (II) {
1521 // Match GCC's naming convention for internal linkage symbols, for
1522 // symbols that are not actually visible outside of this TU. GCC
1523 // distinguishes between internal and external linkage symbols in
1524 // its mangling, to support cases like this that were valid C++ prior
1525 // to DR426:
1527 // void test() { extern void foo(); }
1528 // static void foo();
1530 // Don't bother with the L marker for names in anonymous namespaces; the
1531 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1532 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1533 // implying internal linkage.
1534 if (Context.isInternalLinkageDecl(ND))
1535 Out << 'L';
1537 bool IsRegCall = FD &&
1538 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1539 clang::CC_X86RegCall;
1540 bool IsDeviceStub =
1541 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1542 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1543 if (IsDeviceStub)
1544 mangleDeviceStubName(II);
1545 else if (IsRegCall)
1546 mangleRegCallName(II);
1547 else
1548 mangleSourceName(II);
1550 writeAbiTags(ND, AdditionalAbiTags);
1551 break;
1554 // Otherwise, an anonymous entity. We must have a declaration.
1555 assert(ND && "mangling empty name without declaration");
1557 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1558 if (NS->isAnonymousNamespace()) {
1559 // This is how gcc mangles these names.
1560 Out << "12_GLOBAL__N_1";
1561 break;
1565 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1566 // We must have an anonymous union or struct declaration.
1567 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1569 // Itanium C++ ABI 5.1.2:
1571 // For the purposes of mangling, the name of an anonymous union is
1572 // considered to be the name of the first named data member found by a
1573 // pre-order, depth-first, declaration-order walk of the data members of
1574 // the anonymous union. If there is no such data member (i.e., if all of
1575 // the data members in the union are unnamed), then there is no way for
1576 // a program to refer to the anonymous union, and there is therefore no
1577 // need to mangle its name.
1578 assert(RD->isAnonymousStructOrUnion()
1579 && "Expected anonymous struct or union!");
1580 const FieldDecl *FD = RD->findFirstNamedDataMember();
1582 // It's actually possible for various reasons for us to get here
1583 // with an empty anonymous struct / union. Fortunately, it
1584 // doesn't really matter what name we generate.
1585 if (!FD) break;
1586 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1588 mangleSourceName(FD->getIdentifier());
1589 // Not emitting abi tags: internal name anyway.
1590 break;
1593 // Class extensions have no name as a category, and it's possible
1594 // for them to be the semantic parent of certain declarations
1595 // (primarily, tag decls defined within declarations). Such
1596 // declarations will always have internal linkage, so the name
1597 // doesn't really matter, but we shouldn't crash on them. For
1598 // safety, just handle all ObjC containers here.
1599 if (isa<ObjCContainerDecl>(ND))
1600 break;
1602 // We must have an anonymous struct.
1603 const TagDecl *TD = cast<TagDecl>(ND);
1604 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1605 assert(TD->getDeclContext() == D->getDeclContext() &&
1606 "Typedef should not be in another decl context!");
1607 assert(D->getDeclName().getAsIdentifierInfo() &&
1608 "Typedef was not named!");
1609 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1610 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1611 // Explicit abi tags are still possible; take from underlying type, not
1612 // from typedef.
1613 writeAbiTags(TD, nullptr);
1614 break;
1617 // <unnamed-type-name> ::= <closure-type-name>
1619 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1620 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1621 // # Parameter types or 'v' for 'void'.
1622 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1623 std::optional<unsigned> DeviceNumber =
1624 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1626 // If we have a device-number via the discriminator, use that to mangle
1627 // the lambda, otherwise use the typical lambda-mangling-number. In either
1628 // case, a '0' should be mangled as a normal unnamed class instead of as a
1629 // lambda.
1630 if (Record->isLambda() &&
1631 ((DeviceNumber && *DeviceNumber > 0) ||
1632 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1633 assert(!AdditionalAbiTags &&
1634 "Lambda type cannot have additional abi tags");
1635 mangleLambda(Record);
1636 break;
1640 if (TD->isExternallyVisible()) {
1641 unsigned UnnamedMangle =
1642 getASTContext().getManglingNumber(TD, Context.isAux());
1643 Out << "Ut";
1644 if (UnnamedMangle > 1)
1645 Out << UnnamedMangle - 2;
1646 Out << '_';
1647 writeAbiTags(TD, AdditionalAbiTags);
1648 break;
1651 // Get a unique id for the anonymous struct. If it is not a real output
1652 // ID doesn't matter so use fake one.
1653 unsigned AnonStructId =
1654 NullOut ? 0
1655 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1657 // Mangle it as a source name in the form
1658 // [n] $_<id>
1659 // where n is the length of the string.
1660 SmallString<8> Str;
1661 Str += "$_";
1662 Str += llvm::utostr(AnonStructId);
1664 Out << Str.size();
1665 Out << Str;
1666 break;
1669 case DeclarationName::ObjCZeroArgSelector:
1670 case DeclarationName::ObjCOneArgSelector:
1671 case DeclarationName::ObjCMultiArgSelector:
1672 llvm_unreachable("Can't mangle Objective-C selector names here!");
1674 case DeclarationName::CXXConstructorName: {
1675 const CXXRecordDecl *InheritedFrom = nullptr;
1676 TemplateName InheritedTemplateName;
1677 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1678 if (auto Inherited =
1679 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1680 InheritedFrom = Inherited.getConstructor()->getParent();
1681 InheritedTemplateName =
1682 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1683 InheritedTemplateArgs =
1684 Inherited.getConstructor()->getTemplateSpecializationArgs();
1687 if (ND == Structor)
1688 // If the named decl is the C++ constructor we're mangling, use the type
1689 // we were given.
1690 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1691 else
1692 // Otherwise, use the complete constructor name. This is relevant if a
1693 // class with a constructor is declared within a constructor.
1694 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1696 // FIXME: The template arguments are part of the enclosing prefix or
1697 // nested-name, but it's more convenient to mangle them here.
1698 if (InheritedTemplateArgs)
1699 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1701 writeAbiTags(ND, AdditionalAbiTags);
1702 break;
1705 case DeclarationName::CXXDestructorName:
1706 if (ND == Structor)
1707 // If the named decl is the C++ destructor we're mangling, use the type we
1708 // were given.
1709 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1710 else
1711 // Otherwise, use the complete destructor name. This is relevant if a
1712 // class with a destructor is declared within a destructor.
1713 mangleCXXDtorType(Dtor_Complete);
1714 assert(ND);
1715 writeAbiTags(ND, AdditionalAbiTags);
1716 break;
1718 case DeclarationName::CXXOperatorName:
1719 if (ND && Arity == UnknownArity) {
1720 Arity = cast<FunctionDecl>(ND)->getNumParams();
1722 // If we have a member function, we need to include the 'this' pointer.
1723 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1724 if (MD->isImplicitObjectMemberFunction())
1725 Arity++;
1727 [[fallthrough]];
1728 case DeclarationName::CXXConversionFunctionName:
1729 case DeclarationName::CXXLiteralOperatorName:
1730 mangleOperatorName(Name, Arity);
1731 writeAbiTags(ND, AdditionalAbiTags);
1732 break;
1734 case DeclarationName::CXXDeductionGuideName:
1735 llvm_unreachable("Can't mangle a deduction guide name!");
1737 case DeclarationName::CXXUsingDirective:
1738 llvm_unreachable("Can't mangle a using directive name!");
1742 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1743 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1744 // <number> ::= [n] <non-negative decimal integer>
1745 // <identifier> ::= <unqualified source code identifier>
1746 if (getASTContext().getLangOpts().RegCall4)
1747 Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1748 << II->getName();
1749 else
1750 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1751 << II->getName();
1754 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1755 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1756 // <number> ::= [n] <non-negative decimal integer>
1757 // <identifier> ::= <unqualified source code identifier>
1758 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1759 << II->getName();
1762 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1763 // <source-name> ::= <positive length number> <identifier>
1764 // <number> ::= [n] <non-negative decimal integer>
1765 // <identifier> ::= <unqualified source code identifier>
1766 Out << II->getLength() << II->getName();
1769 void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1770 const DeclContext *DC,
1771 const AbiTagList *AdditionalAbiTags,
1772 bool NoFunction) {
1773 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1774 // <nested-name>
1775 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1776 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1777 // <template-args> E
1779 Out << 'N';
1780 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1781 Qualifiers MethodQuals = Method->getMethodQualifiers();
1782 // We do not consider restrict a distinguishing attribute for overloading
1783 // purposes so we must not mangle it.
1784 if (Method->isExplicitObjectMemberFunction())
1785 Out << 'H';
1786 MethodQuals.removeRestrict();
1787 mangleQualifiers(MethodQuals);
1788 mangleRefQualifier(Method->getRefQualifier());
1791 // Check if we have a template.
1792 const TemplateArgumentList *TemplateArgs = nullptr;
1793 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1794 mangleTemplatePrefix(TD, NoFunction);
1795 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1796 } else {
1797 manglePrefix(DC, NoFunction);
1798 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1801 Out << 'E';
1803 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1804 ArrayRef<TemplateArgument> Args) {
1805 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1807 Out << 'N';
1809 mangleTemplatePrefix(TD);
1810 mangleTemplateArgs(asTemplateName(TD), Args);
1812 Out << 'E';
1815 void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1816 GlobalDecl GD, const NamedDecl *PrefixND,
1817 const AbiTagList *AdditionalAbiTags) {
1818 // A <closure-prefix> represents a variable or field, not a regular
1819 // DeclContext, so needs special handling. In this case we're mangling a
1820 // limited form of <nested-name>:
1822 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1824 Out << 'N';
1826 mangleClosurePrefix(PrefixND);
1827 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1829 Out << 'E';
1832 static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1833 GlobalDecl GD;
1834 // The Itanium spec says:
1835 // For entities in constructors and destructors, the mangling of the
1836 // complete object constructor or destructor is used as the base function
1837 // name, i.e. the C1 or D1 version.
1838 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1839 GD = GlobalDecl(CD, Ctor_Complete);
1840 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1841 GD = GlobalDecl(DD, Dtor_Complete);
1842 else
1843 GD = GlobalDecl(cast<FunctionDecl>(DC));
1844 return GD;
1847 void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1848 const AbiTagList *AdditionalAbiTags) {
1849 const Decl *D = GD.getDecl();
1850 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1851 // := Z <function encoding> E s [<discriminator>]
1852 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1853 // _ <entity name>
1854 // <discriminator> := _ <non-negative number>
1855 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1856 const RecordDecl *RD = GetLocalClassDecl(D);
1857 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1859 Out << 'Z';
1862 AbiTagState LocalAbiTags(AbiTags);
1864 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1865 mangleObjCMethodName(MD);
1866 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1867 mangleBlockForPrefix(BD);
1868 else
1869 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1871 // Implicit ABI tags (from namespace) are not available in the following
1872 // entity; reset to actually emitted tags, which are available.
1873 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1876 Out << 'E';
1878 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1879 // be a bug that is fixed in trunk.
1881 if (RD) {
1882 // The parameter number is omitted for the last parameter, 0 for the
1883 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1884 // <entity name> will of course contain a <closure-type-name>: Its
1885 // numbering will be local to the particular argument in which it appears
1886 // -- other default arguments do not affect its encoding.
1887 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1888 if (CXXRD && CXXRD->isLambda()) {
1889 if (const ParmVarDecl *Parm
1890 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1891 if (const FunctionDecl *Func
1892 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1893 Out << 'd';
1894 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1895 if (Num > 1)
1896 mangleNumber(Num - 2);
1897 Out << '_';
1902 // Mangle the name relative to the closest enclosing function.
1903 // equality ok because RD derived from ND above
1904 if (D == RD) {
1905 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1906 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1907 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1908 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1909 else
1910 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1911 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1912 mangleUnqualifiedBlock(BD);
1913 } else {
1914 const NamedDecl *ND = cast<NamedDecl>(D);
1915 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1916 AdditionalAbiTags, true /*NoFunction*/);
1918 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1919 // Mangle a block in a default parameter; see above explanation for
1920 // lambdas.
1921 if (const ParmVarDecl *Parm
1922 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1923 if (const FunctionDecl *Func
1924 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1925 Out << 'd';
1926 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1927 if (Num > 1)
1928 mangleNumber(Num - 2);
1929 Out << '_';
1933 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1934 mangleUnqualifiedBlock(BD);
1935 } else {
1936 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1939 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1940 unsigned disc;
1941 if (Context.getNextDiscriminator(ND, disc)) {
1942 if (disc < 10)
1943 Out << '_' << disc;
1944 else
1945 Out << "__" << disc << '_';
1950 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1951 if (GetLocalClassDecl(Block)) {
1952 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1953 return;
1955 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1956 if (isLocalContainerContext(DC)) {
1957 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1958 return;
1960 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1961 mangleClosurePrefix(PrefixND);
1962 else
1963 manglePrefix(DC);
1964 mangleUnqualifiedBlock(Block);
1967 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1968 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1969 // <data-member-prefix> now, with no substitutions and no <template-args>.
1970 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1971 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1972 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1973 Context->getDeclContext()->isRecord()) {
1974 const auto *ND = cast<NamedDecl>(Context);
1975 if (ND->getIdentifier()) {
1976 mangleSourceNameWithAbiTags(ND);
1977 Out << 'M';
1982 // If we have a block mangling number, use it.
1983 unsigned Number = Block->getBlockManglingNumber();
1984 // Otherwise, just make up a number. It doesn't matter what it is because
1985 // the symbol in question isn't externally visible.
1986 if (!Number)
1987 Number = Context.getBlockId(Block, false);
1988 else {
1989 // Stored mangling numbers are 1-based.
1990 --Number;
1992 Out << "Ub";
1993 if (Number > 0)
1994 Out << Number - 1;
1995 Out << '_';
1998 // <template-param-decl>
1999 // ::= Ty # template type parameter
2000 // ::= Tk <concept name> [<template-args>] # constrained type parameter
2001 // ::= Tn <type> # template non-type parameter
2002 // ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2003 // # template template parameter
2004 // ::= Tp <template-param-decl> # template parameter pack
2005 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2006 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2007 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2008 if (Ty->isParameterPack())
2009 Out << "Tp";
2010 const TypeConstraint *Constraint = Ty->getTypeConstraint();
2011 if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2012 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2013 Out << "Tk";
2014 mangleTypeConstraint(Constraint);
2015 } else {
2016 Out << "Ty";
2018 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2019 if (Tn->isExpandedParameterPack()) {
2020 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2021 Out << "Tn";
2022 mangleType(Tn->getExpansionType(I));
2024 } else {
2025 QualType T = Tn->getType();
2026 if (Tn->isParameterPack()) {
2027 Out << "Tp";
2028 if (auto *PackExpansion = T->getAs<PackExpansionType>())
2029 T = PackExpansion->getPattern();
2031 Out << "Tn";
2032 mangleType(T);
2034 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2035 if (Tt->isExpandedParameterPack()) {
2036 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2037 ++I)
2038 mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2039 } else {
2040 if (Tt->isParameterPack())
2041 Out << "Tp";
2042 mangleTemplateParameterList(Tt->getTemplateParameters());
2047 void CXXNameMangler::mangleTemplateParameterList(
2048 const TemplateParameterList *Params) {
2049 Out << "Tt";
2050 for (auto *Param : *Params)
2051 mangleTemplateParamDecl(Param);
2052 mangleRequiresClause(Params->getRequiresClause());
2053 Out << "E";
2056 void CXXNameMangler::mangleTypeConstraint(
2057 const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
2058 const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
2059 if (!Arguments.empty())
2060 mangleTemplateName(Concept, Arguments);
2061 else if (DC->isTranslationUnit() || isStdNamespace(DC))
2062 mangleUnscopedName(Concept, DC, nullptr);
2063 else
2064 mangleNestedName(Concept, DC, nullptr);
2067 void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2068 llvm::SmallVector<TemplateArgument, 8> Args;
2069 if (Constraint->getTemplateArgsAsWritten()) {
2070 for (const TemplateArgumentLoc &ArgLoc :
2071 Constraint->getTemplateArgsAsWritten()->arguments())
2072 Args.push_back(ArgLoc.getArgument());
2074 return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
2077 void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2078 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2079 if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2080 Out << 'Q';
2081 mangleExpression(RequiresClause);
2085 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2086 // When trying to be ABI-compatibility with clang 12 and before, mangle a
2087 // <data-member-prefix> now, with no substitutions.
2088 if (Decl *Context = Lambda->getLambdaContextDecl()) {
2089 if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2090 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
2091 !isa<ParmVarDecl>(Context)) {
2092 if (const IdentifierInfo *Name
2093 = cast<NamedDecl>(Context)->getIdentifier()) {
2094 mangleSourceName(Name);
2095 const TemplateArgumentList *TemplateArgs = nullptr;
2096 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2097 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2098 Out << 'M';
2103 Out << "Ul";
2104 mangleLambdaSig(Lambda);
2105 Out << "E";
2107 // The number is omitted for the first closure type with a given
2108 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2109 // (in lexical order) with that same <lambda-sig> and context.
2111 // The AST keeps track of the number for us.
2113 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2114 // and host-side compilations, an extra device mangle context may be created
2115 // if the host-side CXX ABI has different numbering for lambda. In such case,
2116 // if the mangle context is that device-side one, use the device-side lambda
2117 // mangling number for this lambda.
2118 std::optional<unsigned> DeviceNumber =
2119 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2120 unsigned Number =
2121 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2123 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2124 if (Number > 1)
2125 mangleNumber(Number - 2);
2126 Out << '_';
2129 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2130 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2131 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2132 mangleTemplateParamDecl(D);
2134 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2135 if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2136 mangleRequiresClause(TPL->getRequiresClause());
2138 auto *Proto =
2139 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2140 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2141 Lambda->getLambdaStaticInvoker());
2144 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2145 switch (qualifier->getKind()) {
2146 case NestedNameSpecifier::Global:
2147 // nothing
2148 return;
2150 case NestedNameSpecifier::Super:
2151 llvm_unreachable("Can't mangle __super specifier");
2153 case NestedNameSpecifier::Namespace:
2154 mangleName(qualifier->getAsNamespace());
2155 return;
2157 case NestedNameSpecifier::NamespaceAlias:
2158 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2159 return;
2161 case NestedNameSpecifier::TypeSpec:
2162 case NestedNameSpecifier::TypeSpecWithTemplate:
2163 manglePrefix(QualType(qualifier->getAsType(), 0));
2164 return;
2166 case NestedNameSpecifier::Identifier:
2167 // Clang 14 and before did not consider this substitutable.
2168 bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
2169 if (!Clang14Compat && mangleSubstitution(qualifier))
2170 return;
2172 // Member expressions can have these without prefixes, but that
2173 // should end up in mangleUnresolvedPrefix instead.
2174 assert(qualifier->getPrefix());
2175 manglePrefix(qualifier->getPrefix());
2177 mangleSourceName(qualifier->getAsIdentifier());
2179 if (!Clang14Compat)
2180 addSubstitution(qualifier);
2181 return;
2184 llvm_unreachable("unexpected nested name specifier");
2187 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2188 // <prefix> ::= <prefix> <unqualified-name>
2189 // ::= <template-prefix> <template-args>
2190 // ::= <closure-prefix>
2191 // ::= <template-param>
2192 // ::= # empty
2193 // ::= <substitution>
2195 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2197 if (DC->isTranslationUnit())
2198 return;
2200 if (NoFunction && isLocalContainerContext(DC))
2201 return;
2203 assert(!isLocalContainerContext(DC));
2205 const NamedDecl *ND = cast<NamedDecl>(DC);
2206 if (mangleSubstitution(ND))
2207 return;
2209 // Check if we have a template-prefix or a closure-prefix.
2210 const TemplateArgumentList *TemplateArgs = nullptr;
2211 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2212 mangleTemplatePrefix(TD);
2213 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2214 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2215 mangleClosurePrefix(PrefixND, NoFunction);
2216 mangleUnqualifiedName(ND, nullptr, nullptr);
2217 } else {
2218 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2219 manglePrefix(DC, NoFunction);
2220 mangleUnqualifiedName(ND, DC, nullptr);
2223 addSubstitution(ND);
2226 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2227 // <template-prefix> ::= <prefix> <template unqualified-name>
2228 // ::= <template-param>
2229 // ::= <substitution>
2230 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2231 return mangleTemplatePrefix(TD);
2233 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2234 assert(Dependent && "unexpected template name kind");
2236 // Clang 11 and before mangled the substitution for a dependent template name
2237 // after already having emitted (a substitution for) the prefix.
2238 bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2239 if (!Clang11Compat && mangleSubstitution(Template))
2240 return;
2242 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2243 manglePrefix(Qualifier);
2245 if (Clang11Compat && mangleSubstitution(Template))
2246 return;
2248 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2249 mangleSourceName(Id);
2250 else
2251 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2253 addSubstitution(Template);
2256 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2257 bool NoFunction) {
2258 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2259 // <template-prefix> ::= <prefix> <template unqualified-name>
2260 // ::= <template-param>
2261 // ::= <substitution>
2262 // <template-template-param> ::= <template-param>
2263 // <substitution>
2265 if (mangleSubstitution(ND))
2266 return;
2268 // <template-template-param> ::= <template-param>
2269 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2270 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2271 } else {
2272 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2273 manglePrefix(DC, NoFunction);
2274 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2275 mangleUnqualifiedName(GD, DC, nullptr);
2276 else
2277 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2278 nullptr);
2281 addSubstitution(ND);
2284 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2285 if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2286 return nullptr;
2288 const NamedDecl *Context = nullptr;
2289 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2290 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2291 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2292 if (RD->isLambda())
2293 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2295 if (!Context)
2296 return nullptr;
2298 // Only lambdas within the initializer of a non-local variable or non-static
2299 // data member get a <closure-prefix>.
2300 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2301 isa<FieldDecl>(Context))
2302 return Context;
2304 return nullptr;
2307 void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2308 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2309 // ::= <template-prefix> <template-args> M
2310 if (mangleSubstitution(ND))
2311 return;
2313 const TemplateArgumentList *TemplateArgs = nullptr;
2314 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2315 mangleTemplatePrefix(TD, NoFunction);
2316 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2317 } else {
2318 const auto *DC = Context.getEffectiveDeclContext(ND);
2319 manglePrefix(DC, NoFunction);
2320 mangleUnqualifiedName(ND, DC, nullptr);
2323 Out << 'M';
2325 addSubstitution(ND);
2328 /// Mangles a template name under the production <type>. Required for
2329 /// template template arguments.
2330 /// <type> ::= <class-enum-type>
2331 /// ::= <template-param>
2332 /// ::= <substitution>
2333 void CXXNameMangler::mangleType(TemplateName TN) {
2334 if (mangleSubstitution(TN))
2335 return;
2337 TemplateDecl *TD = nullptr;
2339 switch (TN.getKind()) {
2340 case TemplateName::QualifiedTemplate:
2341 case TemplateName::UsingTemplate:
2342 case TemplateName::Template:
2343 TD = TN.getAsTemplateDecl();
2344 goto HaveDecl;
2346 HaveDecl:
2347 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2348 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2349 else
2350 mangleName(TD);
2351 break;
2353 case TemplateName::OverloadedTemplate:
2354 case TemplateName::AssumedTemplate:
2355 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2357 case TemplateName::DependentTemplate: {
2358 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2359 assert(Dependent->isIdentifier());
2361 // <class-enum-type> ::= <name>
2362 // <name> ::= <nested-name>
2363 mangleUnresolvedPrefix(Dependent->getQualifier());
2364 mangleSourceName(Dependent->getIdentifier());
2365 break;
2368 case TemplateName::SubstTemplateTemplateParm: {
2369 // Substituted template parameters are mangled as the substituted
2370 // template. This will check for the substitution twice, which is
2371 // fine, but we have to return early so that we don't try to *add*
2372 // the substitution twice.
2373 SubstTemplateTemplateParmStorage *subst
2374 = TN.getAsSubstTemplateTemplateParm();
2375 mangleType(subst->getReplacement());
2376 return;
2379 case TemplateName::SubstTemplateTemplateParmPack: {
2380 // FIXME: not clear how to mangle this!
2381 // template <template <class> class T...> class A {
2382 // template <template <class> class U...> void foo(B<T,U> x...);
2383 // };
2384 Out << "_SUBSTPACK_";
2385 break;
2389 addSubstitution(TN);
2392 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2393 StringRef Prefix) {
2394 // Only certain other types are valid as prefixes; enumerate them.
2395 switch (Ty->getTypeClass()) {
2396 case Type::Builtin:
2397 case Type::Complex:
2398 case Type::Adjusted:
2399 case Type::Decayed:
2400 case Type::Pointer:
2401 case Type::BlockPointer:
2402 case Type::LValueReference:
2403 case Type::RValueReference:
2404 case Type::MemberPointer:
2405 case Type::ConstantArray:
2406 case Type::IncompleteArray:
2407 case Type::VariableArray:
2408 case Type::DependentSizedArray:
2409 case Type::DependentAddressSpace:
2410 case Type::DependentVector:
2411 case Type::DependentSizedExtVector:
2412 case Type::Vector:
2413 case Type::ExtVector:
2414 case Type::ConstantMatrix:
2415 case Type::DependentSizedMatrix:
2416 case Type::FunctionProto:
2417 case Type::FunctionNoProto:
2418 case Type::Paren:
2419 case Type::Attributed:
2420 case Type::BTFTagAttributed:
2421 case Type::Auto:
2422 case Type::DeducedTemplateSpecialization:
2423 case Type::PackExpansion:
2424 case Type::ObjCObject:
2425 case Type::ObjCInterface:
2426 case Type::ObjCObjectPointer:
2427 case Type::ObjCTypeParam:
2428 case Type::Atomic:
2429 case Type::Pipe:
2430 case Type::MacroQualified:
2431 case Type::BitInt:
2432 case Type::DependentBitInt:
2433 llvm_unreachable("type is illegal as a nested name specifier");
2435 case Type::SubstTemplateTypeParmPack:
2436 // FIXME: not clear how to mangle this!
2437 // template <class T...> class A {
2438 // template <class U...> void foo(decltype(T::foo(U())) x...);
2439 // };
2440 Out << "_SUBSTPACK_";
2441 break;
2443 // <unresolved-type> ::= <template-param>
2444 // ::= <decltype>
2445 // ::= <template-template-param> <template-args>
2446 // (this last is not official yet)
2447 case Type::TypeOfExpr:
2448 case Type::TypeOf:
2449 case Type::Decltype:
2450 case Type::TemplateTypeParm:
2451 case Type::UnaryTransform:
2452 case Type::SubstTemplateTypeParm:
2453 unresolvedType:
2454 // Some callers want a prefix before the mangled type.
2455 Out << Prefix;
2457 // This seems to do everything we want. It's not really
2458 // sanctioned for a substituted template parameter, though.
2459 mangleType(Ty);
2461 // We never want to print 'E' directly after an unresolved-type,
2462 // so we return directly.
2463 return true;
2465 case Type::Typedef:
2466 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2467 break;
2469 case Type::UnresolvedUsing:
2470 mangleSourceNameWithAbiTags(
2471 cast<UnresolvedUsingType>(Ty)->getDecl());
2472 break;
2474 case Type::Enum:
2475 case Type::Record:
2476 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2477 break;
2479 case Type::TemplateSpecialization: {
2480 const TemplateSpecializationType *TST =
2481 cast<TemplateSpecializationType>(Ty);
2482 TemplateName TN = TST->getTemplateName();
2483 switch (TN.getKind()) {
2484 case TemplateName::Template:
2485 case TemplateName::QualifiedTemplate: {
2486 TemplateDecl *TD = TN.getAsTemplateDecl();
2488 // If the base is a template template parameter, this is an
2489 // unresolved type.
2490 assert(TD && "no template for template specialization type");
2491 if (isa<TemplateTemplateParmDecl>(TD))
2492 goto unresolvedType;
2494 mangleSourceNameWithAbiTags(TD);
2495 break;
2498 case TemplateName::OverloadedTemplate:
2499 case TemplateName::AssumedTemplate:
2500 case TemplateName::DependentTemplate:
2501 llvm_unreachable("invalid base for a template specialization type");
2503 case TemplateName::SubstTemplateTemplateParm: {
2504 SubstTemplateTemplateParmStorage *subst =
2505 TN.getAsSubstTemplateTemplateParm();
2506 mangleExistingSubstitution(subst->getReplacement());
2507 break;
2510 case TemplateName::SubstTemplateTemplateParmPack: {
2511 // FIXME: not clear how to mangle this!
2512 // template <template <class U> class T...> class A {
2513 // template <class U...> void foo(decltype(T<U>::foo) x...);
2514 // };
2515 Out << "_SUBSTPACK_";
2516 break;
2518 case TemplateName::UsingTemplate: {
2519 TemplateDecl *TD = TN.getAsTemplateDecl();
2520 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2521 mangleSourceNameWithAbiTags(TD);
2522 break;
2526 // Note: we don't pass in the template name here. We are mangling the
2527 // original source-level template arguments, so we shouldn't consider
2528 // conversions to the corresponding template parameter.
2529 // FIXME: Other compilers mangle partially-resolved template arguments in
2530 // unresolved-qualifier-levels.
2531 mangleTemplateArgs(TemplateName(), TST->template_arguments());
2532 break;
2535 case Type::InjectedClassName:
2536 mangleSourceNameWithAbiTags(
2537 cast<InjectedClassNameType>(Ty)->getDecl());
2538 break;
2540 case Type::DependentName:
2541 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2542 break;
2544 case Type::DependentTemplateSpecialization: {
2545 const DependentTemplateSpecializationType *DTST =
2546 cast<DependentTemplateSpecializationType>(Ty);
2547 TemplateName Template = getASTContext().getDependentTemplateName(
2548 DTST->getQualifier(), DTST->getIdentifier());
2549 mangleSourceName(DTST->getIdentifier());
2550 mangleTemplateArgs(Template, DTST->template_arguments());
2551 break;
2554 case Type::Using:
2555 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2556 Prefix);
2557 case Type::Elaborated:
2558 return mangleUnresolvedTypeOrSimpleId(
2559 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2562 return false;
2565 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2566 switch (Name.getNameKind()) {
2567 case DeclarationName::CXXConstructorName:
2568 case DeclarationName::CXXDestructorName:
2569 case DeclarationName::CXXDeductionGuideName:
2570 case DeclarationName::CXXUsingDirective:
2571 case DeclarationName::Identifier:
2572 case DeclarationName::ObjCMultiArgSelector:
2573 case DeclarationName::ObjCOneArgSelector:
2574 case DeclarationName::ObjCZeroArgSelector:
2575 llvm_unreachable("Not an operator name");
2577 case DeclarationName::CXXConversionFunctionName:
2578 // <operator-name> ::= cv <type> # (cast)
2579 Out << "cv";
2580 mangleType(Name.getCXXNameType());
2581 break;
2583 case DeclarationName::CXXLiteralOperatorName:
2584 Out << "li";
2585 mangleSourceName(Name.getCXXLiteralIdentifier());
2586 return;
2588 case DeclarationName::CXXOperatorName:
2589 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2590 break;
2594 void
2595 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2596 switch (OO) {
2597 // <operator-name> ::= nw # new
2598 case OO_New: Out << "nw"; break;
2599 // ::= na # new[]
2600 case OO_Array_New: Out << "na"; break;
2601 // ::= dl # delete
2602 case OO_Delete: Out << "dl"; break;
2603 // ::= da # delete[]
2604 case OO_Array_Delete: Out << "da"; break;
2605 // ::= ps # + (unary)
2606 // ::= pl # + (binary or unknown)
2607 case OO_Plus:
2608 Out << (Arity == 1? "ps" : "pl"); break;
2609 // ::= ng # - (unary)
2610 // ::= mi # - (binary or unknown)
2611 case OO_Minus:
2612 Out << (Arity == 1? "ng" : "mi"); break;
2613 // ::= ad # & (unary)
2614 // ::= an # & (binary or unknown)
2615 case OO_Amp:
2616 Out << (Arity == 1? "ad" : "an"); break;
2617 // ::= de # * (unary)
2618 // ::= ml # * (binary or unknown)
2619 case OO_Star:
2620 // Use binary when unknown.
2621 Out << (Arity == 1? "de" : "ml"); break;
2622 // ::= co # ~
2623 case OO_Tilde: Out << "co"; break;
2624 // ::= dv # /
2625 case OO_Slash: Out << "dv"; break;
2626 // ::= rm # %
2627 case OO_Percent: Out << "rm"; break;
2628 // ::= or # |
2629 case OO_Pipe: Out << "or"; break;
2630 // ::= eo # ^
2631 case OO_Caret: Out << "eo"; break;
2632 // ::= aS # =
2633 case OO_Equal: Out << "aS"; break;
2634 // ::= pL # +=
2635 case OO_PlusEqual: Out << "pL"; break;
2636 // ::= mI # -=
2637 case OO_MinusEqual: Out << "mI"; break;
2638 // ::= mL # *=
2639 case OO_StarEqual: Out << "mL"; break;
2640 // ::= dV # /=
2641 case OO_SlashEqual: Out << "dV"; break;
2642 // ::= rM # %=
2643 case OO_PercentEqual: Out << "rM"; break;
2644 // ::= aN # &=
2645 case OO_AmpEqual: Out << "aN"; break;
2646 // ::= oR # |=
2647 case OO_PipeEqual: Out << "oR"; break;
2648 // ::= eO # ^=
2649 case OO_CaretEqual: Out << "eO"; break;
2650 // ::= ls # <<
2651 case OO_LessLess: Out << "ls"; break;
2652 // ::= rs # >>
2653 case OO_GreaterGreater: Out << "rs"; break;
2654 // ::= lS # <<=
2655 case OO_LessLessEqual: Out << "lS"; break;
2656 // ::= rS # >>=
2657 case OO_GreaterGreaterEqual: Out << "rS"; break;
2658 // ::= eq # ==
2659 case OO_EqualEqual: Out << "eq"; break;
2660 // ::= ne # !=
2661 case OO_ExclaimEqual: Out << "ne"; break;
2662 // ::= lt # <
2663 case OO_Less: Out << "lt"; break;
2664 // ::= gt # >
2665 case OO_Greater: Out << "gt"; break;
2666 // ::= le # <=
2667 case OO_LessEqual: Out << "le"; break;
2668 // ::= ge # >=
2669 case OO_GreaterEqual: Out << "ge"; break;
2670 // ::= nt # !
2671 case OO_Exclaim: Out << "nt"; break;
2672 // ::= aa # &&
2673 case OO_AmpAmp: Out << "aa"; break;
2674 // ::= oo # ||
2675 case OO_PipePipe: Out << "oo"; break;
2676 // ::= pp # ++
2677 case OO_PlusPlus: Out << "pp"; break;
2678 // ::= mm # --
2679 case OO_MinusMinus: Out << "mm"; break;
2680 // ::= cm # ,
2681 case OO_Comma: Out << "cm"; break;
2682 // ::= pm # ->*
2683 case OO_ArrowStar: Out << "pm"; break;
2684 // ::= pt # ->
2685 case OO_Arrow: Out << "pt"; break;
2686 // ::= cl # ()
2687 case OO_Call: Out << "cl"; break;
2688 // ::= ix # []
2689 case OO_Subscript: Out << "ix"; break;
2691 // ::= qu # ?
2692 // The conditional operator can't be overloaded, but we still handle it when
2693 // mangling expressions.
2694 case OO_Conditional: Out << "qu"; break;
2695 // Proposal on cxx-abi-dev, 2015-10-21.
2696 // ::= aw # co_await
2697 case OO_Coawait: Out << "aw"; break;
2698 // Proposed in cxx-abi github issue 43.
2699 // ::= ss # <=>
2700 case OO_Spaceship: Out << "ss"; break;
2702 case OO_None:
2703 case NUM_OVERLOADED_OPERATORS:
2704 llvm_unreachable("Not an overloaded operator");
2708 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2709 // Vendor qualifiers come first and if they are order-insensitive they must
2710 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2712 // <type> ::= U <addrspace-expr>
2713 if (DAST) {
2714 Out << "U2ASI";
2715 mangleExpression(DAST->getAddrSpaceExpr());
2716 Out << "E";
2719 // Address space qualifiers start with an ordinary letter.
2720 if (Quals.hasAddressSpace()) {
2721 // Address space extension:
2723 // <type> ::= U <target-addrspace>
2724 // <type> ::= U <OpenCL-addrspace>
2725 // <type> ::= U <CUDA-addrspace>
2727 SmallString<64> ASString;
2728 LangAS AS = Quals.getAddressSpace();
2730 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2731 // <target-addrspace> ::= "AS" <address-space-number>
2732 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2733 if (TargetAS != 0 ||
2734 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2735 ASString = "AS" + llvm::utostr(TargetAS);
2736 } else {
2737 switch (AS) {
2738 default: llvm_unreachable("Not a language specific address space");
2739 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2740 // "private"| "generic" | "device" |
2741 // "host" ]
2742 case LangAS::opencl_global:
2743 ASString = "CLglobal";
2744 break;
2745 case LangAS::opencl_global_device:
2746 ASString = "CLdevice";
2747 break;
2748 case LangAS::opencl_global_host:
2749 ASString = "CLhost";
2750 break;
2751 case LangAS::opencl_local:
2752 ASString = "CLlocal";
2753 break;
2754 case LangAS::opencl_constant:
2755 ASString = "CLconstant";
2756 break;
2757 case LangAS::opencl_private:
2758 ASString = "CLprivate";
2759 break;
2760 case LangAS::opencl_generic:
2761 ASString = "CLgeneric";
2762 break;
2763 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2764 // "device" | "host" ]
2765 case LangAS::sycl_global:
2766 ASString = "SYglobal";
2767 break;
2768 case LangAS::sycl_global_device:
2769 ASString = "SYdevice";
2770 break;
2771 case LangAS::sycl_global_host:
2772 ASString = "SYhost";
2773 break;
2774 case LangAS::sycl_local:
2775 ASString = "SYlocal";
2776 break;
2777 case LangAS::sycl_private:
2778 ASString = "SYprivate";
2779 break;
2780 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2781 case LangAS::cuda_device:
2782 ASString = "CUdevice";
2783 break;
2784 case LangAS::cuda_constant:
2785 ASString = "CUconstant";
2786 break;
2787 case LangAS::cuda_shared:
2788 ASString = "CUshared";
2789 break;
2790 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2791 case LangAS::ptr32_sptr:
2792 ASString = "ptr32_sptr";
2793 break;
2794 case LangAS::ptr32_uptr:
2795 ASString = "ptr32_uptr";
2796 break;
2797 case LangAS::ptr64:
2798 ASString = "ptr64";
2799 break;
2802 if (!ASString.empty())
2803 mangleVendorQualifier(ASString);
2806 // The ARC ownership qualifiers start with underscores.
2807 // Objective-C ARC Extension:
2809 // <type> ::= U "__strong"
2810 // <type> ::= U "__weak"
2811 // <type> ::= U "__autoreleasing"
2813 // Note: we emit __weak first to preserve the order as
2814 // required by the Itanium ABI.
2815 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2816 mangleVendorQualifier("__weak");
2818 // __unaligned (from -fms-extensions)
2819 if (Quals.hasUnaligned())
2820 mangleVendorQualifier("__unaligned");
2822 // Remaining ARC ownership qualifiers.
2823 switch (Quals.getObjCLifetime()) {
2824 case Qualifiers::OCL_None:
2825 break;
2827 case Qualifiers::OCL_Weak:
2828 // Do nothing as we already handled this case above.
2829 break;
2831 case Qualifiers::OCL_Strong:
2832 mangleVendorQualifier("__strong");
2833 break;
2835 case Qualifiers::OCL_Autoreleasing:
2836 mangleVendorQualifier("__autoreleasing");
2837 break;
2839 case Qualifiers::OCL_ExplicitNone:
2840 // The __unsafe_unretained qualifier is *not* mangled, so that
2841 // __unsafe_unretained types in ARC produce the same manglings as the
2842 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2843 // better ABI compatibility.
2845 // It's safe to do this because unqualified 'id' won't show up
2846 // in any type signatures that need to be mangled.
2847 break;
2850 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2851 if (Quals.hasRestrict())
2852 Out << 'r';
2853 if (Quals.hasVolatile())
2854 Out << 'V';
2855 if (Quals.hasConst())
2856 Out << 'K';
2859 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2860 Out << 'U' << name.size() << name;
2863 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2864 // <ref-qualifier> ::= R # lvalue reference
2865 // ::= O # rvalue-reference
2866 switch (RefQualifier) {
2867 case RQ_None:
2868 break;
2870 case RQ_LValue:
2871 Out << 'R';
2872 break;
2874 case RQ_RValue:
2875 Out << 'O';
2876 break;
2880 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2881 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2884 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2885 ASTContext &Ctx) {
2886 if (Quals)
2887 return true;
2888 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2889 return true;
2890 if (Ty->isOpenCLSpecificType())
2891 return true;
2892 // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2893 if (Ty->isSVESizelessBuiltinType() &&
2894 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2895 return true;
2896 if (Ty->isBuiltinType())
2897 return false;
2898 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2899 // substitution candidates.
2900 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2901 isa<AutoType>(Ty))
2902 return false;
2903 // A placeholder type for class template deduction is substitutable with
2904 // its corresponding template name; this is handled specially when mangling
2905 // the type.
2906 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2907 if (DeducedTST->getDeducedType().isNull())
2908 return false;
2909 return true;
2912 void CXXNameMangler::mangleType(QualType T) {
2913 // If our type is instantiation-dependent but not dependent, we mangle
2914 // it as it was written in the source, removing any top-level sugar.
2915 // Otherwise, use the canonical type.
2917 // FIXME: This is an approximation of the instantiation-dependent name
2918 // mangling rules, since we should really be using the type as written and
2919 // augmented via semantic analysis (i.e., with implicit conversions and
2920 // default template arguments) for any instantiation-dependent type.
2921 // Unfortunately, that requires several changes to our AST:
2922 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2923 // uniqued, so that we can handle substitutions properly
2924 // - Default template arguments will need to be represented in the
2925 // TemplateSpecializationType, since they need to be mangled even though
2926 // they aren't written.
2927 // - Conversions on non-type template arguments need to be expressed, since
2928 // they can affect the mangling of sizeof/alignof.
2930 // FIXME: This is wrong when mapping to the canonical type for a dependent
2931 // type discards instantiation-dependent portions of the type, such as for:
2933 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2934 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2936 // It's also wrong in the opposite direction when instantiation-dependent,
2937 // canonically-equivalent types differ in some irrelevant portion of inner
2938 // type sugar. In such cases, we fail to form correct substitutions, eg:
2940 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2942 // We should instead canonicalize the non-instantiation-dependent parts,
2943 // regardless of whether the type as a whole is dependent or instantiation
2944 // dependent.
2945 if (!T->isInstantiationDependentType() || T->isDependentType())
2946 T = T.getCanonicalType();
2947 else {
2948 // Desugar any types that are purely sugar.
2949 do {
2950 // Don't desugar through template specialization types that aren't
2951 // type aliases. We need to mangle the template arguments as written.
2952 if (const TemplateSpecializationType *TST
2953 = dyn_cast<TemplateSpecializationType>(T))
2954 if (!TST->isTypeAlias())
2955 break;
2957 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2958 // instantation-dependent qualifiers. See
2959 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2961 QualType Desugared
2962 = T.getSingleStepDesugaredType(Context.getASTContext());
2963 if (Desugared == T)
2964 break;
2966 T = Desugared;
2967 } while (true);
2969 SplitQualType split = T.split();
2970 Qualifiers quals = split.Quals;
2971 const Type *ty = split.Ty;
2973 bool isSubstitutable =
2974 isTypeSubstitutable(quals, ty, Context.getASTContext());
2975 if (isSubstitutable && mangleSubstitution(T))
2976 return;
2978 // If we're mangling a qualified array type, push the qualifiers to
2979 // the element type.
2980 if (quals && isa<ArrayType>(T)) {
2981 ty = Context.getASTContext().getAsArrayType(T);
2982 quals = Qualifiers();
2984 // Note that we don't update T: we want to add the
2985 // substitution at the original type.
2988 if (quals || ty->isDependentAddressSpaceType()) {
2989 if (const DependentAddressSpaceType *DAST =
2990 dyn_cast<DependentAddressSpaceType>(ty)) {
2991 SplitQualType splitDAST = DAST->getPointeeType().split();
2992 mangleQualifiers(splitDAST.Quals, DAST);
2993 mangleType(QualType(splitDAST.Ty, 0));
2994 } else {
2995 mangleQualifiers(quals);
2997 // Recurse: even if the qualified type isn't yet substitutable,
2998 // the unqualified type might be.
2999 mangleType(QualType(ty, 0));
3001 } else {
3002 switch (ty->getTypeClass()) {
3003 #define ABSTRACT_TYPE(CLASS, PARENT)
3004 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
3005 case Type::CLASS: \
3006 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3007 return;
3008 #define TYPE(CLASS, PARENT) \
3009 case Type::CLASS: \
3010 mangleType(static_cast<const CLASS##Type*>(ty)); \
3011 break;
3012 #include "clang/AST/TypeNodes.inc"
3016 // Add the substitution.
3017 if (isSubstitutable)
3018 addSubstitution(T);
3021 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
3022 if (!mangleStandardSubstitution(ND))
3023 mangleName(ND);
3026 void CXXNameMangler::mangleType(const BuiltinType *T) {
3027 // <type> ::= <builtin-type>
3028 // <builtin-type> ::= v # void
3029 // ::= w # wchar_t
3030 // ::= b # bool
3031 // ::= c # char
3032 // ::= a # signed char
3033 // ::= h # unsigned char
3034 // ::= s # short
3035 // ::= t # unsigned short
3036 // ::= i # int
3037 // ::= j # unsigned int
3038 // ::= l # long
3039 // ::= m # unsigned long
3040 // ::= x # long long, __int64
3041 // ::= y # unsigned long long, __int64
3042 // ::= n # __int128
3043 // ::= o # unsigned __int128
3044 // ::= f # float
3045 // ::= d # double
3046 // ::= e # long double, __float80
3047 // ::= g # __float128
3048 // ::= g # __ibm128
3049 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
3050 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
3051 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
3052 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
3053 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point
3054 // type _FloatN (N bits);
3055 // ::= Di # char32_t
3056 // ::= Ds # char16_t
3057 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3058 // ::= u <source-name> # vendor extended type
3059 std::string type_name;
3060 // Normalize integer types as vendor extended types:
3061 // u<length>i<type size>
3062 // u<length>u<type size>
3063 if (NormalizeIntegers && T->isInteger()) {
3064 if (T->isSignedInteger()) {
3065 switch (getASTContext().getTypeSize(T)) {
3066 case 8:
3067 // Pick a representative for each integer size in the substitution
3068 // dictionary. (Its actual defined size is not relevant.)
3069 if (mangleSubstitution(BuiltinType::SChar))
3070 break;
3071 Out << "u2i8";
3072 addSubstitution(BuiltinType::SChar);
3073 break;
3074 case 16:
3075 if (mangleSubstitution(BuiltinType::Short))
3076 break;
3077 Out << "u3i16";
3078 addSubstitution(BuiltinType::Short);
3079 break;
3080 case 32:
3081 if (mangleSubstitution(BuiltinType::Int))
3082 break;
3083 Out << "u3i32";
3084 addSubstitution(BuiltinType::Int);
3085 break;
3086 case 64:
3087 if (mangleSubstitution(BuiltinType::Long))
3088 break;
3089 Out << "u3i64";
3090 addSubstitution(BuiltinType::Long);
3091 break;
3092 case 128:
3093 if (mangleSubstitution(BuiltinType::Int128))
3094 break;
3095 Out << "u4i128";
3096 addSubstitution(BuiltinType::Int128);
3097 break;
3098 default:
3099 llvm_unreachable("Unknown integer size for normalization");
3101 } else {
3102 switch (getASTContext().getTypeSize(T)) {
3103 case 8:
3104 if (mangleSubstitution(BuiltinType::UChar))
3105 break;
3106 Out << "u2u8";
3107 addSubstitution(BuiltinType::UChar);
3108 break;
3109 case 16:
3110 if (mangleSubstitution(BuiltinType::UShort))
3111 break;
3112 Out << "u3u16";
3113 addSubstitution(BuiltinType::UShort);
3114 break;
3115 case 32:
3116 if (mangleSubstitution(BuiltinType::UInt))
3117 break;
3118 Out << "u3u32";
3119 addSubstitution(BuiltinType::UInt);
3120 break;
3121 case 64:
3122 if (mangleSubstitution(BuiltinType::ULong))
3123 break;
3124 Out << "u3u64";
3125 addSubstitution(BuiltinType::ULong);
3126 break;
3127 case 128:
3128 if (mangleSubstitution(BuiltinType::UInt128))
3129 break;
3130 Out << "u4u128";
3131 addSubstitution(BuiltinType::UInt128);
3132 break;
3133 default:
3134 llvm_unreachable("Unknown integer size for normalization");
3137 return;
3139 switch (T->getKind()) {
3140 case BuiltinType::Void:
3141 Out << 'v';
3142 break;
3143 case BuiltinType::Bool:
3144 Out << 'b';
3145 break;
3146 case BuiltinType::Char_U:
3147 case BuiltinType::Char_S:
3148 Out << 'c';
3149 break;
3150 case BuiltinType::UChar:
3151 Out << 'h';
3152 break;
3153 case BuiltinType::UShort:
3154 Out << 't';
3155 break;
3156 case BuiltinType::UInt:
3157 Out << 'j';
3158 break;
3159 case BuiltinType::ULong:
3160 Out << 'm';
3161 break;
3162 case BuiltinType::ULongLong:
3163 Out << 'y';
3164 break;
3165 case BuiltinType::UInt128:
3166 Out << 'o';
3167 break;
3168 case BuiltinType::SChar:
3169 Out << 'a';
3170 break;
3171 case BuiltinType::WChar_S:
3172 case BuiltinType::WChar_U:
3173 Out << 'w';
3174 break;
3175 case BuiltinType::Char8:
3176 Out << "Du";
3177 break;
3178 case BuiltinType::Char16:
3179 Out << "Ds";
3180 break;
3181 case BuiltinType::Char32:
3182 Out << "Di";
3183 break;
3184 case BuiltinType::Short:
3185 Out << 's';
3186 break;
3187 case BuiltinType::Int:
3188 Out << 'i';
3189 break;
3190 case BuiltinType::Long:
3191 Out << 'l';
3192 break;
3193 case BuiltinType::LongLong:
3194 Out << 'x';
3195 break;
3196 case BuiltinType::Int128:
3197 Out << 'n';
3198 break;
3199 case BuiltinType::Float16:
3200 Out << "DF16_";
3201 break;
3202 case BuiltinType::ShortAccum:
3203 case BuiltinType::Accum:
3204 case BuiltinType::LongAccum:
3205 case BuiltinType::UShortAccum:
3206 case BuiltinType::UAccum:
3207 case BuiltinType::ULongAccum:
3208 case BuiltinType::ShortFract:
3209 case BuiltinType::Fract:
3210 case BuiltinType::LongFract:
3211 case BuiltinType::UShortFract:
3212 case BuiltinType::UFract:
3213 case BuiltinType::ULongFract:
3214 case BuiltinType::SatShortAccum:
3215 case BuiltinType::SatAccum:
3216 case BuiltinType::SatLongAccum:
3217 case BuiltinType::SatUShortAccum:
3218 case BuiltinType::SatUAccum:
3219 case BuiltinType::SatULongAccum:
3220 case BuiltinType::SatShortFract:
3221 case BuiltinType::SatFract:
3222 case BuiltinType::SatLongFract:
3223 case BuiltinType::SatUShortFract:
3224 case BuiltinType::SatUFract:
3225 case BuiltinType::SatULongFract:
3226 llvm_unreachable("Fixed point types are disabled for c++");
3227 case BuiltinType::Half:
3228 Out << "Dh";
3229 break;
3230 case BuiltinType::Float:
3231 Out << 'f';
3232 break;
3233 case BuiltinType::Double:
3234 Out << 'd';
3235 break;
3236 case BuiltinType::LongDouble: {
3237 const TargetInfo *TI =
3238 getASTContext().getLangOpts().OpenMP &&
3239 getASTContext().getLangOpts().OpenMPIsTargetDevice
3240 ? getASTContext().getAuxTargetInfo()
3241 : &getASTContext().getTargetInfo();
3242 Out << TI->getLongDoubleMangling();
3243 break;
3245 case BuiltinType::Float128: {
3246 const TargetInfo *TI =
3247 getASTContext().getLangOpts().OpenMP &&
3248 getASTContext().getLangOpts().OpenMPIsTargetDevice
3249 ? getASTContext().getAuxTargetInfo()
3250 : &getASTContext().getTargetInfo();
3251 Out << TI->getFloat128Mangling();
3252 break;
3254 case BuiltinType::BFloat16: {
3255 const TargetInfo *TI =
3256 ((getASTContext().getLangOpts().OpenMP &&
3257 getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3258 getASTContext().getLangOpts().SYCLIsDevice)
3259 ? getASTContext().getAuxTargetInfo()
3260 : &getASTContext().getTargetInfo();
3261 Out << TI->getBFloat16Mangling();
3262 break;
3264 case BuiltinType::Ibm128: {
3265 const TargetInfo *TI = &getASTContext().getTargetInfo();
3266 Out << TI->getIbm128Mangling();
3267 break;
3269 case BuiltinType::NullPtr:
3270 Out << "Dn";
3271 break;
3273 #define BUILTIN_TYPE(Id, SingletonId)
3274 #define PLACEHOLDER_TYPE(Id, SingletonId) \
3275 case BuiltinType::Id:
3276 #include "clang/AST/BuiltinTypes.def"
3277 case BuiltinType::Dependent:
3278 if (!NullOut)
3279 llvm_unreachable("mangling a placeholder type");
3280 break;
3281 case BuiltinType::ObjCId:
3282 Out << "11objc_object";
3283 break;
3284 case BuiltinType::ObjCClass:
3285 Out << "10objc_class";
3286 break;
3287 case BuiltinType::ObjCSel:
3288 Out << "13objc_selector";
3289 break;
3290 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3291 case BuiltinType::Id: \
3292 type_name = "ocl_" #ImgType "_" #Suffix; \
3293 Out << type_name.size() << type_name; \
3294 break;
3295 #include "clang/Basic/OpenCLImageTypes.def"
3296 case BuiltinType::OCLSampler:
3297 Out << "11ocl_sampler";
3298 break;
3299 case BuiltinType::OCLEvent:
3300 Out << "9ocl_event";
3301 break;
3302 case BuiltinType::OCLClkEvent:
3303 Out << "12ocl_clkevent";
3304 break;
3305 case BuiltinType::OCLQueue:
3306 Out << "9ocl_queue";
3307 break;
3308 case BuiltinType::OCLReserveID:
3309 Out << "13ocl_reserveid";
3310 break;
3311 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3312 case BuiltinType::Id: \
3313 type_name = "ocl_" #ExtType; \
3314 Out << type_name.size() << type_name; \
3315 break;
3316 #include "clang/Basic/OpenCLExtensionTypes.def"
3317 // The SVE types are effectively target-specific. The mangling scheme
3318 // is defined in the appendices to the Procedure Call Standard for the
3319 // Arm Architecture.
3320 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3321 ElBits, IsSigned, IsFP, IsBF) \
3322 case BuiltinType::Id: \
3323 if (T->getKind() == BuiltinType::SveBFloat16 && \
3324 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \
3325 /* Prior to Clang 18.0 we used this incorrect mangled name */ \
3326 type_name = "__SVBFloat16_t"; \
3327 Out << "u" << type_name.size() << type_name; \
3328 } else { \
3329 type_name = MangledName; \
3330 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3331 << type_name; \
3333 break;
3334 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3335 case BuiltinType::Id: \
3336 type_name = MangledName; \
3337 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3338 << type_name; \
3339 break;
3340 #define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \
3341 case BuiltinType::Id: \
3342 type_name = MangledName; \
3343 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3344 << type_name; \
3345 break;
3346 #include "clang/Basic/AArch64SVEACLETypes.def"
3347 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3348 case BuiltinType::Id: \
3349 type_name = #Name; \
3350 Out << 'u' << type_name.size() << type_name; \
3351 break;
3352 #include "clang/Basic/PPCTypes.def"
3353 // TODO: Check the mangling scheme for RISC-V V.
3354 #define RVV_TYPE(Name, Id, SingletonId) \
3355 case BuiltinType::Id: \
3356 type_name = Name; \
3357 Out << 'u' << type_name.size() << type_name; \
3358 break;
3359 #include "clang/Basic/RISCVVTypes.def"
3360 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3361 case BuiltinType::Id: \
3362 type_name = MangledName; \
3363 Out << 'u' << type_name.size() << type_name; \
3364 break;
3365 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3369 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3370 switch (CC) {
3371 case CC_C:
3372 return "";
3374 case CC_X86VectorCall:
3375 case CC_X86Pascal:
3376 case CC_X86RegCall:
3377 case CC_AAPCS:
3378 case CC_AAPCS_VFP:
3379 case CC_AArch64VectorCall:
3380 case CC_AArch64SVEPCS:
3381 case CC_AMDGPUKernelCall:
3382 case CC_IntelOclBicc:
3383 case CC_SpirFunction:
3384 case CC_OpenCLKernel:
3385 case CC_PreserveMost:
3386 case CC_PreserveAll:
3387 case CC_M68kRTD:
3388 // FIXME: we should be mangling all of the above.
3389 return "";
3391 case CC_X86ThisCall:
3392 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3393 // used explicitly. At this point, we don't have that much information in
3394 // the AST, since clang tends to bake the convention into the canonical
3395 // function type. thiscall only rarely used explicitly, so don't mangle it
3396 // for now.
3397 return "";
3399 case CC_X86StdCall:
3400 return "stdcall";
3401 case CC_X86FastCall:
3402 return "fastcall";
3403 case CC_X86_64SysV:
3404 return "sysv_abi";
3405 case CC_Win64:
3406 return "ms_abi";
3407 case CC_Swift:
3408 return "swiftcall";
3409 case CC_SwiftAsync:
3410 return "swiftasynccall";
3412 llvm_unreachable("bad calling convention");
3415 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3416 // Fast path.
3417 if (T->getExtInfo() == FunctionType::ExtInfo())
3418 return;
3420 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3421 // This will get more complicated in the future if we mangle other
3422 // things here; but for now, since we mangle ns_returns_retained as
3423 // a qualifier on the result type, we can get away with this:
3424 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3425 if (!CCQualifier.empty())
3426 mangleVendorQualifier(CCQualifier);
3428 // FIXME: regparm
3429 // FIXME: noreturn
3432 void
3433 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3434 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3436 // Note that these are *not* substitution candidates. Demanglers might
3437 // have trouble with this if the parameter type is fully substituted.
3439 switch (PI.getABI()) {
3440 case ParameterABI::Ordinary:
3441 break;
3443 // All of these start with "swift", so they come before "ns_consumed".
3444 case ParameterABI::SwiftContext:
3445 case ParameterABI::SwiftAsyncContext:
3446 case ParameterABI::SwiftErrorResult:
3447 case ParameterABI::SwiftIndirectResult:
3448 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3449 break;
3452 if (PI.isConsumed())
3453 mangleVendorQualifier("ns_consumed");
3455 if (PI.isNoEscape())
3456 mangleVendorQualifier("noescape");
3459 // <type> ::= <function-type>
3460 // <function-type> ::= [<CV-qualifiers>] F [Y]
3461 // <bare-function-type> [<ref-qualifier>] E
3462 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3463 mangleExtFunctionInfo(T);
3465 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3466 // e.g. "const" in "int (A::*)() const".
3467 mangleQualifiers(T->getMethodQuals());
3469 // Mangle instantiation-dependent exception-specification, if present,
3470 // per cxx-abi-dev proposal on 2016-10-11.
3471 if (T->hasInstantiationDependentExceptionSpec()) {
3472 if (isComputedNoexcept(T->getExceptionSpecType())) {
3473 Out << "DO";
3474 mangleExpression(T->getNoexceptExpr());
3475 Out << "E";
3476 } else {
3477 assert(T->getExceptionSpecType() == EST_Dynamic);
3478 Out << "Dw";
3479 for (auto ExceptTy : T->exceptions())
3480 mangleType(ExceptTy);
3481 Out << "E";
3483 } else if (T->isNothrow()) {
3484 Out << "Do";
3487 Out << 'F';
3489 // FIXME: We don't have enough information in the AST to produce the 'Y'
3490 // encoding for extern "C" function types.
3491 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3493 // Mangle the ref-qualifier, if present.
3494 mangleRefQualifier(T->getRefQualifier());
3496 Out << 'E';
3499 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3500 // Function types without prototypes can arise when mangling a function type
3501 // within an overloadable function in C. We mangle these as the absence of any
3502 // parameter types (not even an empty parameter list).
3503 Out << 'F';
3505 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3507 FunctionTypeDepth.enterResultType();
3508 mangleType(T->getReturnType());
3509 FunctionTypeDepth.leaveResultType();
3511 FunctionTypeDepth.pop(saved);
3512 Out << 'E';
3515 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3516 bool MangleReturnType,
3517 const FunctionDecl *FD) {
3518 // Record that we're in a function type. See mangleFunctionParam
3519 // for details on what we're trying to achieve here.
3520 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3522 // <bare-function-type> ::= <signature type>+
3523 if (MangleReturnType) {
3524 FunctionTypeDepth.enterResultType();
3526 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3527 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3528 mangleVendorQualifier("ns_returns_retained");
3530 // Mangle the return type without any direct ARC ownership qualifiers.
3531 QualType ReturnTy = Proto->getReturnType();
3532 if (ReturnTy.getObjCLifetime()) {
3533 auto SplitReturnTy = ReturnTy.split();
3534 SplitReturnTy.Quals.removeObjCLifetime();
3535 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3537 mangleType(ReturnTy);
3539 FunctionTypeDepth.leaveResultType();
3542 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3543 // <builtin-type> ::= v # void
3544 Out << 'v';
3545 } else {
3546 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3547 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3548 // Mangle extended parameter info as order-sensitive qualifiers here.
3549 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3550 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3553 // Mangle the type.
3554 QualType ParamTy = Proto->getParamType(I);
3555 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3557 if (FD) {
3558 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3559 // Attr can only take 1 character, so we can hardcode the length
3560 // below.
3561 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3562 if (Attr->isDynamic())
3563 Out << "U25pass_dynamic_object_size" << Attr->getType();
3564 else
3565 Out << "U17pass_object_size" << Attr->getType();
3570 // <builtin-type> ::= z # ellipsis
3571 if (Proto->isVariadic())
3572 Out << 'z';
3575 if (FD) {
3576 FunctionTypeDepth.enterResultType();
3577 mangleRequiresClause(FD->getTrailingRequiresClause());
3580 FunctionTypeDepth.pop(saved);
3583 // <type> ::= <class-enum-type>
3584 // <class-enum-type> ::= <name>
3585 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3586 mangleName(T->getDecl());
3589 // <type> ::= <class-enum-type>
3590 // <class-enum-type> ::= <name>
3591 void CXXNameMangler::mangleType(const EnumType *T) {
3592 mangleType(static_cast<const TagType*>(T));
3594 void CXXNameMangler::mangleType(const RecordType *T) {
3595 mangleType(static_cast<const TagType*>(T));
3597 void CXXNameMangler::mangleType(const TagType *T) {
3598 mangleName(T->getDecl());
3601 // <type> ::= <array-type>
3602 // <array-type> ::= A <positive dimension number> _ <element type>
3603 // ::= A [<dimension expression>] _ <element type>
3604 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3605 Out << 'A' << T->getSize() << '_';
3606 mangleType(T->getElementType());
3608 void CXXNameMangler::mangleType(const VariableArrayType *T) {
3609 Out << 'A';
3610 // decayed vla types (size 0) will just be skipped.
3611 if (T->getSizeExpr())
3612 mangleExpression(T->getSizeExpr());
3613 Out << '_';
3614 mangleType(T->getElementType());
3616 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3617 Out << 'A';
3618 // A DependentSizedArrayType might not have size expression as below
3620 // template<int ...N> int arr[] = {N...};
3621 if (T->getSizeExpr())
3622 mangleExpression(T->getSizeExpr());
3623 Out << '_';
3624 mangleType(T->getElementType());
3626 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3627 Out << "A_";
3628 mangleType(T->getElementType());
3631 // <type> ::= <pointer-to-member-type>
3632 // <pointer-to-member-type> ::= M <class type> <member type>
3633 void CXXNameMangler::mangleType(const MemberPointerType *T) {
3634 Out << 'M';
3635 mangleType(QualType(T->getClass(), 0));
3636 QualType PointeeType = T->getPointeeType();
3637 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3638 mangleType(FPT);
3640 // Itanium C++ ABI 5.1.8:
3642 // The type of a non-static member function is considered to be different,
3643 // for the purposes of substitution, from the type of a namespace-scope or
3644 // static member function whose type appears similar. The types of two
3645 // non-static member functions are considered to be different, for the
3646 // purposes of substitution, if the functions are members of different
3647 // classes. In other words, for the purposes of substitution, the class of
3648 // which the function is a member is considered part of the type of
3649 // function.
3651 // Given that we already substitute member function pointers as a
3652 // whole, the net effect of this rule is just to unconditionally
3653 // suppress substitution on the function type in a member pointer.
3654 // We increment the SeqID here to emulate adding an entry to the
3655 // substitution table.
3656 ++SeqID;
3657 } else
3658 mangleType(PointeeType);
3661 // <type> ::= <template-param>
3662 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3663 mangleTemplateParameter(T->getDepth(), T->getIndex());
3666 // <type> ::= <template-param>
3667 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3668 // FIXME: not clear how to mangle this!
3669 // template <class T...> class A {
3670 // template <class U...> void foo(T(*)(U) x...);
3671 // };
3672 Out << "_SUBSTPACK_";
3675 // <type> ::= P <type> # pointer-to
3676 void CXXNameMangler::mangleType(const PointerType *T) {
3677 Out << 'P';
3678 mangleType(T->getPointeeType());
3680 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3681 Out << 'P';
3682 mangleType(T->getPointeeType());
3685 // <type> ::= R <type> # reference-to
3686 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3687 Out << 'R';
3688 mangleType(T->getPointeeType());
3691 // <type> ::= O <type> # rvalue reference-to (C++0x)
3692 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3693 Out << 'O';
3694 mangleType(T->getPointeeType());
3697 // <type> ::= C <type> # complex pair (C 2000)
3698 void CXXNameMangler::mangleType(const ComplexType *T) {
3699 Out << 'C';
3700 mangleType(T->getElementType());
3703 // ARM's ABI for Neon vector types specifies that they should be mangled as
3704 // if they are structs (to match ARM's initial implementation). The
3705 // vector type must be one of the special types predefined by ARM.
3706 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3707 QualType EltType = T->getElementType();
3708 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3709 const char *EltName = nullptr;
3710 if (T->getVectorKind() == VectorKind::NeonPoly) {
3711 switch (cast<BuiltinType>(EltType)->getKind()) {
3712 case BuiltinType::SChar:
3713 case BuiltinType::UChar:
3714 EltName = "poly8_t";
3715 break;
3716 case BuiltinType::Short:
3717 case BuiltinType::UShort:
3718 EltName = "poly16_t";
3719 break;
3720 case BuiltinType::LongLong:
3721 case BuiltinType::ULongLong:
3722 EltName = "poly64_t";
3723 break;
3724 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3726 } else {
3727 switch (cast<BuiltinType>(EltType)->getKind()) {
3728 case BuiltinType::SChar: EltName = "int8_t"; break;
3729 case BuiltinType::UChar: EltName = "uint8_t"; break;
3730 case BuiltinType::Short: EltName = "int16_t"; break;
3731 case BuiltinType::UShort: EltName = "uint16_t"; break;
3732 case BuiltinType::Int: EltName = "int32_t"; break;
3733 case BuiltinType::UInt: EltName = "uint32_t"; break;
3734 case BuiltinType::LongLong: EltName = "int64_t"; break;
3735 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3736 case BuiltinType::Double: EltName = "float64_t"; break;
3737 case BuiltinType::Float: EltName = "float32_t"; break;
3738 case BuiltinType::Half: EltName = "float16_t"; break;
3739 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3740 default:
3741 llvm_unreachable("unexpected Neon vector element type");
3744 const char *BaseName = nullptr;
3745 unsigned BitSize = (T->getNumElements() *
3746 getASTContext().getTypeSize(EltType));
3747 if (BitSize == 64)
3748 BaseName = "__simd64_";
3749 else {
3750 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3751 BaseName = "__simd128_";
3753 Out << strlen(BaseName) + strlen(EltName);
3754 Out << BaseName << EltName;
3757 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3758 DiagnosticsEngine &Diags = Context.getDiags();
3759 unsigned DiagID = Diags.getCustomDiagID(
3760 DiagnosticsEngine::Error,
3761 "cannot mangle this dependent neon vector type yet");
3762 Diags.Report(T->getAttributeLoc(), DiagID);
3765 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3766 switch (EltType->getKind()) {
3767 case BuiltinType::SChar:
3768 return "Int8";
3769 case BuiltinType::Short:
3770 return "Int16";
3771 case BuiltinType::Int:
3772 return "Int32";
3773 case BuiltinType::Long:
3774 case BuiltinType::LongLong:
3775 return "Int64";
3776 case BuiltinType::UChar:
3777 return "Uint8";
3778 case BuiltinType::UShort:
3779 return "Uint16";
3780 case BuiltinType::UInt:
3781 return "Uint32";
3782 case BuiltinType::ULong:
3783 case BuiltinType::ULongLong:
3784 return "Uint64";
3785 case BuiltinType::Half:
3786 return "Float16";
3787 case BuiltinType::Float:
3788 return "Float32";
3789 case BuiltinType::Double:
3790 return "Float64";
3791 case BuiltinType::BFloat16:
3792 return "Bfloat16";
3793 default:
3794 llvm_unreachable("Unexpected vector element base type");
3798 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3799 // the equivalent internal name. The vector type must be one of the special
3800 // types predefined by ARM.
3801 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3802 QualType EltType = T->getElementType();
3803 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3804 unsigned BitSize =
3805 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3806 (void)BitSize; // Silence warning.
3808 assert((BitSize == 64 || BitSize == 128) &&
3809 "Neon vector type not 64 or 128 bits");
3811 StringRef EltName;
3812 if (T->getVectorKind() == VectorKind::NeonPoly) {
3813 switch (cast<BuiltinType>(EltType)->getKind()) {
3814 case BuiltinType::UChar:
3815 EltName = "Poly8";
3816 break;
3817 case BuiltinType::UShort:
3818 EltName = "Poly16";
3819 break;
3820 case BuiltinType::ULong:
3821 case BuiltinType::ULongLong:
3822 EltName = "Poly64";
3823 break;
3824 default:
3825 llvm_unreachable("unexpected Neon polynomial vector element type");
3827 } else
3828 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3830 std::string TypeName =
3831 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3832 Out << TypeName.length() << TypeName;
3834 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3835 DiagnosticsEngine &Diags = Context.getDiags();
3836 unsigned DiagID = Diags.getCustomDiagID(
3837 DiagnosticsEngine::Error,
3838 "cannot mangle this dependent neon vector type yet");
3839 Diags.Report(T->getAttributeLoc(), DiagID);
3842 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3843 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3844 // type as the sizeless variants.
3846 // The mangling scheme for VLS types is implemented as a "pseudo" template:
3848 // '__SVE_VLS<<type>, <vector length>>'
3850 // Combining the existing SVE type and a specific vector length (in bits).
3851 // For example:
3853 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3855 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3857 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3859 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3861 // The latest ACLE specification (00bet5) does not contain details of this
3862 // mangling scheme, it will be specified in the next revision. The mangling
3863 // scheme is otherwise defined in the appendices to the Procedure Call Standard
3864 // for the Arm Architecture, see
3865 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3866 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3867 assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
3868 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
3869 "expected fixed-length SVE vector!");
3871 QualType EltType = T->getElementType();
3872 assert(EltType->isBuiltinType() &&
3873 "expected builtin type for fixed-length SVE vector!");
3875 StringRef TypeName;
3876 switch (cast<BuiltinType>(EltType)->getKind()) {
3877 case BuiltinType::SChar:
3878 TypeName = "__SVInt8_t";
3879 break;
3880 case BuiltinType::UChar: {
3881 if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3882 TypeName = "__SVUint8_t";
3883 else
3884 TypeName = "__SVBool_t";
3885 break;
3887 case BuiltinType::Short:
3888 TypeName = "__SVInt16_t";
3889 break;
3890 case BuiltinType::UShort:
3891 TypeName = "__SVUint16_t";
3892 break;
3893 case BuiltinType::Int:
3894 TypeName = "__SVInt32_t";
3895 break;
3896 case BuiltinType::UInt:
3897 TypeName = "__SVUint32_t";
3898 break;
3899 case BuiltinType::Long:
3900 TypeName = "__SVInt64_t";
3901 break;
3902 case BuiltinType::ULong:
3903 TypeName = "__SVUint64_t";
3904 break;
3905 case BuiltinType::Half:
3906 TypeName = "__SVFloat16_t";
3907 break;
3908 case BuiltinType::Float:
3909 TypeName = "__SVFloat32_t";
3910 break;
3911 case BuiltinType::Double:
3912 TypeName = "__SVFloat64_t";
3913 break;
3914 case BuiltinType::BFloat16:
3915 TypeName = "__SVBfloat16_t";
3916 break;
3917 default:
3918 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3921 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3923 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
3924 VecSizeInBits *= 8;
3926 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3927 << VecSizeInBits << "EE";
3930 void CXXNameMangler::mangleAArch64FixedSveVectorType(
3931 const DependentVectorType *T) {
3932 DiagnosticsEngine &Diags = Context.getDiags();
3933 unsigned DiagID = Diags.getCustomDiagID(
3934 DiagnosticsEngine::Error,
3935 "cannot mangle this dependent fixed-length SVE vector type yet");
3936 Diags.Report(T->getAttributeLoc(), DiagID);
3939 void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
3940 assert(T->getVectorKind() == VectorKind::RVVFixedLengthData &&
3941 "expected fixed-length RVV vector!");
3943 QualType EltType = T->getElementType();
3944 assert(EltType->isBuiltinType() &&
3945 "expected builtin type for fixed-length RVV vector!");
3947 SmallString<20> TypeNameStr;
3948 llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
3949 TypeNameOS << "__rvv_";
3950 switch (cast<BuiltinType>(EltType)->getKind()) {
3951 case BuiltinType::SChar:
3952 TypeNameOS << "int8";
3953 break;
3954 case BuiltinType::UChar:
3955 TypeNameOS << "uint8";
3956 break;
3957 case BuiltinType::Short:
3958 TypeNameOS << "int16";
3959 break;
3960 case BuiltinType::UShort:
3961 TypeNameOS << "uint16";
3962 break;
3963 case BuiltinType::Int:
3964 TypeNameOS << "int32";
3965 break;
3966 case BuiltinType::UInt:
3967 TypeNameOS << "uint32";
3968 break;
3969 case BuiltinType::Long:
3970 TypeNameOS << "int64";
3971 break;
3972 case BuiltinType::ULong:
3973 TypeNameOS << "uint64";
3974 break;
3975 case BuiltinType::Half:
3976 TypeNameOS << "float16";
3977 break;
3978 case BuiltinType::Float:
3979 TypeNameOS << "float32";
3980 break;
3981 case BuiltinType::Double:
3982 TypeNameOS << "float64";
3983 break;
3984 default:
3985 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
3988 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3990 // Apend the LMUL suffix.
3991 auto VScale = getASTContext().getTargetInfo().getVScaleRange(
3992 getASTContext().getLangOpts());
3993 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
3994 TypeNameOS << 'm';
3995 if (VecSizeInBits >= VLen)
3996 TypeNameOS << (VecSizeInBits / VLen);
3997 else
3998 TypeNameOS << 'f' << (VLen / VecSizeInBits);
4000 TypeNameOS << "_t";
4002 Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
4003 << VecSizeInBits << "EE";
4006 void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4007 const DependentVectorType *T) {
4008 DiagnosticsEngine &Diags = Context.getDiags();
4009 unsigned DiagID = Diags.getCustomDiagID(
4010 DiagnosticsEngine::Error,
4011 "cannot mangle this dependent fixed-length RVV vector type yet");
4012 Diags.Report(T->getAttributeLoc(), DiagID);
4015 // GNU extension: vector types
4016 // <type> ::= <vector-type>
4017 // <vector-type> ::= Dv <positive dimension number> _
4018 // <extended element type>
4019 // ::= Dv [<dimension expression>] _ <element type>
4020 // <extended element type> ::= <element type>
4021 // ::= p # AltiVec vector pixel
4022 // ::= b # Altivec vector bool
4023 void CXXNameMangler::mangleType(const VectorType *T) {
4024 if ((T->getVectorKind() == VectorKind::Neon ||
4025 T->getVectorKind() == VectorKind::NeonPoly)) {
4026 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4027 llvm::Triple::ArchType Arch =
4028 getASTContext().getTargetInfo().getTriple().getArch();
4029 if ((Arch == llvm::Triple::aarch64 ||
4030 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4031 mangleAArch64NeonVectorType(T);
4032 else
4033 mangleNeonVectorType(T);
4034 return;
4035 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4036 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4037 mangleAArch64FixedSveVectorType(T);
4038 return;
4039 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4040 mangleRISCVFixedRVVVectorType(T);
4041 return;
4043 Out << "Dv" << T->getNumElements() << '_';
4044 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4045 Out << 'p';
4046 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4047 Out << 'b';
4048 else
4049 mangleType(T->getElementType());
4052 void CXXNameMangler::mangleType(const DependentVectorType *T) {
4053 if ((T->getVectorKind() == VectorKind::Neon ||
4054 T->getVectorKind() == VectorKind::NeonPoly)) {
4055 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4056 llvm::Triple::ArchType Arch =
4057 getASTContext().getTargetInfo().getTriple().getArch();
4058 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4059 !Target.isOSDarwin())
4060 mangleAArch64NeonVectorType(T);
4061 else
4062 mangleNeonVectorType(T);
4063 return;
4064 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4065 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4066 mangleAArch64FixedSveVectorType(T);
4067 return;
4068 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4069 mangleRISCVFixedRVVVectorType(T);
4070 return;
4073 Out << "Dv";
4074 mangleExpression(T->getSizeExpr());
4075 Out << '_';
4076 if (T->getVectorKind() == VectorKind::AltiVecPixel)
4077 Out << 'p';
4078 else if (T->getVectorKind() == VectorKind::AltiVecBool)
4079 Out << 'b';
4080 else
4081 mangleType(T->getElementType());
4084 void CXXNameMangler::mangleType(const ExtVectorType *T) {
4085 mangleType(static_cast<const VectorType*>(T));
4087 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4088 Out << "Dv";
4089 mangleExpression(T->getSizeExpr());
4090 Out << '_';
4091 mangleType(T->getElementType());
4094 void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4095 // Mangle matrix types as a vendor extended type:
4096 // u<Len>matrix_typeI<Rows><Columns><element type>E
4098 StringRef VendorQualifier = "matrix_type";
4099 Out << "u" << VendorQualifier.size() << VendorQualifier;
4101 Out << "I";
4102 auto &ASTCtx = getASTContext();
4103 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4104 llvm::APSInt Rows(BitWidth);
4105 Rows = T->getNumRows();
4106 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4107 llvm::APSInt Columns(BitWidth);
4108 Columns = T->getNumColumns();
4109 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4110 mangleType(T->getElementType());
4111 Out << "E";
4114 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4115 // Mangle matrix types as a vendor extended type:
4116 // u<Len>matrix_typeI<row expr><column expr><element type>E
4117 StringRef VendorQualifier = "matrix_type";
4118 Out << "u" << VendorQualifier.size() << VendorQualifier;
4120 Out << "I";
4121 mangleTemplateArgExpr(T->getRowExpr());
4122 mangleTemplateArgExpr(T->getColumnExpr());
4123 mangleType(T->getElementType());
4124 Out << "E";
4127 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4128 SplitQualType split = T->getPointeeType().split();
4129 mangleQualifiers(split.Quals, T);
4130 mangleType(QualType(split.Ty, 0));
4133 void CXXNameMangler::mangleType(const PackExpansionType *T) {
4134 // <type> ::= Dp <type> # pack expansion (C++0x)
4135 Out << "Dp";
4136 mangleType(T->getPattern());
4139 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4140 mangleSourceName(T->getDecl()->getIdentifier());
4143 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4144 // Treat __kindof as a vendor extended type qualifier.
4145 if (T->isKindOfType())
4146 Out << "U8__kindof";
4148 if (!T->qual_empty()) {
4149 // Mangle protocol qualifiers.
4150 SmallString<64> QualStr;
4151 llvm::raw_svector_ostream QualOS(QualStr);
4152 QualOS << "objcproto";
4153 for (const auto *I : T->quals()) {
4154 StringRef name = I->getName();
4155 QualOS << name.size() << name;
4157 Out << 'U' << QualStr.size() << QualStr;
4160 mangleType(T->getBaseType());
4162 if (T->isSpecialized()) {
4163 // Mangle type arguments as I <type>+ E
4164 Out << 'I';
4165 for (auto typeArg : T->getTypeArgs())
4166 mangleType(typeArg);
4167 Out << 'E';
4171 void CXXNameMangler::mangleType(const BlockPointerType *T) {
4172 Out << "U13block_pointer";
4173 mangleType(T->getPointeeType());
4176 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4177 // Mangle injected class name types as if the user had written the
4178 // specialization out fully. It may not actually be possible to see
4179 // this mangling, though.
4180 mangleType(T->getInjectedSpecializationType());
4183 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4184 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4185 mangleTemplateName(TD, T->template_arguments());
4186 } else {
4187 if (mangleSubstitution(QualType(T, 0)))
4188 return;
4190 mangleTemplatePrefix(T->getTemplateName());
4192 // FIXME: GCC does not appear to mangle the template arguments when
4193 // the template in question is a dependent template name. Should we
4194 // emulate that badness?
4195 mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4196 addSubstitution(QualType(T, 0));
4200 void CXXNameMangler::mangleType(const DependentNameType *T) {
4201 // Proposal by cxx-abi-dev, 2014-03-26
4202 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
4203 // # dependent elaborated type specifier using
4204 // # 'typename'
4205 // ::= Ts <name> # dependent elaborated type specifier using
4206 // # 'struct' or 'class'
4207 // ::= Tu <name> # dependent elaborated type specifier using
4208 // # 'union'
4209 // ::= Te <name> # dependent elaborated type specifier using
4210 // # 'enum'
4211 switch (T->getKeyword()) {
4212 case ElaboratedTypeKeyword::None:
4213 case ElaboratedTypeKeyword::Typename:
4214 break;
4215 case ElaboratedTypeKeyword::Struct:
4216 case ElaboratedTypeKeyword::Class:
4217 case ElaboratedTypeKeyword::Interface:
4218 Out << "Ts";
4219 break;
4220 case ElaboratedTypeKeyword::Union:
4221 Out << "Tu";
4222 break;
4223 case ElaboratedTypeKeyword::Enum:
4224 Out << "Te";
4225 break;
4227 // Typename types are always nested
4228 Out << 'N';
4229 manglePrefix(T->getQualifier());
4230 mangleSourceName(T->getIdentifier());
4231 Out << 'E';
4234 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4235 // Dependently-scoped template types are nested if they have a prefix.
4236 Out << 'N';
4238 // TODO: avoid making this TemplateName.
4239 TemplateName Prefix =
4240 getASTContext().getDependentTemplateName(T->getQualifier(),
4241 T->getIdentifier());
4242 mangleTemplatePrefix(Prefix);
4244 // FIXME: GCC does not appear to mangle the template arguments when
4245 // the template in question is a dependent template name. Should we
4246 // emulate that badness?
4247 mangleTemplateArgs(Prefix, T->template_arguments());
4248 Out << 'E';
4251 void CXXNameMangler::mangleType(const TypeOfType *T) {
4252 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4253 // "extension with parameters" mangling.
4254 Out << "u6typeof";
4257 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4258 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4259 // "extension with parameters" mangling.
4260 Out << "u6typeof";
4263 void CXXNameMangler::mangleType(const DecltypeType *T) {
4264 Expr *E = T->getUnderlyingExpr();
4266 // type ::= Dt <expression> E # decltype of an id-expression
4267 // # or class member access
4268 // ::= DT <expression> E # decltype of an expression
4270 // This purports to be an exhaustive list of id-expressions and
4271 // class member accesses. Note that we do not ignore parentheses;
4272 // parentheses change the semantics of decltype for these
4273 // expressions (and cause the mangler to use the other form).
4274 if (isa<DeclRefExpr>(E) ||
4275 isa<MemberExpr>(E) ||
4276 isa<UnresolvedLookupExpr>(E) ||
4277 isa<DependentScopeDeclRefExpr>(E) ||
4278 isa<CXXDependentScopeMemberExpr>(E) ||
4279 isa<UnresolvedMemberExpr>(E))
4280 Out << "Dt";
4281 else
4282 Out << "DT";
4283 mangleExpression(E);
4284 Out << 'E';
4287 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4288 // If this is dependent, we need to record that. If not, we simply
4289 // mangle it as the underlying type since they are equivalent.
4290 if (T->isDependentType()) {
4291 Out << "u";
4293 StringRef BuiltinName;
4294 switch (T->getUTTKind()) {
4295 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4296 case UnaryTransformType::Enum: \
4297 BuiltinName = "__" #Trait; \
4298 break;
4299 #include "clang/Basic/TransformTypeTraits.def"
4301 Out << BuiltinName.size() << BuiltinName;
4304 Out << "I";
4305 mangleType(T->getBaseType());
4306 Out << "E";
4309 void CXXNameMangler::mangleType(const AutoType *T) {
4310 assert(T->getDeducedType().isNull() &&
4311 "Deduced AutoType shouldn't be handled here!");
4312 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4313 "shouldn't need to mangle __auto_type!");
4314 // <builtin-type> ::= Da # auto
4315 // ::= Dc # decltype(auto)
4316 // ::= Dk # constrained auto
4317 // ::= DK # constrained decltype(auto)
4318 if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4319 Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4320 mangleTypeConstraint(T->getTypeConstraintConcept(),
4321 T->getTypeConstraintArguments());
4322 } else {
4323 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4327 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4328 QualType Deduced = T->getDeducedType();
4329 if (!Deduced.isNull())
4330 return mangleType(Deduced);
4332 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4333 assert(TD && "shouldn't form deduced TST unless we know we have a template");
4335 if (mangleSubstitution(TD))
4336 return;
4338 mangleName(GlobalDecl(TD));
4339 addSubstitution(TD);
4342 void CXXNameMangler::mangleType(const AtomicType *T) {
4343 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4344 // (Until there's a standardized mangling...)
4345 Out << "U7_Atomic";
4346 mangleType(T->getValueType());
4349 void CXXNameMangler::mangleType(const PipeType *T) {
4350 // Pipe type mangling rules are described in SPIR 2.0 specification
4351 // A.1 Data types and A.3 Summary of changes
4352 // <type> ::= 8ocl_pipe
4353 Out << "8ocl_pipe";
4356 void CXXNameMangler::mangleType(const BitIntType *T) {
4357 // 5.1.5.2 Builtin types
4358 // <type> ::= DB <number | instantiation-dependent expression> _
4359 // ::= DU <number | instantiation-dependent expression> _
4360 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4363 void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4364 // 5.1.5.2 Builtin types
4365 // <type> ::= DB <number | instantiation-dependent expression> _
4366 // ::= DU <number | instantiation-dependent expression> _
4367 Out << "D" << (T->isUnsigned() ? "U" : "B");
4368 mangleExpression(T->getNumBitsExpr());
4369 Out << "_";
4372 void CXXNameMangler::mangleIntegerLiteral(QualType T,
4373 const llvm::APSInt &Value) {
4374 // <expr-primary> ::= L <type> <value number> E # integer literal
4375 Out << 'L';
4377 mangleType(T);
4378 if (T->isBooleanType()) {
4379 // Boolean values are encoded as 0/1.
4380 Out << (Value.getBoolValue() ? '1' : '0');
4381 } else {
4382 mangleNumber(Value);
4384 Out << 'E';
4388 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4389 // Ignore member expressions involving anonymous unions.
4390 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4391 if (!RT->getDecl()->isAnonymousStructOrUnion())
4392 break;
4393 const auto *ME = dyn_cast<MemberExpr>(Base);
4394 if (!ME)
4395 break;
4396 Base = ME->getBase();
4397 IsArrow = ME->isArrow();
4400 if (Base->isImplicitCXXThis()) {
4401 // Note: GCC mangles member expressions to the implicit 'this' as
4402 // *this., whereas we represent them as this->. The Itanium C++ ABI
4403 // does not specify anything here, so we follow GCC.
4404 Out << "dtdefpT";
4405 } else {
4406 Out << (IsArrow ? "pt" : "dt");
4407 mangleExpression(Base);
4411 /// Mangles a member expression.
4412 void CXXNameMangler::mangleMemberExpr(const Expr *base,
4413 bool isArrow,
4414 NestedNameSpecifier *qualifier,
4415 NamedDecl *firstQualifierLookup,
4416 DeclarationName member,
4417 const TemplateArgumentLoc *TemplateArgs,
4418 unsigned NumTemplateArgs,
4419 unsigned arity) {
4420 // <expression> ::= dt <expression> <unresolved-name>
4421 // ::= pt <expression> <unresolved-name>
4422 if (base)
4423 mangleMemberExprBase(base, isArrow);
4424 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4427 /// Look at the callee of the given call expression and determine if
4428 /// it's a parenthesized id-expression which would have triggered ADL
4429 /// otherwise.
4430 static bool isParenthesizedADLCallee(const CallExpr *call) {
4431 const Expr *callee = call->getCallee();
4432 const Expr *fn = callee->IgnoreParens();
4434 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4435 // too, but for those to appear in the callee, it would have to be
4436 // parenthesized.
4437 if (callee == fn) return false;
4439 // Must be an unresolved lookup.
4440 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4441 if (!lookup) return false;
4443 assert(!lookup->requiresADL());
4445 // Must be an unqualified lookup.
4446 if (lookup->getQualifier()) return false;
4448 // Must not have found a class member. Note that if one is a class
4449 // member, they're all class members.
4450 if (lookup->getNumDecls() > 0 &&
4451 (*lookup->decls_begin())->isCXXClassMember())
4452 return false;
4454 // Otherwise, ADL would have been triggered.
4455 return true;
4458 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4459 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4460 Out << CastEncoding;
4461 mangleType(ECE->getType());
4462 mangleExpression(ECE->getSubExpr());
4465 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4466 if (auto *Syntactic = InitList->getSyntacticForm())
4467 InitList = Syntactic;
4468 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4469 mangleExpression(InitList->getInit(i));
4472 void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4473 const concepts::Requirement *Req) {
4474 using concepts::Requirement;
4476 // TODO: We can't mangle the result of a failed substitution. It's not clear
4477 // whether we should be mangling the original form prior to any substitution
4478 // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4479 auto HandleSubstitutionFailure =
4480 [&](SourceLocation Loc) {
4481 DiagnosticsEngine &Diags = Context.getDiags();
4482 unsigned DiagID = Diags.getCustomDiagID(
4483 DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4484 "containing a substitution failure");
4485 Diags.Report(Loc, DiagID);
4486 Out << 'F';
4489 switch (Req->getKind()) {
4490 case Requirement::RK_Type: {
4491 const auto *TR = cast<concepts::TypeRequirement>(Req);
4492 if (TR->isSubstitutionFailure())
4493 return HandleSubstitutionFailure(
4494 TR->getSubstitutionDiagnostic()->DiagLoc);
4496 Out << 'T';
4497 mangleType(TR->getType()->getType());
4498 break;
4501 case Requirement::RK_Simple:
4502 case Requirement::RK_Compound: {
4503 const auto *ER = cast<concepts::ExprRequirement>(Req);
4504 if (ER->isExprSubstitutionFailure())
4505 return HandleSubstitutionFailure(
4506 ER->getExprSubstitutionDiagnostic()->DiagLoc);
4508 Out << 'X';
4509 mangleExpression(ER->getExpr());
4511 if (ER->hasNoexceptRequirement())
4512 Out << 'N';
4514 if (!ER->getReturnTypeRequirement().isEmpty()) {
4515 if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4516 return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4517 .getSubstitutionDiagnostic()
4518 ->DiagLoc);
4520 Out << 'R';
4521 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4523 break;
4526 case Requirement::RK_Nested:
4527 const auto *NR = cast<concepts::NestedRequirement>(Req);
4528 if (NR->hasInvalidConstraint()) {
4529 // FIXME: NestedRequirement should track the location of its requires
4530 // keyword.
4531 return HandleSubstitutionFailure(RequiresExprLoc);
4534 Out << 'Q';
4535 mangleExpression(NR->getConstraintExpr());
4536 break;
4540 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4541 bool AsTemplateArg) {
4542 // <expression> ::= <unary operator-name> <expression>
4543 // ::= <binary operator-name> <expression> <expression>
4544 // ::= <trinary operator-name> <expression> <expression> <expression>
4545 // ::= cv <type> expression # conversion with one argument
4546 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4547 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4548 // ::= sc <type> <expression> # static_cast<type> (expression)
4549 // ::= cc <type> <expression> # const_cast<type> (expression)
4550 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4551 // ::= st <type> # sizeof (a type)
4552 // ::= at <type> # alignof (a type)
4553 // ::= <template-param>
4554 // ::= <function-param>
4555 // ::= fpT # 'this' expression (part of <function-param>)
4556 // ::= sr <type> <unqualified-name> # dependent name
4557 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4558 // ::= ds <expression> <expression> # expr.*expr
4559 // ::= sZ <template-param> # size of a parameter pack
4560 // ::= sZ <function-param> # size of a function parameter pack
4561 // ::= u <source-name> <template-arg>* E # vendor extended expression
4562 // ::= <expr-primary>
4563 // <expr-primary> ::= L <type> <value number> E # integer literal
4564 // ::= L <type> <value float> E # floating literal
4565 // ::= L <type> <string type> E # string literal
4566 // ::= L <nullptr type> E # nullptr literal "LDnE"
4567 // ::= L <pointer type> 0 E # null pointer template argument
4568 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4569 // ::= L <mangled-name> E # external name
4570 QualType ImplicitlyConvertedToType;
4572 // A top-level expression that's not <expr-primary> needs to be wrapped in
4573 // X...E in a template arg.
4574 bool IsPrimaryExpr = true;
4575 auto NotPrimaryExpr = [&] {
4576 if (AsTemplateArg && IsPrimaryExpr)
4577 Out << 'X';
4578 IsPrimaryExpr = false;
4581 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4582 switch (D->getKind()) {
4583 default:
4584 // <expr-primary> ::= L <mangled-name> E # external name
4585 Out << 'L';
4586 mangle(D);
4587 Out << 'E';
4588 break;
4590 case Decl::ParmVar:
4591 NotPrimaryExpr();
4592 mangleFunctionParam(cast<ParmVarDecl>(D));
4593 break;
4595 case Decl::EnumConstant: {
4596 // <expr-primary>
4597 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4598 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4599 break;
4602 case Decl::NonTypeTemplateParm:
4603 NotPrimaryExpr();
4604 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4605 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4606 break;
4610 // 'goto recurse' is used when handling a simple "unwrapping" node which
4611 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4612 // to be preserved.
4613 recurse:
4614 switch (E->getStmtClass()) {
4615 case Expr::NoStmtClass:
4616 #define ABSTRACT_STMT(Type)
4617 #define EXPR(Type, Base)
4618 #define STMT(Type, Base) \
4619 case Expr::Type##Class:
4620 #include "clang/AST/StmtNodes.inc"
4621 // fallthrough
4623 // These all can only appear in local or variable-initialization
4624 // contexts and so should never appear in a mangling.
4625 case Expr::AddrLabelExprClass:
4626 case Expr::DesignatedInitUpdateExprClass:
4627 case Expr::ImplicitValueInitExprClass:
4628 case Expr::ArrayInitLoopExprClass:
4629 case Expr::ArrayInitIndexExprClass:
4630 case Expr::NoInitExprClass:
4631 case Expr::ParenListExprClass:
4632 case Expr::MSPropertyRefExprClass:
4633 case Expr::MSPropertySubscriptExprClass:
4634 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4635 case Expr::RecoveryExprClass:
4636 case Expr::OMPArraySectionExprClass:
4637 case Expr::OMPArrayShapingExprClass:
4638 case Expr::OMPIteratorExprClass:
4639 case Expr::CXXInheritedCtorInitExprClass:
4640 case Expr::CXXParenListInitExprClass:
4641 llvm_unreachable("unexpected statement kind");
4643 case Expr::ConstantExprClass:
4644 E = cast<ConstantExpr>(E)->getSubExpr();
4645 goto recurse;
4647 // FIXME: invent manglings for all these.
4648 case Expr::BlockExprClass:
4649 case Expr::ChooseExprClass:
4650 case Expr::CompoundLiteralExprClass:
4651 case Expr::ExtVectorElementExprClass:
4652 case Expr::GenericSelectionExprClass:
4653 case Expr::ObjCEncodeExprClass:
4654 case Expr::ObjCIsaExprClass:
4655 case Expr::ObjCIvarRefExprClass:
4656 case Expr::ObjCMessageExprClass:
4657 case Expr::ObjCPropertyRefExprClass:
4658 case Expr::ObjCProtocolExprClass:
4659 case Expr::ObjCSelectorExprClass:
4660 case Expr::ObjCStringLiteralClass:
4661 case Expr::ObjCBoxedExprClass:
4662 case Expr::ObjCArrayLiteralClass:
4663 case Expr::ObjCDictionaryLiteralClass:
4664 case Expr::ObjCSubscriptRefExprClass:
4665 case Expr::ObjCIndirectCopyRestoreExprClass:
4666 case Expr::ObjCAvailabilityCheckExprClass:
4667 case Expr::OffsetOfExprClass:
4668 case Expr::PredefinedExprClass:
4669 case Expr::ShuffleVectorExprClass:
4670 case Expr::ConvertVectorExprClass:
4671 case Expr::StmtExprClass:
4672 case Expr::ArrayTypeTraitExprClass:
4673 case Expr::ExpressionTraitExprClass:
4674 case Expr::VAArgExprClass:
4675 case Expr::CUDAKernelCallExprClass:
4676 case Expr::AsTypeExprClass:
4677 case Expr::PseudoObjectExprClass:
4678 case Expr::AtomicExprClass:
4679 case Expr::SourceLocExprClass:
4680 case Expr::BuiltinBitCastExprClass:
4682 NotPrimaryExpr();
4683 if (!NullOut) {
4684 // As bad as this diagnostic is, it's better than crashing.
4685 DiagnosticsEngine &Diags = Context.getDiags();
4686 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4687 "cannot yet mangle expression type %0");
4688 Diags.Report(E->getExprLoc(), DiagID)
4689 << E->getStmtClassName() << E->getSourceRange();
4690 return;
4692 break;
4695 case Expr::CXXUuidofExprClass: {
4696 NotPrimaryExpr();
4697 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4698 // As of clang 12, uuidof uses the vendor extended expression
4699 // mangling. Previously, it used a special-cased nonstandard extension.
4700 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4701 Out << "u8__uuidof";
4702 if (UE->isTypeOperand())
4703 mangleType(UE->getTypeOperand(Context.getASTContext()));
4704 else
4705 mangleTemplateArgExpr(UE->getExprOperand());
4706 Out << 'E';
4707 } else {
4708 if (UE->isTypeOperand()) {
4709 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4710 Out << "u8__uuidoft";
4711 mangleType(UuidT);
4712 } else {
4713 Expr *UuidExp = UE->getExprOperand();
4714 Out << "u8__uuidofz";
4715 mangleExpression(UuidExp);
4718 break;
4721 // Even gcc-4.5 doesn't mangle this.
4722 case Expr::BinaryConditionalOperatorClass: {
4723 NotPrimaryExpr();
4724 DiagnosticsEngine &Diags = Context.getDiags();
4725 unsigned DiagID =
4726 Diags.getCustomDiagID(DiagnosticsEngine::Error,
4727 "?: operator with omitted middle operand cannot be mangled");
4728 Diags.Report(E->getExprLoc(), DiagID)
4729 << E->getStmtClassName() << E->getSourceRange();
4730 return;
4733 // These are used for internal purposes and cannot be meaningfully mangled.
4734 case Expr::OpaqueValueExprClass:
4735 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4737 case Expr::InitListExprClass: {
4738 NotPrimaryExpr();
4739 Out << "il";
4740 mangleInitListElements(cast<InitListExpr>(E));
4741 Out << "E";
4742 break;
4745 case Expr::DesignatedInitExprClass: {
4746 NotPrimaryExpr();
4747 auto *DIE = cast<DesignatedInitExpr>(E);
4748 for (const auto &Designator : DIE->designators()) {
4749 if (Designator.isFieldDesignator()) {
4750 Out << "di";
4751 mangleSourceName(Designator.getFieldName());
4752 } else if (Designator.isArrayDesignator()) {
4753 Out << "dx";
4754 mangleExpression(DIE->getArrayIndex(Designator));
4755 } else {
4756 assert(Designator.isArrayRangeDesignator() &&
4757 "unknown designator kind");
4758 Out << "dX";
4759 mangleExpression(DIE->getArrayRangeStart(Designator));
4760 mangleExpression(DIE->getArrayRangeEnd(Designator));
4763 mangleExpression(DIE->getInit());
4764 break;
4767 case Expr::CXXDefaultArgExprClass:
4768 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4769 goto recurse;
4771 case Expr::CXXDefaultInitExprClass:
4772 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4773 goto recurse;
4775 case Expr::CXXStdInitializerListExprClass:
4776 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4777 goto recurse;
4779 case Expr::SubstNonTypeTemplateParmExprClass:
4780 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4781 goto recurse;
4783 case Expr::UserDefinedLiteralClass:
4784 // We follow g++'s approach of mangling a UDL as a call to the literal
4785 // operator.
4786 case Expr::CXXMemberCallExprClass: // fallthrough
4787 case Expr::CallExprClass: {
4788 NotPrimaryExpr();
4789 const CallExpr *CE = cast<CallExpr>(E);
4791 // <expression> ::= cp <simple-id> <expression>* E
4792 // We use this mangling only when the call would use ADL except
4793 // for being parenthesized. Per discussion with David
4794 // Vandervoorde, 2011.04.25.
4795 if (isParenthesizedADLCallee(CE)) {
4796 Out << "cp";
4797 // The callee here is a parenthesized UnresolvedLookupExpr with
4798 // no qualifier and should always get mangled as a <simple-id>
4799 // anyway.
4801 // <expression> ::= cl <expression>* E
4802 } else {
4803 Out << "cl";
4806 unsigned CallArity = CE->getNumArgs();
4807 for (const Expr *Arg : CE->arguments())
4808 if (isa<PackExpansionExpr>(Arg))
4809 CallArity = UnknownArity;
4811 mangleExpression(CE->getCallee(), CallArity);
4812 for (const Expr *Arg : CE->arguments())
4813 mangleExpression(Arg);
4814 Out << 'E';
4815 break;
4818 case Expr::CXXNewExprClass: {
4819 NotPrimaryExpr();
4820 const CXXNewExpr *New = cast<CXXNewExpr>(E);
4821 if (New->isGlobalNew()) Out << "gs";
4822 Out << (New->isArray() ? "na" : "nw");
4823 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
4824 E = New->placement_arg_end(); I != E; ++I)
4825 mangleExpression(*I);
4826 Out << '_';
4827 mangleType(New->getAllocatedType());
4828 if (New->hasInitializer()) {
4829 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
4830 Out << "il";
4831 else
4832 Out << "pi";
4833 const Expr *Init = New->getInitializer();
4834 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4835 // Directly inline the initializers.
4836 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4837 E = CCE->arg_end();
4838 I != E; ++I)
4839 mangleExpression(*I);
4840 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4841 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4842 mangleExpression(PLE->getExpr(i));
4843 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
4844 isa<InitListExpr>(Init)) {
4845 // Only take InitListExprs apart for list-initialization.
4846 mangleInitListElements(cast<InitListExpr>(Init));
4847 } else
4848 mangleExpression(Init);
4850 Out << 'E';
4851 break;
4854 case Expr::CXXPseudoDestructorExprClass: {
4855 NotPrimaryExpr();
4856 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4857 if (const Expr *Base = PDE->getBase())
4858 mangleMemberExprBase(Base, PDE->isArrow());
4859 NestedNameSpecifier *Qualifier = PDE->getQualifier();
4860 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4861 if (Qualifier) {
4862 mangleUnresolvedPrefix(Qualifier,
4863 /*recursive=*/true);
4864 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4865 Out << 'E';
4866 } else {
4867 Out << "sr";
4868 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4869 Out << 'E';
4871 } else if (Qualifier) {
4872 mangleUnresolvedPrefix(Qualifier);
4874 // <base-unresolved-name> ::= dn <destructor-name>
4875 Out << "dn";
4876 QualType DestroyedType = PDE->getDestroyedType();
4877 mangleUnresolvedTypeOrSimpleId(DestroyedType);
4878 break;
4881 case Expr::MemberExprClass: {
4882 NotPrimaryExpr();
4883 const MemberExpr *ME = cast<MemberExpr>(E);
4884 mangleMemberExpr(ME->getBase(), ME->isArrow(),
4885 ME->getQualifier(), nullptr,
4886 ME->getMemberDecl()->getDeclName(),
4887 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4888 Arity);
4889 break;
4892 case Expr::UnresolvedMemberExprClass: {
4893 NotPrimaryExpr();
4894 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4895 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4896 ME->isArrow(), ME->getQualifier(), nullptr,
4897 ME->getMemberName(),
4898 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4899 Arity);
4900 break;
4903 case Expr::CXXDependentScopeMemberExprClass: {
4904 NotPrimaryExpr();
4905 const CXXDependentScopeMemberExpr *ME
4906 = cast<CXXDependentScopeMemberExpr>(E);
4907 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4908 ME->isArrow(), ME->getQualifier(),
4909 ME->getFirstQualifierFoundInScope(),
4910 ME->getMember(),
4911 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4912 Arity);
4913 break;
4916 case Expr::UnresolvedLookupExprClass: {
4917 NotPrimaryExpr();
4918 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4919 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4920 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4921 Arity);
4922 break;
4925 case Expr::CXXUnresolvedConstructExprClass: {
4926 NotPrimaryExpr();
4927 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4928 unsigned N = CE->getNumArgs();
4930 if (CE->isListInitialization()) {
4931 assert(N == 1 && "unexpected form for list initialization");
4932 auto *IL = cast<InitListExpr>(CE->getArg(0));
4933 Out << "tl";
4934 mangleType(CE->getType());
4935 mangleInitListElements(IL);
4936 Out << "E";
4937 break;
4940 Out << "cv";
4941 mangleType(CE->getType());
4942 if (N != 1) Out << '_';
4943 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
4944 if (N != 1) Out << 'E';
4945 break;
4948 case Expr::CXXConstructExprClass: {
4949 // An implicit cast is silent, thus may contain <expr-primary>.
4950 const auto *CE = cast<CXXConstructExpr>(E);
4951 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
4952 assert(
4953 CE->getNumArgs() >= 1 &&
4954 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
4955 "implicit CXXConstructExpr must have one argument");
4956 E = cast<CXXConstructExpr>(E)->getArg(0);
4957 goto recurse;
4959 NotPrimaryExpr();
4960 Out << "il";
4961 for (auto *E : CE->arguments())
4962 mangleExpression(E);
4963 Out << "E";
4964 break;
4967 case Expr::CXXTemporaryObjectExprClass: {
4968 NotPrimaryExpr();
4969 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
4970 unsigned N = CE->getNumArgs();
4971 bool List = CE->isListInitialization();
4973 if (List)
4974 Out << "tl";
4975 else
4976 Out << "cv";
4977 mangleType(CE->getType());
4978 if (!List && N != 1)
4979 Out << '_';
4980 if (CE->isStdInitListInitialization()) {
4981 // We implicitly created a std::initializer_list<T> for the first argument
4982 // of a constructor of type U in an expression of the form U{a, b, c}.
4983 // Strip all the semantic gunk off the initializer list.
4984 auto *SILE =
4985 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
4986 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
4987 mangleInitListElements(ILE);
4988 } else {
4989 for (auto *E : CE->arguments())
4990 mangleExpression(E);
4992 if (List || N != 1)
4993 Out << 'E';
4994 break;
4997 case Expr::CXXScalarValueInitExprClass:
4998 NotPrimaryExpr();
4999 Out << "cv";
5000 mangleType(E->getType());
5001 Out << "_E";
5002 break;
5004 case Expr::CXXNoexceptExprClass:
5005 NotPrimaryExpr();
5006 Out << "nx";
5007 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5008 break;
5010 case Expr::UnaryExprOrTypeTraitExprClass: {
5011 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5012 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5014 if (!SAE->isInstantiationDependent()) {
5015 // Itanium C++ ABI:
5016 // If the operand of a sizeof or alignof operator is not
5017 // instantiation-dependent it is encoded as an integer literal
5018 // reflecting the result of the operator.
5020 // If the result of the operator is implicitly converted to a known
5021 // integer type, that type is used for the literal; otherwise, the type
5022 // of std::size_t or std::ptrdiff_t is used.
5024 // FIXME: We still include the operand in the profile in this case. This
5025 // can lead to mangling collisions between function templates that we
5026 // consider to be different.
5027 QualType T = (ImplicitlyConvertedToType.isNull() ||
5028 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5029 : ImplicitlyConvertedToType;
5030 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5031 mangleIntegerLiteral(T, V);
5032 break;
5035 NotPrimaryExpr(); // But otherwise, they are not.
5037 auto MangleAlignofSizeofArg = [&] {
5038 if (SAE->isArgumentType()) {
5039 Out << 't';
5040 mangleType(SAE->getArgumentType());
5041 } else {
5042 Out << 'z';
5043 mangleExpression(SAE->getArgumentExpr());
5047 switch(SAE->getKind()) {
5048 case UETT_SizeOf:
5049 Out << 's';
5050 MangleAlignofSizeofArg();
5051 break;
5052 case UETT_PreferredAlignOf:
5053 // As of clang 12, we mangle __alignof__ differently than alignof. (They
5054 // have acted differently since Clang 8, but were previously mangled the
5055 // same.)
5056 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5057 Out << "u11__alignof__";
5058 if (SAE->isArgumentType())
5059 mangleType(SAE->getArgumentType());
5060 else
5061 mangleTemplateArgExpr(SAE->getArgumentExpr());
5062 Out << 'E';
5063 break;
5065 [[fallthrough]];
5066 case UETT_AlignOf:
5067 Out << 'a';
5068 MangleAlignofSizeofArg();
5069 break;
5070 case UETT_VecStep: {
5071 DiagnosticsEngine &Diags = Context.getDiags();
5072 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
5073 "cannot yet mangle vec_step expression");
5074 Diags.Report(DiagID);
5075 return;
5077 case UETT_OpenMPRequiredSimdAlign: {
5078 DiagnosticsEngine &Diags = Context.getDiags();
5079 unsigned DiagID = Diags.getCustomDiagID(
5080 DiagnosticsEngine::Error,
5081 "cannot yet mangle __builtin_omp_required_simd_align expression");
5082 Diags.Report(DiagID);
5083 return;
5085 case UETT_VectorElements: {
5086 DiagnosticsEngine &Diags = Context.getDiags();
5087 unsigned DiagID = Diags.getCustomDiagID(
5088 DiagnosticsEngine::Error,
5089 "cannot yet mangle __builtin_vectorelements expression");
5090 Diags.Report(DiagID);
5091 return;
5094 break;
5097 case Expr::TypeTraitExprClass: {
5098 // <expression> ::= u <source-name> <template-arg>* E # vendor extension
5099 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5100 NotPrimaryExpr();
5101 Out << 'u';
5102 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5103 Out << Spelling.size() << Spelling;
5104 for (TypeSourceInfo *TSI : TTE->getArgs()) {
5105 mangleType(TSI->getType());
5107 Out << 'E';
5108 break;
5111 case Expr::CXXThrowExprClass: {
5112 NotPrimaryExpr();
5113 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5114 // <expression> ::= tw <expression> # throw expression
5115 // ::= tr # rethrow
5116 if (TE->getSubExpr()) {
5117 Out << "tw";
5118 mangleExpression(TE->getSubExpr());
5119 } else {
5120 Out << "tr";
5122 break;
5125 case Expr::CXXTypeidExprClass: {
5126 NotPrimaryExpr();
5127 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5128 // <expression> ::= ti <type> # typeid (type)
5129 // ::= te <expression> # typeid (expression)
5130 if (TIE->isTypeOperand()) {
5131 Out << "ti";
5132 mangleType(TIE->getTypeOperand(Context.getASTContext()));
5133 } else {
5134 Out << "te";
5135 mangleExpression(TIE->getExprOperand());
5137 break;
5140 case Expr::CXXDeleteExprClass: {
5141 NotPrimaryExpr();
5142 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5143 // <expression> ::= [gs] dl <expression> # [::] delete expr
5144 // ::= [gs] da <expression> # [::] delete [] expr
5145 if (DE->isGlobalDelete()) Out << "gs";
5146 Out << (DE->isArrayForm() ? "da" : "dl");
5147 mangleExpression(DE->getArgument());
5148 break;
5151 case Expr::UnaryOperatorClass: {
5152 NotPrimaryExpr();
5153 const UnaryOperator *UO = cast<UnaryOperator>(E);
5154 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5155 /*Arity=*/1);
5156 mangleExpression(UO->getSubExpr());
5157 break;
5160 case Expr::ArraySubscriptExprClass: {
5161 NotPrimaryExpr();
5162 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5164 // Array subscript is treated as a syntactically weird form of
5165 // binary operator.
5166 Out << "ix";
5167 mangleExpression(AE->getLHS());
5168 mangleExpression(AE->getRHS());
5169 break;
5172 case Expr::MatrixSubscriptExprClass: {
5173 NotPrimaryExpr();
5174 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5175 Out << "ixix";
5176 mangleExpression(ME->getBase());
5177 mangleExpression(ME->getRowIdx());
5178 mangleExpression(ME->getColumnIdx());
5179 break;
5182 case Expr::CompoundAssignOperatorClass: // fallthrough
5183 case Expr::BinaryOperatorClass: {
5184 NotPrimaryExpr();
5185 const BinaryOperator *BO = cast<BinaryOperator>(E);
5186 if (BO->getOpcode() == BO_PtrMemD)
5187 Out << "ds";
5188 else
5189 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5190 /*Arity=*/2);
5191 mangleExpression(BO->getLHS());
5192 mangleExpression(BO->getRHS());
5193 break;
5196 case Expr::CXXRewrittenBinaryOperatorClass: {
5197 NotPrimaryExpr();
5198 // The mangled form represents the original syntax.
5199 CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5200 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5201 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5202 /*Arity=*/2);
5203 mangleExpression(Decomposed.LHS);
5204 mangleExpression(Decomposed.RHS);
5205 break;
5208 case Expr::ConditionalOperatorClass: {
5209 NotPrimaryExpr();
5210 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5211 mangleOperatorName(OO_Conditional, /*Arity=*/3);
5212 mangleExpression(CO->getCond());
5213 mangleExpression(CO->getLHS(), Arity);
5214 mangleExpression(CO->getRHS(), Arity);
5215 break;
5218 case Expr::ImplicitCastExprClass: {
5219 ImplicitlyConvertedToType = E->getType();
5220 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5221 goto recurse;
5224 case Expr::ObjCBridgedCastExprClass: {
5225 NotPrimaryExpr();
5226 // Mangle ownership casts as a vendor extended operator __bridge,
5227 // __bridge_transfer, or __bridge_retain.
5228 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5229 Out << "v1U" << Kind.size() << Kind;
5230 mangleCastExpression(E, "cv");
5231 break;
5234 case Expr::CStyleCastExprClass:
5235 NotPrimaryExpr();
5236 mangleCastExpression(E, "cv");
5237 break;
5239 case Expr::CXXFunctionalCastExprClass: {
5240 NotPrimaryExpr();
5241 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5242 // FIXME: Add isImplicit to CXXConstructExpr.
5243 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5244 if (CCE->getParenOrBraceRange().isInvalid())
5245 Sub = CCE->getArg(0)->IgnoreImplicit();
5246 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5247 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5248 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5249 Out << "tl";
5250 mangleType(E->getType());
5251 mangleInitListElements(IL);
5252 Out << "E";
5253 } else {
5254 mangleCastExpression(E, "cv");
5256 break;
5259 case Expr::CXXStaticCastExprClass:
5260 NotPrimaryExpr();
5261 mangleCastExpression(E, "sc");
5262 break;
5263 case Expr::CXXDynamicCastExprClass:
5264 NotPrimaryExpr();
5265 mangleCastExpression(E, "dc");
5266 break;
5267 case Expr::CXXReinterpretCastExprClass:
5268 NotPrimaryExpr();
5269 mangleCastExpression(E, "rc");
5270 break;
5271 case Expr::CXXConstCastExprClass:
5272 NotPrimaryExpr();
5273 mangleCastExpression(E, "cc");
5274 break;
5275 case Expr::CXXAddrspaceCastExprClass:
5276 NotPrimaryExpr();
5277 mangleCastExpression(E, "ac");
5278 break;
5280 case Expr::CXXOperatorCallExprClass: {
5281 NotPrimaryExpr();
5282 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5283 unsigned NumArgs = CE->getNumArgs();
5284 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5285 // (the enclosing MemberExpr covers the syntactic portion).
5286 if (CE->getOperator() != OO_Arrow)
5287 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5288 // Mangle the arguments.
5289 for (unsigned i = 0; i != NumArgs; ++i)
5290 mangleExpression(CE->getArg(i));
5291 break;
5294 case Expr::ParenExprClass:
5295 E = cast<ParenExpr>(E)->getSubExpr();
5296 goto recurse;
5298 case Expr::ConceptSpecializationExprClass: {
5299 auto *CSE = cast<ConceptSpecializationExpr>(E);
5300 if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5301 // Clang 17 and before mangled concept-ids as if they resolved to an
5302 // entity, meaning that references to enclosing template arguments don't
5303 // work.
5304 Out << "L_Z";
5305 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5306 Out << 'E';
5307 break;
5309 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5310 NotPrimaryExpr();
5311 mangleUnresolvedName(
5312 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5313 CSE->getConceptNameInfo().getName(),
5314 CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5315 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5316 break;
5319 case Expr::RequiresExprClass: {
5320 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5321 auto *RE = cast<RequiresExpr>(E);
5322 // This is a primary-expression in the C++ grammar, but does not have an
5323 // <expr-primary> mangling (starting with 'L').
5324 NotPrimaryExpr();
5325 if (RE->getLParenLoc().isValid()) {
5326 Out << "rQ";
5327 FunctionTypeDepthState saved = FunctionTypeDepth.push();
5328 if (RE->getLocalParameters().empty()) {
5329 Out << 'v';
5330 } else {
5331 for (ParmVarDecl *Param : RE->getLocalParameters()) {
5332 mangleType(Context.getASTContext().getSignatureParameterType(
5333 Param->getType()));
5336 Out << '_';
5338 // The rest of the mangling is in the immediate scope of the parameters.
5339 FunctionTypeDepth.enterResultType();
5340 for (const concepts::Requirement *Req : RE->getRequirements())
5341 mangleRequirement(RE->getExprLoc(), Req);
5342 FunctionTypeDepth.pop(saved);
5343 Out << 'E';
5344 } else {
5345 Out << "rq";
5346 for (const concepts::Requirement *Req : RE->getRequirements())
5347 mangleRequirement(RE->getExprLoc(), Req);
5348 Out << 'E';
5350 break;
5353 case Expr::DeclRefExprClass:
5354 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5355 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5356 break;
5358 case Expr::SubstNonTypeTemplateParmPackExprClass:
5359 NotPrimaryExpr();
5360 // FIXME: not clear how to mangle this!
5361 // template <unsigned N...> class A {
5362 // template <class U...> void foo(U (&x)[N]...);
5363 // };
5364 Out << "_SUBSTPACK_";
5365 break;
5367 case Expr::FunctionParmPackExprClass: {
5368 NotPrimaryExpr();
5369 // FIXME: not clear how to mangle this!
5370 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5371 Out << "v110_SUBSTPACK";
5372 MangleDeclRefExpr(FPPE->getParameterPack());
5373 break;
5376 case Expr::DependentScopeDeclRefExprClass: {
5377 NotPrimaryExpr();
5378 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5379 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5380 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5381 Arity);
5382 break;
5385 case Expr::CXXBindTemporaryExprClass:
5386 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5387 goto recurse;
5389 case Expr::ExprWithCleanupsClass:
5390 E = cast<ExprWithCleanups>(E)->getSubExpr();
5391 goto recurse;
5393 case Expr::FloatingLiteralClass: {
5394 // <expr-primary>
5395 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5396 mangleFloatLiteral(FL->getType(), FL->getValue());
5397 break;
5400 case Expr::FixedPointLiteralClass:
5401 // Currently unimplemented -- might be <expr-primary> in future?
5402 mangleFixedPointLiteral();
5403 break;
5405 case Expr::CharacterLiteralClass:
5406 // <expr-primary>
5407 Out << 'L';
5408 mangleType(E->getType());
5409 Out << cast<CharacterLiteral>(E)->getValue();
5410 Out << 'E';
5411 break;
5413 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5414 case Expr::ObjCBoolLiteralExprClass:
5415 // <expr-primary>
5416 Out << "Lb";
5417 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5418 Out << 'E';
5419 break;
5421 case Expr::CXXBoolLiteralExprClass:
5422 // <expr-primary>
5423 Out << "Lb";
5424 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5425 Out << 'E';
5426 break;
5428 case Expr::IntegerLiteralClass: {
5429 // <expr-primary>
5430 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5431 if (E->getType()->isSignedIntegerType())
5432 Value.setIsSigned(true);
5433 mangleIntegerLiteral(E->getType(), Value);
5434 break;
5437 case Expr::ImaginaryLiteralClass: {
5438 // <expr-primary>
5439 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5440 // Mangle as if a complex literal.
5441 // Proposal from David Vandevoorde, 2010.06.30.
5442 Out << 'L';
5443 mangleType(E->getType());
5444 if (const FloatingLiteral *Imag =
5445 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5446 // Mangle a floating-point zero of the appropriate type.
5447 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5448 Out << '_';
5449 mangleFloat(Imag->getValue());
5450 } else {
5451 Out << "0_";
5452 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5453 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5454 Value.setIsSigned(true);
5455 mangleNumber(Value);
5457 Out << 'E';
5458 break;
5461 case Expr::StringLiteralClass: {
5462 // <expr-primary>
5463 // Revised proposal from David Vandervoorde, 2010.07.15.
5464 Out << 'L';
5465 assert(isa<ConstantArrayType>(E->getType()));
5466 mangleType(E->getType());
5467 Out << 'E';
5468 break;
5471 case Expr::GNUNullExprClass:
5472 // <expr-primary>
5473 // Mangle as if an integer literal 0.
5474 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5475 break;
5477 case Expr::CXXNullPtrLiteralExprClass: {
5478 // <expr-primary>
5479 Out << "LDnE";
5480 break;
5483 case Expr::LambdaExprClass: {
5484 // A lambda-expression can't appear in the signature of an
5485 // externally-visible declaration, so there's no standard mangling for
5486 // this, but mangling as a literal of the closure type seems reasonable.
5487 Out << "L";
5488 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5489 Out << "E";
5490 break;
5493 case Expr::PackExpansionExprClass:
5494 NotPrimaryExpr();
5495 Out << "sp";
5496 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5497 break;
5499 case Expr::SizeOfPackExprClass: {
5500 NotPrimaryExpr();
5501 auto *SPE = cast<SizeOfPackExpr>(E);
5502 if (SPE->isPartiallySubstituted()) {
5503 Out << "sP";
5504 for (const auto &A : SPE->getPartialArguments())
5505 mangleTemplateArg(A, false);
5506 Out << "E";
5507 break;
5510 Out << "sZ";
5511 const NamedDecl *Pack = SPE->getPack();
5512 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5513 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5514 else if (const NonTypeTemplateParmDecl *NTTP
5515 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5516 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5517 else if (const TemplateTemplateParmDecl *TempTP
5518 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5519 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5520 else
5521 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5522 break;
5525 case Expr::MaterializeTemporaryExprClass:
5526 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5527 goto recurse;
5529 case Expr::CXXFoldExprClass: {
5530 NotPrimaryExpr();
5531 auto *FE = cast<CXXFoldExpr>(E);
5532 if (FE->isLeftFold())
5533 Out << (FE->getInit() ? "fL" : "fl");
5534 else
5535 Out << (FE->getInit() ? "fR" : "fr");
5537 if (FE->getOperator() == BO_PtrMemD)
5538 Out << "ds";
5539 else
5540 mangleOperatorName(
5541 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5542 /*Arity=*/2);
5544 if (FE->getLHS())
5545 mangleExpression(FE->getLHS());
5546 if (FE->getRHS())
5547 mangleExpression(FE->getRHS());
5548 break;
5551 case Expr::CXXThisExprClass:
5552 NotPrimaryExpr();
5553 Out << "fpT";
5554 break;
5556 case Expr::CoawaitExprClass:
5557 // FIXME: Propose a non-vendor mangling.
5558 NotPrimaryExpr();
5559 Out << "v18co_await";
5560 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5561 break;
5563 case Expr::DependentCoawaitExprClass:
5564 // FIXME: Propose a non-vendor mangling.
5565 NotPrimaryExpr();
5566 Out << "v18co_await";
5567 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5568 break;
5570 case Expr::CoyieldExprClass:
5571 // FIXME: Propose a non-vendor mangling.
5572 NotPrimaryExpr();
5573 Out << "v18co_yield";
5574 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5575 break;
5576 case Expr::SYCLUniqueStableNameExprClass: {
5577 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5578 NotPrimaryExpr();
5580 Out << "u33__builtin_sycl_unique_stable_name";
5581 mangleType(USN->getTypeSourceInfo()->getType());
5583 Out << "E";
5584 break;
5588 if (AsTemplateArg && !IsPrimaryExpr)
5589 Out << 'E';
5592 /// Mangle an expression which refers to a parameter variable.
5594 /// <expression> ::= <function-param>
5595 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5596 /// <function-param> ::= fp <top-level CV-qualifiers>
5597 /// <parameter-2 non-negative number> _ # L == 0, I > 0
5598 /// <function-param> ::= fL <L-1 non-negative number>
5599 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
5600 /// <function-param> ::= fL <L-1 non-negative number>
5601 /// p <top-level CV-qualifiers>
5602 /// <I-1 non-negative number> _ # L > 0, I > 0
5604 /// L is the nesting depth of the parameter, defined as 1 if the
5605 /// parameter comes from the innermost function prototype scope
5606 /// enclosing the current context, 2 if from the next enclosing
5607 /// function prototype scope, and so on, with one special case: if
5608 /// we've processed the full parameter clause for the innermost
5609 /// function type, then L is one less. This definition conveniently
5610 /// makes it irrelevant whether a function's result type was written
5611 /// trailing or leading, but is otherwise overly complicated; the
5612 /// numbering was first designed without considering references to
5613 /// parameter in locations other than return types, and then the
5614 /// mangling had to be generalized without changing the existing
5615 /// manglings.
5617 /// I is the zero-based index of the parameter within its parameter
5618 /// declaration clause. Note that the original ABI document describes
5619 /// this using 1-based ordinals.
5620 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5621 unsigned parmDepth = parm->getFunctionScopeDepth();
5622 unsigned parmIndex = parm->getFunctionScopeIndex();
5624 // Compute 'L'.
5625 // parmDepth does not include the declaring function prototype.
5626 // FunctionTypeDepth does account for that.
5627 assert(parmDepth < FunctionTypeDepth.getDepth());
5628 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5629 if (FunctionTypeDepth.isInResultType())
5630 nestingDepth--;
5632 if (nestingDepth == 0) {
5633 Out << "fp";
5634 } else {
5635 Out << "fL" << (nestingDepth - 1) << 'p';
5638 // Top-level qualifiers. We don't have to worry about arrays here,
5639 // because parameters declared as arrays should already have been
5640 // transformed to have pointer type. FIXME: apparently these don't
5641 // get mangled if used as an rvalue of a known non-class type?
5642 assert(!parm->getType()->isArrayType()
5643 && "parameter's type is still an array type?");
5645 if (const DependentAddressSpaceType *DAST =
5646 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5647 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5648 } else {
5649 mangleQualifiers(parm->getType().getQualifiers());
5652 // Parameter index.
5653 if (parmIndex != 0) {
5654 Out << (parmIndex - 1);
5656 Out << '_';
5659 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5660 const CXXRecordDecl *InheritedFrom) {
5661 // <ctor-dtor-name> ::= C1 # complete object constructor
5662 // ::= C2 # base object constructor
5663 // ::= CI1 <type> # complete inheriting constructor
5664 // ::= CI2 <type> # base inheriting constructor
5666 // In addition, C5 is a comdat name with C1 and C2 in it.
5667 Out << 'C';
5668 if (InheritedFrom)
5669 Out << 'I';
5670 switch (T) {
5671 case Ctor_Complete:
5672 Out << '1';
5673 break;
5674 case Ctor_Base:
5675 Out << '2';
5676 break;
5677 case Ctor_Comdat:
5678 Out << '5';
5679 break;
5680 case Ctor_DefaultClosure:
5681 case Ctor_CopyingClosure:
5682 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5684 if (InheritedFrom)
5685 mangleName(InheritedFrom);
5688 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5689 // <ctor-dtor-name> ::= D0 # deleting destructor
5690 // ::= D1 # complete object destructor
5691 // ::= D2 # base object destructor
5693 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5694 switch (T) {
5695 case Dtor_Deleting:
5696 Out << "D0";
5697 break;
5698 case Dtor_Complete:
5699 Out << "D1";
5700 break;
5701 case Dtor_Base:
5702 Out << "D2";
5703 break;
5704 case Dtor_Comdat:
5705 Out << "D5";
5706 break;
5710 // Helper to provide ancillary information on a template used to mangle its
5711 // arguments.
5712 struct CXXNameMangler::TemplateArgManglingInfo {
5713 const CXXNameMangler &Mangler;
5714 TemplateDecl *ResolvedTemplate = nullptr;
5715 bool SeenPackExpansionIntoNonPack = false;
5716 const NamedDecl *UnresolvedExpandedPack = nullptr;
5718 TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
5719 : Mangler(Mangler) {
5720 if (TemplateDecl *TD = TN.getAsTemplateDecl())
5721 ResolvedTemplate = TD;
5724 /// Information about how to mangle a template argument.
5725 struct Info {
5726 /// Do we need to mangle the template argument with an exactly correct type?
5727 bool NeedExactType;
5728 /// If we need to prefix the mangling with a mangling of the template
5729 /// parameter, the corresponding parameter.
5730 const NamedDecl *TemplateParameterToMangle;
5733 /// Determine whether the resolved template might be overloaded on its
5734 /// template parameter list. If so, the mangling needs to include enough
5735 /// information to reconstruct the template parameter list.
5736 bool isOverloadable() {
5737 // Function templates are generally overloadable. As a special case, a
5738 // member function template of a generic lambda is not overloadable.
5739 if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {
5740 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5741 if (!RD || !RD->isGenericLambda())
5742 return true;
5745 // All other templates are not overloadable. Partial specializations would
5746 // be, but we never mangle them.
5747 return false;
5750 /// Determine whether we need to prefix this <template-arg> mangling with a
5751 /// <template-param-decl>. This happens if the natural template parameter for
5752 /// the argument mangling is not the same as the actual template parameter.
5753 bool needToMangleTemplateParam(const NamedDecl *Param,
5754 const TemplateArgument &Arg) {
5755 // For a template type parameter, the natural parameter is 'typename T'.
5756 // The actual parameter might be constrained.
5757 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5758 return TTP->hasTypeConstraint();
5760 if (Arg.getKind() == TemplateArgument::Pack) {
5761 // For an empty pack, the natural parameter is `typename...`.
5762 if (Arg.pack_size() == 0)
5763 return true;
5765 // For any other pack, we use the first argument to determine the natural
5766 // template parameter.
5767 return needToMangleTemplateParam(Param, *Arg.pack_begin());
5770 // For a non-type template parameter, the natural parameter is `T V` (for a
5771 // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
5772 // type of the argument, which we require to exactly match. If the actual
5773 // parameter has a deduced or instantiation-dependent type, it is not
5774 // equivalent to the natural parameter.
5775 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
5776 return NTTP->getType()->isInstantiationDependentType() ||
5777 NTTP->getType()->getContainedDeducedType();
5779 // For a template template parameter, the template-head might differ from
5780 // that of the template.
5781 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5782 TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
5783 const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl();
5784 if (!ArgTemplate)
5785 return true;
5787 // Mangle the template parameter list of the parameter and argument to see
5788 // if they are the same. We can't use Profile for this, because it can't
5789 // model the depth difference between parameter and argument and might not
5790 // necessarily have the same definition of "identical" that we use here --
5791 // that is, same mangling.
5792 auto MangleTemplateParamListToString =
5793 [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
5794 unsigned DepthOffset) {
5795 llvm::raw_svector_ostream Stream(Buffer);
5796 CXXNameMangler(Mangler.Context, Stream,
5797 WithTemplateDepthOffset{DepthOffset})
5798 .mangleTemplateParameterList(Params);
5800 llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
5801 MangleTemplateParamListToString(ParamTemplateHead,
5802 TTP->getTemplateParameters(), 0);
5803 // Add the depth of the parameter's template parameter list to all
5804 // parameters appearing in the argument to make the indexes line up
5805 // properly.
5806 MangleTemplateParamListToString(ArgTemplateHead,
5807 ArgTemplate->getTemplateParameters(),
5808 TTP->getTemplateParameters()->getDepth());
5809 return ParamTemplateHead != ArgTemplateHead;
5812 /// Determine information about how this template argument should be mangled.
5813 /// This should be called exactly once for each parameter / argument pair, in
5814 /// order.
5815 Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {
5816 // We need correct types when the template-name is unresolved or when it
5817 // names a template that is able to be overloaded.
5818 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5819 return {true, nullptr};
5821 // Move to the next parameter.
5822 const NamedDecl *Param = UnresolvedExpandedPack;
5823 if (!Param) {
5824 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
5825 "no parameter for argument");
5826 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5828 // If we reach a parameter pack whose argument isn't in pack form, that
5829 // means Sema couldn't or didn't figure out which arguments belonged to
5830 // it, because it contains a pack expansion or because Sema bailed out of
5831 // computing parameter / argument correspondence before this point. Track
5832 // the pack as the corresponding parameter for all further template
5833 // arguments until we hit a pack expansion, at which point we don't know
5834 // the correspondence between parameters and arguments at all.
5835 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5836 UnresolvedExpandedPack = Param;
5840 // If we encounter a pack argument that is expanded into a non-pack
5841 // parameter, we can no longer track parameter / argument correspondence,
5842 // and need to use exact types from this point onwards.
5843 if (Arg.isPackExpansion() &&
5844 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5845 SeenPackExpansionIntoNonPack = true;
5846 return {true, nullptr};
5849 // We need exact types for arguments of a template that might be overloaded
5850 // on template parameter type.
5851 if (isOverloadable())
5852 return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
5854 // Otherwise, we only need a correct type if the parameter has a deduced
5855 // type.
5857 // Note: for an expanded parameter pack, getType() returns the type prior
5858 // to expansion. We could ask for the expanded type with getExpansionType(),
5859 // but it doesn't matter because substitution and expansion don't affect
5860 // whether a deduced type appears in the type.
5861 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
5862 bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
5863 return {NeedExactType, nullptr};
5866 /// Determine if we should mangle a requires-clause after the template
5867 /// argument list. If so, returns the expression to mangle.
5868 const Expr *getTrailingRequiresClauseToMangle() {
5869 if (!isOverloadable())
5870 return nullptr;
5871 return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
5875 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5876 const TemplateArgumentLoc *TemplateArgs,
5877 unsigned NumTemplateArgs) {
5878 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5879 Out << 'I';
5880 TemplateArgManglingInfo Info(*this, TN);
5881 for (unsigned i = 0; i != NumTemplateArgs; ++i) {
5882 mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
5884 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5885 Out << 'E';
5888 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5889 const TemplateArgumentList &AL) {
5890 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5891 Out << 'I';
5892 TemplateArgManglingInfo Info(*this, TN);
5893 for (unsigned i = 0, e = AL.size(); i != e; ++i) {
5894 mangleTemplateArg(Info, i, AL[i]);
5896 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5897 Out << 'E';
5900 void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5901 ArrayRef<TemplateArgument> Args) {
5902 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5903 Out << 'I';
5904 TemplateArgManglingInfo Info(*this, TN);
5905 for (unsigned i = 0; i != Args.size(); ++i) {
5906 mangleTemplateArg(Info, i, Args[i]);
5908 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5909 Out << 'E';
5912 void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
5913 unsigned Index, TemplateArgument A) {
5914 TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);
5916 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5917 if (ArgInfo.TemplateParameterToMangle &&
5918 !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5919 // The template parameter is mangled if the mangling would otherwise be
5920 // ambiguous.
5922 // <template-arg> ::= <template-param-decl> <template-arg>
5924 // Clang 17 and before did not do this.
5925 mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);
5928 mangleTemplateArg(A, ArgInfo.NeedExactType);
5931 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
5932 // <template-arg> ::= <type> # type or template
5933 // ::= X <expression> E # expression
5934 // ::= <expr-primary> # simple expressions
5935 // ::= J <template-arg>* E # argument pack
5936 if (!A.isInstantiationDependent() || A.isDependent())
5937 A = Context.getASTContext().getCanonicalTemplateArgument(A);
5939 switch (A.getKind()) {
5940 case TemplateArgument::Null:
5941 llvm_unreachable("Cannot mangle NULL template argument");
5943 case TemplateArgument::Type:
5944 mangleType(A.getAsType());
5945 break;
5946 case TemplateArgument::Template:
5947 // This is mangled as <type>.
5948 mangleType(A.getAsTemplate());
5949 break;
5950 case TemplateArgument::TemplateExpansion:
5951 // <type> ::= Dp <type> # pack expansion (C++0x)
5952 Out << "Dp";
5953 mangleType(A.getAsTemplateOrTemplatePattern());
5954 break;
5955 case TemplateArgument::Expression:
5956 mangleTemplateArgExpr(A.getAsExpr());
5957 break;
5958 case TemplateArgument::Integral:
5959 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
5960 break;
5961 case TemplateArgument::Declaration: {
5962 // <expr-primary> ::= L <mangled-name> E # external name
5963 ValueDecl *D = A.getAsDecl();
5965 // Template parameter objects are modeled by reproducing a source form
5966 // produced as if by aggregate initialization.
5967 if (A.getParamTypeForDecl()->isRecordType()) {
5968 auto *TPO = cast<TemplateParamObjectDecl>(D);
5969 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
5970 TPO->getValue(), /*TopLevel=*/true,
5971 NeedExactType);
5972 break;
5975 ASTContext &Ctx = Context.getASTContext();
5976 APValue Value;
5977 if (D->isCXXInstanceMember())
5978 // Simple pointer-to-member with no conversion.
5979 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
5980 else if (D->getType()->isArrayType() &&
5981 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
5982 A.getParamTypeForDecl()) &&
5983 !isCompatibleWith(LangOptions::ClangABI::Ver11))
5984 // Build a value corresponding to this implicit array-to-pointer decay.
5985 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5986 {APValue::LValuePathEntry::ArrayIndex(0)},
5987 /*OnePastTheEnd=*/false);
5988 else
5989 // Regular pointer or reference to a declaration.
5990 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
5991 ArrayRef<APValue::LValuePathEntry>(),
5992 /*OnePastTheEnd=*/false);
5993 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
5994 NeedExactType);
5995 break;
5997 case TemplateArgument::NullPtr: {
5998 mangleNullPointer(A.getNullPtrType());
5999 break;
6001 case TemplateArgument::Pack: {
6002 // <template-arg> ::= J <template-arg>* E
6003 Out << 'J';
6004 for (const auto &P : A.pack_elements())
6005 mangleTemplateArg(P, NeedExactType);
6006 Out << 'E';
6011 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6012 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6013 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6014 return;
6017 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6018 // correctly in cases where the template argument was
6019 // constructed from an expression rather than an already-evaluated
6020 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6021 // 'Li0E'.
6023 // We did special-case DeclRefExpr to attempt to DTRT for that one
6024 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6025 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6026 // the proper 'Xfp_E'.
6027 E = E->IgnoreParenImpCasts();
6028 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6029 const ValueDecl *D = DRE->getDecl();
6030 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
6031 Out << 'L';
6032 mangle(D);
6033 Out << 'E';
6034 return;
6037 Out << 'X';
6038 mangleExpression(E);
6039 Out << 'E';
6042 /// Determine whether a given value is equivalent to zero-initialization for
6043 /// the purpose of discarding a trailing portion of a 'tl' mangling.
6045 /// Note that this is not in general equivalent to determining whether the
6046 /// value has an all-zeroes bit pattern.
6047 static bool isZeroInitialized(QualType T, const APValue &V) {
6048 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6049 // pathological cases due to using this, but it's a little awkward
6050 // to do this in linear time in general.
6051 switch (V.getKind()) {
6052 case APValue::None:
6053 case APValue::Indeterminate:
6054 case APValue::AddrLabelDiff:
6055 return false;
6057 case APValue::Struct: {
6058 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6059 assert(RD && "unexpected type for record value");
6060 unsigned I = 0;
6061 for (const CXXBaseSpecifier &BS : RD->bases()) {
6062 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6063 return false;
6064 ++I;
6066 I = 0;
6067 for (const FieldDecl *FD : RD->fields()) {
6068 if (!FD->isUnnamedBitfield() &&
6069 !isZeroInitialized(FD->getType(), V.getStructField(I)))
6070 return false;
6071 ++I;
6073 return true;
6076 case APValue::Union: {
6077 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6078 assert(RD && "unexpected type for union value");
6079 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6080 for (const FieldDecl *FD : RD->fields()) {
6081 if (!FD->isUnnamedBitfield())
6082 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
6083 isZeroInitialized(FD->getType(), V.getUnionValue());
6085 // If there are no fields (other than unnamed bitfields), the value is
6086 // necessarily zero-initialized.
6087 return true;
6090 case APValue::Array: {
6091 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6092 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6093 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
6094 return false;
6095 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
6098 case APValue::Vector: {
6099 const VectorType *VT = T->castAs<VectorType>();
6100 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6101 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
6102 return false;
6103 return true;
6106 case APValue::Int:
6107 return !V.getInt();
6109 case APValue::Float:
6110 return V.getFloat().isPosZero();
6112 case APValue::FixedPoint:
6113 return !V.getFixedPoint().getValue();
6115 case APValue::ComplexFloat:
6116 return V.getComplexFloatReal().isPosZero() &&
6117 V.getComplexFloatImag().isPosZero();
6119 case APValue::ComplexInt:
6120 return !V.getComplexIntReal() && !V.getComplexIntImag();
6122 case APValue::LValue:
6123 return V.isNullPointer();
6125 case APValue::MemberPointer:
6126 return !V.getMemberPointerDecl();
6129 llvm_unreachable("Unhandled APValue::ValueKind enum");
6132 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6133 QualType T = LV.getLValueBase().getType();
6134 for (APValue::LValuePathEntry E : LV.getLValuePath()) {
6135 if (const ArrayType *AT = Ctx.getAsArrayType(T))
6136 T = AT->getElementType();
6137 else if (const FieldDecl *FD =
6138 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
6139 T = FD->getType();
6140 else
6141 T = Ctx.getRecordType(
6142 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6144 return T;
6147 static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
6148 DiagnosticsEngine &Diags,
6149 const FieldDecl *FD) {
6150 // According to:
6151 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6152 // For the purposes of mangling, the name of an anonymous union is considered
6153 // to be the name of the first named data member found by a pre-order,
6154 // depth-first, declaration-order walk of the data members of the anonymous
6155 // union.
6157 if (FD->getIdentifier())
6158 return FD->getIdentifier();
6160 // The only cases where the identifer of a FieldDecl would be blank is if the
6161 // field represents an anonymous record type or if it is an unnamed bitfield.
6162 // There is no type to descend into in the case of a bitfield, so we can just
6163 // return nullptr in that case.
6164 if (FD->isBitField())
6165 return nullptr;
6166 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6168 // Consider only the fields in declaration order, searched depth-first. We
6169 // don't care about the active member of the union, as all we are doing is
6170 // looking for a valid name. We also don't check bases, due to guidance from
6171 // the Itanium ABI folks.
6172 for (const FieldDecl *RDField : RD->fields()) {
6173 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
6174 return II;
6177 // According to the Itanium ABI: If there is no such data member (i.e., if all
6178 // of the data members in the union are unnamed), then there is no way for a
6179 // program to refer to the anonymous union, and there is therefore no need to
6180 // mangle its name. However, we should diagnose this anyway.
6181 unsigned DiagID = Diags.getCustomDiagID(
6182 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
6183 Diags.Report(UnionLoc, DiagID);
6185 return nullptr;
6188 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6189 bool TopLevel,
6190 bool NeedExactType) {
6191 // Ignore all top-level cv-qualifiers, to match GCC.
6192 Qualifiers Quals;
6193 T = getASTContext().getUnqualifiedArrayType(T, Quals);
6195 // A top-level expression that's not a primary expression is wrapped in X...E.
6196 bool IsPrimaryExpr = true;
6197 auto NotPrimaryExpr = [&] {
6198 if (TopLevel && IsPrimaryExpr)
6199 Out << 'X';
6200 IsPrimaryExpr = false;
6203 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6204 switch (V.getKind()) {
6205 case APValue::None:
6206 case APValue::Indeterminate:
6207 Out << 'L';
6208 mangleType(T);
6209 Out << 'E';
6210 break;
6212 case APValue::AddrLabelDiff:
6213 llvm_unreachable("unexpected value kind in template argument");
6215 case APValue::Struct: {
6216 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6217 assert(RD && "unexpected type for record value");
6219 // Drop trailing zero-initialized elements.
6220 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
6221 while (
6222 !Fields.empty() &&
6223 (Fields.back()->isUnnamedBitfield() ||
6224 isZeroInitialized(Fields.back()->getType(),
6225 V.getStructField(Fields.back()->getFieldIndex())))) {
6226 Fields.pop_back();
6228 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
6229 if (Fields.empty()) {
6230 while (!Bases.empty() &&
6231 isZeroInitialized(Bases.back().getType(),
6232 V.getStructBase(Bases.size() - 1)))
6233 Bases = Bases.drop_back();
6236 // <expression> ::= tl <type> <braced-expression>* E
6237 NotPrimaryExpr();
6238 Out << "tl";
6239 mangleType(T);
6240 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6241 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
6242 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
6243 if (Fields[I]->isUnnamedBitfield())
6244 continue;
6245 mangleValueInTemplateArg(Fields[I]->getType(),
6246 V.getStructField(Fields[I]->getFieldIndex()),
6247 false);
6249 Out << 'E';
6250 break;
6253 case APValue::Union: {
6254 assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6255 const FieldDecl *FD = V.getUnionField();
6257 if (!FD) {
6258 Out << 'L';
6259 mangleType(T);
6260 Out << 'E';
6261 break;
6264 // <braced-expression> ::= di <field source-name> <braced-expression>
6265 NotPrimaryExpr();
6266 Out << "tl";
6267 mangleType(T);
6268 if (!isZeroInitialized(T, V)) {
6269 Out << "di";
6270 IdentifierInfo *II = (getUnionInitName(
6271 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
6272 if (II)
6273 mangleSourceName(II);
6274 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6276 Out << 'E';
6277 break;
6280 case APValue::Array: {
6281 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6283 NotPrimaryExpr();
6284 Out << "tl";
6285 mangleType(T);
6287 // Drop trailing zero-initialized elements.
6288 unsigned N = V.getArraySize();
6289 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
6290 N = V.getArrayInitializedElts();
6291 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
6292 --N;
6295 for (unsigned I = 0; I != N; ++I) {
6296 const APValue &Elem = I < V.getArrayInitializedElts()
6297 ? V.getArrayInitializedElt(I)
6298 : V.getArrayFiller();
6299 mangleValueInTemplateArg(ElemT, Elem, false);
6301 Out << 'E';
6302 break;
6305 case APValue::Vector: {
6306 const VectorType *VT = T->castAs<VectorType>();
6308 NotPrimaryExpr();
6309 Out << "tl";
6310 mangleType(T);
6311 unsigned N = V.getVectorLength();
6312 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6313 --N;
6314 for (unsigned I = 0; I != N; ++I)
6315 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6316 Out << 'E';
6317 break;
6320 case APValue::Int:
6321 mangleIntegerLiteral(T, V.getInt());
6322 break;
6324 case APValue::Float:
6325 mangleFloatLiteral(T, V.getFloat());
6326 break;
6328 case APValue::FixedPoint:
6329 mangleFixedPointLiteral();
6330 break;
6332 case APValue::ComplexFloat: {
6333 const ComplexType *CT = T->castAs<ComplexType>();
6334 NotPrimaryExpr();
6335 Out << "tl";
6336 mangleType(T);
6337 if (!V.getComplexFloatReal().isPosZero() ||
6338 !V.getComplexFloatImag().isPosZero())
6339 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
6340 if (!V.getComplexFloatImag().isPosZero())
6341 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
6342 Out << 'E';
6343 break;
6346 case APValue::ComplexInt: {
6347 const ComplexType *CT = T->castAs<ComplexType>();
6348 NotPrimaryExpr();
6349 Out << "tl";
6350 mangleType(T);
6351 if (V.getComplexIntReal().getBoolValue() ||
6352 V.getComplexIntImag().getBoolValue())
6353 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
6354 if (V.getComplexIntImag().getBoolValue())
6355 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
6356 Out << 'E';
6357 break;
6360 case APValue::LValue: {
6361 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6362 assert((T->isPointerType() || T->isReferenceType()) &&
6363 "unexpected type for LValue template arg");
6365 if (V.isNullPointer()) {
6366 mangleNullPointer(T);
6367 break;
6370 APValue::LValueBase B = V.getLValueBase();
6371 if (!B) {
6372 // Non-standard mangling for integer cast to a pointer; this can only
6373 // occur as an extension.
6374 CharUnits Offset = V.getLValueOffset();
6375 if (Offset.isZero()) {
6376 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6377 // a cast, because L <type> 0 E means something else.
6378 NotPrimaryExpr();
6379 Out << "rc";
6380 mangleType(T);
6381 Out << "Li0E";
6382 if (TopLevel)
6383 Out << 'E';
6384 } else {
6385 Out << "L";
6386 mangleType(T);
6387 Out << Offset.getQuantity() << 'E';
6389 break;
6392 ASTContext &Ctx = Context.getASTContext();
6394 enum { Base, Offset, Path } Kind;
6395 if (!V.hasLValuePath()) {
6396 // Mangle as (T*)((char*)&base + N).
6397 if (T->isReferenceType()) {
6398 NotPrimaryExpr();
6399 Out << "decvP";
6400 mangleType(T->getPointeeType());
6401 } else {
6402 NotPrimaryExpr();
6403 Out << "cv";
6404 mangleType(T);
6406 Out << "plcvPcad";
6407 Kind = Offset;
6408 } else {
6409 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
6410 NotPrimaryExpr();
6411 // A final conversion to the template parameter's type is usually
6412 // folded into the 'so' mangling, but we can't do that for 'void*'
6413 // parameters without introducing collisions.
6414 if (NeedExactType && T->isVoidPointerType()) {
6415 Out << "cv";
6416 mangleType(T);
6418 if (T->isPointerType())
6419 Out << "ad";
6420 Out << "so";
6421 mangleType(T->isVoidPointerType()
6422 ? getLValueType(Ctx, V).getUnqualifiedType()
6423 : T->getPointeeType());
6424 Kind = Path;
6425 } else {
6426 if (NeedExactType &&
6427 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
6428 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6429 NotPrimaryExpr();
6430 Out << "cv";
6431 mangleType(T);
6433 if (T->isPointerType()) {
6434 NotPrimaryExpr();
6435 Out << "ad";
6437 Kind = Base;
6441 QualType TypeSoFar = B.getType();
6442 if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6443 Out << 'L';
6444 mangle(VD);
6445 Out << 'E';
6446 } else if (auto *E = B.dyn_cast<const Expr*>()) {
6447 NotPrimaryExpr();
6448 mangleExpression(E);
6449 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6450 NotPrimaryExpr();
6451 Out << "ti";
6452 mangleType(QualType(TI.getType(), 0));
6453 } else {
6454 // We should never see dynamic allocations here.
6455 llvm_unreachable("unexpected lvalue base kind in template argument");
6458 switch (Kind) {
6459 case Base:
6460 break;
6462 case Offset:
6463 Out << 'L';
6464 mangleType(Ctx.getPointerDiffType());
6465 mangleNumber(V.getLValueOffset().getQuantity());
6466 Out << 'E';
6467 break;
6469 case Path:
6470 // <expression> ::= so <referent type> <expr> [<offset number>]
6471 // <union-selector>* [p] E
6472 if (!V.getLValueOffset().isZero())
6473 mangleNumber(V.getLValueOffset().getQuantity());
6475 // We model a past-the-end array pointer as array indexing with index N,
6476 // not with the "past the end" flag. Compensate for that.
6477 bool OnePastTheEnd = V.isLValueOnePastTheEnd();
6479 for (APValue::LValuePathEntry E : V.getLValuePath()) {
6480 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
6481 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6482 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
6483 TypeSoFar = AT->getElementType();
6484 } else {
6485 const Decl *D = E.getAsBaseOrMember().getPointer();
6486 if (auto *FD = dyn_cast<FieldDecl>(D)) {
6487 // <union-selector> ::= _ <number>
6488 if (FD->getParent()->isUnion()) {
6489 Out << '_';
6490 if (FD->getFieldIndex())
6491 Out << (FD->getFieldIndex() - 1);
6493 TypeSoFar = FD->getType();
6494 } else {
6495 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
6500 if (OnePastTheEnd)
6501 Out << 'p';
6502 Out << 'E';
6503 break;
6506 break;
6509 case APValue::MemberPointer:
6510 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6511 if (!V.getMemberPointerDecl()) {
6512 mangleNullPointer(T);
6513 break;
6516 ASTContext &Ctx = Context.getASTContext();
6518 NotPrimaryExpr();
6519 if (!V.getMemberPointerPath().empty()) {
6520 Out << "mc";
6521 mangleType(T);
6522 } else if (NeedExactType &&
6523 !Ctx.hasSameType(
6524 T->castAs<MemberPointerType>()->getPointeeType(),
6525 V.getMemberPointerDecl()->getType()) &&
6526 !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6527 Out << "cv";
6528 mangleType(T);
6530 Out << "adL";
6531 mangle(V.getMemberPointerDecl());
6532 Out << 'E';
6533 if (!V.getMemberPointerPath().empty()) {
6534 CharUnits Offset =
6535 Context.getASTContext().getMemberPointerPathAdjustment(V);
6536 if (!Offset.isZero())
6537 mangleNumber(Offset.getQuantity());
6538 Out << 'E';
6540 break;
6543 if (TopLevel && !IsPrimaryExpr)
6544 Out << 'E';
6547 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
6548 // <template-param> ::= T_ # first template parameter
6549 // ::= T <parameter-2 non-negative number> _
6550 // ::= TL <L-1 non-negative number> __
6551 // ::= TL <L-1 non-negative number> _
6552 // <parameter-2 non-negative number> _
6554 // The latter two manglings are from a proposal here:
6555 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6556 Out << 'T';
6557 Depth += TemplateDepthOffset;
6558 if (Depth != 0)
6559 Out << 'L' << (Depth - 1) << '_';
6560 if (Index != 0)
6561 Out << (Index - 1);
6562 Out << '_';
6565 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
6566 if (SeqID == 0) {
6567 // Nothing.
6568 } else if (SeqID == 1) {
6569 Out << '0';
6570 } else {
6571 SeqID--;
6573 // <seq-id> is encoded in base-36, using digits and upper case letters.
6574 char Buffer[7]; // log(2**32) / log(36) ~= 7
6575 MutableArrayRef<char> BufferRef(Buffer);
6576 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
6578 for (; SeqID != 0; SeqID /= 36) {
6579 unsigned C = SeqID % 36;
6580 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
6583 Out.write(I.base(), I - BufferRef.rbegin());
6585 Out << '_';
6588 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
6589 bool result = mangleSubstitution(tname);
6590 assert(result && "no existing substitution for template name");
6591 (void) result;
6594 // <substitution> ::= S <seq-id> _
6595 // ::= S_
6596 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6597 // Try one of the standard substitutions first.
6598 if (mangleStandardSubstitution(ND))
6599 return true;
6601 ND = cast<NamedDecl>(ND->getCanonicalDecl());
6602 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
6605 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
6606 assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
6607 "mangleSubstitution(NestedNameSpecifier *) is only used for "
6608 "identifier nested name specifiers.");
6609 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
6610 return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
6613 /// Determine whether the given type has any qualifiers that are relevant for
6614 /// substitutions.
6615 static bool hasMangledSubstitutionQualifiers(QualType T) {
6616 Qualifiers Qs = T.getQualifiers();
6617 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
6620 bool CXXNameMangler::mangleSubstitution(QualType T) {
6621 if (!hasMangledSubstitutionQualifiers(T)) {
6622 if (const RecordType *RT = T->getAs<RecordType>())
6623 return mangleSubstitution(RT->getDecl());
6626 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6628 return mangleSubstitution(TypePtr);
6631 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
6632 if (TemplateDecl *TD = Template.getAsTemplateDecl())
6633 return mangleSubstitution(TD);
6635 Template = Context.getASTContext().getCanonicalTemplateName(Template);
6636 return mangleSubstitution(
6637 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6640 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
6641 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
6642 if (I == Substitutions.end())
6643 return false;
6645 unsigned SeqID = I->second;
6646 Out << 'S';
6647 mangleSeqID(SeqID);
6649 return true;
6652 /// Returns whether S is a template specialization of std::Name with a single
6653 /// argument of type A.
6654 bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
6655 QualType A) {
6656 if (S.isNull())
6657 return false;
6659 const RecordType *RT = S->getAs<RecordType>();
6660 if (!RT)
6661 return false;
6663 const ClassTemplateSpecializationDecl *SD =
6664 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6665 if (!SD || !SD->getIdentifier()->isStr(Name))
6666 return false;
6668 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6669 return false;
6671 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6672 if (TemplateArgs.size() != 1)
6673 return false;
6675 if (TemplateArgs[0].getAsType() != A)
6676 return false;
6678 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6679 return false;
6681 return true;
6684 /// Returns whether SD is a template specialization std::Name<char,
6685 /// std::char_traits<char> [, std::allocator<char>]>
6686 /// HasAllocator controls whether the 3rd template argument is needed.
6687 bool CXXNameMangler::isStdCharSpecialization(
6688 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
6689 bool HasAllocator) {
6690 if (!SD->getIdentifier()->isStr(Name))
6691 return false;
6693 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6694 if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
6695 return false;
6697 QualType A = TemplateArgs[0].getAsType();
6698 if (A.isNull())
6699 return false;
6700 // Plain 'char' is named Char_S or Char_U depending on the target ABI.
6701 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
6702 !A->isSpecificBuiltinType(BuiltinType::Char_U))
6703 return false;
6705 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
6706 return false;
6708 if (HasAllocator &&
6709 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
6710 return false;
6712 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6713 return false;
6715 return true;
6718 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
6719 // <substitution> ::= St # ::std::
6720 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
6721 if (isStd(NS)) {
6722 Out << "St";
6723 return true;
6725 return false;
6728 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
6729 if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
6730 return false;
6732 if (TD->getOwningModuleForLinkage())
6733 return false;
6735 // <substitution> ::= Sa # ::std::allocator
6736 if (TD->getIdentifier()->isStr("allocator")) {
6737 Out << "Sa";
6738 return true;
6741 // <<substitution> ::= Sb # ::std::basic_string
6742 if (TD->getIdentifier()->isStr("basic_string")) {
6743 Out << "Sb";
6744 return true;
6746 return false;
6749 if (const ClassTemplateSpecializationDecl *SD =
6750 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
6751 if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6752 return false;
6754 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6755 return false;
6757 // <substitution> ::= Ss # ::std::basic_string<char,
6758 // ::std::char_traits<char>,
6759 // ::std::allocator<char> >
6760 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
6761 Out << "Ss";
6762 return true;
6765 // <substitution> ::= Si # ::std::basic_istream<char,
6766 // ::std::char_traits<char> >
6767 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
6768 Out << "Si";
6769 return true;
6772 // <substitution> ::= So # ::std::basic_ostream<char,
6773 // ::std::char_traits<char> >
6774 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
6775 Out << "So";
6776 return true;
6779 // <substitution> ::= Sd # ::std::basic_iostream<char,
6780 // ::std::char_traits<char> >
6781 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
6782 Out << "Sd";
6783 return true;
6785 return false;
6788 return false;
6791 void CXXNameMangler::addSubstitution(QualType T) {
6792 if (!hasMangledSubstitutionQualifiers(T)) {
6793 if (const RecordType *RT = T->getAs<RecordType>()) {
6794 addSubstitution(RT->getDecl());
6795 return;
6799 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6800 addSubstitution(TypePtr);
6803 void CXXNameMangler::addSubstitution(TemplateName Template) {
6804 if (TemplateDecl *TD = Template.getAsTemplateDecl())
6805 return addSubstitution(TD);
6807 Template = Context.getASTContext().getCanonicalTemplateName(Template);
6808 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6811 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
6812 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
6813 Substitutions[Ptr] = SeqID++;
6816 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
6817 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
6818 if (Other->SeqID > SeqID) {
6819 Substitutions.swap(Other->Substitutions);
6820 SeqID = Other->SeqID;
6824 CXXNameMangler::AbiTagList
6825 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
6826 // When derived abi tags are disabled there is no need to make any list.
6827 if (DisableDerivedAbiTags)
6828 return AbiTagList();
6830 llvm::raw_null_ostream NullOutStream;
6831 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
6832 TrackReturnTypeTags.disableDerivedAbiTags();
6834 const FunctionProtoType *Proto =
6835 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
6836 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
6837 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
6838 TrackReturnTypeTags.mangleType(Proto->getReturnType());
6839 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
6840 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
6842 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6845 CXXNameMangler::AbiTagList
6846 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
6847 // When derived abi tags are disabled there is no need to make any list.
6848 if (DisableDerivedAbiTags)
6849 return AbiTagList();
6851 llvm::raw_null_ostream NullOutStream;
6852 CXXNameMangler TrackVariableType(*this, NullOutStream);
6853 TrackVariableType.disableDerivedAbiTags();
6855 TrackVariableType.mangleType(VD->getType());
6857 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6860 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
6861 const VarDecl *VD) {
6862 llvm::raw_null_ostream NullOutStream;
6863 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
6864 TrackAbiTags.mangle(VD);
6865 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
6870 /// Mangles the name of the declaration D and emits that name to the given
6871 /// output stream.
6873 /// If the declaration D requires a mangled name, this routine will emit that
6874 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
6875 /// and this routine will return false. In this case, the caller should just
6876 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
6877 /// name.
6878 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
6879 raw_ostream &Out) {
6880 const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
6881 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
6882 "Invalid mangleName() call, argument is not a variable or function!");
6884 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
6885 getASTContext().getSourceManager(),
6886 "Mangling declaration");
6888 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
6889 auto Type = GD.getCtorType();
6890 CXXNameMangler Mangler(*this, Out, CD, Type);
6891 return Mangler.mangle(GlobalDecl(CD, Type));
6894 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
6895 auto Type = GD.getDtorType();
6896 CXXNameMangler Mangler(*this, Out, DD, Type);
6897 return Mangler.mangle(GlobalDecl(DD, Type));
6900 CXXNameMangler Mangler(*this, Out, D);
6901 Mangler.mangle(GD);
6904 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
6905 raw_ostream &Out) {
6906 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
6907 Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
6910 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
6911 raw_ostream &Out) {
6912 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
6913 Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
6916 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
6917 const ThunkInfo &Thunk,
6918 raw_ostream &Out) {
6919 // <special-name> ::= T <call-offset> <base encoding>
6920 // # base is the nominal target function of thunk
6921 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
6922 // # base is the nominal target function of thunk
6923 // # first call-offset is 'this' adjustment
6924 // # second call-offset is result adjustment
6926 assert(!isa<CXXDestructorDecl>(MD) &&
6927 "Use mangleCXXDtor for destructor decls!");
6928 CXXNameMangler Mangler(*this, Out);
6929 Mangler.getStream() << "_ZT";
6930 if (!Thunk.Return.isEmpty())
6931 Mangler.getStream() << 'c';
6933 // Mangle the 'this' pointer adjustment.
6934 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
6935 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
6937 // Mangle the return pointer adjustment if there is one.
6938 if (!Thunk.Return.isEmpty())
6939 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
6940 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
6942 Mangler.mangleFunctionEncoding(MD);
6945 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
6946 const CXXDestructorDecl *DD, CXXDtorType Type,
6947 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
6948 // <special-name> ::= T <call-offset> <base encoding>
6949 // # base is the nominal target function of thunk
6950 CXXNameMangler Mangler(*this, Out, DD, Type);
6951 Mangler.getStream() << "_ZT";
6953 // Mangle the 'this' pointer adjustment.
6954 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
6955 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
6957 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
6960 /// Returns the mangled name for a guard variable for the passed in VarDecl.
6961 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
6962 raw_ostream &Out) {
6963 // <special-name> ::= GV <object name> # Guard variable for one-time
6964 // # initialization
6965 CXXNameMangler Mangler(*this, Out);
6966 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
6967 // be a bug that is fixed in trunk.
6968 Mangler.getStream() << "_ZGV";
6969 Mangler.mangleName(D);
6972 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
6973 raw_ostream &Out) {
6974 // These symbols are internal in the Itanium ABI, so the names don't matter.
6975 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
6976 // avoid duplicate symbols.
6977 Out << "__cxx_global_var_init";
6980 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
6981 raw_ostream &Out) {
6982 // Prefix the mangling of D with __dtor_.
6983 CXXNameMangler Mangler(*this, Out);
6984 Mangler.getStream() << "__dtor_";
6985 if (shouldMangleDeclName(D))
6986 Mangler.mangle(D);
6987 else
6988 Mangler.getStream() << D->getName();
6991 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
6992 raw_ostream &Out) {
6993 // Clang generates these internal-linkage functions as part of its
6994 // implementation of the XL ABI.
6995 CXXNameMangler Mangler(*this, Out);
6996 Mangler.getStream() << "__finalize_";
6997 if (shouldMangleDeclName(D))
6998 Mangler.mangle(D);
6999 else
7000 Mangler.getStream() << D->getName();
7003 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7004 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7005 CXXNameMangler Mangler(*this, Out);
7006 Mangler.getStream() << "__filt_";
7007 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7008 if (shouldMangleDeclName(EnclosingFD))
7009 Mangler.mangle(EnclosingDecl);
7010 else
7011 Mangler.getStream() << EnclosingFD->getName();
7014 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7015 GlobalDecl EnclosingDecl, raw_ostream &Out) {
7016 CXXNameMangler Mangler(*this, Out);
7017 Mangler.getStream() << "__fin_";
7018 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7019 if (shouldMangleDeclName(EnclosingFD))
7020 Mangler.mangle(EnclosingDecl);
7021 else
7022 Mangler.getStream() << EnclosingFD->getName();
7025 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7026 raw_ostream &Out) {
7027 // <special-name> ::= TH <object name>
7028 CXXNameMangler Mangler(*this, Out);
7029 Mangler.getStream() << "_ZTH";
7030 Mangler.mangleName(D);
7033 void
7034 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7035 raw_ostream &Out) {
7036 // <special-name> ::= TW <object name>
7037 CXXNameMangler Mangler(*this, Out);
7038 Mangler.getStream() << "_ZTW";
7039 Mangler.mangleName(D);
7042 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
7043 unsigned ManglingNumber,
7044 raw_ostream &Out) {
7045 // We match the GCC mangling here.
7046 // <special-name> ::= GR <object name>
7047 CXXNameMangler Mangler(*this, Out);
7048 Mangler.getStream() << "_ZGR";
7049 Mangler.mangleName(D);
7050 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
7051 Mangler.mangleSeqID(ManglingNumber - 1);
7054 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
7055 raw_ostream &Out) {
7056 // <special-name> ::= TV <type> # virtual table
7057 CXXNameMangler Mangler(*this, Out);
7058 Mangler.getStream() << "_ZTV";
7059 Mangler.mangleNameOrStandardSubstitution(RD);
7062 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
7063 raw_ostream &Out) {
7064 // <special-name> ::= TT <type> # VTT structure
7065 CXXNameMangler Mangler(*this, Out);
7066 Mangler.getStream() << "_ZTT";
7067 Mangler.mangleNameOrStandardSubstitution(RD);
7070 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
7071 int64_t Offset,
7072 const CXXRecordDecl *Type,
7073 raw_ostream &Out) {
7074 // <special-name> ::= TC <type> <offset number> _ <base type>
7075 CXXNameMangler Mangler(*this, Out);
7076 Mangler.getStream() << "_ZTC";
7077 Mangler.mangleNameOrStandardSubstitution(RD);
7078 Mangler.getStream() << Offset;
7079 Mangler.getStream() << '_';
7080 Mangler.mangleNameOrStandardSubstitution(Type);
7083 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
7084 // <special-name> ::= TI <type> # typeinfo structure
7085 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7086 CXXNameMangler Mangler(*this, Out);
7087 Mangler.getStream() << "_ZTI";
7088 Mangler.mangleType(Ty);
7091 void ItaniumMangleContextImpl::mangleCXXRTTIName(
7092 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7093 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
7094 CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
7095 Mangler.getStream() << "_ZTS";
7096 Mangler.mangleType(Ty);
7099 void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7100 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7101 mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
7104 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
7105 llvm_unreachable("Can't mangle string literals");
7108 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7109 raw_ostream &Out) {
7110 CXXNameMangler Mangler(*this, Out);
7111 Mangler.mangleLambdaSig(Lambda);
7114 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7115 raw_ostream &Out) {
7116 // <special-name> ::= GI <module-name> # module initializer function
7117 CXXNameMangler Mangler(*this, Out);
7118 Mangler.getStream() << "_ZGI";
7119 Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
7120 if (M->isModulePartition()) {
7121 // The partition needs including, as partitions can have them too.
7122 auto Partition = M->Name.find(':');
7123 Mangler.mangleModuleNamePrefix(
7124 StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
7125 /*IsPartition*/ true);
7129 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
7130 DiagnosticsEngine &Diags,
7131 bool IsAux) {
7132 return new ItaniumMangleContextImpl(
7133 Context, Diags,
7134 [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
7135 return std::nullopt;
7137 IsAux);
7140 ItaniumMangleContext *
7141 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
7142 DiscriminatorOverrideTy DiscriminatorOverride,
7143 bool IsAux) {
7144 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7145 IsAux);