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