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