clang 17.0.0git
ItaniumMangle.cpp
Go to the documentation of this file.
1//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implements C++ name mangling according to the Itanium C++ ABI,
10// which is used in GCC 3.2 and newer (and many compilers that are
11// ABI-compatible with GCC):
12//
13// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14//
15//===----------------------------------------------------------------------===//
16
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/Mangle.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/ABI.h"
31#include "clang/Basic/Module.h"
34#include "clang/Basic/Thunk.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38#include <optional>
39
40using namespace clang;
41
42namespace {
43
44static bool isLocalContainerContext(const DeclContext *DC) {
45 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
46}
47
48static const FunctionDecl *getStructor(const FunctionDecl *fn) {
49 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
50 return ftd->getTemplatedDecl();
51
52 return fn;
53}
54
55static const NamedDecl *getStructor(const NamedDecl *decl) {
56 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
57 return (fn ? getStructor(fn) : decl);
58}
59
60static bool isLambda(const NamedDecl *ND) {
61 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
62 if (!Record)
63 return false;
64
65 return Record->isLambda();
66}
67
68static const unsigned UnknownArity = ~0U;
69
70class ItaniumMangleContextImpl : public ItaniumMangleContext {
71 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
72 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
73 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
74 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
75 NamespaceDecl *StdNamespace = nullptr;
76
77 bool NeedsUniqueInternalLinkageNames = false;
78
79public:
80 explicit ItaniumMangleContextImpl(
81 ASTContext &Context, DiagnosticsEngine &Diags,
82 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
83 : ItaniumMangleContext(Context, Diags, IsAux),
84 DiscriminatorOverride(DiscriminatorOverride) {}
85
86 /// @name Mangler Entry Points
87 /// @{
88
89 bool shouldMangleCXXName(const NamedDecl *D) override;
90 bool shouldMangleStringLiteral(const StringLiteral *) override {
91 return false;
92 }
93
94 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
95 void needsUniqueInternalLinkageNames() override {
96 NeedsUniqueInternalLinkageNames = true;
97 }
98
99 void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
100 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
101 raw_ostream &) override;
104 raw_ostream &) override;
105 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
106 raw_ostream &) override;
107 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
108 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
109 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
110 const CXXRecordDecl *Type, raw_ostream &) override;
111 void mangleCXXRTTI(QualType T, raw_ostream &) override;
112 void mangleCXXRTTIName(QualType T, raw_ostream &,
113 bool NormalizeIntegers) override;
114 void mangleTypeName(QualType T, raw_ostream &,
115 bool NormalizeIntegers) override;
116
117 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
118 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
119 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
120 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
122 raw_ostream &Out) override;
123 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
124 void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
125 raw_ostream &Out) override;
126 void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
127 raw_ostream &Out) override;
128 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
130 raw_ostream &) override;
131
132 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
133
134 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
135
136 void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
137
138 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
139 // Lambda closure types are already numbered.
140 if (isLambda(ND))
141 return false;
142
143 // Anonymous tags are already numbered.
144 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
145 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
146 return false;
147 }
148
149 // Use the canonical number for externally visible decls.
150 if (ND->isExternallyVisible()) {
151 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
152 if (discriminator == 1)
153 return false;
154 disc = discriminator - 2;
155 return true;
156 }
157
158 // Make up a reasonable number for internal decls.
159 unsigned &discriminator = Uniquifier[ND];
160 if (!discriminator) {
161 const DeclContext *DC = getEffectiveDeclContext(ND);
162 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
163 }
164 if (discriminator == 1)
165 return false;
166 disc = discriminator-2;
167 return true;
168 }
169
170 std::string getLambdaString(const CXXRecordDecl *Lambda) override {
171 // This function matches the one in MicrosoftMangle, which returns
172 // the string that is used in lambda mangled names.
173 assert(Lambda->isLambda() && "RD must be a lambda!");
174 std::string Name("<lambda");
175 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
176 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
177 unsigned LambdaId;
178 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
179 const FunctionDecl *Func =
180 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
181
182 if (Func) {
183 unsigned DefaultArgNo =
184 Func->getNumParams() - Parm->getFunctionScopeIndex();
185 Name += llvm::utostr(DefaultArgNo);
186 Name += "_";
187 }
188
189 if (LambdaManglingNumber)
190 LambdaId = LambdaManglingNumber;
191 else
192 LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
193
194 Name += llvm::utostr(LambdaId);
195 Name += '>';
196 return Name;
197 }
198
199 DiscriminatorOverrideTy getDiscriminatorOverride() const override {
200 return DiscriminatorOverride;
201 }
202
203 NamespaceDecl *getStdNamespace();
204
205 const DeclContext *getEffectiveDeclContext(const Decl *D);
206 const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
207 return getEffectiveDeclContext(cast<Decl>(DC));
208 }
209
210 bool isInternalLinkageDecl(const NamedDecl *ND);
211 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
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 /// The next substitution sequence number.
238 unsigned SeqID = 0;
239
240 class FunctionTypeDepthState {
241 unsigned Bits;
242
243 enum { InResultTypeMask = 1 };
244
245 public:
246 FunctionTypeDepthState() : Bits(0) {}
247
248 /// The number of function types we're inside.
249 unsigned getDepth() const {
250 return Bits >> 1;
251 }
252
253 /// True if we're in the return type of the innermost function type.
254 bool isInResultType() const {
255 return Bits & InResultTypeMask;
256 }
257
258 FunctionTypeDepthState push() {
259 FunctionTypeDepthState tmp = *this;
260 Bits = (Bits & ~InResultTypeMask) + 2;
261 return tmp;
262 }
263
264 void enterResultType() {
265 Bits |= InResultTypeMask;
266 }
267
268 void leaveResultType() {
269 Bits &= ~InResultTypeMask;
270 }
271
272 void pop(FunctionTypeDepthState saved) {
273 assert(getDepth() == saved.getDepth() + 1);
274 Bits = saved.Bits;
275 }
276
277 } FunctionTypeDepth;
278
279 // abi_tag is a gcc attribute, taking one or more strings called "tags".
280 // The goal is to annotate against which version of a library an object was
281 // built and to be able to provide backwards compatibility ("dual abi").
282 // For more information see docs/ItaniumMangleAbiTags.rst.
283 typedef SmallVector<StringRef, 4> AbiTagList;
284
285 // State to gather all implicit and explicit tags used in a mangled name.
286 // Must always have an instance of this while emitting any name to keep
287 // track.
288 class AbiTagState final {
289 public:
290 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
291 Parent = LinkHead;
292 LinkHead = this;
293 }
294
295 // No copy, no move.
296 AbiTagState(const AbiTagState &) = delete;
297 AbiTagState &operator=(const AbiTagState &) = delete;
298
299 ~AbiTagState() { pop(); }
300
301 void write(raw_ostream &Out, const NamedDecl *ND,
302 const AbiTagList *AdditionalAbiTags) {
303 ND = cast<NamedDecl>(ND->getCanonicalDecl());
304 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
305 assert(
306 !AdditionalAbiTags &&
307 "only function and variables need a list of additional abi tags");
308 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
309 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
310 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
311 AbiTag->tags().end());
312 }
313 // Don't emit abi tags for namespaces.
314 return;
315 }
316 }
317
318 AbiTagList TagList;
319 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
321 AbiTag->tags().end());
322 TagList.insert(TagList.end(), AbiTag->tags().begin(),
323 AbiTag->tags().end());
324 }
325
326 if (AdditionalAbiTags) {
327 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
328 AdditionalAbiTags->end());
329 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
330 AdditionalAbiTags->end());
331 }
332
333 llvm::sort(TagList);
334 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
335
336 writeSortedUniqueAbiTags(Out, TagList);
337 }
338
339 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
340 void setUsedAbiTags(const AbiTagList &AbiTags) {
341 UsedAbiTags = AbiTags;
342 }
343
344 const AbiTagList &getEmittedAbiTags() const {
345 return EmittedAbiTags;
346 }
347
348 const AbiTagList &getSortedUniqueUsedAbiTags() {
349 llvm::sort(UsedAbiTags);
350 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
351 UsedAbiTags.end());
352 return UsedAbiTags;
353 }
354
355 private:
356 //! All abi tags used implicitly or explicitly.
357 AbiTagList UsedAbiTags;
358 //! All explicit abi tags (i.e. not from namespace).
359 AbiTagList EmittedAbiTags;
360
361 AbiTagState *&LinkHead;
362 AbiTagState *Parent = nullptr;
363
364 void pop() {
365 assert(LinkHead == this &&
366 "abi tag link head must point to us on destruction");
367 if (Parent) {
368 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
369 UsedAbiTags.begin(), UsedAbiTags.end());
370 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
371 EmittedAbiTags.begin(),
372 EmittedAbiTags.end());
373 }
374 LinkHead = Parent;
375 }
376
377 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
378 for (const auto &Tag : AbiTags) {
379 EmittedAbiTags.push_back(Tag);
380 Out << "B";
381 Out << Tag.size();
382 Out << Tag;
383 }
384 }
385 };
386
387 AbiTagState *AbiTags = nullptr;
388 AbiTagState AbiTagsRoot;
389
390 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
391 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
392
393 ASTContext &getASTContext() const { return Context.getASTContext(); }
394
395 bool isStd(const NamespaceDecl *NS);
396 bool isStdNamespace(const DeclContext *DC);
397
398 const RecordDecl *GetLocalClassDecl(const Decl *D);
399 const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
400 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
401 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
402 llvm::StringRef Name, bool HasAllocator);
403
404public:
405 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
406 const NamedDecl *D = nullptr, bool NullOut_ = false)
407 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
408 AbiTagsRoot(AbiTags) {
409 // These can't be mangled without a ctor type or dtor type.
410 assert(!D || (!isa<CXXDestructorDecl>(D) &&
411 !isa<CXXConstructorDecl>(D)));
412 }
413 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
415 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
416 AbiTagsRoot(AbiTags) {}
417 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
419 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
420 AbiTagsRoot(AbiTags) {}
421
422 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
423 bool NormalizeIntegers_)
424 : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
425 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
426 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
427 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
428 StructorType(Outer.StructorType), SeqID(Outer.SeqID),
429 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
430 Substitutions(Outer.Substitutions),
431 ModuleSubstitutions(Outer.ModuleSubstitutions) {}
432
433 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
434 : CXXNameMangler(Outer, (raw_ostream &)Out_) {
435 NullOut = true;
436 }
437
438 raw_ostream &getStream() { return Out; }
439
440 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
441 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
442
443 void mangle(GlobalDecl GD);
444 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
445 void mangleNumber(const llvm::APSInt &I);
446 void mangleNumber(int64_t Number);
447 void mangleFloat(const llvm::APFloat &F);
448 void mangleFunctionEncoding(GlobalDecl GD);
449 void mangleSeqID(unsigned SeqID);
450 void mangleName(GlobalDecl GD);
451 void mangleType(QualType T);
452 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
453 void mangleLambdaSig(const CXXRecordDecl *Lambda);
454 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
455
456private:
457
458 bool mangleSubstitution(const NamedDecl *ND);
459 bool mangleSubstitution(NestedNameSpecifier *NNS);
460 bool mangleSubstitution(QualType T);
461 bool mangleSubstitution(TemplateName Template);
462 bool mangleSubstitution(uintptr_t Ptr);
463
464 void mangleExistingSubstitution(TemplateName name);
465
466 bool mangleStandardSubstitution(const NamedDecl *ND);
467
468 void addSubstitution(const NamedDecl *ND) {
469 ND = cast<NamedDecl>(ND->getCanonicalDecl());
470
471 addSubstitution(reinterpret_cast<uintptr_t>(ND));
472 }
473 void addSubstitution(NestedNameSpecifier *NNS) {
474 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
475
476 addSubstitution(reinterpret_cast<uintptr_t>(NNS));
477 }
478 void addSubstitution(QualType T);
479 void addSubstitution(TemplateName Template);
480 void addSubstitution(uintptr_t Ptr);
481 // Destructive copy substitutions from other mangler.
482 void extendSubstitutions(CXXNameMangler* Other);
483
484 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
485 bool recursive = false);
486 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
487 DeclarationName name,
488 const TemplateArgumentLoc *TemplateArgs,
489 unsigned NumTemplateArgs,
490 unsigned KnownArity = UnknownArity);
491
492 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
493
494 void mangleNameWithAbiTags(GlobalDecl GD,
495 const AbiTagList *AdditionalAbiTags);
496 void mangleModuleName(const NamedDecl *ND);
497 void mangleTemplateName(const TemplateDecl *TD,
499 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
500 const AbiTagList *AdditionalAbiTags) {
501 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
502 UnknownArity, AdditionalAbiTags);
503 }
504 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
505 const DeclContext *DC, unsigned KnownArity,
506 const AbiTagList *AdditionalAbiTags);
507 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
508 const AbiTagList *AdditionalAbiTags);
509 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
510 const AbiTagList *AdditionalAbiTags);
511 void mangleSourceName(const IdentifierInfo *II);
512 void mangleRegCallName(const IdentifierInfo *II);
513 void mangleDeviceStubName(const IdentifierInfo *II);
514 void mangleSourceNameWithAbiTags(
515 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
516 void mangleLocalName(GlobalDecl GD,
517 const AbiTagList *AdditionalAbiTags);
518 void mangleBlockForPrefix(const BlockDecl *Block);
519 void mangleUnqualifiedBlock(const BlockDecl *Block);
520 void mangleTemplateParamDecl(const NamedDecl *Decl);
521 void mangleLambda(const CXXRecordDecl *Lambda);
522 void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
523 const AbiTagList *AdditionalAbiTags,
524 bool NoFunction=false);
525 void mangleNestedName(const TemplateDecl *TD,
527 void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
528 const NamedDecl *PrefixND,
529 const AbiTagList *AdditionalAbiTags);
530 void manglePrefix(NestedNameSpecifier *qualifier);
531 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
532 void manglePrefix(QualType type);
533 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
534 void mangleTemplatePrefix(TemplateName Template);
535 const NamedDecl *getClosurePrefix(const Decl *ND);
536 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
537 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
538 StringRef Prefix = "");
539 void mangleOperatorName(DeclarationName Name, unsigned Arity);
540 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
541 void mangleVendorQualifier(StringRef qualifier);
542 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
543 void mangleRefQualifier(RefQualifierKind RefQualifier);
544
545 void mangleObjCMethodName(const ObjCMethodDecl *MD);
546
547 // Declare manglers for every type class.
548#define ABSTRACT_TYPE(CLASS, PARENT)
549#define NON_CANONICAL_TYPE(CLASS, PARENT)
550#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
551#include "clang/AST/TypeNodes.inc"
552
553 void mangleType(const TagType*);
554 void mangleType(TemplateName);
555 static StringRef getCallingConvQualifierName(CallingConv CC);
556 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
557 void mangleExtFunctionInfo(const FunctionType *T);
558 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
559 const FunctionDecl *FD = nullptr);
560 void mangleNeonVectorType(const VectorType *T);
561 void mangleNeonVectorType(const DependentVectorType *T);
562 void mangleAArch64NeonVectorType(const VectorType *T);
563 void mangleAArch64NeonVectorType(const DependentVectorType *T);
564 void mangleAArch64FixedSveVectorType(const VectorType *T);
565 void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
566
567 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
568 void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
569 void mangleFixedPointLiteral();
570 void mangleNullPointer(QualType T);
571
572 void mangleMemberExprBase(const Expr *base, bool isArrow);
573 void mangleMemberExpr(const Expr *base, bool isArrow,
574 NestedNameSpecifier *qualifier,
575 NamedDecl *firstQualifierLookup,
576 DeclarationName name,
577 const TemplateArgumentLoc *TemplateArgs,
578 unsigned NumTemplateArgs,
579 unsigned knownArity);
580 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
581 void mangleInitListElements(const InitListExpr *InitList);
582 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
583 bool AsTemplateArg = false);
584 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
585 void mangleCXXDtorType(CXXDtorType T);
586
587 void mangleTemplateArgs(TemplateName TN,
588 const TemplateArgumentLoc *TemplateArgs,
589 unsigned NumTemplateArgs);
590 void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
591 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
592 void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
593 void mangleTemplateArgExpr(const Expr *E);
594 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
595 bool NeedExactType = false);
596
597 void mangleTemplateParameter(unsigned Depth, unsigned Index);
598
599 void mangleFunctionParam(const ParmVarDecl *parm);
600
601 void writeAbiTags(const NamedDecl *ND,
602 const AbiTagList *AdditionalAbiTags);
603
604 // Returns sorted unique list of ABI tags.
605 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
606 // Returns sorted unique list of ABI tags.
607 AbiTagList makeVariableTypeTags(const VarDecl *VD);
608};
609
610}
611
612NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
613 if (!StdNamespace) {
614 StdNamespace = NamespaceDecl::Create(
615 getASTContext(), getASTContext().getTranslationUnitDecl(),
616 /*Inline=*/false, SourceLocation(), SourceLocation(),
617 &getASTContext().Idents.get("std"),
618 /*PrevDecl=*/nullptr, /*Nested=*/false);
619 StdNamespace->setImplicit();
620 }
621 return StdNamespace;
622}
623
624/// Retrieve the declaration context that should be used when mangling the given
625/// declaration.
626const DeclContext *
627ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
628 // The ABI assumes that lambda closure types that occur within
629 // default arguments live in the context of the function. However, due to
630 // the way in which Clang parses and creates function declarations, this is
631 // not the case: the lambda closure type ends up living in the context
632 // where the function itself resides, because the function declaration itself
633 // had not yet been created. Fix the context here.
634 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
635 if (RD->isLambda())
636 if (ParmVarDecl *ContextParam =
637 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
638 return ContextParam->getDeclContext();
639 }
640
641 // Perform the same check for block literals.
642 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
643 if (ParmVarDecl *ContextParam =
644 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
645 return ContextParam->getDeclContext();
646 }
647
648 // On ARM and AArch64, the va_list tag is always mangled as if in the std
649 // namespace. We do not represent va_list as actually being in the std
650 // namespace in C because this would result in incorrect debug info in C,
651 // among other things. It is important for both languages to have the same
652 // mangling in order for -fsanitize=cfi-icall to work.
653 if (D == getASTContext().getVaListTagDecl()) {
654 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
655 if (T.isARM() || T.isThumb() || T.isAArch64())
656 return getStdNamespace();
657 }
658
659 const DeclContext *DC = D->getDeclContext();
660 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
661 isa<OMPDeclareMapperDecl>(DC)) {
662 return getEffectiveDeclContext(cast<Decl>(DC));
663 }
664
665 if (const auto *VD = dyn_cast<VarDecl>(D))
666 if (VD->isExternC())
667 return getASTContext().getTranslationUnitDecl();
668
669 if (const auto *FD = dyn_cast<FunctionDecl>(D))
670 if (FD->isExternC())
671 return getASTContext().getTranslationUnitDecl();
672
673 return DC->getRedeclContext();
674}
675
676bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
677 if (ND && ND->getFormalLinkage() == InternalLinkage &&
678 !ND->isExternallyVisible() &&
679 getEffectiveDeclContext(ND)->isFileContext() &&
681 return true;
682 return false;
683}
684
685// Check if this Function Decl needs a unique internal linkage name.
686bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
687 const NamedDecl *ND) {
688 if (!NeedsUniqueInternalLinkageNames || !ND)
689 return false;
690
691 const auto *FD = dyn_cast<FunctionDecl>(ND);
692 if (!FD)
693 return false;
694
695 // For C functions without prototypes, return false as their
696 // names should not be mangled.
697 if (!FD->getType()->getAs<FunctionProtoType>())
698 return false;
699
700 if (isInternalLinkageDecl(ND))
701 return true;
702
703 return false;
704}
705
706bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
707 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
708 LanguageLinkage L = FD->getLanguageLinkage();
709 // Overloadable functions need mangling.
710 if (FD->hasAttr<OverloadableAttr>())
711 return true;
712
713 // "main" is not mangled.
714 if (FD->isMain())
715 return false;
716
717 // The Windows ABI expects that we would never mangle "typical"
718 // user-defined entry points regardless of visibility or freestanding-ness.
719 //
720 // N.B. This is distinct from asking about "main". "main" has a lot of
721 // special rules associated with it in the standard while these
722 // user-defined entry points are outside of the purview of the standard.
723 // For example, there can be only one definition for "main" in a standards
724 // compliant program; however nothing forbids the existence of wmain and
725 // WinMain in the same translation unit.
726 if (FD->isMSVCRTEntryPoint())
727 return false;
728
729 // C++ functions and those whose names are not a simple identifier need
730 // mangling.
731 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
732 return true;
733
734 // C functions are not mangled.
735 if (L == CLanguageLinkage)
736 return false;
737 }
738
739 // Otherwise, no mangling is done outside C++ mode.
740 if (!getASTContext().getLangOpts().CPlusPlus)
741 return false;
742
743 if (const auto *VD = dyn_cast<VarDecl>(D)) {
744 // Decompositions are mangled.
745 if (isa<DecompositionDecl>(VD))
746 return true;
747
748 // C variables are not mangled.
749 if (VD->isExternC())
750 return false;
751
752 // Variables at global scope are not mangled unless they have internal
753 // linkage or are specializations or are attached to a named module.
754 const DeclContext *DC = getEffectiveDeclContext(D);
755 // Check for extern variable declared locally.
756 if (DC->isFunctionOrMethod() && D->hasLinkage())
757 while (!DC->isFileContext())
758 DC = getEffectiveParentContext(DC);
760 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
761 !isa<VarTemplateSpecializationDecl>(VD) &&
762 !VD->getOwningModuleForLinkage())
763 return false;
764 }
765
766 return true;
767}
768
769void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
770 const AbiTagList *AdditionalAbiTags) {
771 assert(AbiTags && "require AbiTagState");
772 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
773}
774
775void CXXNameMangler::mangleSourceNameWithAbiTags(
776 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
777 mangleSourceName(ND->getIdentifier());
778 writeAbiTags(ND, AdditionalAbiTags);
779}
780
781void CXXNameMangler::mangle(GlobalDecl GD) {
782 // <mangled-name> ::= _Z <encoding>
783 // ::= <data name>
784 // ::= <special-name>
785 Out << "_Z";
786 if (isa<FunctionDecl>(GD.getDecl()))
787 mangleFunctionEncoding(GD);
789 BindingDecl>(GD.getDecl()))
790 mangleName(GD);
791 else if (const IndirectFieldDecl *IFD =
792 dyn_cast<IndirectFieldDecl>(GD.getDecl()))
793 mangleName(IFD->getAnonField());
794 else
795 llvm_unreachable("unexpected kind of global decl");
796}
797
798void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
799 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
800 // <encoding> ::= <function name> <bare-function-type>
801
802 // Don't mangle in the type if this isn't a decl we should typically mangle.
803 if (!Context.shouldMangleDeclName(FD)) {
804 mangleName(GD);
805 return;
806 }
807
808 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
809 if (ReturnTypeAbiTags.empty()) {
810 // There are no tags for return type, the simplest case.
811 mangleName(GD);
812 mangleFunctionEncodingBareType(FD);
813 return;
814 }
815
816 // Mangle function name and encoding to temporary buffer.
817 // We have to output name and encoding to the same mangler to get the same
818 // substitution as it will be in final mangling.
819 SmallString<256> FunctionEncodingBuf;
820 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
821 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
822 // Output name of the function.
823 FunctionEncodingMangler.disableDerivedAbiTags();
824 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
825
826 // Remember length of the function name in the buffer.
827 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
828 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
829
830 // Get tags from return type that are not present in function name or
831 // encoding.
832 const AbiTagList &UsedAbiTags =
833 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
834 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
835 AdditionalAbiTags.erase(
836 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
837 UsedAbiTags.begin(), UsedAbiTags.end(),
838 AdditionalAbiTags.begin()),
839 AdditionalAbiTags.end());
840
841 // Output name with implicit tags and function encoding from temporary buffer.
842 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
843 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
844
845 // Function encoding could create new substitutions so we have to add
846 // temp mangled substitutions to main mangler.
847 extendSubstitutions(&FunctionEncodingMangler);
848}
849
850void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
851 if (FD->hasAttr<EnableIfAttr>()) {
852 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
853 Out << "Ua9enable_ifI";
854 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
855 E = FD->getAttrs().end();
856 I != E; ++I) {
857 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
858 if (!EIA)
859 continue;
860 if (Context.getASTContext().getLangOpts().getClangABICompat() >
861 LangOptions::ClangABI::Ver11) {
862 mangleTemplateArgExpr(EIA->getCond());
863 } else {
864 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
865 // even though <template-arg> should not include an X/E around
866 // <expr-primary>.
867 Out << 'X';
868 mangleExpression(EIA->getCond());
869 Out << 'E';
870 }
871 }
872 Out << 'E';
873 FunctionTypeDepth.pop(Saved);
874 }
875
876 // When mangling an inheriting constructor, the bare function type used is
877 // that of the inherited constructor.
878 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
879 if (auto Inherited = CD->getInheritedConstructor())
880 FD = Inherited.getConstructor();
881
882 // Whether the mangling of a function type includes the return type depends on
883 // the context and the nature of the function. The rules for deciding whether
884 // the return type is included are:
885 //
886 // 1. Template functions (names or types) have return types encoded, with
887 // the exceptions listed below.
888 // 2. Function types not appearing as part of a function name mangling,
889 // e.g. parameters, pointer types, etc., have return type encoded, with the
890 // exceptions listed below.
891 // 3. Non-template function names do not have return types encoded.
892 //
893 // The exceptions mentioned in (1) and (2) above, for which the return type is
894 // never included, are
895 // 1. Constructors.
896 // 2. Destructors.
897 // 3. Conversion operator functions, e.g. operator int.
898 bool MangleReturnType = false;
899 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
900 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
901 isa<CXXConversionDecl>(FD)))
902 MangleReturnType = true;
903
904 // Mangle the type of the primary template.
905 FD = PrimaryTemplate->getTemplatedDecl();
906 }
907
908 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
909 MangleReturnType, FD);
910}
911
912/// Return whether a given namespace is the 'std' namespace.
913bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
914 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
915 return false;
916
918 return II && II->isStr("std");
919}
920
921// isStdNamespace - Return whether a given decl context is a toplevel 'std'
922// namespace.
923bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
924 if (!DC->isNamespace())
925 return false;
926
927 return isStd(cast<NamespaceDecl>(DC));
928}
929
930static const GlobalDecl
931isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
932 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
933 // Check if we have a function template.
934 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
935 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
936 TemplateArgs = FD->getTemplateSpecializationArgs();
937 return GD.getWithDecl(TD);
938 }
939 }
940
941 // Check if we have a class template.
942 if (const ClassTemplateSpecializationDecl *Spec =
943 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
944 TemplateArgs = &Spec->getTemplateArgs();
945 return GD.getWithDecl(Spec->getSpecializedTemplate());
946 }
947
948 // Check if we have a variable template.
949 if (const VarTemplateSpecializationDecl *Spec =
950 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
951 TemplateArgs = &Spec->getTemplateArgs();
952 return GD.getWithDecl(Spec->getSpecializedTemplate());
953 }
954
955 return GlobalDecl();
956}
957
959 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
960 return TemplateName(const_cast<TemplateDecl*>(TD));
961}
962
963void CXXNameMangler::mangleName(GlobalDecl GD) {
964 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
965 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
966 // Variables should have implicit tags from its type.
967 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
968 if (VariableTypeAbiTags.empty()) {
969 // Simple case no variable type tags.
970 mangleNameWithAbiTags(VD, nullptr);
971 return;
972 }
973
974 // Mangle variable name to null stream to collect tags.
975 llvm::raw_null_ostream NullOutStream;
976 CXXNameMangler VariableNameMangler(*this, NullOutStream);
977 VariableNameMangler.disableDerivedAbiTags();
978 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
979
980 // Get tags from variable type that are not present in its name.
981 const AbiTagList &UsedAbiTags =
982 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
983 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
984 AdditionalAbiTags.erase(
985 std::set_difference(VariableTypeAbiTags.begin(),
986 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
987 UsedAbiTags.end(), AdditionalAbiTags.begin()),
988 AdditionalAbiTags.end());
989
990 // Output name with implicit tags.
991 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
992 } else {
993 mangleNameWithAbiTags(GD, nullptr);
994 }
995}
996
997const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
998 const DeclContext *DC = Context.getEffectiveDeclContext(D);
999 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1000 if (isLocalContainerContext(DC))
1001 return dyn_cast<RecordDecl>(D);
1002 D = cast<Decl>(DC);
1003 DC = Context.getEffectiveDeclContext(D);
1004 }
1005 return nullptr;
1006}
1007
1008void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1009 const AbiTagList *AdditionalAbiTags) {
1010 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1011 // <name> ::= [<module-name>] <nested-name>
1012 // ::= [<module-name>] <unscoped-name>
1013 // ::= [<module-name>] <unscoped-template-name> <template-args>
1014 // ::= <local-name>
1015 //
1016 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1017
1018 // If this is an extern variable declared locally, the relevant DeclContext
1019 // is that of the containing namespace, or the translation unit.
1020 // FIXME: This is a hack; extern variables declared locally should have
1021 // a proper semantic declaration context!
1022 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
1023 while (!DC->isNamespace() && !DC->isTranslationUnit())
1024 DC = Context.getEffectiveParentContext(DC);
1025 else if (GetLocalClassDecl(ND)) {
1026 mangleLocalName(GD, AdditionalAbiTags);
1027 return;
1028 }
1029
1030 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1031
1032 if (isLocalContainerContext(DC)) {
1033 mangleLocalName(GD, AdditionalAbiTags);
1034 return;
1035 }
1036
1037 // Closures can require a nested-name mangling even if they're semantically
1038 // in the global namespace.
1039 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1040 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1041 return;
1042 }
1043
1044 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1045 // Check if we have a template.
1046 const TemplateArgumentList *TemplateArgs = nullptr;
1047 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1048 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1049 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1050 return;
1051 }
1052
1053 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1054 return;
1055 }
1056
1057 mangleNestedName(GD, DC, AdditionalAbiTags);
1058}
1059
1060void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1061 if (ND->isExternallyVisible())
1062 if (Module *M = ND->getOwningModuleForLinkage())
1063 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1064}
1065
1066// <module-name> ::= <module-subname>
1067// ::= <module-name> <module-subname>
1068// ::= <substitution>
1069// <module-subname> ::= W <source-name>
1070// ::= W P <source-name>
1071void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1072 // <substitution> ::= S <seq-id> _
1073 auto It = ModuleSubstitutions.find(Name);
1074 if (It != ModuleSubstitutions.end()) {
1075 Out << 'S';
1076 mangleSeqID(It->second);
1077 return;
1078 }
1079
1080 // FIXME: Preserve hierarchy in module names rather than flattening
1081 // them to strings; use Module*s as substitution keys.
1082 auto Parts = Name.rsplit('.');
1083 if (Parts.second.empty())
1084 Parts.second = Parts.first;
1085 else {
1086 mangleModuleNamePrefix(Parts.first, IsPartition);
1087 IsPartition = false;
1088 }
1089
1090 Out << 'W';
1091 if (IsPartition)
1092 Out << 'P';
1093 Out << Parts.second.size() << Parts.second;
1094 ModuleSubstitutions.insert({Name, SeqID++});
1095}
1096
1097void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1099 const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1100
1101 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1102 mangleUnscopedTemplateName(TD, DC, nullptr);
1103 mangleTemplateArgs(asTemplateName(TD), Args);
1104 } else {
1105 mangleNestedName(TD, Args);
1106 }
1107}
1108
1109void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1110 const AbiTagList *AdditionalAbiTags) {
1111 // <unscoped-name> ::= <unqualified-name>
1112 // ::= St <unqualified-name> # ::std::
1113
1114 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1115 if (isStdNamespace(DC))
1116 Out << "St";
1117
1118 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1119}
1120
1121void CXXNameMangler::mangleUnscopedTemplateName(
1122 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1123 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1124 // <unscoped-template-name> ::= <unscoped-name>
1125 // ::= <substitution>
1126 if (mangleSubstitution(ND))
1127 return;
1128
1129 // <template-template-param> ::= <template-param>
1130 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1131 assert(!AdditionalAbiTags &&
1132 "template template param cannot have abi tags");
1133 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1134 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1135 mangleUnscopedName(GD, DC, AdditionalAbiTags);
1136 } else {
1137 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1138 AdditionalAbiTags);
1139 }
1140
1141 addSubstitution(ND);
1142}
1143
1144void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1145 // ABI:
1146 // Floating-point literals are encoded using a fixed-length
1147 // lowercase hexadecimal string corresponding to the internal
1148 // representation (IEEE on Itanium), high-order bytes first,
1149 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1150 // on Itanium.
1151 // The 'without leading zeroes' thing seems to be an editorial
1152 // mistake; see the discussion on cxx-abi-dev beginning on
1153 // 2012-01-16.
1154
1155 // Our requirements here are just barely weird enough to justify
1156 // using a custom algorithm instead of post-processing APInt::toString().
1157
1158 llvm::APInt valueBits = f.bitcastToAPInt();
1159 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1160 assert(numCharacters != 0);
1161
1162 // Allocate a buffer of the right number of characters.
1163 SmallVector<char, 20> buffer(numCharacters);
1164
1165 // Fill the buffer left-to-right.
1166 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1167 // The bit-index of the next hex digit.
1168 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1169
1170 // Project out 4 bits starting at 'digitIndex'.
1171 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1172 hexDigit >>= (digitBitIndex % 64);
1173 hexDigit &= 0xF;
1174
1175 // Map that over to a lowercase hex digit.
1176 static const char charForHex[16] = {
1177 '0', '1', '2', '3', '4', '5', '6', '7',
1178 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1179 };
1180 buffer[stringIndex] = charForHex[hexDigit];
1181 }
1182
1183 Out.write(buffer.data(), numCharacters);
1184}
1185
1186void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1187 Out << 'L';
1188 mangleType(T);
1189 mangleFloat(V);
1190 Out << 'E';
1191}
1192
1193void CXXNameMangler::mangleFixedPointLiteral() {
1194 DiagnosticsEngine &Diags = Context.getDiags();
1195 unsigned DiagID = Diags.getCustomDiagID(
1196 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1197 Diags.Report(DiagID);
1198}
1199
1200void CXXNameMangler::mangleNullPointer(QualType T) {
1201 // <expr-primary> ::= L <type> 0 E
1202 Out << 'L';
1203 mangleType(T);
1204 Out << "0E";
1205}
1206
1207void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1208 if (Value.isSigned() && Value.isNegative()) {
1209 Out << 'n';
1210 Value.abs().print(Out, /*signed*/ false);
1211 } else {
1212 Value.print(Out, /*signed*/ false);
1213 }
1214}
1215
1216void CXXNameMangler::mangleNumber(int64_t Number) {
1217 // <number> ::= [n] <non-negative decimal integer>
1218 if (Number < 0) {
1219 Out << 'n';
1220 Number = -Number;
1221 }
1222
1223 Out << Number;
1224}
1225
1226void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1227 // <call-offset> ::= h <nv-offset> _
1228 // ::= v <v-offset> _
1229 // <nv-offset> ::= <offset number> # non-virtual base override
1230 // <v-offset> ::= <offset number> _ <virtual offset number>
1231 // # virtual base override, with vcall offset
1232 if (!Virtual) {
1233 Out << 'h';
1234 mangleNumber(NonVirtual);
1235 Out << '_';
1236 return;
1237 }
1238
1239 Out << 'v';
1240 mangleNumber(NonVirtual);
1241 Out << '_';
1242 mangleNumber(Virtual);
1243 Out << '_';
1244}
1245
1246void CXXNameMangler::manglePrefix(QualType type) {
1247 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1248 if (!mangleSubstitution(QualType(TST, 0))) {
1249 mangleTemplatePrefix(TST->getTemplateName());
1250
1251 // FIXME: GCC does not appear to mangle the template arguments when
1252 // the template in question is a dependent template name. Should we
1253 // emulate that badness?
1254 mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1255 addSubstitution(QualType(TST, 0));
1256 }
1257 } else if (const auto *DTST =
1259 if (!mangleSubstitution(QualType(DTST, 0))) {
1260 TemplateName Template = getASTContext().getDependentTemplateName(
1261 DTST->getQualifier(), DTST->getIdentifier());
1262 mangleTemplatePrefix(Template);
1263
1264 // FIXME: GCC does not appear to mangle the template arguments when
1265 // the template in question is a dependent template name. Should we
1266 // emulate that badness?
1267 mangleTemplateArgs(Template, DTST->template_arguments());
1268 addSubstitution(QualType(DTST, 0));
1269 }
1270 } else {
1271 // We use the QualType mangle type variant here because it handles
1272 // substitutions.
1273 mangleType(type);
1274 }
1275}
1276
1277/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1278///
1279/// \param recursive - true if this is being called recursively,
1280/// i.e. if there is more prefix "to the right".
1281void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1282 bool recursive) {
1283
1284 // x, ::x
1285 // <unresolved-name> ::= [gs] <base-unresolved-name>
1286
1287 // T::x / decltype(p)::x
1288 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1289
1290 // T::N::x /decltype(p)::N::x
1291 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1292 // <base-unresolved-name>
1293
1294 // A::x, N::y, A<T>::z; "gs" means leading "::"
1295 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1296 // <base-unresolved-name>
1297
1298 switch (qualifier->getKind()) {
1300 Out << "gs";
1301
1302 // We want an 'sr' unless this is the entire NNS.
1303 if (recursive)
1304 Out << "sr";
1305
1306 // We never want an 'E' here.
1307 return;
1308
1310 llvm_unreachable("Can't mangle __super specifier");
1311
1313 if (qualifier->getPrefix())
1314 mangleUnresolvedPrefix(qualifier->getPrefix(),
1315 /*recursive*/ true);
1316 else
1317 Out << "sr";
1318 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1319 break;
1321 if (qualifier->getPrefix())
1322 mangleUnresolvedPrefix(qualifier->getPrefix(),
1323 /*recursive*/ true);
1324 else
1325 Out << "sr";
1326 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1327 break;
1328
1331 const Type *type = qualifier->getAsType();
1332
1333 // We only want to use an unresolved-type encoding if this is one of:
1334 // - a decltype
1335 // - a template type parameter
1336 // - a template template parameter with arguments
1337 // In all of these cases, we should have no prefix.
1338 if (qualifier->getPrefix()) {
1339 mangleUnresolvedPrefix(qualifier->getPrefix(),
1340 /*recursive*/ true);
1341 } else {
1342 // Otherwise, all the cases want this.
1343 Out << "sr";
1344 }
1345
1346 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1347 return;
1348
1349 break;
1350 }
1351
1353 // Member expressions can have these without prefixes.
1354 if (qualifier->getPrefix())
1355 mangleUnresolvedPrefix(qualifier->getPrefix(),
1356 /*recursive*/ true);
1357 else
1358 Out << "sr";
1359
1360 mangleSourceName(qualifier->getAsIdentifier());
1361 // An Identifier has no type information, so we can't emit abi tags for it.
1362 break;
1363 }
1364
1365 // If this was the innermost part of the NNS, and we fell out to
1366 // here, append an 'E'.
1367 if (!recursive)
1368 Out << 'E';
1369}
1370
1371/// Mangle an unresolved-name, which is generally used for names which
1372/// weren't resolved to specific entities.
1373void CXXNameMangler::mangleUnresolvedName(
1374 NestedNameSpecifier *qualifier, DeclarationName name,
1375 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1376 unsigned knownArity) {
1377 if (qualifier) mangleUnresolvedPrefix(qualifier);
1378 switch (name.getNameKind()) {
1379 // <base-unresolved-name> ::= <simple-id>
1381 mangleSourceName(name.getAsIdentifierInfo());
1382 break;
1383 // <base-unresolved-name> ::= dn <destructor-name>
1385 Out << "dn";
1386 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1387 break;
1388 // <base-unresolved-name> ::= on <operator-name>
1392 Out << "on";
1393 mangleOperatorName(name, knownArity);
1394 break;
1396 llvm_unreachable("Can't mangle a constructor name!");
1398 llvm_unreachable("Can't mangle a using directive name!");
1400 llvm_unreachable("Can't mangle a deduction guide name!");
1404 llvm_unreachable("Can't mangle Objective-C selector names here!");
1405 }
1406
1407 // The <simple-id> and on <operator-name> productions end in an optional
1408 // <template-args>.
1409 if (TemplateArgs)
1410 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1411}
1412
1413void CXXNameMangler::mangleUnqualifiedName(
1414 GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1415 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1416 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1417 // <unqualified-name> ::= [<module-name>] <operator-name>
1418 // ::= <ctor-dtor-name>
1419 // ::= [<module-name>] <source-name>
1420 // ::= [<module-name>] DC <source-name>* E
1421
1422 if (ND && DC && DC->isFileContext())
1423 mangleModuleName(ND);
1424
1425 unsigned Arity = KnownArity;
1426 switch (Name.getNameKind()) {
1428 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1429
1430 // We mangle decomposition declarations as the names of their bindings.
1431 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1432 // FIXME: Non-standard mangling for decomposition declarations:
1433 //
1434 // <unqualified-name> ::= DC <source-name>* E
1435 //
1436 // Proposed on cxx-abi-dev on 2016-08-12
1437 Out << "DC";
1438 for (auto *BD : DD->bindings())
1439 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1440 Out << 'E';
1441 writeAbiTags(ND, AdditionalAbiTags);
1442 break;
1443 }
1444
1445 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1446 // We follow MSVC in mangling GUID declarations as if they were variables
1447 // with a particular reserved name. Continue the pretense here.
1448 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1449 llvm::raw_svector_ostream GUIDOS(GUID);
1450 Context.mangleMSGuidDecl(GD, GUIDOS);
1451 Out << GUID.size() << GUID;
1452 break;
1453 }
1454
1455 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1456 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1457 Out << "TA";
1458 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1459 TPO->getValue(), /*TopLevel=*/true);
1460 break;
1461 }
1462
1463 if (II) {
1464 // Match GCC's naming convention for internal linkage symbols, for
1465 // symbols that are not actually visible outside of this TU. GCC
1466 // distinguishes between internal and external linkage symbols in
1467 // its mangling, to support cases like this that were valid C++ prior
1468 // to DR426:
1469 //
1470 // void test() { extern void foo(); }
1471 // static void foo();
1472 //
1473 // Don't bother with the L marker for names in anonymous namespaces; the
1474 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1475 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1476 // implying internal linkage.
1477 if (Context.isInternalLinkageDecl(ND))
1478 Out << 'L';
1479
1480 auto *FD = dyn_cast<FunctionDecl>(ND);
1481 bool IsRegCall = FD &&
1482 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1484 bool IsDeviceStub =
1485 FD && FD->hasAttr<CUDAGlobalAttr>() &&
1486 GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1487 if (IsDeviceStub)
1488 mangleDeviceStubName(II);
1489 else if (IsRegCall)
1490 mangleRegCallName(II);
1491 else
1492 mangleSourceName(II);
1493
1494 writeAbiTags(ND, AdditionalAbiTags);
1495 break;
1496 }
1497
1498 // Otherwise, an anonymous entity. We must have a declaration.
1499 assert(ND && "mangling empty name without declaration");
1500
1501 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1502 if (NS->isAnonymousNamespace()) {
1503 // This is how gcc mangles these names.
1504 Out << "12_GLOBAL__N_1";
1505 break;
1506 }
1507 }
1508
1509 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1510 // We must have an anonymous union or struct declaration.
1511 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1512
1513 // Itanium C++ ABI 5.1.2:
1514 //
1515 // For the purposes of mangling, the name of an anonymous union is
1516 // considered to be the name of the first named data member found by a
1517 // pre-order, depth-first, declaration-order walk of the data members of
1518 // the anonymous union. If there is no such data member (i.e., if all of
1519 // the data members in the union are unnamed), then there is no way for
1520 // a program to refer to the anonymous union, and there is therefore no
1521 // need to mangle its name.
1522 assert(RD->isAnonymousStructOrUnion()
1523 && "Expected anonymous struct or union!");
1524 const FieldDecl *FD = RD->findFirstNamedDataMember();
1525
1526 // It's actually possible for various reasons for us to get here
1527 // with an empty anonymous struct / union. Fortunately, it
1528 // doesn't really matter what name we generate.
1529 if (!FD) break;
1530 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1531
1532 mangleSourceName(FD->getIdentifier());
1533 // Not emitting abi tags: internal name anyway.
1534 break;
1535 }
1536
1537 // Class extensions have no name as a category, and it's possible
1538 // for them to be the semantic parent of certain declarations
1539 // (primarily, tag decls defined within declarations). Such
1540 // declarations will always have internal linkage, so the name
1541 // doesn't really matter, but we shouldn't crash on them. For
1542 // safety, just handle all ObjC containers here.
1543 if (isa<ObjCContainerDecl>(ND))
1544 break;
1545
1546 // We must have an anonymous struct.
1547 const TagDecl *TD = cast<TagDecl>(ND);
1548 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1549 assert(TD->getDeclContext() == D->getDeclContext() &&
1550 "Typedef should not be in another decl context!");
1551 assert(D->getDeclName().getAsIdentifierInfo() &&
1552 "Typedef was not named!");
1553 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1554 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1555 // Explicit abi tags are still possible; take from underlying type, not
1556 // from typedef.
1557 writeAbiTags(TD, nullptr);
1558 break;
1559 }
1560
1561 // <unnamed-type-name> ::= <closure-type-name>
1562 //
1563 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1564 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1565 // # Parameter types or 'v' for 'void'.
1566 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1567 std::optional<unsigned> DeviceNumber =
1568 Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1569
1570 // If we have a device-number via the discriminator, use that to mangle
1571 // the lambda, otherwise use the typical lambda-mangling-number. In either
1572 // case, a '0' should be mangled as a normal unnamed class instead of as a
1573 // lambda.
1574 if (Record->isLambda() &&
1575 ((DeviceNumber && *DeviceNumber > 0) ||
1576 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1577 assert(!AdditionalAbiTags &&
1578 "Lambda type cannot have additional abi tags");
1579 mangleLambda(Record);
1580 break;
1581 }
1582 }
1583
1584 if (TD->isExternallyVisible()) {
1585 unsigned UnnamedMangle =
1586 getASTContext().getManglingNumber(TD, Context.isAux());
1587 Out << "Ut";
1588 if (UnnamedMangle > 1)
1589 Out << UnnamedMangle - 2;
1590 Out << '_';
1591 writeAbiTags(TD, AdditionalAbiTags);
1592 break;
1593 }
1594
1595 // Get a unique id for the anonymous struct. If it is not a real output
1596 // ID doesn't matter so use fake one.
1597 unsigned AnonStructId =
1598 NullOut ? 0
1599 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1600
1601 // Mangle it as a source name in the form
1602 // [n] $_<id>
1603 // where n is the length of the string.
1604 SmallString<8> Str;
1605 Str += "$_";
1606 Str += llvm::utostr(AnonStructId);
1607
1608 Out << Str.size();
1609 Out << Str;
1610 break;
1611 }
1612
1616 llvm_unreachable("Can't mangle Objective-C selector names here!");
1617
1619 const CXXRecordDecl *InheritedFrom = nullptr;
1620 TemplateName InheritedTemplateName;
1621 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1622 if (auto Inherited =
1623 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1624 InheritedFrom = Inherited.getConstructor()->getParent();
1625 InheritedTemplateName =
1626 TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1627 InheritedTemplateArgs =
1628 Inherited.getConstructor()->getTemplateSpecializationArgs();
1629 }
1630
1631 if (ND == Structor)
1632 // If the named decl is the C++ constructor we're mangling, use the type
1633 // we were given.
1634 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1635 else
1636 // Otherwise, use the complete constructor name. This is relevant if a
1637 // class with a constructor is declared within a constructor.
1638 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1639
1640 // FIXME: The template arguments are part of the enclosing prefix or
1641 // nested-name, but it's more convenient to mangle them here.
1642 if (InheritedTemplateArgs)
1643 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1644
1645 writeAbiTags(ND, AdditionalAbiTags);
1646 break;
1647 }
1648
1650 if (ND == Structor)
1651 // If the named decl is the C++ destructor we're mangling, use the type we
1652 // were given.
1653 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1654 else
1655 // Otherwise, use the complete destructor name. This is relevant if a
1656 // class with a destructor is declared within a destructor.
1657 mangleCXXDtorType(Dtor_Complete);
1658 writeAbiTags(ND, AdditionalAbiTags);
1659 break;
1660
1662 if (ND && Arity == UnknownArity) {
1663 Arity = cast<FunctionDecl>(ND)->getNumParams();
1664
1665 // If we have a member function, we need to include the 'this' pointer.
1666 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1667 if (!MD->isStatic())
1668 Arity++;
1669 }
1670 [[fallthrough]];
1673 mangleOperatorName(Name, Arity);
1674 writeAbiTags(ND, AdditionalAbiTags);
1675 break;
1676
1678 llvm_unreachable("Can't mangle a deduction guide name!");
1679
1681 llvm_unreachable("Can't mangle a using directive name!");
1682 }
1683}
1684
1685void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1686 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1687 // <number> ::= [n] <non-negative decimal integer>
1688 // <identifier> ::= <unqualified source code identifier>
1689 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1690 << II->getName();
1691}
1692
1693void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1694 // <source-name> ::= <positive length number> __device_stub__ <identifier>
1695 // <number> ::= [n] <non-negative decimal integer>
1696 // <identifier> ::= <unqualified source code identifier>
1697 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1698 << II->getName();
1699}
1700
1701void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1702 // <source-name> ::= <positive length number> <identifier>
1703 // <number> ::= [n] <non-negative decimal integer>
1704 // <identifier> ::= <unqualified source code identifier>
1705 Out << II->getLength() << II->getName();
1706}
1707
1708void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1709 const DeclContext *DC,
1710 const AbiTagList *AdditionalAbiTags,
1711 bool NoFunction) {
1712 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1713 // <nested-name>
1714 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1715 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1716 // <template-args> E
1717
1718 Out << 'N';
1719 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1720 Qualifiers MethodQuals = Method->getMethodQualifiers();
1721 // We do not consider restrict a distinguishing attribute for overloading
1722 // purposes so we must not mangle it.
1723 MethodQuals.removeRestrict();
1724 mangleQualifiers(MethodQuals);
1725 mangleRefQualifier(Method->getRefQualifier());
1726 }
1727
1728 // Check if we have a template.
1729 const TemplateArgumentList *TemplateArgs = nullptr;
1730 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1731 mangleTemplatePrefix(TD, NoFunction);
1732 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1733 } else {
1734 manglePrefix(DC, NoFunction);
1735 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1736 }
1737
1738 Out << 'E';
1739}
1740void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1742 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1743
1744 Out << 'N';
1745
1746 mangleTemplatePrefix(TD);
1747 mangleTemplateArgs(asTemplateName(TD), Args);
1748
1749 Out << 'E';
1750}
1751
1752void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1753 GlobalDecl GD, const NamedDecl *PrefixND,
1754 const AbiTagList *AdditionalAbiTags) {
1755 // A <closure-prefix> represents a variable or field, not a regular
1756 // DeclContext, so needs special handling. In this case we're mangling a
1757 // limited form of <nested-name>:
1758 //
1759 // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1760
1761 Out << 'N';
1762
1763 mangleClosurePrefix(PrefixND);
1764 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1765
1766 Out << 'E';
1767}
1768
1770 GlobalDecl GD;
1771 // The Itanium spec says:
1772 // For entities in constructors and destructors, the mangling of the
1773 // complete object constructor or destructor is used as the base function
1774 // name, i.e. the C1 or D1 version.
1775 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1776 GD = GlobalDecl(CD, Ctor_Complete);
1777 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1778 GD = GlobalDecl(DD, Dtor_Complete);
1779 else
1780 GD = GlobalDecl(cast<FunctionDecl>(DC));
1781 return GD;
1782}
1783
1784void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1785 const AbiTagList *AdditionalAbiTags) {
1786 const Decl *D = GD.getDecl();
1787 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1788 // := Z <function encoding> E s [<discriminator>]
1789 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1790 // _ <entity name>
1791 // <discriminator> := _ <non-negative number>
1792 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1793 const RecordDecl *RD = GetLocalClassDecl(D);
1794 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1795
1796 Out << 'Z';
1797
1798 {
1799 AbiTagState LocalAbiTags(AbiTags);
1800
1801 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1802 mangleObjCMethodName(MD);
1803 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1804 mangleBlockForPrefix(BD);
1805 else
1806 mangleFunctionEncoding(getParentOfLocalEntity(DC));
1807
1808 // Implicit ABI tags (from namespace) are not available in the following
1809 // entity; reset to actually emitted tags, which are available.
1810 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1811 }
1812
1813 Out << 'E';
1814
1815 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1816 // be a bug that is fixed in trunk.
1817
1818 if (RD) {
1819 // The parameter number is omitted for the last parameter, 0 for the
1820 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1821 // <entity name> will of course contain a <closure-type-name>: Its
1822 // numbering will be local to the particular argument in which it appears
1823 // -- other default arguments do not affect its encoding.
1824 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1825 if (CXXRD && CXXRD->isLambda()) {
1826 if (const ParmVarDecl *Parm
1827 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1828 if (const FunctionDecl *Func
1829 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1830 Out << 'd';
1831 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1832 if (Num > 1)
1833 mangleNumber(Num - 2);
1834 Out << '_';
1835 }
1836 }
1837 }
1838
1839 // Mangle the name relative to the closest enclosing function.
1840 // equality ok because RD derived from ND above
1841 if (D == RD) {
1842 mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1843 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1844 if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1845 mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1846 else
1847 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1848 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1849 mangleUnqualifiedBlock(BD);
1850 } else {
1851 const NamedDecl *ND = cast<NamedDecl>(D);
1852 mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1853 AdditionalAbiTags, true /*NoFunction*/);
1854 }
1855 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1856 // Mangle a block in a default parameter; see above explanation for
1857 // lambdas.
1858 if (const ParmVarDecl *Parm
1859 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1860 if (const FunctionDecl *Func
1861 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1862 Out << 'd';
1863 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1864 if (Num > 1)
1865 mangleNumber(Num - 2);
1866 Out << '_';
1867 }
1868 }
1869
1870 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1871 mangleUnqualifiedBlock(BD);
1872 } else {
1873 mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1874 }
1875
1876 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1877 unsigned disc;
1878 if (Context.getNextDiscriminator(ND, disc)) {
1879 if (disc < 10)
1880 Out << '_' << disc;
1881 else
1882 Out << "__" << disc << '_';
1883 }
1884 }
1885}
1886
1887void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1888 if (GetLocalClassDecl(Block)) {
1889 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1890 return;
1891 }
1892 const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1893 if (isLocalContainerContext(DC)) {
1894 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1895 return;
1896 }
1897 if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1898 mangleClosurePrefix(PrefixND);
1899 else
1900 manglePrefix(DC);
1901 mangleUnqualifiedBlock(Block);
1902}
1903
1904void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1905 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1906 // <data-member-prefix> now, with no substitutions and no <template-args>.
1907 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1908 if (getASTContext().getLangOpts().getClangABICompat() <=
1909 LangOptions::ClangABI::Ver12 &&
1910 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1911 Context->getDeclContext()->isRecord()) {
1912 const auto *ND = cast<NamedDecl>(Context);
1913 if (ND->getIdentifier()) {
1914 mangleSourceNameWithAbiTags(ND);
1915 Out << 'M';
1916 }
1917 }
1918 }
1919
1920 // If we have a block mangling number, use it.
1921 unsigned Number = Block->getBlockManglingNumber();
1922 // Otherwise, just make up a number. It doesn't matter what it is because
1923 // the symbol in question isn't externally visible.
1924 if (!Number)
1925 Number = Context.getBlockId(Block, false);
1926 else {
1927 // Stored mangling numbers are 1-based.
1928 --Number;
1929 }
1930 Out << "Ub";
1931 if (Number > 0)
1932 Out << Number - 1;
1933 Out << '_';
1934}
1935
1936// <template-param-decl>
1937// ::= Ty # template type parameter
1938// ::= Tn <type> # template non-type parameter
1939// ::= Tt <template-param-decl>* E # template template parameter
1940// ::= Tp <template-param-decl> # template parameter pack
1941void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1942 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1943 if (Ty->isParameterPack())
1944 Out << "Tp";
1945 Out << "Ty";
1946 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1947 if (Tn->isExpandedParameterPack()) {
1948 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1949 Out << "Tn";
1950 mangleType(Tn->getExpansionType(I));
1951 }
1952 } else {
1953 QualType T = Tn->getType();
1954 if (Tn->isParameterPack()) {
1955 Out << "Tp";
1956 if (auto *PackExpansion = T->getAs<PackExpansionType>())
1957 T = PackExpansion->getPattern();
1958 }
1959 Out << "Tn";
1960 mangleType(T);
1961 }
1962 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1963 if (Tt->isExpandedParameterPack()) {
1964 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1965 ++I) {
1966 Out << "Tt";
1967 for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1968 mangleTemplateParamDecl(Param);
1969 Out << "E";
1970 }
1971 } else {
1972 if (Tt->isParameterPack())
1973 Out << "Tp";
1974 Out << "Tt";
1975 for (auto *Param : *Tt->getTemplateParameters())
1976 mangleTemplateParamDecl(Param);
1977 Out << "E";
1978 }
1979 }
1980}
1981
1982void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1983 // When trying to be ABI-compatibility with clang 12 and before, mangle a
1984 // <data-member-prefix> now, with no substitutions.
1985 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1986 if (getASTContext().getLangOpts().getClangABICompat() <=
1987 LangOptions::ClangABI::Ver12 &&
1988 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1989 !isa<ParmVarDecl>(Context)) {
1990 if (const IdentifierInfo *Name
1991 = cast<NamedDecl>(Context)->getIdentifier()) {
1992 mangleSourceName(Name);
1993 const TemplateArgumentList *TemplateArgs = nullptr;
1994 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1995 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1996 Out << 'M';
1997 }
1998 }
1999 }
2000
2001 Out << "Ul";
2002 mangleLambdaSig(Lambda);
2003 Out << "E";
2004
2005 // The number is omitted for the first closure type with a given
2006 // <lambda-sig> in a given context; it is n-2 for the nth closure type
2007 // (in lexical order) with that same <lambda-sig> and context.
2008 //
2009 // The AST keeps track of the number for us.
2010 //
2011 // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2012 // and host-side compilations, an extra device mangle context may be created
2013 // if the host-side CXX ABI has different numbering for lambda. In such case,
2014 // if the mangle context is that device-side one, use the device-side lambda
2015 // mangling number for this lambda.
2016 std::optional<unsigned> DeviceNumber =
2017 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2018 unsigned Number =
2019 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2020
2021 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2022 if (Number > 1)
2023 mangleNumber(Number - 2);
2024 Out << '_';
2025}
2026
2027void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2028 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2029 mangleTemplateParamDecl(D);
2030 auto *Proto =
2032 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2033 Lambda->getLambdaStaticInvoker());
2034}
2035
2036void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2037 switch (qualifier->getKind()) {
2039 // nothing
2040 return;
2041
2043 llvm_unreachable("Can't mangle __super specifier");
2044
2046 mangleName(qualifier->getAsNamespace());
2047 return;
2048
2050 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2051 return;
2052
2055 manglePrefix(QualType(qualifier->getAsType(), 0));
2056 return;
2057
2059 // Clang 14 and before did not consider this substitutable.
2060 bool Clang14Compat = getASTContext().getLangOpts().getClangABICompat() <=
2061 LangOptions::ClangABI::Ver14;
2062 if (!Clang14Compat && mangleSubstitution(qualifier))
2063 return;
2064
2065 // Member expressions can have these without prefixes, but that
2066 // should end up in mangleUnresolvedPrefix instead.
2067 assert(qualifier->getPrefix());
2068 manglePrefix(qualifier->getPrefix());
2069
2070 mangleSourceName(qualifier->getAsIdentifier());
2071
2072 if (!Clang14Compat)
2073 addSubstitution(qualifier);
2074 return;
2075 }
2076
2077 llvm_unreachable("unexpected nested name specifier");
2078}
2079
2080void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2081 // <prefix> ::= <prefix> <unqualified-name>
2082 // ::= <template-prefix> <template-args>
2083 // ::= <closure-prefix>
2084 // ::= <template-param>
2085 // ::= # empty
2086 // ::= <substitution>
2087
2088 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2089
2090 if (DC->isTranslationUnit())
2091 return;
2092
2093 if (NoFunction && isLocalContainerContext(DC))
2094 return;
2095
2096 assert(!isLocalContainerContext(DC));
2097
2098 const NamedDecl *ND = cast<NamedDecl>(DC);
2099 if (mangleSubstitution(ND))
2100 return;
2101
2102 // Check if we have a template-prefix or a closure-prefix.
2103 const TemplateArgumentList *TemplateArgs = nullptr;
2104 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2105 mangleTemplatePrefix(TD);
2106 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2107 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2108 mangleClosurePrefix(PrefixND, NoFunction);
2109 mangleUnqualifiedName(ND, nullptr, nullptr);
2110 } else {
2111 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2112 manglePrefix(DC, NoFunction);
2113 mangleUnqualifiedName(ND, DC, nullptr);
2114 }
2115
2116 addSubstitution(ND);
2117}
2118
2119void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2120 // <template-prefix> ::= <prefix> <template unqualified-name>
2121 // ::= <template-param>
2122 // ::= <substitution>
2123 if (TemplateDecl *TD = Template.getAsTemplateDecl())
2124 return mangleTemplatePrefix(TD);
2125
2126 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2127 assert(Dependent && "unexpected template name kind");
2128
2129 // Clang 11 and before mangled the substitution for a dependent template name
2130 // after already having emitted (a substitution for) the prefix.
2131 bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
2132 LangOptions::ClangABI::Ver11;
2133 if (!Clang11Compat && mangleSubstitution(Template))
2134 return;
2135
2136 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2137 manglePrefix(Qualifier);
2138
2139 if (Clang11Compat && mangleSubstitution(Template))
2140 return;
2141
2142 if (const IdentifierInfo *Id = Dependent->getIdentifier())
2143 mangleSourceName(Id);
2144 else
2145 mangleOperatorName(Dependent->getOperator(), UnknownArity);
2146
2147 addSubstitution(Template);
2148}
2149
2150void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2151 bool NoFunction) {
2152 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2153 // <template-prefix> ::= <prefix> <template unqualified-name>
2154 // ::= <template-param>
2155 // ::= <substitution>
2156 // <template-template-param> ::= <template-param>
2157 // <substitution>
2158
2159 if (mangleSubstitution(ND))
2160 return;
2161
2162 // <template-template-param> ::= <template-param>
2163 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2164 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2165 } else {
2166 const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2167 manglePrefix(DC, NoFunction);
2168 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2169 mangleUnqualifiedName(GD, DC, nullptr);
2170 else
2171 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2172 nullptr);
2173 }
2174
2175 addSubstitution(ND);
2176}
2177
2178const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2179 if (getASTContext().getLangOpts().getClangABICompat() <=
2180 LangOptions::ClangABI::Ver12)
2181 return nullptr;
2182
2183 const NamedDecl *Context = nullptr;
2184 if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2185 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2186 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2187 if (RD->isLambda())
2188 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2189 }
2190 if (!Context)
2191 return nullptr;
2192
2193 // Only lambdas within the initializer of a non-local variable or non-static
2194 // data member get a <closure-prefix>.
2195 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2196 isa<FieldDecl>(Context))
2197 return Context;
2198
2199 return nullptr;
2200}
2201
2202void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2203 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2204 // ::= <template-prefix> <template-args> M
2205 if (mangleSubstitution(ND))
2206 return;
2207
2208 const TemplateArgumentList *TemplateArgs = nullptr;
2209 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2210 mangleTemplatePrefix(TD, NoFunction);
2211 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2212 } else {
2213 const auto *DC = Context.getEffectiveDeclContext(ND);
2214 manglePrefix(DC, NoFunction);
2215 mangleUnqualifiedName(ND, DC, nullptr);
2216 }
2217
2218 Out << 'M';
2219
2220 addSubstitution(ND);
2221}
2222
2223/// Mangles a template name under the production <type>. Required for
2224/// template template arguments.
2225/// <type> ::= <class-enum-type>
2226/// ::= <template-param>
2227/// ::= <substitution>
2228void CXXNameMangler::mangleType(TemplateName TN) {
2229 if (mangleSubstitution(TN))
2230 return;
2231
2232 TemplateDecl *TD = nullptr;
2233
2234 switch (TN.getKind()) {
2238 TD = TN.getAsTemplateDecl();
2239 goto HaveDecl;
2240
2241 HaveDecl:
2242 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2243 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2244 else
2245 mangleName(TD);
2246 break;
2247
2250 llvm_unreachable("can't mangle an overloaded template name as a <type>");
2251
2253 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2254 assert(Dependent->isIdentifier());
2255
2256 // <class-enum-type> ::= <name>
2257 // <name> ::= <nested-name>
2258 mangleUnresolvedPrefix(Dependent->getQualifier());
2259 mangleSourceName(Dependent->getIdentifier());
2260 break;
2261 }
2262
2264 // Substituted template parameters are mangled as the substituted
2265 // template. This will check for the substitution twice, which is
2266 // fine, but we have to return early so that we don't try to *add*
2267 // the substitution twice.
2270 mangleType(subst->getReplacement());
2271 return;
2272 }
2273
2275 // FIXME: not clear how to mangle this!
2276 // template <template <class> class T...> class A {
2277 // template <template <class> class U...> void foo(B<T,U> x...);
2278 // };
2279 Out << "_SUBSTPACK_";
2280 break;
2281 }
2282 }
2283
2284 addSubstitution(TN);
2285}
2286
2287bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2288 StringRef Prefix) {
2289 // Only certain other types are valid as prefixes; enumerate them.
2290 switch (Ty->getTypeClass()) {
2291 case Type::Builtin:
2292 case Type::Complex:
2293 case Type::Adjusted:
2294 case Type::Decayed:
2295 case Type::Pointer:
2296 case Type::BlockPointer:
2297 case Type::LValueReference:
2298 case Type::RValueReference:
2299 case Type::MemberPointer:
2300 case Type::ConstantArray:
2301 case Type::IncompleteArray:
2302 case Type::VariableArray:
2303 case Type::DependentSizedArray:
2304 case Type::DependentAddressSpace:
2305 case Type::DependentVector:
2306 case Type::DependentSizedExtVector:
2307 case Type::Vector:
2308 case Type::ExtVector:
2309 case Type::ConstantMatrix:
2310 case Type::DependentSizedMatrix:
2311 case Type::FunctionProto:
2312 case Type::FunctionNoProto:
2313 case Type::Paren:
2314 case Type::Attributed:
2315 case Type::BTFTagAttributed:
2316 case Type::Auto:
2317 case Type::DeducedTemplateSpecialization:
2318 case Type::PackExpansion:
2319 case Type::ObjCObject:
2320 case Type::ObjCInterface:
2321 case Type::ObjCObjectPointer:
2322 case Type::ObjCTypeParam:
2323 case Type::Atomic:
2324 case Type::Pipe:
2325 case Type::MacroQualified:
2326 case Type::BitInt:
2327 case Type::DependentBitInt:
2328 llvm_unreachable("type is illegal as a nested name specifier");
2329
2330 case Type::SubstTemplateTypeParmPack:
2331 // FIXME: not clear how to mangle this!
2332 // template <class T...> class A {
2333 // template <class U...> void foo(decltype(T::foo(U())) x...);
2334 // };
2335 Out << "_SUBSTPACK_";
2336 break;
2337
2338 // <unresolved-type> ::= <template-param>
2339 // ::= <decltype>
2340 // ::= <template-template-param> <template-args>
2341 // (this last is not official yet)
2342 case Type::TypeOfExpr:
2343 case Type::TypeOf:
2344 case Type::Decltype:
2345 case Type::TemplateTypeParm:
2346 case Type::UnaryTransform:
2347 case Type::SubstTemplateTypeParm:
2348 unresolvedType:
2349 // Some callers want a prefix before the mangled type.
2350 Out << Prefix;
2351
2352 // This seems to do everything we want. It's not really
2353 // sanctioned for a substituted template parameter, though.
2354 mangleType(Ty);
2355
2356 // We never want to print 'E' directly after an unresolved-type,
2357 // so we return directly.
2358 return true;
2359
2360 case Type::Typedef:
2361 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2362 break;
2363
2364 case Type::UnresolvedUsing:
2365 mangleSourceNameWithAbiTags(
2366 cast<UnresolvedUsingType>(Ty)->getDecl());
2367 break;
2368
2369 case Type::Enum:
2370 case Type::Record:
2371 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2372 break;
2373
2374 case Type::TemplateSpecialization: {
2375 const TemplateSpecializationType *TST =
2376 cast<TemplateSpecializationType>(Ty);
2377 TemplateName TN = TST->getTemplateName();
2378 switch (TN.getKind()) {
2382
2383 // If the base is a template template parameter, this is an
2384 // unresolved type.
2385 assert(TD && "no template for template specialization type");
2386 if (isa<TemplateTemplateParmDecl>(TD))
2387 goto unresolvedType;
2388
2389 mangleSourceNameWithAbiTags(TD);
2390 break;
2391 }
2392
2396 llvm_unreachable("invalid base for a template specialization type");
2397
2401 mangleExistingSubstitution(subst->getReplacement());
2402 break;
2403 }
2404
2406 // FIXME: not clear how to mangle this!
2407 // template <template <class U> class T...> class A {
2408 // template <class U...> void foo(decltype(T<U>::foo) x...);
2409 // };
2410 Out << "_SUBSTPACK_";
2411 break;
2412 }
2415 assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2416 mangleSourceNameWithAbiTags(TD);
2417 break;
2418 }
2419 }
2420
2421 // Note: we don't pass in the template name here. We are mangling the
2422 // original source-level template arguments, so we shouldn't consider
2423 // conversions to the corresponding template parameter.
2424 // FIXME: Other compilers mangle partially-resolved template arguments in
2425 // unresolved-qualifier-levels.
2426 mangleTemplateArgs(TemplateName(), TST->template_arguments());
2427 break;
2428 }
2429
2430 case Type::InjectedClassName:
2431 mangleSourceNameWithAbiTags(
2432 cast<InjectedClassNameType>(Ty)->getDecl());
2433 break;
2434
2435 case Type::DependentName:
2436 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2437 break;
2438
2439 case Type::DependentTemplateSpecialization: {
2441 cast<DependentTemplateSpecializationType>(Ty);
2442 TemplateName Template = getASTContext().getDependentTemplateName(
2443 DTST->getQualifier(), DTST->getIdentifier());
2444 mangleSourceName(DTST->getIdentifier());
2445 mangleTemplateArgs(Template, DTST->template_arguments());
2446 break;
2447 }
2448
2449 case Type::Using:
2450 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2451 Prefix);
2452 case Type::Elaborated:
2453 return mangleUnresolvedTypeOrSimpleId(
2454 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2455 }
2456
2457 return false;
2458}
2459
2460void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2461 switch (Name.getNameKind()) {
2470 llvm_unreachable("Not an operator name");
2471
2473 // <operator-name> ::= cv <type> # (cast)
2474 Out << "cv";
2475 mangleType(Name.getCXXNameType());
2476 break;
2477
2479 Out << "li";
2480 mangleSourceName(Name.getCXXLiteralIdentifier());
2481 return;
2482
2484 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2485 break;
2486 }
2487}
2488
2489void
2490CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2491 switch (OO) {
2492 // <operator-name> ::= nw # new
2493 case OO_New: Out << "nw"; break;
2494 // ::= na # new[]
2495 case OO_Array_New: Out << "na"; break;
2496 // ::= dl # delete
2497 case OO_Delete: Out << "dl"; break;
2498 // ::= da # delete[]
2499 case OO_Array_Delete: Out << "da"; break;
2500 // ::= ps # + (unary)
2501 // ::= pl # + (binary or unknown)
2502 case OO_Plus:
2503 Out << (Arity == 1? "ps" : "pl"); break;
2504 // ::= ng # - (unary)
2505 // ::= mi # - (binary or unknown)
2506 case OO_Minus:
2507 Out << (Arity == 1? "ng" : "mi"); break;
2508 // ::= ad # & (unary)
2509 // ::= an # & (binary or unknown)
2510 case OO_Amp:
2511 Out << (Arity == 1? "ad" : "an"); break;
2512 // ::= de # * (unary)
2513 // ::= ml # * (binary or unknown)
2514 case OO_Star:
2515 // Use binary when unknown.
2516 Out << (Arity == 1? "de" : "ml"); break;
2517 // ::= co # ~
2518 case OO_Tilde: Out << "co"; break;
2519 // ::= dv # /
2520 case OO_Slash: Out << "dv"; break;
2521 // ::= rm # %
2522 case OO_Percent: Out << "rm"; break;
2523 // ::= or # |
2524 case OO_Pipe: Out << "or"; break;
2525 // ::= eo # ^
2526 case OO_Caret: Out << "eo"; break;
2527 // ::= aS # =
2528 case OO_Equal: Out << "aS"; break;
2529 // ::= pL # +=
2530 case OO_PlusEqual: Out << "pL"; break;
2531 // ::= mI # -=
2532 case OO_MinusEqual: Out << "mI"; break;
2533 // ::= mL # *=
2534 case OO_StarEqual: Out << "mL"; break;
2535 // ::= dV # /=
2536 case OO_SlashEqual: Out << "dV"; break;
2537 // ::= rM # %=
2538 case OO_PercentEqual: Out << "rM"; break;
2539 // ::= aN # &=
2540 case OO_AmpEqual: Out << "aN"; break;
2541 // ::= oR # |=
2542 case OO_PipeEqual: Out << "oR"; break;
2543 // ::= eO # ^=
2544 case OO_CaretEqual: Out << "eO"; break;
2545 // ::= ls # <<
2546 case OO_LessLess: Out << "ls"; break;
2547 // ::= rs # >>
2548 case OO_GreaterGreater: Out << "rs"; break;
2549 // ::= lS # <<=
2550 case OO_LessLessEqual: Out << "lS"; break;
2551 // ::= rS # >>=
2552 case OO_GreaterGreaterEqual: Out << "rS"; break;
2553 // ::= eq # ==
2554 case OO_EqualEqual: Out << "eq"; break;
2555 // ::= ne # !=
2556 case OO_ExclaimEqual: Out << "ne"; break;
2557 // ::= lt # <
2558 case OO_Less: Out << "lt"; break;
2559 // ::= gt # >
2560 case OO_Greater: Out << "gt"; break;
2561 // ::= le # <=
2562 case OO_LessEqual: Out << "le"; break;
2563 // ::= ge # >=
2564 case OO_GreaterEqual: Out << "ge"; break;
2565 // ::= nt # !
2566 case OO_Exclaim: Out << "nt"; break;
2567 // ::= aa # &&
2568 case OO_AmpAmp: Out << "aa"; break;
2569 // ::= oo # ||
2570 case OO_PipePipe: Out << "oo"; break;
2571 // ::= pp # ++
2572 case OO_PlusPlus: Out << "pp"; break;
2573 // ::= mm # --
2574 case OO_MinusMinus: Out << "mm"; break;
2575 // ::= cm # ,
2576 case OO_Comma: Out << "cm"; break;
2577 // ::= pm # ->*
2578 case OO_ArrowStar: Out << "pm"; break;
2579 // ::= pt # ->
2580 case OO_Arrow: Out << "pt"; break;
2581 // ::= cl # ()
2582 case OO_Call: Out << "cl"; break;
2583 // ::= ix # []
2584 case OO_Subscript: Out << "ix"; break;
2585
2586 // ::= qu # ?
2587 // The conditional operator can't be overloaded, but we still handle it when
2588 // mangling expressions.
2589 case OO_Conditional: Out << "qu"; break;
2590 // Proposal on cxx-abi-dev, 2015-10-21.
2591 // ::= aw # co_await
2592 case OO_Coawait: Out << "aw"; break;
2593 // Proposed in cxx-abi github issue 43.
2594 // ::= ss # <=>
2595 case OO_Spaceship: Out << "ss"; break;
2596
2597 case OO_None:
2599 llvm_unreachable("Not an overloaded operator");
2600 }
2601}
2602
2603void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2604 // Vendor qualifiers come first and if they are order-insensitive they must
2605 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2606
2607 // <type> ::= U <addrspace-expr>
2608 if (DAST) {
2609 Out << "U2ASI";
2610 mangleExpression(DAST->getAddrSpaceExpr());
2611 Out << "E";
2612 }
2613
2614 // Address space qualifiers start with an ordinary letter.
2615 if (Quals.hasAddressSpace()) {
2616 // Address space extension:
2617 //
2618 // <type> ::= U <target-addrspace>
2619 // <type> ::= U <OpenCL-addrspace>
2620 // <type> ::= U <CUDA-addrspace>
2621
2622 SmallString<64> ASString;
2623 LangAS AS = Quals.getAddressSpace();
2624
2625 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2626 // <target-addrspace> ::= "AS" <address-space-number>
2627 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2628 if (TargetAS != 0 ||
2629 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2630 ASString = "AS" + llvm::utostr(TargetAS);
2631 } else {
2632 switch (AS) {
2633 default: llvm_unreachable("Not a language specific address space");
2634 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2635 // "private"| "generic" | "device" |
2636 // "host" ]
2637 case LangAS::opencl_global:
2638 ASString = "CLglobal";
2639 break;
2640 case LangAS::opencl_global_device:
2641 ASString = "CLdevice";
2642 break;
2643 case LangAS::opencl_global_host:
2644 ASString = "CLhost";
2645 break;
2646 case LangAS::opencl_local:
2647 ASString = "CLlocal";
2648 break;
2649 case LangAS::opencl_constant:
2650 ASString = "CLconstant";
2651 break;
2652 case LangAS::opencl_private:
2653 ASString = "CLprivate";
2654 break;
2655 case LangAS::opencl_generic:
2656 ASString = "CLgeneric";
2657 break;
2658 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2659 // "device" | "host" ]
2660 case LangAS::sycl_global:
2661 ASString = "SYglobal";
2662 break;
2663 case LangAS::sycl_global_device:
2664 ASString = "SYdevice";
2665 break;
2666 case LangAS::sycl_global_host:
2667 ASString = "SYhost";
2668 break;
2669 case LangAS::sycl_local:
2670 ASString = "SYlocal";
2671 break;
2672 case LangAS::sycl_private:
2673 ASString = "SYprivate";
2674 break;
2675 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2676 case LangAS::cuda_device:
2677 ASString = "CUdevice";
2678 break;
2679 case LangAS::cuda_constant:
2680 ASString = "CUconstant";
2681 break;
2682 case LangAS::cuda_shared:
2683 ASString = "CUshared";
2684 break;
2685 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2686 case LangAS::ptr32_sptr:
2687 ASString = "ptr32_sptr";
2688 break;
2689 case LangAS::ptr32_uptr:
2690 ASString = "ptr32_uptr";
2691 break;
2692 case LangAS::ptr64:
2693 ASString = "ptr64";
2694 break;
2695 }
2696 }
2697 if (!ASString.empty())
2698 mangleVendorQualifier(ASString);
2699 }
2700
2701 // The ARC ownership qualifiers start with underscores.
2702 // Objective-C ARC Extension:
2703 //
2704 // <type> ::= U "__strong"
2705 // <type> ::= U "__weak"
2706 // <type> ::= U "__autoreleasing"
2707 //
2708 // Note: we emit __weak first to preserve the order as
2709 // required by the Itanium ABI.
2711 mangleVendorQualifier("__weak");
2712
2713 // __unaligned (from -fms-extensions)
2714 if (Quals.hasUnaligned())
2715 mangleVendorQualifier("__unaligned");
2716
2717 // Remaining ARC ownership qualifiers.
2718 switch (Quals.getObjCLifetime()) {
2720 break;
2721
2723 // Do nothing as we already handled this case above.
2724 break;
2725
2727 mangleVendorQualifier("__strong");
2728 break;
2729
2731 mangleVendorQualifier("__autoreleasing");
2732 break;
2733
2735 // The __unsafe_unretained qualifier is *not* mangled, so that
2736 // __unsafe_unretained types in ARC produce the same manglings as the
2737 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2738 // better ABI compatibility.
2739 //
2740 // It's safe to do this because unqualified 'id' won't show up
2741 // in any type signatures that need to be mangled.
2742 break;
2743 }
2744
2745 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2746 if (Quals.hasRestrict())
2747 Out << 'r';
2748 if (Quals.hasVolatile())
2749 Out << 'V';
2750 if (Quals.hasConst())
2751 Out << 'K';
2752}
2753
2754void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2755 Out << 'U' << name.size() << name;
2756}
2757
2758void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2759 // <ref-qualifier> ::= R # lvalue reference
2760 // ::= O # rvalue-reference
2761 switch (RefQualifier) {
2762 case RQ_None:
2763 break;
2764
2765 case RQ_LValue:
2766 Out << 'R';
2767 break;
2768
2769 case RQ_RValue:
2770 Out << 'O';
2771 break;
2772 }
2773}
2774
2775void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2776 Context.mangleObjCMethodNameAsSourceName(MD, Out);
2777}
2778
2779static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2780 ASTContext &Ctx) {
2781 if (Quals)
2782 return true;
2783 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2784 return true;
2785 if (Ty->isOpenCLSpecificType())
2786 return true;
2787 if (Ty->isBuiltinType())
2788 return false;
2789 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2790 // substitution candidates.
2791 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2792 isa<AutoType>(Ty))
2793 return false;
2794 // A placeholder type for class template deduction is substitutable with
2795 // its corresponding template name; this is handled specially when mangling
2796 // the type.
2797 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2798 if (DeducedTST->getDeducedType().isNull())
2799 return false;
2800 return true;
2801}
2802
2803void CXXNameMangler::mangleType(QualType T) {
2804 // If our type is instantiation-dependent but not dependent, we mangle
2805 // it as it was written in the source, removing any top-level sugar.
2806 // Otherwise, use the canonical type.
2807 //
2808 // FIXME: This is an approximation of the instantiation-dependent name
2809 // mangling rules, since we should really be using the type as written and
2810 // augmented via semantic analysis (i.e., with implicit conversions and
2811 // default template arguments) for any instantiation-dependent type.
2812 // Unfortunately, that requires several changes to our AST:
2813 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2814 // uniqued, so that we can handle substitutions properly
2815 // - Default template arguments will need to be represented in the
2816 // TemplateSpecializationType, since they need to be mangled even though
2817 // they aren't written.
2818 // - Conversions on non-type template arguments need to be expressed, since
2819 // they can affect the mangling of sizeof/alignof.
2820 //
2821 // FIXME: This is wrong when mapping to the canonical type for a dependent
2822 // type discards instantiation-dependent portions of the type, such as for:
2823 //
2824 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2825 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2826 //
2827 // It's also wrong in the opposite direction when instantiation-dependent,
2828 // canonically-equivalent types differ in some irrelevant portion of inner
2829 // type sugar. In such cases, we fail to form correct substitutions, eg:
2830 //
2831 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2832 //
2833 // We should instead canonicalize the non-instantiation-dependent parts,
2834 // regardless of whether the type as a whole is dependent or instantiation
2835 // dependent.
2837 T = T.getCanonicalType();
2838 else {
2839 // Desugar any types that are purely sugar.
2840 do {
2841 // Don't desugar through template specialization types that aren't
2842 // type aliases. We need to mangle the template arguments as written.
2843 if (const TemplateSpecializationType *TST
2844 = dyn_cast<TemplateSpecializationType>(T))
2845 if (!TST->isTypeAlias())
2846 break;
2847
2848 // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2849 // instantation-dependent qualifiers. See
2850 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2851
2852 QualType Desugared
2853 = T.getSingleStepDesugaredType(Context.getASTContext());
2854 if (Desugared == T)
2855 break;
2856
2857 T = Desugared;
2858 } while (true);
2859 }
2860 SplitQualType split = T.split();
2861 Qualifiers quals = split.Quals;
2862 const Type *ty = split.Ty;
2863
2864 bool isSubstitutable =
2865 isTypeSubstitutable(quals, ty, Context.getASTContext());
2866 if (isSubstitutable && mangleSubstitution(T))
2867 return;
2868
2869 // If we're mangling a qualified array type, push the qualifiers to
2870 // the element type.
2871 if (quals && isa<ArrayType>(T)) {
2872 ty = Context.getASTContext().getAsArrayType(T);
2873 quals = Qualifiers();
2874
2875 // Note that we don't update T: we want to add the
2876 // substitution at the original type.
2877 }
2878
2879 if (quals || ty->isDependentAddressSpaceType()) {
2880 if (const DependentAddressSpaceType *DAST =
2881 dyn_cast<DependentAddressSpaceType>(ty)) {
2882 SplitQualType splitDAST = DAST->getPointeeType().split();
2883 mangleQualifiers(splitDAST.Quals, DAST);
2884 mangleType(QualType(splitDAST.Ty, 0));
2885 } else {
2886 mangleQualifiers(quals);
2887
2888 // Recurse: even if the qualified type isn't yet substitutable,
2889 // the unqualified type might be.
2890 mangleType(QualType(ty, 0));
2891 }
2892 } else {
2893 switch (ty->getTypeClass()) {
2894#define ABSTRACT_TYPE(CLASS, PARENT)
2895#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2896 case Type::CLASS: \
2897 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2898 return;
2899#define TYPE(CLASS, PARENT) \
2900 case Type::CLASS: \
2901 mangleType(static_cast<const CLASS##Type*>(ty)); \
2902 break;
2903#include "clang/AST/TypeNodes.inc"
2904 }
2905 }
2906
2907 // Add the substitution.
2908 if (isSubstitutable)
2909 addSubstitution(T);
2910}
2911
2912void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2913 if (!mangleStandardSubstitution(ND))
2914 mangleName(ND);
2915}
2916
2917void CXXNameMangler::mangleType(const BuiltinType *T) {
2918 // <type> ::= <builtin-type>
2919 // <builtin-type> ::= v # void
2920 // ::= w # wchar_t
2921 // ::= b # bool
2922 // ::= c # char
2923 // ::= a # signed char
2924 // ::= h # unsigned char
2925 // ::= s # short
2926 // ::= t # unsigned short
2927 // ::= i # int
2928 // ::= j # unsigned int
2929 // ::= l # long
2930 // ::= m # unsigned long
2931 // ::= x # long long, __int64
2932 // ::= y # unsigned long long, __int64
2933 // ::= n # __int128
2934 // ::= o # unsigned __int128
2935 // ::= f # float
2936 // ::= d # double
2937 // ::= e # long double, __float80
2938 // ::= g # __float128
2939 // ::= g # __ibm128
2940 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2941 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2942 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2943 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2944 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2945 // ::= Di # char32_t
2946 // ::= Ds # char16_t
2947 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2948 // ::= u <source-name> # vendor extended type
2949 std::string type_name;
2950 // Normalize integer types as vendor extended types:
2951 // u<length>i<type size>
2952 // u<length>u<type size>
2953 if (NormalizeIntegers && T->isInteger()) {
2954 if (T->isSignedInteger()) {
2955 switch (getASTContext().getTypeSize(T)) {
2956 case 8:
2957 // Pick a representative for each integer size in the substitution
2958 // dictionary. (Its actual defined size is not relevant.)
2959 if (mangleSubstitution(BuiltinType::SChar))
2960 break;
2961 Out << "u2i8";
2962 addSubstitution(BuiltinType::SChar);
2963 break;
2964 case 16:
2965 if (mangleSubstitution(BuiltinType::Short))
2966 break;
2967 Out << "u3i16";
2968 addSubstitution(BuiltinType::Short);
2969 break;
2970 case 32:
2971 if (mangleSubstitution(BuiltinType::Int))
2972 break;
2973 Out << "u3i32";
2974 addSubstitution(BuiltinType::Int);
2975 break;
2976 case 64:
2977 if (mangleSubstitution(BuiltinType::Long))
2978 break;
2979 Out << "u3i64";
2980 addSubstitution(BuiltinType::Long);
2981 break;
2982 case 128:
2983 if (mangleSubstitution(BuiltinType::Int128))
2984 break;
2985 Out << "u4i128";
2986 addSubstitution(BuiltinType::Int128);
2987 break;
2988 default:
2989 llvm_unreachable("Unknown integer size for normalization");
2990 }
2991 } else {
2992 switch (getASTContext().getTypeSize(T)) {
2993 case 8:
2994 if (mangleSubstitution(BuiltinType::UChar))
2995 break;
2996 Out << "u2u8";
2997 addSubstitution(BuiltinType::UChar);
2998 break;
2999 case 16:
3000 if (mangleSubstitution(BuiltinType::UShort))
3001 break;
3002 Out << "u3u16";
3003 addSubstitution(BuiltinType::UShort);
3004 break;
3005 case 32:
3006 if (mangleSubstitution(BuiltinType::UInt))
3007 break;
3008 Out << "u3u32";
3009 addSubstitution(BuiltinType::UInt);
3010 break;
3011 case 64:
3012 if (mangleSubstitution(BuiltinType::ULong))
3013 break;
3014 Out << "u3u64";
3015 addSubstitution(BuiltinType::ULong);
3016 break;
3017 case 128:
3018 if (mangleSubstitution(BuiltinType::UInt128))
3019 break;
3020 Out << "u4u128";
3021 addSubstitution(BuiltinType::UInt128);
3022 break;
3023 default:
3024 llvm_unreachable("Unknown integer size for normalization");
3025 }
3026 }
3027 return;
3028 }
3029 switch (T->getKind()) {
3030 case BuiltinType::Void:
3031 Out << 'v';
3032 break;
3033 case BuiltinType::Bool:
3034 Out << 'b';
3035 break;
3036 case BuiltinType::Char_U:
3037 case BuiltinType::Char_S:
3038 Out << 'c';
3039 break;
3040 case BuiltinType::UChar:
3041 Out << 'h';
3042 break;
3043 case BuiltinType::UShort:
3044 Out << 't';
3045 break;
3046 case BuiltinType::UInt:
3047 Out << 'j';
3048 break;
3049 case BuiltinType::ULong:
3050 Out << 'm';
3051 break;
3052 case BuiltinType::ULongLong:
3053 Out << 'y';
3054 break;
3055 case BuiltinType::UInt128:
3056 Out << 'o';
3057 break;
3058 case BuiltinType::SChar:
3059 Out << 'a';
3060 break;
3061 case BuiltinType::WChar_S:
3062 case BuiltinType::WChar_U:
3063 Out << 'w';
3064 break;
3065 case BuiltinType::Char8:
3066 Out << "Du";
3067 break;
3068 case BuiltinType::Char16:
3069 Out << "Ds";
3070 break;
3071 case BuiltinType::Char32:
3072 Out << "Di";
3073 break;
3074 case BuiltinType::Short:
3075 Out << 's';
3076 break;
3077 case BuiltinType::Int:
3078 Out << 'i';
3079 break;
3080 case BuiltinType::Long:
3081 Out << 'l';
3082 break;
3083 case BuiltinType::LongLong:
3084 Out << 'x';
3085 break;
3086 case BuiltinType::Int128:
3087 Out << 'n';
3088 break;
3089 case BuiltinType::Float16:
3090 Out << "DF16_";
3091 break;
3092 case BuiltinType::ShortAccum:
3093 case BuiltinType::Accum:
3094 case BuiltinType::LongAccum:
3095 case BuiltinType::UShortAccum:
3096 case BuiltinType::UAccum:
3097 case BuiltinType::ULongAccum:
3098 case BuiltinType::ShortFract:
3099 case BuiltinType::Fract:
3100 case BuiltinType::LongFract:
3101 case BuiltinType::UShortFract:
3102 case BuiltinType::UFract:
3103 case BuiltinType::ULongFract:
3104 case BuiltinType::SatShortAccum:
3105 case BuiltinType::SatAccum:
3106 case BuiltinType::SatLongAccum:
3107 case BuiltinType::SatUShortAccum:
3108 case BuiltinType::SatUAccum:
3109 case BuiltinType::SatULongAccum:
3110 case BuiltinType::SatShortFract:
3111 case BuiltinType::SatFract:
3112 case BuiltinType::SatLongFract:
3113 case BuiltinType::SatUShortFract:
3114 case BuiltinType::SatUFract:
3115 case BuiltinType::SatULongFract:
3116 llvm_unreachable("Fixed point types are disabled for c++");
3117 case BuiltinType::Half:
3118 Out << "Dh";
3119 break;
3120 case BuiltinType::Float:
3121 Out << 'f';
3122 break;
3123 case BuiltinType::Double:
3124 Out << 'd';
3125 break;
3126 case BuiltinType::LongDouble: {
3127 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3128 getASTContext().getLangOpts().OpenMPIsDevice
3129 ? getASTContext().getAuxTargetInfo()
3130 : &getASTContext().getTargetInfo();
3131 Out << TI->getLongDoubleMangling();
3132 break;
3133 }
3134 case BuiltinType::Float128: {
3135 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
3136 getASTContext().getLangOpts().OpenMPIsDevice
3137 ? getASTContext().getAuxTargetInfo()
3138 : &getASTContext().getTargetInfo();
3139 Out << TI->getFloat128Mangling();
3140 break;
3141 }
3142 case BuiltinType::BFloat16: {
3143 const TargetInfo *TI = ((getASTContext().getLangOpts().OpenMP &&
3144 getASTContext().getLangOpts().OpenMPIsDevice) ||
3145 getASTContext().getLangOpts().SYCLIsDevice)
3146 ? getASTContext().getAuxTargetInfo()
3147 : &getASTContext().getTargetInfo();
3148 Out << TI->getBFloat16Mangling();
3149 break;
3150 }
3151 case BuiltinType::Ibm128: {
3152 const TargetInfo *TI = &getASTContext().getTargetInfo();
3153 Out << TI->getIbm128Mangling();
3154 break;
3155 }
3156 case BuiltinType::NullPtr:
3157 Out << "Dn";
3158 break;
3159
3160#define BUILTIN_TYPE(Id, SingletonId)
3161#define PLACEHOLDER_TYPE(Id, SingletonId) \
3162 case BuiltinType::Id:
3163#include "clang/AST/BuiltinTypes.def"
3164 case BuiltinType::Dependent:
3165 if (!NullOut)
3166 llvm_unreachable("mangling a placeholder type");
3167 break;
3168 case BuiltinType::ObjCId:
3169 Out << "11objc_object";
3170 break;
3171 case BuiltinType::ObjCClass:
3172 Out << "10objc_class";
3173 break;
3174 case BuiltinType::ObjCSel:
3175 Out << "13objc_selector";
3176 break;
3177#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3178 case BuiltinType::Id: \
3179 type_name = "ocl_" #ImgType "_" #Suffix; \
3180 Out << type_name.size() << type_name; \
3181 break;
3182#include "clang/Basic/OpenCLImageTypes.def"
3183 case BuiltinType::OCLSampler:
3184 Out << "11ocl_sampler";
3185 break;
3186 case BuiltinType::OCLEvent:
3187 Out << "9ocl_event";
3188 break;
3189 case BuiltinType::OCLClkEvent:
3190 Out << "12ocl_clkevent";
3191 break;
3192 case BuiltinType::OCLQueue:
3193 Out << "9ocl_queue";
3194 break;
3195 case BuiltinType::OCLReserveID:
3196 Out << "13ocl_reserveid";
3197 break;
3198#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3199 case BuiltinType::Id: \
3200 type_name = "ocl_" #ExtType; \
3201 Out << type_name.size() << type_name; \
3202 break;
3203#include "clang/Basic/OpenCLExtensionTypes.def"
3204 // The SVE types are effectively target-specific. The mangling scheme
3205 // is defined in the appendices to the Procedure Call Standard for the
3206 // Arm Architecture.
3207#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
3208 ElBits, IsSigned, IsFP, IsBF) \
3209 case BuiltinType::Id: \
3210 type_name = MangledName; \
3211 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3212 << type_name; \
3213 break;
3214#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3215 case BuiltinType::Id: \
3216 type_name = MangledName; \
3217 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3218 << type_name; \
3219 break;
3220#define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \
3221 case BuiltinType::Id: \
3222 type_name = MangledName; \
3223 Out << (type_name == InternalName ? "u" : "") << type_name.size() \
3224 << type_name; \
3225 break;
3226#include "clang/Basic/AArch64SVEACLETypes.def"
3227#define PPC_VECTOR_TYPE(Name, Id, Size) \
3228 case BuiltinType::Id: \
3229 type_name = #Name; \
3230 Out << 'u' << type_name.size() << type_name; \
3231 break;
3232#include "clang/Basic/PPCTypes.def"
3233 // TODO: Check the mangling scheme for RISC-V V.
3234#define RVV_TYPE(Name, Id, SingletonId) \
3235 case BuiltinType::Id: \
3236 type_name = Name; \
3237 Out << 'u' << type_name.size() << type_name; \
3238 break;
3239#include "clang/Basic/RISCVVTypes.def"
3240#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \
3241 case BuiltinType::Id: \
3242 type_name = MangledName; \
3243 Out << 'u' << type_name.size() << type_name; \
3244 break;
3245#include "clang/Basic/WebAssemblyReferenceTypes.def"
3246 }
3247}
3248
3249StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3250 switch (CC) {
3251 case CC_C:
3252 return "";
3253
3254 case CC_X86VectorCall:
3255 case CC_X86Pascal:
3256 case CC_X86RegCall:
3257 case CC_AAPCS:
3258 case CC_AAPCS_VFP:
3260 case CC_AArch64SVEPCS:
3262 case CC_IntelOclBicc:
3263 case CC_SpirFunction:
3264 case CC_OpenCLKernel:
3265 case CC_PreserveMost:
3266 case CC_PreserveAll:
3267 // FIXME: we should be mangling all of the above.
3268 return "";
3269
3270 case CC_X86ThisCall:
3271 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3272 // used explicitly. At this point, we don't have that much information in
3273 // the AST, since clang tends to bake the convention into the canonical
3274 // function type. thiscall only rarely used explicitly, so don't mangle it
3275 // for now.
3276 return "";
3277
3278 case CC_X86StdCall:
3279 return "stdcall";
3280 case CC_X86FastCall:
3281 return "fastcall";
3282 case CC_X86_64SysV:
3283 return "sysv_abi";
3284 case CC_Win64:
3285 return "ms_abi";
3286 case CC_Swift:
3287 return "swiftcall";
3288 case CC_SwiftAsync:
3289 return "swiftasynccall";
3290 }
3291 llvm_unreachable("bad calling convention");
3292}
3293
3294void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3295 // Fast path.
3296 if (T->getExtInfo() == FunctionType::ExtInfo())
3297 return;
3298
3299 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3300 // This will get more complicated in the future if we mangle other
3301 // things here; but for now, since we mangle ns_returns_retained as
3302 // a qualifier on the result type, we can get away with this:
3303 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3304 if (!CCQualifier.empty())
3305 mangleVendorQualifier(CCQualifier);
3306
3307 // FIXME: regparm
3308 // FIXME: noreturn
3309}
3310
3311void
3312CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3313 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3314
3315 // Note that these are *not* substitution candidates. Demanglers might
3316 // have trouble with this if the parameter type is fully substituted.
3317
3318 switch (PI.getABI()) {
3319 case ParameterABI::Ordinary:
3320 break;
3321
3322 // All of these start with "swift", so they come before "ns_consumed".
3323 case ParameterABI::SwiftContext:
3324 case ParameterABI::SwiftAsyncContext:
3325 case ParameterABI::SwiftErrorResult:
3326 case ParameterABI::SwiftIndirectResult:
3327 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3328 break;
3329 }
3330
3331 if (PI.isConsumed())
3332 mangleVendorQualifier("ns_consumed");
3333
3334 if (PI.isNoEscape())
3335 mangleVendorQualifier("noescape");
3336}
3337
3338// <type> ::= <function-type>
3339// <function-type> ::= [<CV-qualifiers>] F [Y]
3340// <bare-function-type> [<ref-qualifier>] E
3341void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3342 mangleExtFunctionInfo(T);
3343
3344 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
3345 // e.g. "const" in "int (A::*)() const".
3346 mangleQualifiers(T->getMethodQuals());
3347
3348 // Mangle instantiation-dependent exception-specification, if present,
3349 // per cxx-abi-dev proposal on 2016-10-11.
3352 Out << "DO";
3353 mangleExpression(T->getNoexceptExpr());
3354 Out << "E";
3355 } else {
3356 assert(T->getExceptionSpecType() == EST_Dynamic);
3357 Out << "Dw";
3358 for (auto ExceptTy : T->exceptions())
3359 mangleType(ExceptTy);
3360 Out << "E";
3361 }
3362 } else if (T->isNothrow()) {
3363 Out << "Do";
3364 }
3365
3366 Out << 'F';
3367
3368 // FIXME: We don't have enough information in the AST to produce the 'Y'
3369 // encoding for extern "C" function types.
3370 mangleBareFunctionType(T, /*MangleReturnType=*/true);
3371
3372 // Mangle the ref-qualifier, if present.
3373 mangleRefQualifier(T->getRefQualifier());
3374
3375 Out << 'E';
3376}
3377
3378void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3379 // Function types without prototypes can arise when mangling a function type
3380 // within an overloadable function in C. We mangle these as the absence of any
3381 // parameter types (not even an empty parameter list).
3382 Out << 'F';
3383
3384 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3385
3386 FunctionTypeDepth.enterResultType();
3387 mangleType(T->getReturnType());
3388 FunctionTypeDepth.leaveResultType();
3389
3390 FunctionTypeDepth.pop(saved);
3391 Out << 'E';
3392}
3393
3394void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3395 bool MangleReturnType,
3396 const FunctionDecl *FD) {
3397 // Record that we're in a function type. See mangleFunctionParam
3398 // for details on what we're trying to achieve here.
3399 FunctionTypeDepthState saved = FunctionTypeDepth.push();
3400
3401 // <bare-function-type> ::= <signature type>+
3402 if (MangleReturnType) {
3403 FunctionTypeDepth.enterResultType();
3404
3405 // Mangle ns_returns_retained as an order-sensitive qualifier here.
3406 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3407 mangleVendorQualifier("ns_returns_retained");
3408
3409 // Mangle the return type without any direct ARC ownership qualifiers.
3410 QualType ReturnTy = Proto->getReturnType();
3411 if (ReturnTy.getObjCLifetime()) {
3412 auto SplitReturnTy = ReturnTy.split();
3413 SplitReturnTy.Quals.removeObjCLifetime();
3414 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3415 }
3416 mangleType(ReturnTy);
3417
3418 FunctionTypeDepth.leaveResultType();
3419 }
3420
3421 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3422 // <builtin-type> ::= v # void
3423 Out << 'v';
3424
3425 FunctionTypeDepth.pop(saved);
3426 return;
3427 }
3428
3429 assert(!FD || FD->getNumParams() == Proto->getNumParams());
3430 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3431 // Mangle extended parameter info as order-sensitive qualifiers here.
3432 if (Proto->hasExtParameterInfos() && FD == nullptr) {
3433 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3434 }
3435
3436 // Mangle the type.
3437 QualType ParamTy = Proto->getParamType(I);
3438 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3439
3440 if (FD) {
3441 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3442 // Attr can only take 1 character, so we can hardcode the length below.
3443 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3444 if (Attr->isDynamic())
3445 Out << "U25pass_dynamic_object_size" << Attr->getType();
3446 else
3447 Out << "U17pass_object_size" << Attr->getType();
3448 }
3449 }
3450 }
3451
3452 FunctionTypeDepth.pop(saved);
3453
3454 // <builtin-type> ::= z # ellipsis
3455 if (Proto->isVariadic())
3456 Out << 'z';
3457}
3458
3459// <type> ::= <class-enum-type>
3460// <class-enum-type> ::= <name>
3461void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3462 mangleName(T->getDecl());
3463}
3464
3465// <type> ::= <class-enum-type>
3466// <class-enum-type> ::= <name>
3467void CXXNameMangler::mangleType(const EnumType *T) {
3468 mangleType(static_cast<const TagType*>(T));
3469}
3470void CXXNameMangler::mangleType(const RecordType *T) {
3471 mangleType(static_cast<const TagType*>(T));
3472}
3473void CXXNameMangler::mangleType(const TagType *T) {
3474 mangleName(T->getDecl());
3475}
3476
3477// <type> ::= <array-type>
3478// <array-type> ::= A <positive dimension number> _ <element type>
3479// ::= A [<dimension expression>] _ <element type>
3480void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3481 Out << 'A' << T->getSize() << '_';
3482 mangleType(T->getElementType());
3483}
3484void CXXNameMangler::mangleType(const VariableArrayType *T) {
3485 Out << 'A';
3486 // decayed vla types (size 0) will just be skipped.
3487 if (T->getSizeExpr())
3488 mangleExpression(T->getSizeExpr());
3489 Out << '_';
3490 mangleType(T->getElementType());
3491}
3492void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3493 Out << 'A';
3494 // A DependentSizedArrayType might not have size expression as below
3495 //
3496 // template<int ...N> int arr[] = {N...};
3497 if (T->getSizeExpr())
3498 mangleExpression(T->getSizeExpr());
3499 Out << '_';
3500 mangleType(T->getElementType());
3501}
3502void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3503 Out << "A_";
3504 mangleType(T->getElementType());
3505}
3506
3507// <type> ::= <pointer-to-member-type>
3508// <pointer-to-member-type> ::= M <class type> <member type>
3509void CXXNameMangler::mangleType(const MemberPointerType *T) {
3510 Out << 'M';
3511 mangleType(QualType(T->getClass(), 0));
3512 QualType PointeeType = T->getPointeeType();
3513 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3514 mangleType(FPT);
3515
3516 // Itanium C++ ABI 5.1.8:
3517 //
3518 // The type of a non-static member function is considered to be different,
3519 // for the purposes of substitution, from the type of a namespace-scope or
3520 // static member function whose type appears similar. The types of two
3521 // non-static member functions are considered to be different, for the
3522 // purposes of substitution, if the functions are members of different
3523 // classes. In other words, for the purposes of substitution, the class of
3524 // which the function is a member is considered part of the type of
3525 // function.
3526
3527 // Given that we already substitute member function pointers as a
3528 // whole, the net effect of this rule is just to unconditionally
3529 // suppress substitution on the function type in a member pointer.
3530 // We increment the SeqID here to emulate adding an entry to the
3531 // substitution table.
3532 ++SeqID;
3533 } else
3534 mangleType(PointeeType);
3535}
3536
3537// <type> ::= <template-param>
3538void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3539 mangleTemplateParameter(T->getDepth(), T->getIndex());
3540}
3541
3542// <type> ::= <template-param>
3543void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3544 // FIXME: not clear how to mangle this!
3545 // template <class T...> class A {
3546 // template <class U...> void foo(T(*)(U) x...);
3547 // };
3548 Out << "_SUBSTPACK_";
3549}
3550
3551// <type> ::= P <type> # pointer-to
3552void CXXNameMangler::mangleType(const PointerType *T) {
3553 Out << 'P';
3554 mangleType(T->getPointeeType());
3555}
3556void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3557 Out << 'P';
3558 mangleType(T->getPointeeType());
3559}
3560
3561// <type> ::= R <type> # reference-to
3562void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3563 Out << 'R';
3564 mangleType(T->getPointeeType());
3565}
3566
3567// <type> ::= O <type> # rvalue reference-to (C++0x)
3568void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3569 Out << 'O';
3570 mangleType(T->getPointeeType());
3571}
3572
3573// <type> ::= C <type> # complex pair (C 2000)
3574void CXXNameMangler::mangleType(const ComplexType *T) {
3575 Out << 'C';
3576 mangleType(T->getElementType());
3577}
3578
3579// ARM's ABI for Neon vector types specifies that they should be mangled as
3580// if they are structs (to match ARM's initial implementation). The
3581// vector type must be one of the special types predefined by ARM.
3582void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3583 QualType EltType = T->getElementType();
3584 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3585 const char *EltName = nullptr;
3587 switch (cast<BuiltinType>(EltType)->getKind()) {
3588 case BuiltinType::SChar:
3589 case BuiltinType::UChar:
3590 EltName = "poly8_t";
3591 break;
3592 case BuiltinType::Short:
3593 case BuiltinType::UShort:
3594 EltName = "poly16_t";
3595 break;
3596 case BuiltinType::LongLong:
3597 case BuiltinType::ULongLong:
3598 EltName = "poly64_t";
3599 break;
3600 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3601 }
3602 } else {
3603 switch (cast<BuiltinType>(EltType)->getKind()) {
3604 case BuiltinType::SChar: EltName = "int8_t"; break;
3605 case BuiltinType::UChar: EltName = "uint8_t"; break;
3606 case BuiltinType::Short: EltName = "int16_t"; break;
3607 case BuiltinType::UShort: EltName = "uint16_t"; break;
3608 case BuiltinType::Int: EltName = "int32_t"; break;
3609 case BuiltinType::UInt: EltName = "uint32_t"; break;
3610 case BuiltinType::LongLong: EltName = "int64_t"; break;
3611 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3612 case BuiltinType::Double: EltName = "float64_t"; break;
3613 case BuiltinType::Float: EltName = "float32_t"; break;
3614 case BuiltinType::Half: EltName = "float16_t"; break;
3615 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3616 default:
3617 llvm_unreachable("unexpected Neon vector element type");
3618 }
3619 }
3620 const char *BaseName = nullptr;
3621 unsigned BitSize = (T->getNumElements() *
3622 getASTContext().getTypeSize(EltType));
3623 if (BitSize == 64)
3624 BaseName = "__simd64_";
3625 else {
3626 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3627 BaseName = "__simd128_";
3628 }
3629 Out << strlen(BaseName) + strlen(EltName);
3630 Out << BaseName << EltName;
3631}
3632
3633void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3634 DiagnosticsEngine &Diags = Context.getDiags();
3635 unsigned DiagID = Diags.getCustomDiagID(
3637 "cannot mangle this dependent neon vector type yet");
3638 Diags.Report(T->getAttributeLoc(), DiagID);
3639}
3640
3641static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3642 switch (EltType->getKind()) {
3643 case BuiltinType::SChar:
3644 return "Int8";
3645 case BuiltinType::Short:
3646 return "Int16";
3647 case BuiltinType::Int:
3648 return "Int32";
3649 case BuiltinType::Long:
3650 case BuiltinType::LongLong:
3651 return "Int64";
3652 case BuiltinType::UChar:
3653 return "Uint8";
3654 case BuiltinType::UShort:
3655 return "Uint16";
3656 case BuiltinType::UInt:
3657 return "Uint32";
3658 case BuiltinType::ULong:
3659 case BuiltinType::ULongLong:
3660 return "Uint64";
3661 case BuiltinType::Half:
3662 return "Float16";
3663 case BuiltinType::Float:
3664 return "Float32";
3665 case BuiltinType::Double:
3666 return "Float64";
3667 case BuiltinType::BFloat16:
3668 return "Bfloat16";
3669 default:
3670 llvm_unreachable("Unexpected vector element base type");
3671 }
3672}
3673
3674// AArch64's ABI for Neon vector types specifies that they should be mangled as
3675// the equivalent internal name. The vector type must be one of the special
3676// types predefined by ARM.
3677void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3678 QualType EltType = T->getElementType();
3679 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3680 unsigned BitSize =
3681 (T->getNumElements() * getASTContext().getTypeSize(EltType));
3682 (void)BitSize; // Silence warning.
3683
3684 assert((BitSize == 64 || BitSize == 128) &&
3685 "Neon vector type not 64 or 128 bits");
3686
3687 StringRef EltName;
3689 switch (cast<BuiltinType>(EltType)->getKind()) {
3690 case BuiltinType::UChar:
3691 EltName = "Poly8";
3692 break;
3693 case BuiltinType::UShort:
3694 EltName = "Poly16";
3695 break;
3696 case BuiltinType::ULong:
3697 case BuiltinType::ULongLong:
3698 EltName = "Poly64";
3699 break;
3700 default:
3701 llvm_unreachable("unexpected Neon polynomial vector element type");
3702 }
3703 } else
3704 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3705
3706 std::string TypeName =
3707 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3708 Out << TypeName.length() << TypeName;
3709}
3710void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3711 DiagnosticsEngine &Diags = Context.getDiags();
3712 unsigned DiagID = Diags.getCustomDiagID(
3714 "cannot mangle this dependent neon vector type yet");
3715 Diags.Report(T->getAttributeLoc(), DiagID);
3716}
3717
3718// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3719// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3720// type as the sizeless variants.
3721//
3722// The mangling scheme for VLS types is implemented as a "pseudo" template:
3723//
3724// '__SVE_VLS<<type>, <vector length>>'
3725//
3726// Combining the existing SVE type and a specific vector length (in bits).
3727// For example:
3728//
3729// typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3730//
3731// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3732//
3733// "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3734//
3735// i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3736//
3737// The latest ACLE specification (00bet5) does not contain details of this
3738// mangling scheme, it will be specified in the next revision. The mangling
3739// scheme is otherwise defined in the appendices to the Procedure Call Standard
3740// for the Arm Architecture, see
3741// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3742void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3745 "expected fixed-length SVE vector!");
3746
3747 QualType EltType = T->getElementType();
3748 assert(EltType->isBuiltinType() &&
3749 "expected builtin type for fixed-length SVE vector!");
3750
3751 StringRef TypeName;
3752 switch (cast<BuiltinType>(EltType)->getKind()) {
3753 case BuiltinType::SChar:
3754 TypeName = "__SVInt8_t";
3755 break;
3756 case BuiltinType::UChar: {
3758 TypeName = "__SVUint8_t";
3759 else
3760 TypeName = "__SVBool_t";
3761 break;
3762 }
3763 case BuiltinType::Short:
3764 TypeName = "__SVInt16_t";
3765 break;
3766 case BuiltinType::UShort:
3767 TypeName = "__SVUint16_t";
3768 break;
3769 case BuiltinType::Int:
3770 TypeName = "__SVInt32_t";
3771 break;
3772 case BuiltinType::UInt:
3773 TypeName = "__SVUint32_t";
3774 break;
3775 case BuiltinType::Long:
3776 TypeName = "__SVInt64_t";
3777 break;
3778 case BuiltinType::ULong:
3779 TypeName = "__SVUint64_t";
3780 break;
3781 case BuiltinType::Half:
3782 TypeName = "__SVFloat16_t";
3783 break;
3784 case BuiltinType::Float:
3785 TypeName = "__SVFloat32_t";
3786 break;
3787 case BuiltinType::Double:
3788 TypeName = "__SVFloat64_t";
3789 break;
3790 case BuiltinType::BFloat16:
3791 TypeName = "__SVBfloat16_t";
3792 break;
3793 default:
3794 llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3795 }
3796
3797 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3798
3800 VecSizeInBits *= 8;
3801
3802 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3803 << VecSizeInBits << "EE";
3804}
3805
3806void CXXNameMangler::mangleAArch64FixedSveVectorType(
3807 const DependentVectorType *T) {
3808 DiagnosticsEngine &Diags = Context.getDiags();
3809 unsigned DiagID = Diags.getCustomDiagID(
3811 "cannot mangle this dependent fixed-length SVE vector type yet");
3812 Diags.Report(T->getAttributeLoc(), DiagID);
3813}
3814
3815// GNU extension: vector types
3816// <type> ::= <vector-type>
3817// <vector-type> ::= Dv <positive dimension number> _
3818// <extended element type>
3819// ::= Dv [<dimension expression>] _ <element type>
3820// <extended element type> ::= <element type>
3821// ::= p # AltiVec vector pixel
3822// ::= b # Altivec vector bool
3823void CXXNameMangler::mangleType(const VectorType *T) {
3826 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3827 llvm::Triple::ArchType Arch =
3828 getASTContext().getTargetInfo().getTriple().getArch();
3829 if ((Arch == llvm::Triple::aarch64 ||
3830 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3831 mangleAArch64NeonVectorType(T);
3832 else
3833 mangleNeonVectorType(T);
3834 return;
3837 mangleAArch64FixedSveVectorType(T);
3838 return;
3839 }
3840 Out << "Dv" << T->getNumElements() << '_';
3842 Out << 'p';
3843 else if (T->getVectorKind() == VectorType::AltiVecBool)
3844 Out << 'b';
3845 else
3846 mangleType(T->getElementType());
3847}
3848
3849void CXXNameMangler::mangleType(const DependentVectorType *T) {
3852 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3853 llvm::Triple::ArchType Arch =
3854 getASTContext().getTargetInfo().getTriple().getArch();
3855 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3856 !Target.isOSDarwin())
3857 mangleAArch64NeonVectorType(T);
3858 else
3859 mangleNeonVectorType(T);
3860 return;
3863 mangleAArch64FixedSveVectorType(T);
3864 return;
3865 }
3866
3867 Out << "Dv";
3868 mangleExpression(T->getSizeExpr());
3869 Out << '_';
3871 Out << 'p';
3872 else if (T->getVectorKind() == VectorType::AltiVecBool)
3873 Out << 'b';
3874 else
3875 mangleType(T->getElementType());
3876}
3877
3878void CXXNameMangler::mangleType(const ExtVectorType *T) {
3879 mangleType(static_cast<const VectorType*>(T));
3880}
3881void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3882 Out << "Dv";
3883 mangleExpression(T->getSizeExpr());
3884 Out << '_';
3885 mangleType(T->getElementType());
3886}
3887
3888void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
3889 // Mangle matrix types as a vendor extended type:
3890 // u<Len>matrix_typeI<Rows><Columns><element type>E
3891
3892 StringRef VendorQualifier = "matrix_type";
3893 Out << "u" << VendorQualifier.size() << VendorQualifier;
3894
3895 Out << "I";
3896 auto &ASTCtx = getASTContext();
3897 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
3898 llvm::APSInt Rows(BitWidth);
3899 Rows = T->getNumRows();
3900 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
3901 llvm::APSInt Columns(BitWidth);
3902 Columns = T->getNumColumns();
3903 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
3904 mangleType(T->getElementType());
3905 Out << "E";
3906}
3907
3908void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
3909 // Mangle matrix types as a vendor extended type:
3910 // u<Len>matrix_typeI<row expr><column expr><element type>E
3911 StringRef VendorQualifier = "matrix_type";
3912 Out << "u" << VendorQualifier.size() << VendorQualifier;
3913
3914 Out << "I";
3915 mangleTemplateArgExpr(T->getRowExpr());
3916 mangleTemplateArgExpr(T->getColumnExpr());
3917 mangleType(T->getElementType());
3918 Out << "E";
3919}
3920
3921void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3922 SplitQualType split = T->getPointeeType().split();
3923 mangleQualifiers(split.Quals, T);
3924 mangleType(QualType(split.Ty, 0));
3925}
3926
3927void CXXNameMangler::mangleType(const PackExpansionType *T) {
3928 // <type> ::= Dp <type> # pack expansion (C++0x)
3929 Out << "Dp";
3930 mangleType(T->getPattern());
3931}
3932
3933void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3934 mangleSourceName(T->getDecl()->getIdentifier());
3935}
3936
3937void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3938 // Treat __kindof as a vendor extended type qualifier.
3939 if (T->isKindOfType())
3940 Out << "U8__kindof";
3941
3942 if (!T->qual_empty()) {
3943 // Mangle protocol qualifiers.
3944 SmallString<64> QualStr;
3945 llvm::raw_svector_ostream QualOS(QualStr);
3946 QualOS << "objcproto";
3947 for (const auto *I : T->quals()) {
3948 StringRef name = I->getName();
3949 QualOS << name.size() << name;
3950 }
3951 Out << 'U' << QualStr.size() << QualStr;
3952 }
3953
3954 mangleType(T->getBaseType());
3955
3956 if (T->isSpecialized()) {
3957 // Mangle type arguments as I <type>+ E
3958 Out << 'I';
3959 for (auto typeArg : T->getTypeArgs())
3960 mangleType(typeArg);
3961 Out << 'E';
3962 }
3963}
3964
3965void CXXNameMangler::mangleType(const BlockPointerType *T) {
3966 Out << "U13block_pointer";
3967 mangleType(T->getPointeeType());
3968}
3969
3970void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3971 // Mangle injected class name types as if the user had written the
3972 // specialization out fully. It may not actually be possible to see
3973 // this mangling, though.
3974 mangleType(T->getInjectedSpecializationType());
3975}
3976
3977void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3979 mangleTemplateName(TD, T->template_arguments());
3980 } else {
3981 if (mangleSubstitution(QualType(T, 0)))
3982 return;
3983
3984 mangleTemplatePrefix(T->getTemplateName());
3985
3986 // FIXME: GCC does not appear to mangle the template arguments when
3987 // the template in question is a dependent template name. Should we
3988 // emulate that badness?
3989 mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
3990 addSubstitution(QualType(T, 0));
3991 }
3992}
3993
3994void CXXNameMangler::mangleType(const DependentNameType *T) {
3995 // Proposal by cxx-abi-dev, 2014-03-26
3996 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3997 // # dependent elaborated type specifier using
3998 // # 'typename'
3999 // ::= Ts <name> # dependent elaborated type specifier using
4000 // # 'struct' or 'class'
4001 // ::= Tu <name> # dependent elaborated type specifier using
4002 // # 'union'
4003 // ::= Te <name> # dependent elaborated type specifier using
4004 // # 'enum'
4005 switch (T->getKeyword()) {
4006 case ETK_None:
4007 case ETK_Typename:
4008 break;
4009 case ETK_Struct:
4010 case ETK_Class:
4011 case ETK_Interface:
4012 Out << "Ts";
4013 break;
4014 case ETK_Union:
4015 Out << "Tu";
4016 break;
4017 case ETK_Enum:
4018 Out << "Te";
4019 break;
4020 }
4021 // Typename types are always nested
4022 Out << 'N';
4023 manglePrefix(T->getQualifier());
4024 mangleSourceName(T->getIdentifier());
4025 Out << 'E';
4026}
4027
4028void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4029 // Dependently-scoped template types are nested if they have a prefix.
4030 Out << 'N';
4031
4032 // TODO: avoid making this TemplateName.
4033 TemplateName Prefix =
4034 getASTContext().getDependentTemplateName(T->getQualifier(),
4035 T->getIdentifier());
4036 mangleTemplatePrefix(Prefix);
4037
4038 // FIXME: GCC does not appear to mangle the template arguments when
4039 // the template in question is a dependent template name. Should we
4040 // emulate that badness?
4041 mangleTemplateArgs(Prefix, T->template_arguments());
4042 Out << 'E';
4043}
4044
4045void CXXNameMangler::mangleType(const TypeOfType *T) {
4046 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4047 // "extension with parameters" mangling.
4048 Out << "u6typeof";
4049}
4050
4051void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4052 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4053 // "extension with parameters" mangling.
4054 Out << "u6typeof";
4055}
4056
4057void CXXNameMangler::mangleType(const DecltypeType *T) {
4058 Expr *E = T->getUnderlyingExpr();
4059
4060 // type ::= Dt <expression> E # decltype of an id-expression
4061 // # or class member access
4062 // ::= DT <expression> E # decltype of an expression
4063
4064 // This purports to be an exhaustive list of id-expressions and
4065 // class member accesses. Note that we do not ignore parentheses;
4066 // parentheses change the semantics of decltype for these
4067 // expressions (and cause the mangler to use the other form).
4068 if (isa<DeclRefExpr>(E) ||
4069 isa<MemberExpr>(E) ||
4070 isa<UnresolvedLookupExpr>(E) ||
4071 isa<DependentScopeDeclRefExpr>(E) ||
4072 isa<CXXDependentScopeMemberExpr>(E) ||
4073 isa<UnresolvedMemberExpr>(E))
4074 Out << "Dt";
4075 else
4076 Out << "DT";
4077 mangleExpression(E);
4078 Out << 'E';
4079}
4080
4081void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4082 // If this is dependent, we need to record that. If not, we simply
4083 // mangle it as the underlying type since they are equivalent.
4084 if (T->isDependentType()) {
4085 Out << "u";
4086
4087 StringRef BuiltinName;
4088 switch (T->getUTTKind()) {
4089#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
4090 case UnaryTransformType::Enum: \
4091 BuiltinName = "__" #Trait; \
4092 break;
4093#include "clang/Basic/TransformTypeTraits.def"
4094 }
4095 Out << BuiltinName.size() << BuiltinName;
4096 }
4097
4098 Out << "I";
4099 mangleType(T->getBaseType());
4100 Out << "E";
4101}
4102
4103void CXXNameMangler::mangleType(const AutoType *T) {
4104 assert(T->getDeducedType().isNull() &&
4105 "Deduced AutoType shouldn't be handled here!");
4106 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4107 "shouldn't need to mangle __auto_type!");
4108 // <builtin-type> ::= Da # auto
4109 // ::= Dc # decltype(auto)
4110 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4111}
4112
4113void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4114 QualType Deduced = T->getDeducedType();
4115 if (!Deduced.isNull())
4116 return mangleType(Deduced);
4117
4119 assert(TD && "shouldn't form deduced TST unless we know we have a template");
4120
4121 if (mangleSubstitution(TD))
4122 return;
4123
4124 mangleName(GlobalDecl(TD));
4125 addSubstitution(TD);
4126}
4127
4128void CXXNameMangler::mangleType(const AtomicType *T) {
4129 // <type> ::= U <source-name> <type> # vendor extended type qualifier
4130 // (Until there's a standardized mangling...)
4131 Out << "U7_Atomic";
4132 mangleType(T->getValueType());
4133}
4134
4135void CXXNameMangler::mangleType(const PipeType *T) {
4136 // Pipe type mangling rules are described in SPIR 2.0 specification
4137 // A.1 Data types and A.3 Summary of changes
4138 // <type> ::= 8ocl_pipe
4139 Out << "8ocl_pipe";
4140}
4141
4142void CXXNameMangler::mangleType(const BitIntType *T) {
4143 // 5.1.5.2 Builtin types
4144 // <type> ::= DB <number | instantiation-dependent expression> _
4145 // ::= DU <number | instantiation-dependent expression> _
4146 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4147}
4148
4149void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4150 // 5.1.5.2 Builtin types
4151 // <type> ::= DB <number | instantiation-dependent expression> _
4152 // ::= DU <number | instantiation-dependent expression> _
4153 Out << "D" << (T->isUnsigned() ? "U" : "B");
4154 mangleExpression(T->getNumBitsExpr());
4155 Out << "_";
4156}
4157
4158void CXXNameMangler::mangleIntegerLiteral(QualType T,
4159 const llvm::APSInt &Value) {
4160 // <expr-primary> ::= L <type> <value number> E # integer literal
4161 Out << 'L';
4162
4163 mangleType(T);
4164 if (T->isBooleanType()) {
4165 // Boolean values are encoded as 0/1.
4166 Out << (Value.getBoolValue() ? '1' : '0');
4167 } else {
4168 mangleNumber(Value);
4169 }
4170 Out << 'E';
4171
4172}
4173
4174void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4175 // Ignore member expressions involving anonymous unions.
4176 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4177 if (!RT->getDecl()->isAnonymousStructOrUnion())
4178 break;
4179 const auto *ME = dyn_cast<MemberExpr>(Base);
4180 if (!ME)
4181 break;
4182 Base = ME->getBase();
4183 IsArrow = ME->isArrow();
4184 }
4185
4186 if (Base->isImplicitCXXThis()) {
4187 // Note: GCC mangles member expressions to the implicit 'this' as
4188 // *this., whereas we represent them as this->. The Itanium C++ ABI
4189 // does not specify anything here, so we follow GCC.
4190 Out << "dtdefpT";
4191 } else {
4192 Out << (IsArrow ? "pt" : "dt");
4193 mangleExpression(Base);
4194 }
4195}
4196
4197/// Mangles a member expression.
4198void CXXNameMangler::mangleMemberExpr(const Expr *base,
4199 bool isArrow,
4200 NestedNameSpecifier *qualifier,
4201 NamedDecl *firstQualifierLookup,
4202 DeclarationName member,
4203 const TemplateArgumentLoc *TemplateArgs,
4204 unsigned NumTemplateArgs,
4205 unsigned arity) {
4206 // <expression> ::= dt <expression> <unresolved-name>
4207 // ::= pt <expression> <unresolved-name>
4208 if (base)
4209 mangleMemberExprBase(base, isArrow);
4210 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4211}
4212
4213/// Look at the callee of the given call expression and determine if
4214/// it's a parenthesized id-expression which would have triggered ADL
4215/// otherwise.
4216static bool isParenthesizedADLCallee(const CallExpr *call) {
4217 const Expr *callee = call->getCallee();
4218 const Expr *fn = callee->IgnoreParens();
4219
4220 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
4221 // too, but for those to appear in the callee, it would have to be
4222 // parenthesized.
4223 if (callee == fn) return false;
4224
4225 // Must be an unresolved lookup.
4226 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4227 if (!lookup) return false;
4228
4229 assert(!lookup->requiresADL());
4230
4231 // Must be an unqualified lookup.
4232 if (lookup->getQualifier()) return false;
4233
4234 // Must not have found a class member. Note that if one is a class
4235 // member, they're all class members.
4236 if (lookup->getNumDecls() > 0 &&
4237 (*lookup->decls_begin())->isCXXClassMember())
4238 return false;
4239
4240 // Otherwise, ADL would have been triggered.
4241 return true;
4242}
4243
4244void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4245 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4246 Out << CastEncoding;
4247 mangleType(ECE->getType());
4248 mangleExpression(ECE->getSubExpr());
4249}
4250
4251void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4252 if (auto *Syntactic = InitList->getSyntacticForm())
4253 InitList = Syntactic;
4254 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4255 mangleExpression(InitList->getInit(i));
4256}
4257
4258void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4259 bool AsTemplateArg) {
4260 // <expression> ::= <unary operator-name> <expression>
4261 // ::= <binary operator-name> <expression> <expression>
4262 // ::= <trinary operator-name> <expression> <expression> <expression>
4263 // ::= cv <type> expression # conversion with one argument
4264 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4265 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
4266 // ::= sc <type> <expression> # static_cast<type> (expression)
4267 // ::= cc <type> <expression> # const_cast<type> (expression)
4268 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
4269 // ::= st <type> # sizeof (a type)
4270 // ::= at <type> # alignof (a type)
4271 // ::= <template-param>
4272 // ::= <function-param>
4273 // ::= fpT # 'this' expression (part of <function-param>)
4274 // ::= sr <type> <unqualified-name> # dependent name
4275 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
4276 // ::= ds <expression> <expression> # expr.*expr
4277 // ::= sZ <template-param> # size of a parameter pack
4278 // ::= sZ <function-param> # size of a function parameter pack
4279 // ::= u <source-name> <template-arg>* E # vendor extended expression
4280 // ::= <expr-primary>
4281 // <expr-primary> ::= L <type> <value number> E # integer literal
4282 // ::= L <type> <value float> E # floating literal
4283 // ::= L <type> <string type> E # string literal
4284 // ::= L <nullptr type> E # nullptr literal "LDnE"
4285 // ::= L <pointer type> 0 E # null pointer template argument
4286 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
4287 // ::= L <mangled-name> E # external name
4288 QualType ImplicitlyConvertedToType;
4289
4290 // A top-level expression that's not <expr-primary> needs to be wrapped in
4291 // X...E in a template arg.
4292 bool IsPrimaryExpr = true;
4293 auto NotPrimaryExpr = [&] {
4294 if (AsTemplateArg && IsPrimaryExpr)
4295 Out << 'X';
4296 IsPrimaryExpr = false;
4297 };
4298
4299 auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4300 switch (D->getKind()) {
4301 default:
4302 // <expr-primary> ::= L <mangled-name> E # external name
4303 Out << 'L';
4304 mangle(D);
4305 Out << 'E';
4306 break;
4307
4308 case Decl::ParmVar:
4309 NotPrimaryExpr();
4310 mangleFunctionParam(cast<ParmVarDecl>(D));
4311 break;
4312
4313 case Decl::EnumConstant: {
4314 // <expr-primary>
4315 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4316 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4317 break;
4318 }
4319
4320 case Decl::NonTypeTemplateParm:
4321 NotPrimaryExpr();
4322 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4323 mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4324 break;
4325 }
4326 };
4327
4328 // 'goto recurse' is used when handling a simple "unwrapping" node which
4329 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4330 // to be preserved.
4331recurse:
4332 switch (E->getStmtClass()) {
4333 case Expr::NoStmtClass:
4334#define ABSTRACT_STMT(Type)
4335#define EXPR(Type, Base)
4336#define STMT(Type, Base) \
4337 case Expr::Type##Class:
4338#include "clang/AST/StmtNodes.inc"
4339 // fallthrough
4340
4341 // These all can only appear in local or variable-initialization
4342 // contexts and so should never appear in a mangling.
4343 case Expr::AddrLabelExprClass:
4344 case Expr::DesignatedInitUpdateExprClass:
4345 case Expr::ImplicitValueInitExprClass:
4346 case Expr::ArrayInitLoopExprClass:
4347 case Expr::ArrayInitIndexExprClass:
4348 case Expr::NoInitExprClass:
4349 case Expr::ParenListExprClass:
4350 case Expr::MSPropertyRefExprClass:
4351 case Expr::MSPropertySubscriptExprClass:
4352 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4353 case Expr::RecoveryExprClass:
4354 case Expr::OMPArraySectionExprClass:
4355 case Expr::OMPArrayShapingExprClass:
4356 case Expr::OMPIteratorExprClass:
4357 case Expr::CXXInheritedCtorInitExprClass:
4358 case Expr::CXXParenListInitExprClass:
4359 llvm_unreachable("unexpected statement kind");
4360
4361 case Expr::ConstantExprClass:
4362 E = cast<ConstantExpr>(E)->getSubExpr();
4363 goto recurse;
4364
4365 // FIXME: invent manglings for all these.
4366 case Expr::BlockExprClass:
4367 case Expr::ChooseExprClass:
4368 case Expr::CompoundLiteralExprClass:
4369 case Expr::ExtVectorElementExprClass:
4370 case Expr::GenericSelectionExprClass:
4371 case Expr::ObjCEncodeExprClass:
4372 case Expr::ObjCIsaExprClass:
4373 case Expr::ObjCIvarRefExprClass:
4374 case Expr::ObjCMessageExprClass:
4375 case Expr::ObjCPropertyRefExprClass:
4376 case Expr::ObjCProtocolExprClass:
4377 case Expr::ObjCSelectorExprClass:
4378 case Expr::ObjCStringLiteralClass:
4379 case Expr::ObjCBoxedExprClass:
4380 case Expr::ObjCArrayLiteralClass:
4381 case Expr::ObjCDictionaryLiteralClass:
4382 case Expr::ObjCSubscriptRefExprClass:
4383 case Expr::ObjCIndirectCopyRestoreExprClass:
4384 case Expr::ObjCAvailabilityCheckExprClass:
4385 case Expr::OffsetOfExprClass:
4386 case Expr::PredefinedExprClass:
4387 case Expr::ShuffleVectorExprClass:
4388 case Expr::ConvertVectorExprClass:
4389 case Expr::StmtExprClass:
4390 case Expr::TypeTraitExprClass:
4391 case Expr::RequiresExprClass:
4392 case Expr::ArrayTypeTraitExprClass:
4393 case Expr::ExpressionTraitExprClass:
4394 case Expr::VAArgExprClass:
4395 case Expr::CUDAKernelCallExprClass:
4396 case Expr::AsTypeExprClass:
4397 case Expr::PseudoObjectExprClass:
4398 case Expr::AtomicExprClass:
4399 case Expr::SourceLocExprClass:
4400 case Expr::BuiltinBitCastExprClass:
4401 {
4402 NotPrimaryExpr();
4403 if (!NullOut) {
4404 // As bad as this diagnostic is, it's better than crashing.
4405 DiagnosticsEngine &Diags = Context.getDiags();
4406 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4407 "cannot yet mangle expression type %0");
4408 Diags.Report(E->getExprLoc(), DiagID)
4409 << E->getStmtClassName() << E->getSourceRange();
4410 return;
4411 }
4412 break;
4413 }
4414
4415 case Expr::CXXUuidofExprClass: {
4416 NotPrimaryExpr();
4417 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4418 // As of clang 12, uuidof uses the vendor extended expression
4419 // mangling. Previously, it used a special-cased nonstandard extension.
4420 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4421 LangOptions::ClangABI::Ver11) {
4422 Out << "u8__uuidof";
4423 if (UE->isTypeOperand())
4424 mangleType(UE->getTypeOperand(Context.getASTContext()));
4425 else
4426 mangleTemplateArgExpr(UE->getExprOperand());
4427 Out << 'E';
4428 } else {
4429 if (UE->isTypeOperand()) {
4430 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4431 Out << "u8__uuidoft";
4432 mangleType(UuidT);
4433 } else {
4434 Expr *UuidExp = UE->getExprOperand();
4435 Out << "u8__uuidofz";
4436 mangleExpression(UuidExp);
4437 }
4438 }
4439 break;
4440 }
4441
4442 // Even gcc-4.5 doesn't mangle this.
4443 case Expr::BinaryConditionalOperatorClass: {
4444 NotPrimaryExpr();
4445 DiagnosticsEngine &Diags = Context.getDiags();
4446 unsigned DiagID =
4448 "?: operator with omitted middle operand cannot be mangled");
4449 Diags.Report(E->getExprLoc(), DiagID)
4450 << E->getStmtClassName() << E->getSourceRange();
4451 return;
4452 }
4453
4454 // These are used for internal purposes and cannot be meaningfully mangled.
4455 case Expr::OpaqueValueExprClass:
4456 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4457
4458 case Expr::InitListExprClass: {
4459 NotPrimaryExpr();
4460 Out << "il";
4461 mangleInitListElements(cast<InitListExpr>(E));
4462 Out << "E";
4463 break;
4464 }
4465
4466 case Expr::DesignatedInitExprClass: {
4467 NotPrimaryExpr();
4468 auto *DIE = cast<DesignatedInitExpr>(E);
4469 for (const auto &Designator : DIE->designators()) {
4471 Out << "di";
4472 mangleSourceName(Designator.getFieldName());
4473 } else if (Designator.isArrayDesignator()) {
4474 Out << "dx";
4475 mangleExpression(DIE->getArrayIndex(Designator));
4476 } else {
4478 "unknown designator kind");
4479 Out << "dX";
4480 mangleExpression(DIE->getArrayRangeStart(Designator));
4481 mangleExpression(DIE->getArrayRangeEnd(Designator));
4482 }
4483 }
4484 mangleExpression(DIE->getInit());
4485 break;
4486 }
4487
4488 case Expr::CXXDefaultArgExprClass:
4489 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4490 goto recurse;
4491
4492 case Expr::CXXDefaultInitExprClass:
4493 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4494 goto recurse;
4495
4496 case Expr::CXXStdInitializerListExprClass:
4497 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4498 goto recurse;
4499
4500 case Expr::SubstNonTypeTemplateParmExprClass:
4501 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4502 goto recurse;
4503
4504 case Expr::UserDefinedLiteralClass:
4505 // We follow g++'s approach of mangling a UDL as a call to the literal
4506 // operator.
4507 case Expr::CXXMemberCallExprClass: // fallthrough
4508 case Expr::CallExprClass: {
4509 NotPrimaryExpr();
4510 const CallExpr *CE = cast<CallExpr>(E);
4511
4512 // <expression> ::= cp <simple-id> <expression>* E
4513 // We use this mangling only when the call would use ADL except
4514 // for being parenthesized. Per discussion with David
4515 // Vandervoorde, 2011.04.25.
4516 if (isParenthesizedADLCallee(CE)) {
4517 Out << "cp";
4518 // The callee here is a parenthesized UnresolvedLookupExpr with
4519 // no qualifier and should always get mangled as a <simple-id>
4520 // anyway.
4521
4522 // <expression> ::= cl <expression>* E
4523 } else {
4524 Out << "cl";
4525 }
4526
4527 unsigned CallArity = CE->getNumArgs();
4528 for (const Expr *Arg : CE->arguments())
4529 if (isa<PackExpansionExpr>(Arg))
4530 CallArity = UnknownArity;
4531
4532 mangleExpression(CE->getCallee(), CallArity);
4533 for (const Expr *Arg : CE->arguments())
4534 mangleExpression(Arg);
4535 Out << 'E';
4536 break;
4537 }
4538
4539 case Expr::CXXNewExprClass: {
4540 NotPrimaryExpr();
4541 const CXXNewExpr *New = cast<CXXNewExpr>(E);
4542 if (New->isGlobalNew()) Out << "gs";
4543 Out << (New->isArray() ? "na" : "nw");
4545 E = New->placement_arg_end(); I != E; ++I)
4546 mangleExpression(*I);
4547 Out << '_';
4548 mangleType(New->getAllocatedType());
4549 if (New->hasInitializer()) {
4551 Out << "il";
4552 else
4553 Out << "pi";
4554 const Expr *Init = New->getInitializer();
4555 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4556 // Directly inline the initializers.
4557 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4558 E = CCE->arg_end();
4559 I != E; ++I)
4560 mangleExpression(*I);
4561 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4562 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4563 mangleExpression(PLE->getExpr(i));
4564 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
4565 isa<InitListExpr>(Init)) {
4566 // Only take InitListExprs apart for list-initialization.
4567 mangleInitListElements(cast<InitListExpr>(Init));
4568 } else
4569 mangleExpression(Init);
4570 }
4571 Out << 'E';
4572 break;
4573 }
4574
4575 case Expr::CXXPseudoDestructorExprClass: {
4576 NotPrimaryExpr();
4577 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4578 if (const Expr *Base = PDE->getBase())
4579 mangleMemberExprBase(Base, PDE->isArrow());
4580 NestedNameSpecifier *Qualifier = PDE->getQualifier();
4581 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4582 if (Qualifier) {
4583 mangleUnresolvedPrefix(Qualifier,
4584 /*recursive=*/true);
4585 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4586 Out << 'E';
4587 } else {
4588 Out << "sr";
4589 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4590 Out << 'E';
4591 }
4592 } else if (Qualifier) {
4593 mangleUnresolvedPrefix(Qualifier);
4594 }
4595 // <base-unresolved-name> ::= dn <destructor-name>
4596 Out << "dn";
4597 QualType DestroyedType = PDE->getDestroyedType();
4598 mangleUnresolvedTypeOrSimpleId(DestroyedType);
4599 break;
4600 }
4601
4602 case Expr::MemberExprClass: {
4603 NotPrimaryExpr();
4604 const MemberExpr *ME = cast<MemberExpr>(E);
4605 mangleMemberExpr(ME->getBase(), ME->isArrow(),
4606 ME->getQualifier(), nullptr,
4607 ME->getMemberDecl()->getDeclName(),
4609 Arity);
4610 break;
4611 }
4612
4613 case Expr::UnresolvedMemberExprClass: {
4614 NotPrimaryExpr();
4615 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4616 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4617 ME->isArrow(), ME->getQualifier(), nullptr,
4618 ME->getMemberName(),
4620 Arity);
4621 break;
4622 }
4623
4624 case Expr::CXXDependentScopeMemberExprClass: {
4625 NotPrimaryExpr();
4627 = cast<CXXDependentScopeMemberExpr>(E);
4628 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4629 ME->isArrow(), ME->getQualifier(),
4631 ME->getMember(),
4633 Arity);
4634 break;
4635 }
4636
4637 case Expr::UnresolvedLookupExprClass: {
4638 NotPrimaryExpr();
4639 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4640 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4641 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4642 Arity);
4643 break;
4644 }
4645
4646 case Expr::CXXUnresolvedConstructExprClass: {
4647 NotPrimaryExpr();
4648 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4649 unsigned N = CE->getNumArgs();
4650
4651 if (CE->isListInitialization()) {
4652 assert(N == 1 && "unexpected form for list initialization");
4653 auto *IL = cast<InitListExpr>(CE->getArg(0));
4654 Out << "tl";
4655 mangleType(CE->getType());
4656 mangleInitListElements(IL);
4657 Out << "E";
4658 break;
4659 }
4660
4661 Out << "cv";
4662 mangleType(CE->getType());
4663 if (N != 1) Out << '_';
4664 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
4665 if (N != 1) Out << 'E';
4666 break;
4667 }
4668
4669 case Expr::CXXConstructExprClass: {
4670 // An implicit cast is silent, thus may contain <expr-primary>.
4671 const auto *CE = cast<CXXConstructExpr>(E);
4672 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
4673 assert(
4674 CE->getNumArgs() >= 1 &&
4675 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
4676 "implicit CXXConstructExpr must have one argument");
4677 E = cast<CXXConstructExpr>(E)->getArg(0);
4678 goto recurse;
4679 }
4680 NotPrimaryExpr();
4681 Out << "il";
4682 for (auto *E : CE->arguments())
4683 mangleExpression(E);
4684 Out << "E";
4685 break;
4686 }
4687
4688 case Expr::CXXTemporaryObjectExprClass: {
4689 NotPrimaryExpr();
4690 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
4691 unsigned N = CE->getNumArgs();
4692 bool List = CE->isListInitialization();
4693
4694 if (List)
4695 Out << "tl";
4696 else
4697 Out << "cv";
4698 mangleType(CE->getType());
4699 if (!List && N != 1)
4700 Out << '_';
4701 if (CE->isStdInitListInitialization()) {
4702 // We implicitly created a std::initializer_list<T> for the first argument
4703 // of a constructor of type U in an expression of the form U{a, b, c}.
4704 // Strip all the semantic gunk off the initializer list.
4705 auto *SILE =
4706 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
4707 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
4708 mangleInitListElements(ILE);
4709 } else {
4710 for (auto *E : CE->arguments())
4711 mangleExpression(E);
4712 }
4713 if (List || N != 1)
4714 Out << 'E';
4715 break;
4716 }
4717
4718 case Expr::CXXScalarValueInitExprClass:
4719 NotPrimaryExpr();
4720 Out << "cv";
4721 mangleType(E->getType());
4722 Out << "_E";
4723 break;
4724
4725 case Expr::CXXNoexceptExprClass:
4726 NotPrimaryExpr();
4727 Out << "nx";
4728 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
4729 break;
4730
4731 case Expr::UnaryExprOrTypeTraitExprClass: {
4732 // Non-instantiation-dependent traits are an <expr-primary> integer literal.
4733 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
4734
4735 if (!SAE->isInstantiationDependent()) {
4736 // Itanium C++ ABI:
4737 // If the operand of a sizeof or alignof operator is not
4738 // instantiation-dependent it is encoded as an integer literal
4739 // reflecting the result of the operator.
4740 //
4741 // If the result of the operator is implicitly converted to a known
4742 // integer type, that type is used for the literal; otherwise, the type
4743 // of std::size_t or std::ptrdiff_t is used.
4744 QualType T = (ImplicitlyConvertedToType.isNull() ||
4745 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
4746 : ImplicitlyConvertedToType;
4747 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
4748 mangleIntegerLiteral(T, V);
4749 break;
4750 }
4751
4752 NotPrimaryExpr(); // But otherwise, they are not.
4753
4754 auto MangleAlignofSizeofArg = [&] {
4755 if (SAE->isArgumentType()) {
4756 Out << 't';
4757 mangleType(SAE->getArgumentType());
4758 } else {
4759 Out << 'z';
4760 mangleExpression(SAE->getArgumentExpr());
4761 }
4762 };
4763
4764 switch(SAE->getKind()) {
4765 case UETT_SizeOf:
4766 Out << 's';
4767 MangleAlignofSizeofArg();
4768 break;
4769 case UETT_PreferredAlignOf:
4770 // As of clang 12, we mangle __alignof__ differently than alignof. (They
4771 // have acted differently since Clang 8, but were previously mangled the
4772 // same.)
4773 if (Context.getASTContext().getLangOpts().getClangABICompat() >
4774 LangOptions::ClangABI::Ver11) {
4775 Out << "u11__alignof__";
4776 if (SAE->isArgumentType())
4777 mangleType(SAE->getArgumentType());
4778 else
4779 mangleTemplateArgExpr(SAE->getArgumentExpr());
4780 Out << 'E';
4781 break;
4782 }
4783 [[fallthrough]];
4784 case UETT_AlignOf:
4785 Out << 'a';
4786 MangleAlignofSizeofArg();
4787 break;
4788 case UETT_VecStep: {
4789 DiagnosticsEngine &Diags = Context.getDiags();
4790 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4791 "cannot yet mangle vec_step expression");
4792 Diags.Report(DiagID);
4793 return;
4794 }
4795 case UETT_OpenMPRequiredSimdAlign: {
4796 DiagnosticsEngine &Diags = Context.getDiags();
4797 unsigned DiagID = Diags.getCustomDiagID(
4799 "cannot yet mangle __builtin_omp_required_simd_align expression");
4800 Diags.Report(DiagID);
4801 return;
4802 }
4803 }
4804 break;
4805 }
4806
4807 case Expr::CXXThrowExprClass: {
4808 NotPrimaryExpr();
4809 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4810 // <expression> ::= tw <expression> # throw expression
4811 // ::= tr # rethrow
4812 if (TE->getSubExpr()) {
4813 Out << "tw";
4814 mangleExpression(TE->getSubExpr());
4815 } else {
4816 Out << "tr";
4817 }
4818 break;
4819 }
4820
4821 case Expr::CXXTypeidExprClass: {
4822 NotPrimaryExpr();
4823 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4824 // <expression> ::= ti <type> # typeid (type)
4825 // ::= te <expression> # typeid (expression)
4826 if (TIE->isTypeOperand()) {
4827 Out << "ti";
4828 mangleType(TIE->getTypeOperand(Context.getASTContext()));
4829 } else {
4830 Out << "te";
4831 mangleExpression(TIE->getExprOperand());
4832 }
4833 break;
4834 }
4835
4836 case Expr::CXXDeleteExprClass: {
4837 NotPrimaryExpr();
4838 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4839 // <expression> ::= [gs] dl <expression> # [::] delete expr
4840 // ::= [gs] da <expression> # [::] delete [] expr
4841 if (DE->isGlobalDelete()) Out << "gs";
4842 Out << (DE->isArrayForm() ? "da" : "dl");
4843 mangleExpression(DE->getArgument());
4844 break;
4845 }
4846
4847 case Expr::UnaryOperatorClass: {
4848 NotPrimaryExpr();
4849 const UnaryOperator *UO = cast<UnaryOperator>(E);
4850 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4851 /*Arity=*/1);
4852 mangleExpression(UO->getSubExpr());
4853 break;
4854 }
4855
4856 case Expr::ArraySubscriptExprClass: {
4857 NotPrimaryExpr();
4858 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4859
4860 // Array subscript is treated as a syntactically weird form of
4861 // binary operator.
4862 Out << "ix";
4863 mangleExpression(AE->getLHS());
4864 mangleExpression(AE->getRHS());
4865 break;
4866 }
4867
4868 case Expr::MatrixSubscriptExprClass: {
4869 NotPrimaryExpr();
4870 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
4871 Out << "ixix";
4872 mangleExpression(ME->getBase());
4873 mangleExpression(ME->getRowIdx());
4874 mangleExpression(ME->getColumnIdx());
4875 break;
4876 }
4877
4878 case Expr::CompoundAssignOperatorClass: // fallthrough
4879 case Expr::BinaryOperatorClass: {
4880 NotPrimaryExpr();
4881 const BinaryOperator *BO = cast<BinaryOperator>(E);
4882 if (BO->getOpcode() == BO_PtrMemD)
4883 Out << "ds";
4884 else
4885 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4886 /*Arity=*/2);
4887 mangleExpression(BO->getLHS());
4888 mangleExpression(BO->getRHS());
4889 break;
4890 }
4891
4892 case Expr::CXXRewrittenBinaryOperatorClass: {
4893 NotPrimaryExpr();
4894 // The mangled form represents the original syntax.
4896 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4897 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4898 /*Arity=*/2);
4899 mangleExpression(Decomposed.LHS);
4900 mangleExpression(Decomposed.RHS);
4901 break;
4902 }
4903
4904 case Expr::ConditionalOperatorClass: {
4905 NotPrimaryExpr();
4906 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4907 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4908 mangleExpression(CO->getCond());
4909 mangleExpression(CO->getLHS(), Arity);
4910 mangleExpression(CO->getRHS(), Arity);
4911 break;
4912 }
4913
4914 case Expr::ImplicitCastExprClass: {
4915 ImplicitlyConvertedToType = E->getType();
4916 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4917 goto recurse;
4918 }
4919
4920 case Expr::ObjCBridgedCastExprClass: {
4921 NotPrimaryExpr();
4922 // Mangle ownership casts as a vendor extended operator __bridge,
4923 // __bridge_transfer, or __bridge_retain.
4924 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4925 Out << "v1U" << Kind.size() << Kind;
4926 mangleCastExpression(E, "cv");
4927 break;
4928 }
4929
4930 case Expr::CStyleCastExprClass:
4931 NotPrimaryExpr();
4932 mangleCastExpression(E, "cv");
4933 break;
4934
4935 case Expr::CXXFunctionalCastExprClass: {
4936 NotPrimaryExpr();
4937 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4938 // FIXME: Add isImplicit to CXXConstructExpr.
4939 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4940 if (CCE->getParenOrBraceRange().isInvalid())
4941 Sub = CCE->getArg(0)->IgnoreImplicit();
4942 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4943 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4944 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4945 Out << "tl";
4946 mangleType(E->getType());
4947 mangleInitListElements(IL);
4948 Out << "E";
4949 } else {
4950 mangleCastExpression(E, "cv");
4951 }
4952 break;
4953 }
4954
4955 case Expr::CXXStaticCastExprClass:
4956 NotPrimaryExpr();
4957 mangleCastExpression(E, "sc");
4958 break;
4959 case Expr::CXXDynamicCastExprClass:
4960 NotPrimaryExpr();
4961 mangleCastExpression(E, "dc");
4962 break;
4963 case Expr::CXXReinterpretCastExprClass:
4964 NotPrimaryExpr();
4965 mangleCastExpression(E, "rc");
4966 break;
4967 case Expr::CXXConstCastExprClass:
4968 NotPrimaryExpr();
4969 mangleCastExpression(E, "cc");
4970 break;
4971 case Expr::CXXAddrspaceCastExprClass:
4972 NotPrimaryExpr();
4973 mangleCastExpression(E, "ac");
4974 break;
4975
4976 case Expr::CXXOperatorCallExprClass: {
4977 NotPrimaryExpr();
4978 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4979 unsigned NumArgs = CE->getNumArgs();
4980 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4981 // (the enclosing MemberExpr covers the syntactic portion).
4982 if (CE->getOperator() != OO_Arrow)
4983 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4984 // Mangle the arguments.
4985 for (unsigned i = 0; i != NumArgs; ++i)
4986 mangleExpression(CE->getArg(i));
4987 break;
4988 }
4989
4990 case Expr::ParenExprClass:
4991 E = cast<ParenExpr>(E)->getSubExpr();
4992 goto recurse;
4993
4994 case Expr::ConceptSpecializationExprClass: {
4995 // <expr-primary> ::= L <mangled-name> E # external name
4996 Out << "L_Z";
4997 auto *CSE = cast<ConceptSpecializationExpr>(E);
4998 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
4999 Out << 'E';
5000 break;
5001 }
5002
5003 case Expr::DeclRefExprClass:
5004 // MangleDeclRefExpr helper handles primary-vs-nonprimary
5005 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5006 break;
5007
5008 case Expr::SubstNonTypeTemplateParmPackExprClass:
5009 NotPrimaryExpr();
5010 // FIXME: not clear how to mangle this!
5011 // template <unsigned N...> class A {
5012 // template <class U...> void foo(U (&x)[N]...);
5013 // };
5014 Out << "_SUBSTPACK_";
5015 break;
5016
5017 case Expr::FunctionParmPackExprClass: {
5018 NotPrimaryExpr();
5019 // FIXME: not clear how to mangle this!
5020 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5021 Out << "v110_SUBSTPACK";
5022 MangleDeclRefExpr(FPPE->getParameterPack());
5023 break;
5024 }
5025
5026 case Expr::DependentScopeDeclRefExprClass: {
5027 NotPrimaryExpr();
5028 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5029 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5030 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5031 Arity);
5032 break;
5033 }
5034
5035 case Expr::CXXBindTemporaryExprClass:
5036 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5037 goto recurse;
5038
5039 case Expr::ExprWithCleanupsClass:
5040 E = cast<ExprWithCleanups>(E)->getSubExpr();
5041 goto recurse;
5042
5043 case Expr::FloatingLiteralClass: {
5044 // <expr-primary>
5045 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5046 mangleFloatLiteral(FL->getType(), FL->getValue());
5047 break;
5048 }
5049
5050 case Expr::FixedPointLiteralClass:
5051 // Currently unimplemented -- might be <expr-primary> in future?
5052 mangleFixedPointLiteral();
5053 break;
5054
5055 case Expr::CharacterLiteralClass:
5056 // <expr-primary>
5057 Out << 'L';
5058 mangleType(E->getType());
5059 Out << cast<CharacterLiteral>(E)->getValue();
5060 Out << 'E';
5061 break;
5062
5063 // FIXME. __objc_yes/__objc_no are mangled same as true/false
5064 case Expr::ObjCBoolLiteralExprClass:
5065 // <expr-primary>
5066 Out << "Lb";
5067 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5068 Out << 'E';
5069 break;
5070
5071 case Expr::CXXBoolLiteralExprClass:
5072 // <expr-primary>
5073 Out << "Lb";
5074 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5075 Out << 'E';
5076 break;
5077
5078 case Expr::IntegerLiteralClass: {
5079 // <expr-primary>
5080 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5081 if (E->getType()->isSignedIntegerType())
5082 Value.setIsSigned(true);
5083 mangleIntegerLiteral(E->getType(), Value);
5084 break;
5085 }
5086
5087 case Expr::ImaginaryLiteralClass: {
5088 // <expr-primary>
5089 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5090 // Mangle as if a complex literal.
5091 // Proposal from David Vandevoorde, 2010.06.30.
5092 Out << 'L';
5093 mangleType(E->getType());
5094 if (const FloatingLiteral *Imag =
5095 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5096 // Mangle a floating-point zero of the appropriate type.
5097 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5098 Out << '_';
5099 mangleFloat(Imag->getValue());
5100 } else {
5101 Out << "0_";
5102 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5103 if (IE->getSubExpr()->getType()->isSignedIntegerType())
5104 Value.setIsSigned(true);
5105 mangleNumber(Value);
5106 }
5107 Out << 'E';
5108 break;
5109 }
5110
5111 case Expr::StringLiteralClass: {
5112 // <expr-primary>
5113 // Revised proposal from David Vandervoorde, 2010.07.15.
5114 Out << 'L';
5115 assert(isa<ConstantArrayType>(E->getType()));
5116 mangleType(E->getType());
5117 Out << 'E';
5118 break;
5119 }
5120
5121 case Expr::GNUNullExprClass:
5122 // <expr-primary>
5123 // Mangle as if an integer literal 0.
5124 mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5125 break;
5126
5127 case Expr::CXXNullPtrLiteralExprClass: {
5128 // <expr-primary>
5129 Out << "LDnE";
5130 break;
5131 }
5132
5133 case Expr::LambdaExprClass: {
5134 // A lambda-expression can't appear in the signature of an
5135 // externally-visible declaration, so there's no standard mangling for
5136 // this, but mangling as a literal of the closure type seems reasonable.
5137 Out << "L";
5138 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5139 Out << "E";
5140 break;
5141 }
5142
5143 case Expr::PackExpansionExprClass:
5144 NotPrimaryExpr();
5145 Out << "sp";
5146 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5147 break;
5148
5149 case Expr::SizeOfPackExprClass: {
5150 NotPrimaryExpr();
5151 auto *SPE = cast<SizeOfPackExpr>(E);
5152 if (SPE->isPartiallySubstituted()) {
5153 Out << "sP";
5154 for (const auto &A : SPE->getPartialArguments())
5155 mangleTemplateArg(A, false);
5156 Out << "E";
5157 break;
5158 }
5159
5160 Out << "sZ";
5161 const NamedDecl *Pack = SPE->getPack();
5162 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5163 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5164 else if (const NonTypeTemplateParmDecl *NTTP
5165 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5166 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5167 else if (const TemplateTemplateParmDecl *TempTP
5168 = dyn_cast<TemplateTemplateParmDecl>(Pack))
5169 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5170 else
5171 mangleFunctionParam(cast<ParmVarDecl>(Pack));
5172 break;
5173 }
5174
5175 case Expr::MaterializeTemporaryExprClass:
5176 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5177 goto recurse;
5178
5179 case Expr::CXXFoldExprClass: {
5180 NotPrimaryExpr();
5181 auto *FE = cast<CXXFoldExpr>(E);
5182 if (FE->isLeftFold())
5183 Out << (FE->getInit() ? "fL" : "fl");
5184 else
5185 Out << (FE->getInit() ? "fR" : "fr");
5186
5187 if (FE->getOperator() == BO_PtrMemD)
5188 Out << "ds";
5189 else
5190 mangleOperatorName(
5191 BinaryOperator::getOverloadedOperator(FE->getOperator()),
5192 /*Arity=*/2);
5193
5194 if (FE->getLHS())
5195 mangleExpression(FE->getLHS());
5196 if (FE->getRHS())
5197 mangleExpression(FE->getRHS());
5198 break;
5199 }
5200
5201 case Expr::CXXThisExprClass:
5202 NotPrimaryExpr();
5203 Out << "fpT";
5204 break;
5205
5206 case Expr::CoawaitExprClass:
5207 // FIXME: Propose a non-vendor mangling.
5208 NotPrimaryExpr();
5209 Out << "v18co_await";
5210 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5211 break;
5212
5213 case Expr::DependentCoawaitExprClass:
5214 // FIXME: Propose a non-vendor mangling.
5215 NotPrimaryExpr();
5216 Out << "v18co_await";
5217 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5218 break;
5219
5220 case Expr::CoyieldExprClass:
5221 // FIXME: Propose a non-vendor mangling.
5222 NotPrimaryExpr();
5223 Out << "v18co_yield";
5224 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5225 break;
5226 case Expr::SYCLUniqueStableNameExprClass: {
5227 const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5228 NotPrimaryExpr();
5229
5230 Out << "u33__builtin_sycl_unique_stable_name";
5231 mangleType(USN->getTypeSourceInfo()->getType());
5232
5233 Out << "E";
5234 break;
5235 }
5236 }
5237
5238 if (AsTemplateArg && !IsPrimaryExpr)
5239 Out << 'E';
5240}
5241
5242/// Mangle an expression which refers to a parameter variable.
5243///
5244/// <expression> ::= <function-param>
5245/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
5246/// <function-param> ::= fp <top-level CV-qualifiers>
5247/// <parameter-2 non-negative number> _ # L == 0, I > 0
5248/// <function-param> ::= fL <L-1 non-negative number>
5249/// p <top-level CV-qualifiers> _ # L > 0, I == 0
5250/// <function-param> ::= fL <L-1 non-negative number>
5251/// p <top-level CV-qualifiers>
5252/// <I-1 non-negative number> _ # L > 0, I > 0
5253///
5254/// L is the nesting depth of the parameter, defined as 1 if the
5255/// parameter comes from the innermost function prototype scope
5256/// enclosing the current context, 2 if from the next enclosing
5257/// function prototype scope, and so on, with one special case: if
5258/// we've processed the full parameter clause for the innermost
5259/// function type, then L is one less. This definition conveniently
5260/// makes it irrelevant whether a function's result type was written
5261/// trailing or leading, but is otherwise overly complicated; the
5262/// numbering was first designed without considering references to
5263/// parameter in locations other than return types, and then the
5264/// mangling had to be generalized without changing the existing
5265/// manglings.
5266///
5267/// I is the zero-based index of the parameter within its parameter
5268/// declaration clause. Note that the original ABI document describes
5269/// this using 1-based ordinals.
5270void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5271 unsigned parmDepth = parm->getFunctionScopeDepth();
5272 unsigned parmIndex = parm->getFunctionScopeIndex();
5273
5274 // Compute 'L'.
5275 // parmDepth does not include the declaring function prototype.
5276 // FunctionTypeDepth does account for that.
5277 assert(parmDepth < FunctionTypeDepth.getDepth());
5278 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5279 if (FunctionTypeDepth.isInResultType())
5280 nestingDepth--;
5281
5282 if (nestingDepth == 0) {
5283 Out << "fp";
5284 } else {
5285 Out << "fL" << (nestingDepth - 1) << 'p';
5286 }
5287
5288 // Top-level qualifiers. We don't have to worry about arrays here,
5289 // because parameters declared as arrays should already have been
5290 // transformed to have pointer type. FIXME: apparently these don't
5291 // get mangled if used as an rvalue of a known non-class type?
5292 assert(!parm->getType()->isArrayType()
5293 && "parameter's type is still an array type?");
5294
5295 if (const DependentAddressSpaceType *DAST =
5296 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5297 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5298 } else {
5299 mangleQualifiers(parm->getType().getQualifiers());
5300 }
5301
5302 // Parameter index.
5303 if (parmIndex != 0) {
5304 Out << (parmIndex - 1);
5305 }
5306 Out << '_';
5307}
5308
5309void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5310 const CXXRecordDecl *InheritedFrom) {
5311 // <ctor-dtor-name> ::= C1 # complete object constructor
5312 // ::= C2 # base object constructor
5313 // ::= CI1 <type> # complete inheriting constructor
5314 // ::= CI2 <type> # base inheriting constructor
5315 //
5316 // In addition, C5 is a comdat name with C1 and C2 in it.
5317 Out << 'C';
5318 if (InheritedFrom)
5319 Out << 'I';
5320 switch (T) {
5321 case Ctor_Complete:
5322 Out << '1';
5323 break;
5324 case Ctor_Base:
5325 Out << '2';
5326 break;
5327 case Ctor_Comdat:
5328 Out << '5';
5329 break;
5332 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5333 }
5334 if (InheritedFrom)
5335 mangleName(InheritedFrom);
5336}
5337
5338void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5339 // <ctor-dtor-name> ::= D0 # deleting destructor
5340 // ::= D1 # complete object destructor
5341 // ::= D2 # base object destructor
5342 //
5343 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5344 switch (T) {
5345 case Dtor_Deleting:
5346 Out << "D0";
5347 break;
5348 case Dtor_Complete:
5349 Out << "D1";
5350 break;
5351 case Dtor_Base:
5352 Out << "D2";
5353 break;
5354 case Dtor_Comdat:
5355 Out << "D5";
5356 break;
5357 }
5358}
5359
5360namespace {
5361// Helper to provide ancillary information on a template used to mangle its
5362// arguments.
5363struct TemplateArgManglingInfo {
5364 TemplateDecl *ResolvedTemplate = nullptr;
5365 bool SeenPackExpansionIntoNonPack = false;
5366 const NamedDecl *UnresolvedExpandedPack = nullptr;
5367
5368 TemplateArgManglingInfo(TemplateName TN) {
5369 if (TemplateDecl *TD = TN.getAsTemplateDecl())
5370 ResolvedTemplate = TD;
5371 }
5372
5373 /// Do we need to mangle template arguments with exactly correct types?
5374 ///
5375 /// This should be called exactly once for each parameter / argument pair, in
5376 /// order.
5377 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
5378 // We need correct types when the template-name is unresolved or when it
5379 // names a template that is able to be overloaded.
5380 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5381 return true;
5382
5383 // Move to the next parameter.
5384 const NamedDecl *Param = UnresolvedExpandedPack;
5385 if (!Param) {
5386 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
5387 "no parameter for argument");
5388 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5389
5390 // If we reach an expanded parameter pack whose argument isn't in pack
5391 // form, that means Sema couldn't figure out which arguments belonged to
5392 // it, because it contains a pack expansion. Track the expanded pack for
5393 // all further template arguments until we hit that pack expansion.
5394 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5395 assert(getExpandedPackSize(Param) &&
5396 "failed to form pack argument for parameter pack");
5397 UnresolvedExpandedPack = Param;
5398 }
5399 }
5400
5401 // If we encounter a pack argument that is expanded into a non-pack
5402 // parameter, we can no longer track parameter / argument correspondence,
5403 // and need to use exact types from this point onwards.
5404 if (Arg.isPackExpansion() &&
5405 (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5406 SeenPackExpansionIntoNonPack = true;
5407 return true;
5408 }
5409
5410 // We need exact types for function template arguments because they might be
5411 // overloaded on template parameter type. As a special case, a member
5412 // function template of a generic lambda is not overloadable.
5413 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
5414 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5415 if (!RD || !RD->isGenericLambda())
5416 return true;
5417 }
5418
5419 // Otherwise, we only need a correct type if the parameter has a deduced
5420 // type.
5421 //
5422 // Note: for an expanded parameter pack, getType() returns the type prior
5423 // to expansion. We could ask for the expanded type with getExpansionType(),
5424 // but it doesn't matter because substitution and expansion don't affect
5425 // whether a deduced type appears in the type.
5426 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
5427 return NTTP && NTTP->getType()->getContainedDeducedType();
5428 }
5429};
5430}
5431
5432void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5433 const TemplateArgumentLoc *TemplateArgs,
5434 unsigned NumTemplateArgs) {
5435 // <template-args> ::= I <template-arg>+ E
5436 Out << 'I';
5437 TemplateArgManglingInfo Info(TN);
5438 for (unsigned i = 0; i != NumTemplateArgs; ++i)
5439 mangleTemplateArg(TemplateArgs[i].getArgument(),
5440 Info.needExactType(i, TemplateArgs[i].getArgument()));
5441 Out << 'E';
5442}
5443
5444void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5445 const TemplateArgumentList &AL) {
5446 // <template-args> ::= I <template-arg>+ E
5447 Out << 'I';
5448 TemplateArgManglingInfo Info(TN);
5449 for (unsigned i = 0, e = AL.size(); i != e; ++i)
5450 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
5451 Out << 'E';
5452}
5453
5454void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5456 // <template-args> ::= I <template-arg>+ E
5457 Out << 'I';
5458 TemplateArgManglingInfo Info(TN);
5459 for (unsigned i = 0; i != Args.size(); ++i)
5460 mangleTemplateArg(Args[i], Info.needExactType(i, Args[i]));
5461 Out << 'E';
5462}
5463
5464void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
5465 // <template-arg> ::= <type> # type or template
5466 // ::= X <expression> E # expression
5467 // ::= <expr-primary> # simple expressions
5468 // ::= J <template-arg>* E # argument pack
5469 if (!A.isInstantiationDependent() || A.isDependent())
5470 A = Context.getASTContext().getCanonicalTemplateArgument(A);
5471
5472 switch (A.getKind()) {
5474 llvm_unreachable("Cannot mangle NULL template argument");
5475
5477 mangleType(A.getAsType());
5478 break;
5480 // This is mangled as <type>.
5481 mangleType(A.getAsTemplate());
5482 break;
5484 // <type> ::= Dp <type> # pack expansion (C++0x)
5485 Out << "Dp";
5486 mangleType(A.getAsTemplateOrTemplatePattern());
5487 break;
5489 mangleTemplateArgExpr(A.getAsExpr());
5490 break;
5492 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
5493 break;
5495 // <expr-primary> ::= L <mangled-name> E # external name
5496 ValueDecl *D = A.getAsDecl();
5497
5498 // Template parameter objects are modeled by reproducing a source form
5499 // produced as if by aggregate initialization.
5500 if (A.getParamTypeForDecl()->isRecordType()) {
5501 auto *TPO = cast<TemplateParamObjectDecl>(D);
5502 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
5503 TPO->getValue(), /*TopLevel=*/true,
5504 NeedExactType);
5505 break;
5506 }
5507
5508 ASTContext &Ctx = Context.getASTContext();
5509 APValue Value;
5510 if (D->isCXXInstanceMember())
5511 // Simple pointer-to-member with no conversion.
5512 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
5513 else if (D->getType()->isArrayType() &&
5515 A.getParamTypeForDecl()) &&
5516 Ctx.getLangOpts().getClangABICompat() >
5517 LangOptions::ClangABI::Ver11)
5518 // Build a value corresponding to this implicit array-to-pointer decay.
5521 /*OnePastTheEnd=*/false);
5522 else
5523 // Regular pointer or reference to a declaration.
5526 /*OnePastTheEnd=*/false);
5527 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
5528 NeedExactType);
5529 break;
5530 }
5532 mangleNullPointer(A.getNullPtrType());
5533 break;
5534 }
5536 // <template-arg> ::= J <template-arg>* E
5537 Out << 'J';
5538 for (const auto &P : A.pack_elements())
5539 mangleTemplateArg(P, NeedExactType);
5540 Out << 'E';
5541 }
5542 }
5543}
5544
5545void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
5546 ASTContext &Ctx = Context.getASTContext();
5547 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
5548 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
5549 return;
5550 }
5551
5552 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
5553 // correctly in cases where the template argument was
5554 // constructed from an expression rather than an already-evaluated
5555 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
5556 // 'Li0E'.
5557 //
5558 // We did special-case DeclRefExpr to attempt to DTRT for that one
5559 // expression-kind, but while doing so, unfortunately handled ParmVarDecl
5560 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
5561 // the proper 'Xfp_E'.
5562 E = E->IgnoreParenImpCasts();
5563 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5564 const ValueDecl *D = DRE->getDecl();
5565 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
5566 Out << 'L';
5567 mangle(D);
5568 Out << 'E';
5569 return;
5570 }
5571 }
5572 Out << 'X';
5573 mangleExpression(E);
5574 Out << 'E';
5575}
5576
5577/// Determine whether a given value is equivalent to zero-initialization for
5578/// the purpose of discarding a trailing portion of a 'tl' mangling.
5579///
5580/// Note that this is not in general equivalent to determining whether the
5581/// value has an all-zeroes bit pattern.
5582static bool isZeroInitialized(QualType T, const APValue &V) {
5583 // FIXME: mangleValueInTemplateArg has quadratic time complexity in
5584 // pathological cases due to using this, but it's a little awkward
5585 // to do this in linear time in general.
5586 switch (V.getKind()) {
5587 case APValue::None:
5590 return false;
5591
5592 case APValue::Struct: {
5593 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5594 assert(RD && "unexpected type for record value");
5595 unsigned I = 0;
5596 for (const CXXBaseSpecifier &BS : RD->bases()) {
5597 if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
5598 return false;
5599 ++I;
5600 }
5601 I = 0;
5602 for (const FieldDecl *FD : RD->fields()) {
5603 if (!FD->isUnnamedBitfield() &&
5604 !isZeroInitialized(FD->getType(), V.getStructField(I)))
5605 return false;
5606 ++I;
5607 }
5608 return true;
5609 }
5610
5611 case APValue::Union: {
5612 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5613 assert(RD && "unexpected type for union value");
5614 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
5615 for (const FieldDecl *FD : RD->fields()) {
5616 if (!FD->isUnnamedBitfield())
5617 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
5618 isZeroInitialized(FD->getType(), V.getUnionValue());
5619 }
5620 // If there are no fields (other than unnamed bitfields), the value is
5621 // necessarily zero-initialized.
5622 return true;
5623 }
5624
5625 case APValue::Array: {
5627 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
5628 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
5629 return false;
5630 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
5631 }
5632
5633 case APValue::Vector: {
5634 const VectorType *VT = T->castAs<VectorType>();
5635 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
5636 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
5637 return false;
5638 return true;
5639 }
5640
5641 case APValue::Int:
5642 return !V.getInt();
5643
5644 case APValue::Float:
5645 return V.getFloat().isPosZero();
5646
5648 return !V.getFixedPoint().getValue();
5649
5651 return V.getComplexFloatReal().isPosZero() &&
5652 V.getComplexFloatImag().isPosZero();
5653
5655 return !V.getComplexIntReal() && !V.getComplexIntImag();
5656
5657 case APValue::LValue:
5658 return V.isNullPointer();
5659
5661 return !V.getMemberPointerDecl();
5662 }
5663
5664 llvm_unreachable("Unhandled APValue::ValueKind enum");
5665}
5666
5667static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
5668 QualType T = LV.getLValueBase().getType();
5670 if (const ArrayType *AT = Ctx.getAsArrayType(T))
5671 T = AT->getElementType();
5672 else if (const FieldDecl *FD =
5673 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
5674 T = FD->getType();
5675 else
5676 T = Ctx.getRecordType(
5677 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
5678 }
5679 return T;
5680}
5681
5683 DiagnosticsEngine &Diags,
5684 const FieldDecl *FD) {
5685 // According to:
5686 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
5687 // For the purposes of mangling, the name of an anonymous union is considered
5688 // to be the name of the first named data member found by a pre-order,
5689 // depth-first, declaration-order walk of the data members of the anonymous
5690 // union.
5691
5692 if (FD->getIdentifier())
5693 return FD->getIdentifier();
5694
5695 // The only cases where the identifer of a FieldDecl would be blank is if the
5696 // field represents an anonymous record type or if it is an unnamed bitfield.
5697 // There is no type to descend into in the case of a bitfield, so we can just
5698 // return nullptr in that case.
5699 if (FD->isBitField())
5700 return nullptr;
5701 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
5702
5703 // Consider only the fields in declaration order, searched depth-first. We
5704 // don't care about the active member of the union, as all we are doing is
5705 // looking for a valid name. We also don't check bases, due to guidance from
5706 // the Itanium ABI folks.
5707 for (const FieldDecl *RDField : RD->fields()) {
5708 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
5709 return II;
5710 }
5711
5712 // According to the Itanium ABI: If there is no such data member (i.e., if all
5713 // of the data members in the union are unnamed), then there is no way for a
5714 // program to refer to the anonymous union, and there is therefore no need to
5715 // mangle its name. However, we should diagnose this anyway.
5716 unsigned DiagID = Diags.getCustomDiagID(
5717 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
5718 Diags.Report(UnionLoc, DiagID);
5719
5720 return nullptr;
5721}
5722
5723void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
5724 bool TopLevel,
5725 bool NeedExactType) {
5726 // Ignore all top-level cv-qualifiers, to match GCC.
5727 Qualifiers Quals;
5728 T = getASTContext().getUnqualifiedArrayType(T, Quals);
5729
5730 // A top-level expression that's not a primary expression is wrapped in X...E.
5731 bool IsPrimaryExpr = true;
5732 auto NotPrimaryExpr = [&] {
5733 if (TopLevel && IsPrimaryExpr)
5734 Out << 'X';
5735 IsPrimaryExpr = false;
5736 };
5737
5738 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
5739 switch (V.getKind()) {
5740 case APValue::None:
5742 Out << 'L';
5743 mangleType(T);
5744 Out << 'E';
5745 break;
5746
5748 llvm_unreachable("unexpected value kind in template argument");
5749
5750 case APValue::Struct: {
5751 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5752 assert(RD && "unexpected type for record value");
5753
5754 // Drop trailing zero-initialized elements.
5756 while (
5757 !Fields.empty() &&
5758 (Fields.back()->isUnnamedBitfield() ||
5759 isZeroInitialized(Fields.back()->getType(),
5760 V.getStructField(Fields.back()->getFieldIndex())))) {
5761 Fields.pop_back();
5762 }
5764 if (Fields.empty()) {
5765 while (!Bases.empty() &&
5766 isZeroInitialized(Bases.back().getType(),
5767 V.getStructBase(Bases.size() - 1)))
5768 Bases = Bases.drop_back();
5769 }
5770
5771 // <expression> ::= tl <type> <braced-expression>* E
5772 NotPrimaryExpr();
5773 Out << "tl";
5774 mangleType(T);
5775 for (unsigned I = 0, N = Bases.size(); I != N; ++I)
5776 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
5777 for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
5778 if (Fields[I]->isUnnamedBitfield())
5779 continue;
5780 mangleValueInTemplateArg(Fields[I]->getType(),
5781 V.getStructField(Fields[I]->getFieldIndex()),
5782 false);
5783 }
5784 Out << 'E';
5785 break;
5786 }
5787
5788 case APValue::Union: {
5789 assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
5790 const FieldDecl *FD = V.getUnionField();
5791
5792 if (!FD) {
5793 Out << 'L';
5794 mangleType(T);
5795 Out << 'E';
5796 break;
5797 }
5798
5799 // <braced-expression> ::= di <field source-name> <braced-expression>
5800 NotPrimaryExpr();