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