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