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