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