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