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