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