1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
14 // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
36 #define MANGLE_CHECKER 0
42 using namespace clang;
46 /// Retrieve the declaration context that should be used when mangling the given
48 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49 // The ABI assumes that lambda closure types that occur within
50 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
52 // not the case: the lambda closure type ends up living in the context
53 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
69 const DeclContext *DC = D->getDeclContext();
70 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
74 if (const auto *VD = dyn_cast<VarDecl>(D))
76 return VD->getASTContext().getTranslationUnitDecl();
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
80 return FD->getASTContext().getTranslationUnitDecl();
82 return DC->getRedeclContext();
85 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
89 static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
93 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
94 const DeclContext *DC = getEffectiveDeclContext(D);
95 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
96 if (isLocalContainerContext(DC))
97 return dyn_cast<RecordDecl>(D);
99 DC = getEffectiveDeclContext(D);
104 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
111 static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
116 static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
121 return Record->isLambda();
124 static const unsigned UnknownArity = ~0U;
126 class ItaniumMangleContextImpl : public ItaniumMangleContext {
127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
136 /// @name Mangler Entry Points
139 bool shouldMangleCXXName(const NamedDecl *D) override;
140 bool shouldMangleStringLiteral(const StringLiteral *) override {
143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
148 raw_ostream &) override;
149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
159 raw_ostream &) override;
160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
161 raw_ostream &) override;
163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180 // Lambda closure types are already numbered.
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
195 disc = discriminator - 2;
199 // Make up a reasonable number for internal decls.
200 unsigned &discriminator = Uniquifier[ND];
201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
205 if (discriminator == 1)
207 disc = discriminator-2;
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215 ItaniumMangleContextImpl &Context;
217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType;
230 /// The next substitution sequence number.
233 class FunctionTypeDepthState {
236 enum { InResultTypeMask = 1 };
239 FunctionTypeDepthState() : Bits(0) {}
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
257 void enterResultType() {
258 Bits |= InResultTypeMask;
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
281 class AbiTagState final {
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
292 ~AbiTagState() { pop(); }
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
299 !AdditionalAbiTags &&
300 "only function and variables need a list of additional abi tags");
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
306 // Don't emit abi tags for namespaces.
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
326 std::sort(TagList.begin(), TagList.end());
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
329 writeSortedUniqueAbiTags(Out, TagList);
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
385 ASTContext &getASTContext() const { return Context.getASTContext(); }
388 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
389 const NamedDecl *D = nullptr, bool NullOut_ = false)
390 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
391 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
392 // These can't be mangled without a ctor type or dtor type.
393 assert(!D || (!isa<CXXDestructorDecl>(D) &&
394 !isa<CXXConstructorDecl>(D)));
396 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
397 const CXXConstructorDecl *D, CXXCtorType Type)
398 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
399 SeqID(0), AbiTagsRoot(AbiTags) { }
400 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
401 const CXXDestructorDecl *D, CXXDtorType Type)
402 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
403 SeqID(0), AbiTagsRoot(AbiTags) { }
405 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
406 : Context(Outer.Context), Out(Out_), NullOut(false),
407 Structor(Outer.Structor), StructorType(Outer.StructorType),
408 SeqID(Outer.SeqID), AbiTagsRoot(AbiTags) {}
410 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
411 : Context(Outer.Context), Out(Out_), NullOut(true),
412 Structor(Outer.Structor), StructorType(Outer.StructorType),
413 SeqID(Outer.SeqID), AbiTagsRoot(AbiTags) {}
417 if (Out.str()[0] == '\01')
421 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
422 assert(status == 0 && "Could not demangle mangled name!");
426 raw_ostream &getStream() { return Out; }
428 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
429 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
431 void mangle(const NamedDecl *D);
432 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
433 void mangleNumber(const llvm::APSInt &I);
434 void mangleNumber(int64_t Number);
435 void mangleFloat(const llvm::APFloat &F);
436 void mangleFunctionEncoding(const FunctionDecl *FD);
437 void mangleSeqID(unsigned SeqID);
438 void mangleName(const NamedDecl *ND);
439 void mangleType(QualType T);
440 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
444 bool mangleSubstitution(const NamedDecl *ND);
445 bool mangleSubstitution(QualType T);
446 bool mangleSubstitution(TemplateName Template);
447 bool mangleSubstitution(uintptr_t Ptr);
449 void mangleExistingSubstitution(TemplateName name);
451 bool mangleStandardSubstitution(const NamedDecl *ND);
453 void addSubstitution(const NamedDecl *ND) {
454 ND = cast<NamedDecl>(ND->getCanonicalDecl());
456 addSubstitution(reinterpret_cast<uintptr_t>(ND));
458 void addSubstitution(QualType T);
459 void addSubstitution(TemplateName Template);
460 void addSubstitution(uintptr_t Ptr);
462 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
463 bool recursive = false);
464 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
465 DeclarationName name,
466 unsigned KnownArity = UnknownArity);
468 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
470 void mangleNameWithAbiTags(const NamedDecl *ND,
471 const AbiTagList *AdditionalAbiTags);
472 void mangleTemplateName(const TemplateDecl *TD,
473 const TemplateArgument *TemplateArgs,
474 unsigned NumTemplateArgs);
475 void mangleUnqualifiedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags) {
477 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
480 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
482 const AbiTagList *AdditionalAbiTags);
483 void mangleUnscopedName(const NamedDecl *ND,
484 const AbiTagList *AdditionalAbiTags);
485 void mangleUnscopedTemplateName(const TemplateDecl *ND,
486 const AbiTagList *AdditionalAbiTags);
487 void mangleUnscopedTemplateName(TemplateName,
488 const AbiTagList *AdditionalAbiTags);
489 void mangleSourceName(const IdentifierInfo *II);
490 void mangleSourceNameWithAbiTags(
491 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
492 void mangleLocalName(const Decl *D,
493 const AbiTagList *AdditionalAbiTags);
494 void mangleBlockForPrefix(const BlockDecl *Block);
495 void mangleUnqualifiedBlock(const BlockDecl *Block);
496 void mangleLambda(const CXXRecordDecl *Lambda);
497 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
498 const AbiTagList *AdditionalAbiTags,
499 bool NoFunction=false);
500 void mangleNestedName(const TemplateDecl *TD,
501 const TemplateArgument *TemplateArgs,
502 unsigned NumTemplateArgs);
503 void manglePrefix(NestedNameSpecifier *qualifier);
504 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
505 void manglePrefix(QualType type);
506 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
507 void mangleTemplatePrefix(TemplateName Template);
508 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
509 StringRef Prefix = "");
510 void mangleOperatorName(DeclarationName Name, unsigned Arity);
511 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
512 void mangleVendorQualifier(StringRef qualifier);
513 void mangleQualifiers(Qualifiers Quals);
514 void mangleRefQualifier(RefQualifierKind RefQualifier);
516 void mangleObjCMethodName(const ObjCMethodDecl *MD);
518 // Declare manglers for every type class.
519 #define ABSTRACT_TYPE(CLASS, PARENT)
520 #define NON_CANONICAL_TYPE(CLASS, PARENT)
521 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
522 #include "clang/AST/TypeNodes.def"
524 void mangleType(const TagType*);
525 void mangleType(TemplateName);
526 static StringRef getCallingConvQualifierName(CallingConv CC);
527 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
528 void mangleExtFunctionInfo(const FunctionType *T);
529 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
530 const FunctionDecl *FD = nullptr);
531 void mangleNeonVectorType(const VectorType *T);
532 void mangleAArch64NeonVectorType(const VectorType *T);
534 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
535 void mangleMemberExprBase(const Expr *base, bool isArrow);
536 void mangleMemberExpr(const Expr *base, bool isArrow,
537 NestedNameSpecifier *qualifier,
538 NamedDecl *firstQualifierLookup,
539 DeclarationName name,
540 unsigned knownArity);
541 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
542 void mangleInitListElements(const InitListExpr *InitList);
543 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
544 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
545 void mangleCXXDtorType(CXXDtorType T);
547 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
548 unsigned NumTemplateArgs);
549 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
550 unsigned NumTemplateArgs);
551 void mangleTemplateArgs(const TemplateArgumentList &AL);
552 void mangleTemplateArg(TemplateArgument A);
554 void mangleTemplateParameter(unsigned Index);
556 void mangleFunctionParam(const ParmVarDecl *parm);
558 void writeAbiTags(const NamedDecl *ND,
559 const AbiTagList *AdditionalAbiTags);
561 // Returns sorted unique list of ABI tags.
562 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
563 // Returns sorted unique list of ABI tags.
564 AbiTagList makeVariableTypeTags(const VarDecl *VD);
569 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
570 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
572 LanguageLinkage L = FD->getLanguageLinkage();
573 // Overloadable functions need mangling.
574 if (FD->hasAttr<OverloadableAttr>())
577 // "main" is not mangled.
581 // C++ functions and those whose names are not a simple identifier need
583 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
586 // C functions are not mangled.
587 if (L == CLanguageLinkage)
591 // Otherwise, no mangling is done outside C++ mode.
592 if (!getASTContext().getLangOpts().CPlusPlus)
595 const VarDecl *VD = dyn_cast<VarDecl>(D);
597 // C variables are not mangled.
601 // Variables at global scope with non-internal linkage are not mangled
602 const DeclContext *DC = getEffectiveDeclContext(D);
603 // Check for extern variable declared locally.
604 if (DC->isFunctionOrMethod() && D->hasLinkage())
605 while (!DC->isNamespace() && !DC->isTranslationUnit())
606 DC = getEffectiveParentContext(DC);
607 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
608 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
609 !isa<VarTemplateSpecializationDecl>(D))
616 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
617 const AbiTagList *AdditionalAbiTags) {
618 assert(AbiTags && "require AbiTagState");
619 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
622 void CXXNameMangler::mangleSourceNameWithAbiTags(
623 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
624 mangleSourceName(ND->getIdentifier());
625 writeAbiTags(ND, AdditionalAbiTags);
628 void CXXNameMangler::mangle(const NamedDecl *D) {
629 // <mangled-name> ::= _Z <encoding>
631 // ::= <special-name>
633 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
634 mangleFunctionEncoding(FD);
635 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
637 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
638 mangleName(IFD->getAnonField());
640 mangleName(cast<FieldDecl>(D));
643 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
644 // <encoding> ::= <function name> <bare-function-type>
646 // Don't mangle in the type if this isn't a decl we should typically mangle.
647 if (!Context.shouldMangleDeclName(FD)) {
652 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
653 if (ReturnTypeAbiTags.empty()) {
654 // There are no tags for return type, the simplest case.
656 mangleFunctionEncodingBareType(FD);
660 // Mangle function name and encoding to temporary buffer.
661 // We have to output name and encoding to the same mangler to get the same
662 // substitution as it will be in final mangling.
663 SmallString<256> FunctionEncodingBuf;
664 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
665 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
666 // Output name of the function.
667 FunctionEncodingMangler.disableDerivedAbiTags();
668 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
670 // Remember length of the function name in the buffer.
671 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
672 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
674 // Get tags from return type that are not present in function name or
676 const AbiTagList &UsedAbiTags =
677 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
678 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
679 AdditionalAbiTags.erase(
680 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
681 UsedAbiTags.begin(), UsedAbiTags.end(),
682 AdditionalAbiTags.begin()),
683 AdditionalAbiTags.end());
685 // Output name with implicit tags and function encoding from temporary buffer.
686 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
687 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
690 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
691 if (FD->hasAttr<EnableIfAttr>()) {
692 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
693 Out << "Ua9enable_ifI";
694 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
696 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
697 E = FD->getAttrs().rend();
699 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
703 mangleExpression(EIA->getCond());
707 FunctionTypeDepth.pop(Saved);
710 // When mangling an inheriting constructor, the bare function type used is
711 // that of the inherited constructor.
712 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
713 if (auto Inherited = CD->getInheritedConstructor())
714 FD = Inherited.getConstructor();
716 // Whether the mangling of a function type includes the return type depends on
717 // the context and the nature of the function. The rules for deciding whether
718 // the return type is included are:
720 // 1. Template functions (names or types) have return types encoded, with
721 // the exceptions listed below.
722 // 2. Function types not appearing as part of a function name mangling,
723 // e.g. parameters, pointer types, etc., have return type encoded, with the
724 // exceptions listed below.
725 // 3. Non-template function names do not have return types encoded.
727 // The exceptions mentioned in (1) and (2) above, for which the return type is
728 // never included, are
731 // 3. Conversion operator functions, e.g. operator int.
732 bool MangleReturnType = false;
733 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
734 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
735 isa<CXXConversionDecl>(FD)))
736 MangleReturnType = true;
738 // Mangle the type of the primary template.
739 FD = PrimaryTemplate->getTemplatedDecl();
742 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
743 MangleReturnType, FD);
746 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
747 while (isa<LinkageSpecDecl>(DC)) {
748 DC = getEffectiveParentContext(DC);
754 /// Return whether a given namespace is the 'std' namespace.
755 static bool isStd(const NamespaceDecl *NS) {
756 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
757 ->isTranslationUnit())
760 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
761 return II && II->isStr("std");
764 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
766 static bool isStdNamespace(const DeclContext *DC) {
767 if (!DC->isNamespace())
770 return isStd(cast<NamespaceDecl>(DC));
773 static const TemplateDecl *
774 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
775 // Check if we have a function template.
776 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
777 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
778 TemplateArgs = FD->getTemplateSpecializationArgs();
783 // Check if we have a class template.
784 if (const ClassTemplateSpecializationDecl *Spec =
785 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
786 TemplateArgs = &Spec->getTemplateArgs();
787 return Spec->getSpecializedTemplate();
790 // Check if we have a variable template.
791 if (const VarTemplateSpecializationDecl *Spec =
792 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
793 TemplateArgs = &Spec->getTemplateArgs();
794 return Spec->getSpecializedTemplate();
800 void CXXNameMangler::mangleName(const NamedDecl *ND) {
801 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
802 // Variables should have implicit tags from its type.
803 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
804 if (VariableTypeAbiTags.empty()) {
805 // Simple case no variable type tags.
806 mangleNameWithAbiTags(VD, nullptr);
810 // Mangle variable name to null stream to collect tags.
811 llvm::raw_null_ostream NullOutStream;
812 CXXNameMangler VariableNameMangler(*this, NullOutStream);
813 VariableNameMangler.disableDerivedAbiTags();
814 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
816 // Get tags from variable type that are not present in its name.
817 const AbiTagList &UsedAbiTags =
818 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
819 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
820 AdditionalAbiTags.erase(
821 std::set_difference(VariableTypeAbiTags.begin(),
822 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
823 UsedAbiTags.end(), AdditionalAbiTags.begin()),
824 AdditionalAbiTags.end());
826 // Output name with implicit tags.
827 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
829 mangleNameWithAbiTags(ND, nullptr);
833 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
834 const AbiTagList *AdditionalAbiTags) {
835 // <name> ::= <nested-name>
836 // ::= <unscoped-name>
837 // ::= <unscoped-template-name> <template-args>
840 const DeclContext *DC = getEffectiveDeclContext(ND);
842 // If this is an extern variable declared locally, the relevant DeclContext
843 // is that of the containing namespace, or the translation unit.
844 // FIXME: This is a hack; extern variables declared locally should have
845 // a proper semantic declaration context!
846 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
847 while (!DC->isNamespace() && !DC->isTranslationUnit())
848 DC = getEffectiveParentContext(DC);
849 else if (GetLocalClassDecl(ND)) {
850 mangleLocalName(ND, AdditionalAbiTags);
854 DC = IgnoreLinkageSpecDecls(DC);
856 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
857 // Check if we have a template.
858 const TemplateArgumentList *TemplateArgs = nullptr;
859 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
860 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
861 mangleTemplateArgs(*TemplateArgs);
865 mangleUnscopedName(ND, AdditionalAbiTags);
869 if (isLocalContainerContext(DC)) {
870 mangleLocalName(ND, AdditionalAbiTags);
874 mangleNestedName(ND, DC, AdditionalAbiTags);
877 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
878 const TemplateArgument *TemplateArgs,
879 unsigned NumTemplateArgs) {
880 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
882 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
883 mangleUnscopedTemplateName(TD, nullptr);
884 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
886 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
890 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
891 const AbiTagList *AdditionalAbiTags) {
892 // <unscoped-name> ::= <unqualified-name>
893 // ::= St <unqualified-name> # ::std::
895 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
898 mangleUnqualifiedName(ND, AdditionalAbiTags);
901 void CXXNameMangler::mangleUnscopedTemplateName(
902 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
903 // <unscoped-template-name> ::= <unscoped-name>
904 // ::= <substitution>
905 if (mangleSubstitution(ND))
908 // <template-template-param> ::= <template-param>
909 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
910 assert(!AdditionalAbiTags &&
911 "template template param cannot have abi tags");
912 mangleTemplateParameter(TTP->getIndex());
913 } else if (isa<BuiltinTemplateDecl>(ND)) {
914 mangleUnscopedName(ND, AdditionalAbiTags);
916 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
922 void CXXNameMangler::mangleUnscopedTemplateName(
923 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
924 // <unscoped-template-name> ::= <unscoped-name>
925 // ::= <substitution>
926 if (TemplateDecl *TD = Template.getAsTemplateDecl())
927 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
929 if (mangleSubstitution(Template))
932 assert(!AdditionalAbiTags &&
933 "dependent template name cannot have abi tags");
935 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
936 assert(Dependent && "Not a dependent template name?");
937 if (const IdentifierInfo *Id = Dependent->getIdentifier())
938 mangleSourceName(Id);
940 mangleOperatorName(Dependent->getOperator(), UnknownArity);
942 addSubstitution(Template);
945 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
947 // Floating-point literals are encoded using a fixed-length
948 // lowercase hexadecimal string corresponding to the internal
949 // representation (IEEE on Itanium), high-order bytes first,
950 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
952 // The 'without leading zeroes' thing seems to be an editorial
953 // mistake; see the discussion on cxx-abi-dev beginning on
956 // Our requirements here are just barely weird enough to justify
957 // using a custom algorithm instead of post-processing APInt::toString().
959 llvm::APInt valueBits = f.bitcastToAPInt();
960 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
961 assert(numCharacters != 0);
963 // Allocate a buffer of the right number of characters.
964 SmallVector<char, 20> buffer(numCharacters);
966 // Fill the buffer left-to-right.
967 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
968 // The bit-index of the next hex digit.
969 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
971 // Project out 4 bits starting at 'digitIndex'.
972 llvm::integerPart hexDigit
973 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
974 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
977 // Map that over to a lowercase hex digit.
978 static const char charForHex[16] = {
979 '0', '1', '2', '3', '4', '5', '6', '7',
980 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
982 buffer[stringIndex] = charForHex[hexDigit];
985 Out.write(buffer.data(), numCharacters);
988 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
989 if (Value.isSigned() && Value.isNegative()) {
991 Value.abs().print(Out, /*signed*/ false);
993 Value.print(Out, /*signed*/ false);
997 void CXXNameMangler::mangleNumber(int64_t Number) {
998 // <number> ::= [n] <non-negative decimal integer>
1007 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1008 // <call-offset> ::= h <nv-offset> _
1009 // ::= v <v-offset> _
1010 // <nv-offset> ::= <offset number> # non-virtual base override
1011 // <v-offset> ::= <offset number> _ <virtual offset number>
1012 // # virtual base override, with vcall offset
1015 mangleNumber(NonVirtual);
1021 mangleNumber(NonVirtual);
1023 mangleNumber(Virtual);
1027 void CXXNameMangler::manglePrefix(QualType type) {
1028 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1029 if (!mangleSubstitution(QualType(TST, 0))) {
1030 mangleTemplatePrefix(TST->getTemplateName());
1032 // FIXME: GCC does not appear to mangle the template arguments when
1033 // the template in question is a dependent template name. Should we
1034 // emulate that badness?
1035 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1036 addSubstitution(QualType(TST, 0));
1038 } else if (const auto *DTST =
1039 type->getAs<DependentTemplateSpecializationType>()) {
1040 if (!mangleSubstitution(QualType(DTST, 0))) {
1041 TemplateName Template = getASTContext().getDependentTemplateName(
1042 DTST->getQualifier(), DTST->getIdentifier());
1043 mangleTemplatePrefix(Template);
1045 // FIXME: GCC does not appear to mangle the template arguments when
1046 // the template in question is a dependent template name. Should we
1047 // emulate that badness?
1048 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1049 addSubstitution(QualType(DTST, 0));
1052 // We use the QualType mangle type variant here because it handles
1058 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1060 /// \param recursive - true if this is being called recursively,
1061 /// i.e. if there is more prefix "to the right".
1062 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1066 // <unresolved-name> ::= [gs] <base-unresolved-name>
1068 // T::x / decltype(p)::x
1069 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1071 // T::N::x /decltype(p)::N::x
1072 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1073 // <base-unresolved-name>
1075 // A::x, N::y, A<T>::z; "gs" means leading "::"
1076 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1077 // <base-unresolved-name>
1079 switch (qualifier->getKind()) {
1080 case NestedNameSpecifier::Global:
1083 // We want an 'sr' unless this is the entire NNS.
1087 // We never want an 'E' here.
1090 case NestedNameSpecifier::Super:
1091 llvm_unreachable("Can't mangle __super specifier");
1093 case NestedNameSpecifier::Namespace:
1094 if (qualifier->getPrefix())
1095 mangleUnresolvedPrefix(qualifier->getPrefix(),
1096 /*recursive*/ true);
1099 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1101 case NestedNameSpecifier::NamespaceAlias:
1102 if (qualifier->getPrefix())
1103 mangleUnresolvedPrefix(qualifier->getPrefix(),
1104 /*recursive*/ true);
1107 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1110 case NestedNameSpecifier::TypeSpec:
1111 case NestedNameSpecifier::TypeSpecWithTemplate: {
1112 const Type *type = qualifier->getAsType();
1114 // We only want to use an unresolved-type encoding if this is one of:
1116 // - a template type parameter
1117 // - a template template parameter with arguments
1118 // In all of these cases, we should have no prefix.
1119 if (qualifier->getPrefix()) {
1120 mangleUnresolvedPrefix(qualifier->getPrefix(),
1121 /*recursive*/ true);
1123 // Otherwise, all the cases want this.
1127 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1133 case NestedNameSpecifier::Identifier:
1134 // Member expressions can have these without prefixes.
1135 if (qualifier->getPrefix())
1136 mangleUnresolvedPrefix(qualifier->getPrefix(),
1137 /*recursive*/ true);
1141 mangleSourceName(qualifier->getAsIdentifier());
1142 // An Identifier has no type information, so we can't emit abi tags for it.
1146 // If this was the innermost part of the NNS, and we fell out to
1147 // here, append an 'E'.
1152 /// Mangle an unresolved-name, which is generally used for names which
1153 /// weren't resolved to specific entities.
1154 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1155 DeclarationName name,
1156 unsigned knownArity) {
1157 if (qualifier) mangleUnresolvedPrefix(qualifier);
1158 switch (name.getNameKind()) {
1159 // <base-unresolved-name> ::= <simple-id>
1160 case DeclarationName::Identifier:
1161 mangleSourceName(name.getAsIdentifierInfo());
1163 // <base-unresolved-name> ::= dn <destructor-name>
1164 case DeclarationName::CXXDestructorName:
1166 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1168 // <base-unresolved-name> ::= on <operator-name>
1169 case DeclarationName::CXXConversionFunctionName:
1170 case DeclarationName::CXXLiteralOperatorName:
1171 case DeclarationName::CXXOperatorName:
1173 mangleOperatorName(name, knownArity);
1175 case DeclarationName::CXXConstructorName:
1176 llvm_unreachable("Can't mangle a constructor name!");
1177 case DeclarationName::CXXUsingDirective:
1178 llvm_unreachable("Can't mangle a using directive name!");
1179 case DeclarationName::ObjCMultiArgSelector:
1180 case DeclarationName::ObjCOneArgSelector:
1181 case DeclarationName::ObjCZeroArgSelector:
1182 llvm_unreachable("Can't mangle Objective-C selector names here!");
1186 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1187 DeclarationName Name,
1188 unsigned KnownArity,
1189 const AbiTagList *AdditionalAbiTags) {
1190 unsigned Arity = KnownArity;
1191 // <unqualified-name> ::= <operator-name>
1192 // ::= <ctor-dtor-name>
1193 // ::= <source-name>
1194 switch (Name.getNameKind()) {
1195 case DeclarationName::Identifier: {
1196 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1197 // We must avoid conflicts between internally- and externally-
1198 // linked variable and function declaration names in the same TU:
1199 // void test() { extern void foo(); }
1200 // static void foo();
1201 // This naming convention is the same as that followed by GCC,
1202 // though it shouldn't actually matter.
1203 if (ND && ND->getFormalLinkage() == InternalLinkage &&
1204 getEffectiveDeclContext(ND)->isFileContext())
1207 mangleSourceName(II);
1208 writeAbiTags(ND, AdditionalAbiTags);
1212 // Otherwise, an anonymous entity. We must have a declaration.
1213 assert(ND && "mangling empty name without declaration");
1215 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1216 if (NS->isAnonymousNamespace()) {
1217 // This is how gcc mangles these names.
1218 Out << "12_GLOBAL__N_1";
1223 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1224 // We must have an anonymous union or struct declaration.
1225 const RecordDecl *RD =
1226 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1228 // Itanium C++ ABI 5.1.2:
1230 // For the purposes of mangling, the name of an anonymous union is
1231 // considered to be the name of the first named data member found by a
1232 // pre-order, depth-first, declaration-order walk of the data members of
1233 // the anonymous union. If there is no such data member (i.e., if all of
1234 // the data members in the union are unnamed), then there is no way for
1235 // a program to refer to the anonymous union, and there is therefore no
1236 // need to mangle its name.
1237 assert(RD->isAnonymousStructOrUnion()
1238 && "Expected anonymous struct or union!");
1239 const FieldDecl *FD = RD->findFirstNamedDataMember();
1241 // It's actually possible for various reasons for us to get here
1242 // with an empty anonymous struct / union. Fortunately, it
1243 // doesn't really matter what name we generate.
1245 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1247 mangleSourceName(FD->getIdentifier());
1248 // Not emitting abi tags: internal name anyway.
1252 // Class extensions have no name as a category, and it's possible
1253 // for them to be the semantic parent of certain declarations
1254 // (primarily, tag decls defined within declarations). Such
1255 // declarations will always have internal linkage, so the name
1256 // doesn't really matter, but we shouldn't crash on them. For
1257 // safety, just handle all ObjC containers here.
1258 if (isa<ObjCContainerDecl>(ND))
1261 // We must have an anonymous struct.
1262 const TagDecl *TD = cast<TagDecl>(ND);
1263 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1264 assert(TD->getDeclContext() == D->getDeclContext() &&
1265 "Typedef should not be in another decl context!");
1266 assert(D->getDeclName().getAsIdentifierInfo() &&
1267 "Typedef was not named!");
1268 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1269 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1270 // Explicit abi tags are still possible; take from underlying type, not
1272 writeAbiTags(TD, nullptr);
1276 // <unnamed-type-name> ::= <closure-type-name>
1278 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1279 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1280 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1281 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1282 assert(!AdditionalAbiTags &&
1283 "Lambda type cannot have additional abi tags");
1284 mangleLambda(Record);
1289 if (TD->isExternallyVisible()) {
1290 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1292 if (UnnamedMangle > 1)
1293 Out << UnnamedMangle - 2;
1295 writeAbiTags(TD, AdditionalAbiTags);
1299 // Get a unique id for the anonymous struct. If it is not a real output
1300 // ID doesn't matter so use fake one.
1301 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1303 // Mangle it as a source name in the form
1305 // where n is the length of the string.
1308 Str += llvm::utostr(AnonStructId);
1315 case DeclarationName::ObjCZeroArgSelector:
1316 case DeclarationName::ObjCOneArgSelector:
1317 case DeclarationName::ObjCMultiArgSelector:
1318 llvm_unreachable("Can't mangle Objective-C selector names here!");
1320 case DeclarationName::CXXConstructorName: {
1321 const CXXRecordDecl *InheritedFrom = nullptr;
1322 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1323 if (auto Inherited =
1324 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1325 InheritedFrom = Inherited.getConstructor()->getParent();
1326 InheritedTemplateArgs =
1327 Inherited.getConstructor()->getTemplateSpecializationArgs();
1331 // If the named decl is the C++ constructor we're mangling, use the type
1333 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1335 // Otherwise, use the complete constructor name. This is relevant if a
1336 // class with a constructor is declared within a constructor.
1337 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1339 // FIXME: The template arguments are part of the enclosing prefix or
1340 // nested-name, but it's more convenient to mangle them here.
1341 if (InheritedTemplateArgs)
1342 mangleTemplateArgs(*InheritedTemplateArgs);
1344 writeAbiTags(ND, AdditionalAbiTags);
1348 case DeclarationName::CXXDestructorName:
1350 // If the named decl is the C++ destructor we're mangling, use the type we
1352 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1354 // Otherwise, use the complete destructor name. This is relevant if a
1355 // class with a destructor is declared within a destructor.
1356 mangleCXXDtorType(Dtor_Complete);
1357 writeAbiTags(ND, AdditionalAbiTags);
1360 case DeclarationName::CXXOperatorName:
1361 if (ND && Arity == UnknownArity) {
1362 Arity = cast<FunctionDecl>(ND)->getNumParams();
1364 // If we have a member function, we need to include the 'this' pointer.
1365 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1366 if (!MD->isStatic())
1370 case DeclarationName::CXXConversionFunctionName:
1371 case DeclarationName::CXXLiteralOperatorName:
1372 mangleOperatorName(Name, Arity);
1373 writeAbiTags(ND, AdditionalAbiTags);
1376 case DeclarationName::CXXUsingDirective:
1377 llvm_unreachable("Can't mangle a using directive name!");
1381 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1382 // <source-name> ::= <positive length number> <identifier>
1383 // <number> ::= [n] <non-negative decimal integer>
1384 // <identifier> ::= <unqualified source code identifier>
1385 Out << II->getLength() << II->getName();
1388 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1389 const DeclContext *DC,
1390 const AbiTagList *AdditionalAbiTags,
1393 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1394 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1395 // <template-args> E
1398 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1399 Qualifiers MethodQuals =
1400 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1401 // We do not consider restrict a distinguishing attribute for overloading
1402 // purposes so we must not mangle it.
1403 MethodQuals.removeRestrict();
1404 mangleQualifiers(MethodQuals);
1405 mangleRefQualifier(Method->getRefQualifier());
1408 // Check if we have a template.
1409 const TemplateArgumentList *TemplateArgs = nullptr;
1410 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1411 mangleTemplatePrefix(TD, NoFunction);
1412 mangleTemplateArgs(*TemplateArgs);
1415 manglePrefix(DC, NoFunction);
1416 mangleUnqualifiedName(ND, AdditionalAbiTags);
1421 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1422 const TemplateArgument *TemplateArgs,
1423 unsigned NumTemplateArgs) {
1424 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1428 mangleTemplatePrefix(TD);
1429 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1434 void CXXNameMangler::mangleLocalName(const Decl *D,
1435 const AbiTagList *AdditionalAbiTags) {
1436 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1437 // := Z <function encoding> E s [<discriminator>]
1438 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1440 // <discriminator> := _ <non-negative number>
1441 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1442 const RecordDecl *RD = GetLocalClassDecl(D);
1443 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1448 AbiTagState LocalAbiTags(AbiTags);
1450 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1451 mangleObjCMethodName(MD);
1452 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1453 mangleBlockForPrefix(BD);
1455 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1457 // Implicit ABI tags (from namespace) are not available in the following
1458 // entity; reset to actually emitted tags, which are available.
1459 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1464 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1465 // be a bug that is fixed in trunk.
1468 // The parameter number is omitted for the last parameter, 0 for the
1469 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1470 // <entity name> will of course contain a <closure-type-name>: Its
1471 // numbering will be local to the particular argument in which it appears
1472 // -- other default arguments do not affect its encoding.
1473 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1474 if (CXXRD->isLambda()) {
1475 if (const ParmVarDecl *Parm
1476 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1477 if (const FunctionDecl *Func
1478 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1480 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1482 mangleNumber(Num - 2);
1488 // Mangle the name relative to the closest enclosing function.
1489 // equality ok because RD derived from ND above
1491 mangleUnqualifiedName(RD, AdditionalAbiTags);
1492 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1493 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1494 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1495 mangleUnqualifiedBlock(BD);
1497 const NamedDecl *ND = cast<NamedDecl>(D);
1498 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1499 true /*NoFunction*/);
1501 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1502 // Mangle a block in a default parameter; see above explanation for
1504 if (const ParmVarDecl *Parm
1505 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1506 if (const FunctionDecl *Func
1507 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1509 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1511 mangleNumber(Num - 2);
1516 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1517 mangleUnqualifiedBlock(BD);
1519 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1522 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1524 if (Context.getNextDiscriminator(ND, disc)) {
1528 Out << "__" << disc << '_';
1533 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1534 if (GetLocalClassDecl(Block)) {
1535 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1538 const DeclContext *DC = getEffectiveDeclContext(Block);
1539 if (isLocalContainerContext(DC)) {
1540 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1543 manglePrefix(getEffectiveDeclContext(Block));
1544 mangleUnqualifiedBlock(Block);
1547 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1548 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1549 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1550 Context->getDeclContext()->isRecord()) {
1551 const auto *ND = cast<NamedDecl>(Context);
1552 if (ND->getIdentifier()) {
1553 mangleSourceNameWithAbiTags(ND);
1559 // If we have a block mangling number, use it.
1560 unsigned Number = Block->getBlockManglingNumber();
1561 // Otherwise, just make up a number. It doesn't matter what it is because
1562 // the symbol in question isn't externally visible.
1564 Number = Context.getBlockId(Block, false);
1571 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1572 // If the context of a closure type is an initializer for a class member
1573 // (static or nonstatic), it is encoded in a qualified name with a final
1574 // <prefix> of the form:
1576 // <data-member-prefix> := <member source-name> M
1578 // Technically, the data-member-prefix is part of the <prefix>. However,
1579 // since a closure type will always be mangled with a prefix, it's easier
1580 // to emit that last part of the prefix here.
1581 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1582 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1583 Context->getDeclContext()->isRecord()) {
1584 if (const IdentifierInfo *Name
1585 = cast<NamedDecl>(Context)->getIdentifier()) {
1586 mangleSourceName(Name);
1593 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1594 getAs<FunctionProtoType>();
1595 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1596 Lambda->getLambdaStaticInvoker());
1599 // The number is omitted for the first closure type with a given
1600 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1601 // (in lexical order) with that same <lambda-sig> and context.
1603 // The AST keeps track of the number for us.
1604 unsigned Number = Lambda->getLambdaManglingNumber();
1605 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1607 mangleNumber(Number - 2);
1611 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1612 switch (qualifier->getKind()) {
1613 case NestedNameSpecifier::Global:
1617 case NestedNameSpecifier::Super:
1618 llvm_unreachable("Can't mangle __super specifier");
1620 case NestedNameSpecifier::Namespace:
1621 mangleName(qualifier->getAsNamespace());
1624 case NestedNameSpecifier::NamespaceAlias:
1625 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1628 case NestedNameSpecifier::TypeSpec:
1629 case NestedNameSpecifier::TypeSpecWithTemplate:
1630 manglePrefix(QualType(qualifier->getAsType(), 0));
1633 case NestedNameSpecifier::Identifier:
1634 // Member expressions can have these without prefixes, but that
1635 // should end up in mangleUnresolvedPrefix instead.
1636 assert(qualifier->getPrefix());
1637 manglePrefix(qualifier->getPrefix());
1639 mangleSourceName(qualifier->getAsIdentifier());
1643 llvm_unreachable("unexpected nested name specifier");
1646 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1647 // <prefix> ::= <prefix> <unqualified-name>
1648 // ::= <template-prefix> <template-args>
1649 // ::= <template-param>
1651 // ::= <substitution>
1653 DC = IgnoreLinkageSpecDecls(DC);
1655 if (DC->isTranslationUnit())
1658 if (NoFunction && isLocalContainerContext(DC))
1661 assert(!isLocalContainerContext(DC));
1663 const NamedDecl *ND = cast<NamedDecl>(DC);
1664 if (mangleSubstitution(ND))
1667 // Check if we have a template.
1668 const TemplateArgumentList *TemplateArgs = nullptr;
1669 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1670 mangleTemplatePrefix(TD);
1671 mangleTemplateArgs(*TemplateArgs);
1673 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1674 mangleUnqualifiedName(ND, nullptr);
1677 addSubstitution(ND);
1680 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1681 // <template-prefix> ::= <prefix> <template unqualified-name>
1682 // ::= <template-param>
1683 // ::= <substitution>
1684 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1685 return mangleTemplatePrefix(TD);
1687 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1688 manglePrefix(Qualified->getQualifier());
1690 if (OverloadedTemplateStorage *Overloaded
1691 = Template.getAsOverloadedTemplate()) {
1692 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1693 UnknownArity, nullptr);
1697 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1698 assert(Dependent && "Unknown template name kind?");
1699 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1700 manglePrefix(Qualifier);
1701 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1704 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1706 // <template-prefix> ::= <prefix> <template unqualified-name>
1707 // ::= <template-param>
1708 // ::= <substitution>
1709 // <template-template-param> ::= <template-param>
1712 if (mangleSubstitution(ND))
1715 // <template-template-param> ::= <template-param>
1716 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1717 mangleTemplateParameter(TTP->getIndex());
1719 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1720 if (isa<BuiltinTemplateDecl>(ND))
1721 mangleUnqualifiedName(ND, nullptr);
1723 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1726 addSubstitution(ND);
1729 /// Mangles a template name under the production <type>. Required for
1730 /// template template arguments.
1731 /// <type> ::= <class-enum-type>
1732 /// ::= <template-param>
1733 /// ::= <substitution>
1734 void CXXNameMangler::mangleType(TemplateName TN) {
1735 if (mangleSubstitution(TN))
1738 TemplateDecl *TD = nullptr;
1740 switch (TN.getKind()) {
1741 case TemplateName::QualifiedTemplate:
1742 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1745 case TemplateName::Template:
1746 TD = TN.getAsTemplateDecl();
1750 if (isa<TemplateTemplateParmDecl>(TD))
1751 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1756 case TemplateName::OverloadedTemplate:
1757 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1759 case TemplateName::DependentTemplate: {
1760 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1761 assert(Dependent->isIdentifier());
1763 // <class-enum-type> ::= <name>
1764 // <name> ::= <nested-name>
1765 mangleUnresolvedPrefix(Dependent->getQualifier());
1766 mangleSourceName(Dependent->getIdentifier());
1770 case TemplateName::SubstTemplateTemplateParm: {
1771 // Substituted template parameters are mangled as the substituted
1772 // template. This will check for the substitution twice, which is
1773 // fine, but we have to return early so that we don't try to *add*
1774 // the substitution twice.
1775 SubstTemplateTemplateParmStorage *subst
1776 = TN.getAsSubstTemplateTemplateParm();
1777 mangleType(subst->getReplacement());
1781 case TemplateName::SubstTemplateTemplateParmPack: {
1782 // FIXME: not clear how to mangle this!
1783 // template <template <class> class T...> class A {
1784 // template <template <class> class U...> void foo(B<T,U> x...);
1786 Out << "_SUBSTPACK_";
1791 addSubstitution(TN);
1794 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1796 // Only certain other types are valid as prefixes; enumerate them.
1797 switch (Ty->getTypeClass()) {
1800 case Type::Adjusted:
1803 case Type::BlockPointer:
1804 case Type::LValueReference:
1805 case Type::RValueReference:
1806 case Type::MemberPointer:
1807 case Type::ConstantArray:
1808 case Type::IncompleteArray:
1809 case Type::VariableArray:
1810 case Type::DependentSizedArray:
1811 case Type::DependentSizedExtVector:
1813 case Type::ExtVector:
1814 case Type::FunctionProto:
1815 case Type::FunctionNoProto:
1817 case Type::Attributed:
1819 case Type::PackExpansion:
1820 case Type::ObjCObject:
1821 case Type::ObjCInterface:
1822 case Type::ObjCObjectPointer:
1825 llvm_unreachable("type is illegal as a nested name specifier");
1827 case Type::SubstTemplateTypeParmPack:
1828 // FIXME: not clear how to mangle this!
1829 // template <class T...> class A {
1830 // template <class U...> void foo(decltype(T::foo(U())) x...);
1832 Out << "_SUBSTPACK_";
1835 // <unresolved-type> ::= <template-param>
1837 // ::= <template-template-param> <template-args>
1838 // (this last is not official yet)
1839 case Type::TypeOfExpr:
1841 case Type::Decltype:
1842 case Type::TemplateTypeParm:
1843 case Type::UnaryTransform:
1844 case Type::SubstTemplateTypeParm:
1846 // Some callers want a prefix before the mangled type.
1849 // This seems to do everything we want. It's not really
1850 // sanctioned for a substituted template parameter, though.
1853 // We never want to print 'E' directly after an unresolved-type,
1854 // so we return directly.
1858 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
1861 case Type::UnresolvedUsing:
1862 mangleSourceNameWithAbiTags(
1863 cast<UnresolvedUsingType>(Ty)->getDecl());
1868 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
1871 case Type::TemplateSpecialization: {
1872 const TemplateSpecializationType *TST =
1873 cast<TemplateSpecializationType>(Ty);
1874 TemplateName TN = TST->getTemplateName();
1875 switch (TN.getKind()) {
1876 case TemplateName::Template:
1877 case TemplateName::QualifiedTemplate: {
1878 TemplateDecl *TD = TN.getAsTemplateDecl();
1880 // If the base is a template template parameter, this is an
1882 assert(TD && "no template for template specialization type");
1883 if (isa<TemplateTemplateParmDecl>(TD))
1884 goto unresolvedType;
1886 mangleSourceNameWithAbiTags(TD);
1890 case TemplateName::OverloadedTemplate:
1891 case TemplateName::DependentTemplate:
1892 llvm_unreachable("invalid base for a template specialization type");
1894 case TemplateName::SubstTemplateTemplateParm: {
1895 SubstTemplateTemplateParmStorage *subst =
1896 TN.getAsSubstTemplateTemplateParm();
1897 mangleExistingSubstitution(subst->getReplacement());
1901 case TemplateName::SubstTemplateTemplateParmPack: {
1902 // FIXME: not clear how to mangle this!
1903 // template <template <class U> class T...> class A {
1904 // template <class U...> void foo(decltype(T<U>::foo) x...);
1906 Out << "_SUBSTPACK_";
1911 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1915 case Type::InjectedClassName:
1916 mangleSourceNameWithAbiTags(
1917 cast<InjectedClassNameType>(Ty)->getDecl());
1920 case Type::DependentName:
1921 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1924 case Type::DependentTemplateSpecialization: {
1925 const DependentTemplateSpecializationType *DTST =
1926 cast<DependentTemplateSpecializationType>(Ty);
1927 mangleSourceName(DTST->getIdentifier());
1928 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1932 case Type::Elaborated:
1933 return mangleUnresolvedTypeOrSimpleId(
1934 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1940 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1941 switch (Name.getNameKind()) {
1942 case DeclarationName::CXXConstructorName:
1943 case DeclarationName::CXXDestructorName:
1944 case DeclarationName::CXXUsingDirective:
1945 case DeclarationName::Identifier:
1946 case DeclarationName::ObjCMultiArgSelector:
1947 case DeclarationName::ObjCOneArgSelector:
1948 case DeclarationName::ObjCZeroArgSelector:
1949 llvm_unreachable("Not an operator name");
1951 case DeclarationName::CXXConversionFunctionName:
1952 // <operator-name> ::= cv <type> # (cast)
1954 mangleType(Name.getCXXNameType());
1957 case DeclarationName::CXXLiteralOperatorName:
1959 mangleSourceName(Name.getCXXLiteralIdentifier());
1962 case DeclarationName::CXXOperatorName:
1963 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1969 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1971 // <operator-name> ::= nw # new
1972 case OO_New: Out << "nw"; break;
1974 case OO_Array_New: Out << "na"; break;
1976 case OO_Delete: Out << "dl"; break;
1977 // ::= da # delete[]
1978 case OO_Array_Delete: Out << "da"; break;
1979 // ::= ps # + (unary)
1980 // ::= pl # + (binary or unknown)
1982 Out << (Arity == 1? "ps" : "pl"); break;
1983 // ::= ng # - (unary)
1984 // ::= mi # - (binary or unknown)
1986 Out << (Arity == 1? "ng" : "mi"); break;
1987 // ::= ad # & (unary)
1988 // ::= an # & (binary or unknown)
1990 Out << (Arity == 1? "ad" : "an"); break;
1991 // ::= de # * (unary)
1992 // ::= ml # * (binary or unknown)
1994 // Use binary when unknown.
1995 Out << (Arity == 1? "de" : "ml"); break;
1997 case OO_Tilde: Out << "co"; break;
1999 case OO_Slash: Out << "dv"; break;
2001 case OO_Percent: Out << "rm"; break;
2003 case OO_Pipe: Out << "or"; break;
2005 case OO_Caret: Out << "eo"; break;
2007 case OO_Equal: Out << "aS"; break;
2009 case OO_PlusEqual: Out << "pL"; break;
2011 case OO_MinusEqual: Out << "mI"; break;
2013 case OO_StarEqual: Out << "mL"; break;
2015 case OO_SlashEqual: Out << "dV"; break;
2017 case OO_PercentEqual: Out << "rM"; break;
2019 case OO_AmpEqual: Out << "aN"; break;
2021 case OO_PipeEqual: Out << "oR"; break;
2023 case OO_CaretEqual: Out << "eO"; break;
2025 case OO_LessLess: Out << "ls"; break;
2027 case OO_GreaterGreater: Out << "rs"; break;
2029 case OO_LessLessEqual: Out << "lS"; break;
2031 case OO_GreaterGreaterEqual: Out << "rS"; break;
2033 case OO_EqualEqual: Out << "eq"; break;
2035 case OO_ExclaimEqual: Out << "ne"; break;
2037 case OO_Less: Out << "lt"; break;
2039 case OO_Greater: Out << "gt"; break;
2041 case OO_LessEqual: Out << "le"; break;
2043 case OO_GreaterEqual: Out << "ge"; break;
2045 case OO_Exclaim: Out << "nt"; break;
2047 case OO_AmpAmp: Out << "aa"; break;
2049 case OO_PipePipe: Out << "oo"; break;
2051 case OO_PlusPlus: Out << "pp"; break;
2053 case OO_MinusMinus: Out << "mm"; break;
2055 case OO_Comma: Out << "cm"; break;
2057 case OO_ArrowStar: Out << "pm"; break;
2059 case OO_Arrow: Out << "pt"; break;
2061 case OO_Call: Out << "cl"; break;
2063 case OO_Subscript: Out << "ix"; break;
2066 // The conditional operator can't be overloaded, but we still handle it when
2067 // mangling expressions.
2068 case OO_Conditional: Out << "qu"; break;
2069 // Proposal on cxx-abi-dev, 2015-10-21.
2070 // ::= aw # co_await
2071 case OO_Coawait: Out << "aw"; break;
2074 case NUM_OVERLOADED_OPERATORS:
2075 llvm_unreachable("Not an overloaded operator");
2079 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
2080 // Vendor qualifiers come first.
2082 // Address space qualifiers start with an ordinary letter.
2083 if (Quals.hasAddressSpace()) {
2084 // Address space extension:
2086 // <type> ::= U <target-addrspace>
2087 // <type> ::= U <OpenCL-addrspace>
2088 // <type> ::= U <CUDA-addrspace>
2090 SmallString<64> ASString;
2091 unsigned AS = Quals.getAddressSpace();
2093 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2094 // <target-addrspace> ::= "AS" <address-space-number>
2095 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2096 ASString = "AS" + llvm::utostr(TargetAS);
2099 default: llvm_unreachable("Not a language specific address space");
2100 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
2101 case LangAS::opencl_global: ASString = "CLglobal"; break;
2102 case LangAS::opencl_local: ASString = "CLlocal"; break;
2103 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2104 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2105 case LangAS::cuda_device: ASString = "CUdevice"; break;
2106 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2107 case LangAS::cuda_shared: ASString = "CUshared"; break;
2110 mangleVendorQualifier(ASString);
2113 // The ARC ownership qualifiers start with underscores.
2114 switch (Quals.getObjCLifetime()) {
2115 // Objective-C ARC Extension:
2117 // <type> ::= U "__strong"
2118 // <type> ::= U "__weak"
2119 // <type> ::= U "__autoreleasing"
2120 case Qualifiers::OCL_None:
2123 case Qualifiers::OCL_Weak:
2124 mangleVendorQualifier("__weak");
2127 case Qualifiers::OCL_Strong:
2128 mangleVendorQualifier("__strong");
2131 case Qualifiers::OCL_Autoreleasing:
2132 mangleVendorQualifier("__autoreleasing");
2135 case Qualifiers::OCL_ExplicitNone:
2136 // The __unsafe_unretained qualifier is *not* mangled, so that
2137 // __unsafe_unretained types in ARC produce the same manglings as the
2138 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2139 // better ABI compatibility.
2141 // It's safe to do this because unqualified 'id' won't show up
2142 // in any type signatures that need to be mangled.
2146 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2147 if (Quals.hasRestrict())
2149 if (Quals.hasVolatile())
2151 if (Quals.hasConst())
2155 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2156 Out << 'U' << name.size() << name;
2159 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2160 // <ref-qualifier> ::= R # lvalue reference
2161 // ::= O # rvalue-reference
2162 switch (RefQualifier) {
2176 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2177 Context.mangleObjCMethodName(MD, Out);
2180 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2183 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2185 if (Ty->isOpenCLSpecificType())
2187 if (Ty->isBuiltinType())
2193 void CXXNameMangler::mangleType(QualType T) {
2194 // If our type is instantiation-dependent but not dependent, we mangle
2195 // it as it was written in the source, removing any top-level sugar.
2196 // Otherwise, use the canonical type.
2198 // FIXME: This is an approximation of the instantiation-dependent name
2199 // mangling rules, since we should really be using the type as written and
2200 // augmented via semantic analysis (i.e., with implicit conversions and
2201 // default template arguments) for any instantiation-dependent type.
2202 // Unfortunately, that requires several changes to our AST:
2203 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2204 // uniqued, so that we can handle substitutions properly
2205 // - Default template arguments will need to be represented in the
2206 // TemplateSpecializationType, since they need to be mangled even though
2207 // they aren't written.
2208 // - Conversions on non-type template arguments need to be expressed, since
2209 // they can affect the mangling of sizeof/alignof.
2210 if (!T->isInstantiationDependentType() || T->isDependentType())
2211 T = T.getCanonicalType();
2213 // Desugar any types that are purely sugar.
2215 // Don't desugar through template specialization types that aren't
2216 // type aliases. We need to mangle the template arguments as written.
2217 if (const TemplateSpecializationType *TST
2218 = dyn_cast<TemplateSpecializationType>(T))
2219 if (!TST->isTypeAlias())
2223 = T.getSingleStepDesugaredType(Context.getASTContext());
2230 SplitQualType split = T.split();
2231 Qualifiers quals = split.Quals;
2232 const Type *ty = split.Ty;
2234 bool isSubstitutable = isTypeSubstitutable(quals, ty);
2235 if (isSubstitutable && mangleSubstitution(T))
2238 // If we're mangling a qualified array type, push the qualifiers to
2239 // the element type.
2240 if (quals && isa<ArrayType>(T)) {
2241 ty = Context.getASTContext().getAsArrayType(T);
2242 quals = Qualifiers();
2244 // Note that we don't update T: we want to add the
2245 // substitution at the original type.
2249 mangleQualifiers(quals);
2250 // Recurse: even if the qualified type isn't yet substitutable,
2251 // the unqualified type might be.
2252 mangleType(QualType(ty, 0));
2254 switch (ty->getTypeClass()) {
2255 #define ABSTRACT_TYPE(CLASS, PARENT)
2256 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2258 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2260 #define TYPE(CLASS, PARENT) \
2262 mangleType(static_cast<const CLASS##Type*>(ty)); \
2264 #include "clang/AST/TypeNodes.def"
2268 // Add the substitution.
2269 if (isSubstitutable)
2273 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2274 if (!mangleStandardSubstitution(ND))
2278 void CXXNameMangler::mangleType(const BuiltinType *T) {
2279 // <type> ::= <builtin-type>
2280 // <builtin-type> ::= v # void
2284 // ::= a # signed char
2285 // ::= h # unsigned char
2287 // ::= t # unsigned short
2289 // ::= j # unsigned int
2291 // ::= m # unsigned long
2292 // ::= x # long long, __int64
2293 // ::= y # unsigned long long, __int64
2295 // ::= o # unsigned __int128
2298 // ::= e # long double, __float80
2299 // ::= g # __float128
2300 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2301 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2302 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2303 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2304 // ::= Di # char32_t
2305 // ::= Ds # char16_t
2306 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2307 // ::= u <source-name> # vendor extended type
2308 std::string type_name;
2309 switch (T->getKind()) {
2310 case BuiltinType::Void:
2313 case BuiltinType::Bool:
2316 case BuiltinType::Char_U:
2317 case BuiltinType::Char_S:
2320 case BuiltinType::UChar:
2323 case BuiltinType::UShort:
2326 case BuiltinType::UInt:
2329 case BuiltinType::ULong:
2332 case BuiltinType::ULongLong:
2335 case BuiltinType::UInt128:
2338 case BuiltinType::SChar:
2341 case BuiltinType::WChar_S:
2342 case BuiltinType::WChar_U:
2345 case BuiltinType::Char16:
2348 case BuiltinType::Char32:
2351 case BuiltinType::Short:
2354 case BuiltinType::Int:
2357 case BuiltinType::Long:
2360 case BuiltinType::LongLong:
2363 case BuiltinType::Int128:
2366 case BuiltinType::Half:
2369 case BuiltinType::Float:
2372 case BuiltinType::Double:
2375 case BuiltinType::LongDouble:
2376 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2380 case BuiltinType::Float128:
2381 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2382 Out << "U10__float128"; // Match the GCC mangling
2386 case BuiltinType::NullPtr:
2390 #define BUILTIN_TYPE(Id, SingletonId)
2391 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2392 case BuiltinType::Id:
2393 #include "clang/AST/BuiltinTypes.def"
2394 case BuiltinType::Dependent:
2396 llvm_unreachable("mangling a placeholder type");
2398 case BuiltinType::ObjCId:
2399 Out << "11objc_object";
2401 case BuiltinType::ObjCClass:
2402 Out << "10objc_class";
2404 case BuiltinType::ObjCSel:
2405 Out << "13objc_selector";
2407 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2408 case BuiltinType::Id: \
2409 type_name = "ocl_" #ImgType "_" #Suffix; \
2410 Out << type_name.size() << type_name; \
2412 #include "clang/Basic/OpenCLImageTypes.def"
2413 case BuiltinType::OCLSampler:
2414 Out << "11ocl_sampler";
2416 case BuiltinType::OCLEvent:
2417 Out << "9ocl_event";
2419 case BuiltinType::OCLClkEvent:
2420 Out << "12ocl_clkevent";
2422 case BuiltinType::OCLQueue:
2423 Out << "9ocl_queue";
2425 case BuiltinType::OCLNDRange:
2426 Out << "11ocl_ndrange";
2428 case BuiltinType::OCLReserveID:
2429 Out << "13ocl_reserveid";
2434 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2440 case CC_X86FastCall:
2441 case CC_X86ThisCall:
2442 case CC_X86VectorCall:
2444 case CC_X86_64Win64:
2448 case CC_IntelOclBicc:
2449 case CC_SpirFunction:
2450 case CC_OpenCLKernel:
2451 case CC_PreserveMost:
2452 case CC_PreserveAll:
2453 // FIXME: we should be mangling all of the above.
2459 llvm_unreachable("bad calling convention");
2462 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2464 if (T->getExtInfo() == FunctionType::ExtInfo())
2467 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2468 // This will get more complicated in the future if we mangle other
2469 // things here; but for now, since we mangle ns_returns_retained as
2470 // a qualifier on the result type, we can get away with this:
2471 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2472 if (!CCQualifier.empty())
2473 mangleVendorQualifier(CCQualifier);
2480 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2481 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2483 // Note that these are *not* substitution candidates. Demanglers might
2484 // have trouble with this if the parameter type is fully substituted.
2486 switch (PI.getABI()) {
2487 case ParameterABI::Ordinary:
2490 // All of these start with "swift", so they come before "ns_consumed".
2491 case ParameterABI::SwiftContext:
2492 case ParameterABI::SwiftErrorResult:
2493 case ParameterABI::SwiftIndirectResult:
2494 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2498 if (PI.isConsumed())
2499 mangleVendorQualifier("ns_consumed");
2502 // <type> ::= <function-type>
2503 // <function-type> ::= [<CV-qualifiers>] F [Y]
2504 // <bare-function-type> [<ref-qualifier>] E
2505 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2506 mangleExtFunctionInfo(T);
2508 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2509 // e.g. "const" in "int (A::*)() const".
2510 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2514 // FIXME: We don't have enough information in the AST to produce the 'Y'
2515 // encoding for extern "C" function types.
2516 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2518 // Mangle the ref-qualifier, if present.
2519 mangleRefQualifier(T->getRefQualifier());
2524 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2525 // Function types without prototypes can arise when mangling a function type
2526 // within an overloadable function in C. We mangle these as the absence of any
2527 // parameter types (not even an empty parameter list).
2530 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2532 FunctionTypeDepth.enterResultType();
2533 mangleType(T->getReturnType());
2534 FunctionTypeDepth.leaveResultType();
2536 FunctionTypeDepth.pop(saved);
2540 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2541 bool MangleReturnType,
2542 const FunctionDecl *FD) {
2543 // Record that we're in a function type. See mangleFunctionParam
2544 // for details on what we're trying to achieve here.
2545 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2547 // <bare-function-type> ::= <signature type>+
2548 if (MangleReturnType) {
2549 FunctionTypeDepth.enterResultType();
2551 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2552 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2553 mangleVendorQualifier("ns_returns_retained");
2555 // Mangle the return type without any direct ARC ownership qualifiers.
2556 QualType ReturnTy = Proto->getReturnType();
2557 if (ReturnTy.getObjCLifetime()) {
2558 auto SplitReturnTy = ReturnTy.split();
2559 SplitReturnTy.Quals.removeObjCLifetime();
2560 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2562 mangleType(ReturnTy);
2564 FunctionTypeDepth.leaveResultType();
2567 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2568 // <builtin-type> ::= v # void
2571 FunctionTypeDepth.pop(saved);
2575 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2576 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2577 // Mangle extended parameter info as order-sensitive qualifiers here.
2578 if (Proto->hasExtParameterInfos() && FD == nullptr) {
2579 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2583 QualType ParamTy = Proto->getParamType(I);
2584 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2587 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2588 // Attr can only take 1 character, so we can hardcode the length below.
2589 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2590 Out << "U17pass_object_size" << Attr->getType();
2595 FunctionTypeDepth.pop(saved);
2597 // <builtin-type> ::= z # ellipsis
2598 if (Proto->isVariadic())
2602 // <type> ::= <class-enum-type>
2603 // <class-enum-type> ::= <name>
2604 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2605 mangleName(T->getDecl());
2608 // <type> ::= <class-enum-type>
2609 // <class-enum-type> ::= <name>
2610 void CXXNameMangler::mangleType(const EnumType *T) {
2611 mangleType(static_cast<const TagType*>(T));
2613 void CXXNameMangler::mangleType(const RecordType *T) {
2614 mangleType(static_cast<const TagType*>(T));
2616 void CXXNameMangler::mangleType(const TagType *T) {
2617 mangleName(T->getDecl());
2620 // <type> ::= <array-type>
2621 // <array-type> ::= A <positive dimension number> _ <element type>
2622 // ::= A [<dimension expression>] _ <element type>
2623 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2624 Out << 'A' << T->getSize() << '_';
2625 mangleType(T->getElementType());
2627 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2629 // decayed vla types (size 0) will just be skipped.
2630 if (T->getSizeExpr())
2631 mangleExpression(T->getSizeExpr());
2633 mangleType(T->getElementType());
2635 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2637 mangleExpression(T->getSizeExpr());
2639 mangleType(T->getElementType());
2641 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2643 mangleType(T->getElementType());
2646 // <type> ::= <pointer-to-member-type>
2647 // <pointer-to-member-type> ::= M <class type> <member type>
2648 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2650 mangleType(QualType(T->getClass(), 0));
2651 QualType PointeeType = T->getPointeeType();
2652 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2655 // Itanium C++ ABI 5.1.8:
2657 // The type of a non-static member function is considered to be different,
2658 // for the purposes of substitution, from the type of a namespace-scope or
2659 // static member function whose type appears similar. The types of two
2660 // non-static member functions are considered to be different, for the
2661 // purposes of substitution, if the functions are members of different
2662 // classes. In other words, for the purposes of substitution, the class of
2663 // which the function is a member is considered part of the type of
2666 // Given that we already substitute member function pointers as a
2667 // whole, the net effect of this rule is just to unconditionally
2668 // suppress substitution on the function type in a member pointer.
2669 // We increment the SeqID here to emulate adding an entry to the
2670 // substitution table.
2673 mangleType(PointeeType);
2676 // <type> ::= <template-param>
2677 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2678 mangleTemplateParameter(T->getIndex());
2681 // <type> ::= <template-param>
2682 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2683 // FIXME: not clear how to mangle this!
2684 // template <class T...> class A {
2685 // template <class U...> void foo(T(*)(U) x...);
2687 Out << "_SUBSTPACK_";
2690 // <type> ::= P <type> # pointer-to
2691 void CXXNameMangler::mangleType(const PointerType *T) {
2693 mangleType(T->getPointeeType());
2695 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2697 mangleType(T->getPointeeType());
2700 // <type> ::= R <type> # reference-to
2701 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2703 mangleType(T->getPointeeType());
2706 // <type> ::= O <type> # rvalue reference-to (C++0x)
2707 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2709 mangleType(T->getPointeeType());
2712 // <type> ::= C <type> # complex pair (C 2000)
2713 void CXXNameMangler::mangleType(const ComplexType *T) {
2715 mangleType(T->getElementType());
2718 // ARM's ABI for Neon vector types specifies that they should be mangled as
2719 // if they are structs (to match ARM's initial implementation). The
2720 // vector type must be one of the special types predefined by ARM.
2721 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2722 QualType EltType = T->getElementType();
2723 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2724 const char *EltName = nullptr;
2725 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2726 switch (cast<BuiltinType>(EltType)->getKind()) {
2727 case BuiltinType::SChar:
2728 case BuiltinType::UChar:
2729 EltName = "poly8_t";
2731 case BuiltinType::Short:
2732 case BuiltinType::UShort:
2733 EltName = "poly16_t";
2735 case BuiltinType::ULongLong:
2736 EltName = "poly64_t";
2738 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2741 switch (cast<BuiltinType>(EltType)->getKind()) {
2742 case BuiltinType::SChar: EltName = "int8_t"; break;
2743 case BuiltinType::UChar: EltName = "uint8_t"; break;
2744 case BuiltinType::Short: EltName = "int16_t"; break;
2745 case BuiltinType::UShort: EltName = "uint16_t"; break;
2746 case BuiltinType::Int: EltName = "int32_t"; break;
2747 case BuiltinType::UInt: EltName = "uint32_t"; break;
2748 case BuiltinType::LongLong: EltName = "int64_t"; break;
2749 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2750 case BuiltinType::Double: EltName = "float64_t"; break;
2751 case BuiltinType::Float: EltName = "float32_t"; break;
2752 case BuiltinType::Half: EltName = "float16_t";break;
2754 llvm_unreachable("unexpected Neon vector element type");
2757 const char *BaseName = nullptr;
2758 unsigned BitSize = (T->getNumElements() *
2759 getASTContext().getTypeSize(EltType));
2761 BaseName = "__simd64_";
2763 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2764 BaseName = "__simd128_";
2766 Out << strlen(BaseName) + strlen(EltName);
2767 Out << BaseName << EltName;
2770 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2771 switch (EltType->getKind()) {
2772 case BuiltinType::SChar:
2774 case BuiltinType::Short:
2776 case BuiltinType::Int:
2778 case BuiltinType::Long:
2779 case BuiltinType::LongLong:
2781 case BuiltinType::UChar:
2783 case BuiltinType::UShort:
2785 case BuiltinType::UInt:
2787 case BuiltinType::ULong:
2788 case BuiltinType::ULongLong:
2790 case BuiltinType::Half:
2792 case BuiltinType::Float:
2794 case BuiltinType::Double:
2797 llvm_unreachable("Unexpected vector element base type");
2801 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2802 // the equivalent internal name. The vector type must be one of the special
2803 // types predefined by ARM.
2804 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2805 QualType EltType = T->getElementType();
2806 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2808 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2809 (void)BitSize; // Silence warning.
2811 assert((BitSize == 64 || BitSize == 128) &&
2812 "Neon vector type not 64 or 128 bits");
2815 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2816 switch (cast<BuiltinType>(EltType)->getKind()) {
2817 case BuiltinType::UChar:
2820 case BuiltinType::UShort:
2823 case BuiltinType::ULong:
2824 case BuiltinType::ULongLong:
2828 llvm_unreachable("unexpected Neon polynomial vector element type");
2831 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2833 std::string TypeName =
2834 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2835 Out << TypeName.length() << TypeName;
2838 // GNU extension: vector types
2839 // <type> ::= <vector-type>
2840 // <vector-type> ::= Dv <positive dimension number> _
2841 // <extended element type>
2842 // ::= Dv [<dimension expression>] _ <element type>
2843 // <extended element type> ::= <element type>
2844 // ::= p # AltiVec vector pixel
2845 // ::= b # Altivec vector bool
2846 void CXXNameMangler::mangleType(const VectorType *T) {
2847 if ((T->getVectorKind() == VectorType::NeonVector ||
2848 T->getVectorKind() == VectorType::NeonPolyVector)) {
2849 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2850 llvm::Triple::ArchType Arch =
2851 getASTContext().getTargetInfo().getTriple().getArch();
2852 if ((Arch == llvm::Triple::aarch64 ||
2853 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2854 mangleAArch64NeonVectorType(T);
2856 mangleNeonVectorType(T);
2859 Out << "Dv" << T->getNumElements() << '_';
2860 if (T->getVectorKind() == VectorType::AltiVecPixel)
2862 else if (T->getVectorKind() == VectorType::AltiVecBool)
2865 mangleType(T->getElementType());
2867 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2868 mangleType(static_cast<const VectorType*>(T));
2870 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2872 mangleExpression(T->getSizeExpr());
2874 mangleType(T->getElementType());
2877 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2878 // <type> ::= Dp <type> # pack expansion (C++0x)
2880 mangleType(T->getPattern());
2883 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2884 mangleSourceName(T->getDecl()->getIdentifier());
2887 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2888 // Treat __kindof as a vendor extended type qualifier.
2889 if (T->isKindOfType())
2890 Out << "U8__kindof";
2892 if (!T->qual_empty()) {
2893 // Mangle protocol qualifiers.
2894 SmallString<64> QualStr;
2895 llvm::raw_svector_ostream QualOS(QualStr);
2896 QualOS << "objcproto";
2897 for (const auto *I : T->quals()) {
2898 StringRef name = I->getName();
2899 QualOS << name.size() << name;
2901 Out << 'U' << QualStr.size() << QualStr;
2904 mangleType(T->getBaseType());
2906 if (T->isSpecialized()) {
2907 // Mangle type arguments as I <type>+ E
2909 for (auto typeArg : T->getTypeArgs())
2910 mangleType(typeArg);
2915 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2916 Out << "U13block_pointer";
2917 mangleType(T->getPointeeType());
2920 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2921 // Mangle injected class name types as if the user had written the
2922 // specialization out fully. It may not actually be possible to see
2923 // this mangling, though.
2924 mangleType(T->getInjectedSpecializationType());
2927 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2928 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2929 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
2931 if (mangleSubstitution(QualType(T, 0)))
2934 mangleTemplatePrefix(T->getTemplateName());
2936 // FIXME: GCC does not appear to mangle the template arguments when
2937 // the template in question is a dependent template name. Should we
2938 // emulate that badness?
2939 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2940 addSubstitution(QualType(T, 0));
2944 void CXXNameMangler::mangleType(const DependentNameType *T) {
2945 // Proposal by cxx-abi-dev, 2014-03-26
2946 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2947 // # dependent elaborated type specifier using
2949 // ::= Ts <name> # dependent elaborated type specifier using
2950 // # 'struct' or 'class'
2951 // ::= Tu <name> # dependent elaborated type specifier using
2953 // ::= Te <name> # dependent elaborated type specifier using
2955 switch (T->getKeyword()) {
2970 llvm_unreachable("unexpected keyword for dependent type name");
2972 // Typename types are always nested
2974 manglePrefix(T->getQualifier());
2975 mangleSourceName(T->getIdentifier());
2979 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2980 // Dependently-scoped template types are nested if they have a prefix.
2983 // TODO: avoid making this TemplateName.
2984 TemplateName Prefix =
2985 getASTContext().getDependentTemplateName(T->getQualifier(),
2986 T->getIdentifier());
2987 mangleTemplatePrefix(Prefix);
2989 // FIXME: GCC does not appear to mangle the template arguments when
2990 // the template in question is a dependent template name. Should we
2991 // emulate that badness?
2992 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2996 void CXXNameMangler::mangleType(const TypeOfType *T) {
2997 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2998 // "extension with parameters" mangling.
3002 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3003 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3004 // "extension with parameters" mangling.
3008 void CXXNameMangler::mangleType(const DecltypeType *T) {
3009 Expr *E = T->getUnderlyingExpr();
3011 // type ::= Dt <expression> E # decltype of an id-expression
3012 // # or class member access
3013 // ::= DT <expression> E # decltype of an expression
3015 // This purports to be an exhaustive list of id-expressions and
3016 // class member accesses. Note that we do not ignore parentheses;
3017 // parentheses change the semantics of decltype for these
3018 // expressions (and cause the mangler to use the other form).
3019 if (isa<DeclRefExpr>(E) ||
3020 isa<MemberExpr>(E) ||
3021 isa<UnresolvedLookupExpr>(E) ||
3022 isa<DependentScopeDeclRefExpr>(E) ||
3023 isa<CXXDependentScopeMemberExpr>(E) ||
3024 isa<UnresolvedMemberExpr>(E))
3028 mangleExpression(E);
3032 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3033 // If this is dependent, we need to record that. If not, we simply
3034 // mangle it as the underlying type since they are equivalent.
3035 if (T->isDependentType()) {
3038 switch (T->getUTTKind()) {
3039 case UnaryTransformType::EnumUnderlyingType:
3045 mangleType(T->getBaseType());
3048 void CXXNameMangler::mangleType(const AutoType *T) {
3049 QualType D = T->getDeducedType();
3050 // <builtin-type> ::= Da # dependent auto
3052 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3053 "shouldn't need to mangle __auto_type!");
3054 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3059 void CXXNameMangler::mangleType(const AtomicType *T) {
3060 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3061 // (Until there's a standardized mangling...)
3063 mangleType(T->getValueType());
3066 void CXXNameMangler::mangleType(const PipeType *T) {
3067 // Pipe type mangling rules are described in SPIR 2.0 specification
3068 // A.1 Data types and A.3 Summary of changes
3069 // <type> ::= 8ocl_pipe
3073 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3074 const llvm::APSInt &Value) {
3075 // <expr-primary> ::= L <type> <value number> E # integer literal
3079 if (T->isBooleanType()) {
3080 // Boolean values are encoded as 0/1.
3081 Out << (Value.getBoolValue() ? '1' : '0');
3083 mangleNumber(Value);
3089 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3090 // Ignore member expressions involving anonymous unions.
3091 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3092 if (!RT->getDecl()->isAnonymousStructOrUnion())
3094 const auto *ME = dyn_cast<MemberExpr>(Base);
3097 Base = ME->getBase();
3098 IsArrow = ME->isArrow();
3101 if (Base->isImplicitCXXThis()) {
3102 // Note: GCC mangles member expressions to the implicit 'this' as
3103 // *this., whereas we represent them as this->. The Itanium C++ ABI
3104 // does not specify anything here, so we follow GCC.
3107 Out << (IsArrow ? "pt" : "dt");
3108 mangleExpression(Base);
3112 /// Mangles a member expression.
3113 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3115 NestedNameSpecifier *qualifier,
3116 NamedDecl *firstQualifierLookup,
3117 DeclarationName member,
3119 // <expression> ::= dt <expression> <unresolved-name>
3120 // ::= pt <expression> <unresolved-name>
3122 mangleMemberExprBase(base, isArrow);
3123 mangleUnresolvedName(qualifier, member, arity);
3126 /// Look at the callee of the given call expression and determine if
3127 /// it's a parenthesized id-expression which would have triggered ADL
3129 static bool isParenthesizedADLCallee(const CallExpr *call) {
3130 const Expr *callee = call->getCallee();
3131 const Expr *fn = callee->IgnoreParens();
3133 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3134 // too, but for those to appear in the callee, it would have to be
3136 if (callee == fn) return false;
3138 // Must be an unresolved lookup.
3139 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3140 if (!lookup) return false;
3142 assert(!lookup->requiresADL());
3144 // Must be an unqualified lookup.
3145 if (lookup->getQualifier()) return false;
3147 // Must not have found a class member. Note that if one is a class
3148 // member, they're all class members.
3149 if (lookup->getNumDecls() > 0 &&
3150 (*lookup->decls_begin())->isCXXClassMember())
3153 // Otherwise, ADL would have been triggered.
3157 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3158 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3159 Out << CastEncoding;
3160 mangleType(ECE->getType());
3161 mangleExpression(ECE->getSubExpr());
3164 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3165 if (auto *Syntactic = InitList->getSyntacticForm())
3166 InitList = Syntactic;
3167 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3168 mangleExpression(InitList->getInit(i));
3171 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3172 // <expression> ::= <unary operator-name> <expression>
3173 // ::= <binary operator-name> <expression> <expression>
3174 // ::= <trinary operator-name> <expression> <expression> <expression>
3175 // ::= cv <type> expression # conversion with one argument
3176 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3177 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3178 // ::= sc <type> <expression> # static_cast<type> (expression)
3179 // ::= cc <type> <expression> # const_cast<type> (expression)
3180 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3181 // ::= st <type> # sizeof (a type)
3182 // ::= at <type> # alignof (a type)
3183 // ::= <template-param>
3184 // ::= <function-param>
3185 // ::= sr <type> <unqualified-name> # dependent name
3186 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3187 // ::= ds <expression> <expression> # expr.*expr
3188 // ::= sZ <template-param> # size of a parameter pack
3189 // ::= sZ <function-param> # size of a function parameter pack
3190 // ::= <expr-primary>
3191 // <expr-primary> ::= L <type> <value number> E # integer literal
3192 // ::= L <type <value float> E # floating literal
3193 // ::= L <mangled-name> E # external name
3194 // ::= fpT # 'this' expression
3195 QualType ImplicitlyConvertedToType;
3198 switch (E->getStmtClass()) {
3199 case Expr::NoStmtClass:
3200 #define ABSTRACT_STMT(Type)
3201 #define EXPR(Type, Base)
3202 #define STMT(Type, Base) \
3203 case Expr::Type##Class:
3204 #include "clang/AST/StmtNodes.inc"
3207 // These all can only appear in local or variable-initialization
3208 // contexts and so should never appear in a mangling.
3209 case Expr::AddrLabelExprClass:
3210 case Expr::DesignatedInitUpdateExprClass:
3211 case Expr::ImplicitValueInitExprClass:
3212 case Expr::NoInitExprClass:
3213 case Expr::ParenListExprClass:
3214 case Expr::LambdaExprClass:
3215 case Expr::MSPropertyRefExprClass:
3216 case Expr::MSPropertySubscriptExprClass:
3217 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3218 case Expr::OMPArraySectionExprClass:
3219 case Expr::CXXInheritedCtorInitExprClass:
3220 llvm_unreachable("unexpected statement kind");
3222 // FIXME: invent manglings for all these.
3223 case Expr::BlockExprClass:
3224 case Expr::ChooseExprClass:
3225 case Expr::CompoundLiteralExprClass:
3226 case Expr::DesignatedInitExprClass:
3227 case Expr::ExtVectorElementExprClass:
3228 case Expr::GenericSelectionExprClass:
3229 case Expr::ObjCEncodeExprClass:
3230 case Expr::ObjCIsaExprClass:
3231 case Expr::ObjCIvarRefExprClass:
3232 case Expr::ObjCMessageExprClass:
3233 case Expr::ObjCPropertyRefExprClass:
3234 case Expr::ObjCProtocolExprClass:
3235 case Expr::ObjCSelectorExprClass:
3236 case Expr::ObjCStringLiteralClass:
3237 case Expr::ObjCBoxedExprClass:
3238 case Expr::ObjCArrayLiteralClass:
3239 case Expr::ObjCDictionaryLiteralClass:
3240 case Expr::ObjCSubscriptRefExprClass:
3241 case Expr::ObjCIndirectCopyRestoreExprClass:
3242 case Expr::ObjCAvailabilityCheckExprClass:
3243 case Expr::OffsetOfExprClass:
3244 case Expr::PredefinedExprClass:
3245 case Expr::ShuffleVectorExprClass:
3246 case Expr::ConvertVectorExprClass:
3247 case Expr::StmtExprClass:
3248 case Expr::TypeTraitExprClass:
3249 case Expr::ArrayTypeTraitExprClass:
3250 case Expr::ExpressionTraitExprClass:
3251 case Expr::VAArgExprClass:
3252 case Expr::CUDAKernelCallExprClass:
3253 case Expr::AsTypeExprClass:
3254 case Expr::PseudoObjectExprClass:
3255 case Expr::AtomicExprClass:
3258 // As bad as this diagnostic is, it's better than crashing.
3259 DiagnosticsEngine &Diags = Context.getDiags();
3260 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3261 "cannot yet mangle expression type %0");
3262 Diags.Report(E->getExprLoc(), DiagID)
3263 << E->getStmtClassName() << E->getSourceRange();
3268 case Expr::CXXUuidofExprClass: {
3269 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3270 if (UE->isTypeOperand()) {
3271 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3272 Out << "u8__uuidoft";
3275 Expr *UuidExp = UE->getExprOperand();
3276 Out << "u8__uuidofz";
3277 mangleExpression(UuidExp, Arity);
3282 // Even gcc-4.5 doesn't mangle this.
3283 case Expr::BinaryConditionalOperatorClass: {
3284 DiagnosticsEngine &Diags = Context.getDiags();
3286 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3287 "?: operator with omitted middle operand cannot be mangled");
3288 Diags.Report(E->getExprLoc(), DiagID)
3289 << E->getStmtClassName() << E->getSourceRange();
3293 // These are used for internal purposes and cannot be meaningfully mangled.
3294 case Expr::OpaqueValueExprClass:
3295 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3297 case Expr::InitListExprClass: {
3299 mangleInitListElements(cast<InitListExpr>(E));
3304 case Expr::CXXDefaultArgExprClass:
3305 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3308 case Expr::CXXDefaultInitExprClass:
3309 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3312 case Expr::CXXStdInitializerListExprClass:
3313 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3316 case Expr::SubstNonTypeTemplateParmExprClass:
3317 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3321 case Expr::UserDefinedLiteralClass:
3322 // We follow g++'s approach of mangling a UDL as a call to the literal
3324 case Expr::CXXMemberCallExprClass: // fallthrough
3325 case Expr::CallExprClass: {
3326 const CallExpr *CE = cast<CallExpr>(E);
3328 // <expression> ::= cp <simple-id> <expression>* E
3329 // We use this mangling only when the call would use ADL except
3330 // for being parenthesized. Per discussion with David
3331 // Vandervoorde, 2011.04.25.
3332 if (isParenthesizedADLCallee(CE)) {
3334 // The callee here is a parenthesized UnresolvedLookupExpr with
3335 // no qualifier and should always get mangled as a <simple-id>
3338 // <expression> ::= cl <expression>* E
3343 unsigned CallArity = CE->getNumArgs();
3344 for (const Expr *Arg : CE->arguments())
3345 if (isa<PackExpansionExpr>(Arg))
3346 CallArity = UnknownArity;
3348 mangleExpression(CE->getCallee(), CallArity);
3349 for (const Expr *Arg : CE->arguments())
3350 mangleExpression(Arg);
3355 case Expr::CXXNewExprClass: {
3356 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3357 if (New->isGlobalNew()) Out << "gs";
3358 Out << (New->isArray() ? "na" : "nw");
3359 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3360 E = New->placement_arg_end(); I != E; ++I)
3361 mangleExpression(*I);
3363 mangleType(New->getAllocatedType());
3364 if (New->hasInitializer()) {
3365 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3369 const Expr *Init = New->getInitializer();
3370 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3371 // Directly inline the initializers.
3372 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3375 mangleExpression(*I);
3376 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3377 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3378 mangleExpression(PLE->getExpr(i));
3379 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3380 isa<InitListExpr>(Init)) {
3381 // Only take InitListExprs apart for list-initialization.
3382 mangleInitListElements(cast<InitListExpr>(Init));
3384 mangleExpression(Init);
3390 case Expr::CXXPseudoDestructorExprClass: {
3391 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3392 if (const Expr *Base = PDE->getBase())
3393 mangleMemberExprBase(Base, PDE->isArrow());
3394 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3396 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3398 mangleUnresolvedPrefix(Qualifier,
3399 /*Recursive=*/true);
3400 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3404 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3407 } else if (Qualifier) {
3408 mangleUnresolvedPrefix(Qualifier);
3410 // <base-unresolved-name> ::= dn <destructor-name>
3412 QualType DestroyedType = PDE->getDestroyedType();
3413 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3417 case Expr::MemberExprClass: {
3418 const MemberExpr *ME = cast<MemberExpr>(E);
3419 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3420 ME->getQualifier(), nullptr,
3421 ME->getMemberDecl()->getDeclName(), Arity);
3425 case Expr::UnresolvedMemberExprClass: {
3426 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3427 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3428 ME->isArrow(), ME->getQualifier(), nullptr,
3429 ME->getMemberName(), Arity);
3430 if (ME->hasExplicitTemplateArgs())
3431 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3435 case Expr::CXXDependentScopeMemberExprClass: {
3436 const CXXDependentScopeMemberExpr *ME
3437 = cast<CXXDependentScopeMemberExpr>(E);
3438 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3439 ME->isArrow(), ME->getQualifier(),
3440 ME->getFirstQualifierFoundInScope(),
3441 ME->getMember(), Arity);
3442 if (ME->hasExplicitTemplateArgs())
3443 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3447 case Expr::UnresolvedLookupExprClass: {
3448 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3449 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3451 // All the <unresolved-name> productions end in a
3452 // base-unresolved-name, where <template-args> are just tacked
3454 if (ULE->hasExplicitTemplateArgs())
3455 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
3459 case Expr::CXXUnresolvedConstructExprClass: {
3460 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3461 unsigned N = CE->arg_size();
3464 mangleType(CE->getType());
3465 if (N != 1) Out << '_';
3466 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3467 if (N != 1) Out << 'E';
3471 case Expr::CXXConstructExprClass: {
3472 const auto *CE = cast<CXXConstructExpr>(E);
3473 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3475 CE->getNumArgs() >= 1 &&
3476 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3477 "implicit CXXConstructExpr must have one argument");
3478 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3481 for (auto *E : CE->arguments())
3482 mangleExpression(E);
3487 case Expr::CXXTemporaryObjectExprClass: {
3488 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3489 unsigned N = CE->getNumArgs();
3490 bool List = CE->isListInitialization();
3496 mangleType(CE->getType());
3497 if (!List && N != 1)
3499 if (CE->isStdInitListInitialization()) {
3500 // We implicitly created a std::initializer_list<T> for the first argument
3501 // of a constructor of type U in an expression of the form U{a, b, c}.
3502 // Strip all the semantic gunk off the initializer list.
3504 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3505 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3506 mangleInitListElements(ILE);
3508 for (auto *E : CE->arguments())
3509 mangleExpression(E);
3516 case Expr::CXXScalarValueInitExprClass:
3518 mangleType(E->getType());
3522 case Expr::CXXNoexceptExprClass:
3524 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3527 case Expr::UnaryExprOrTypeTraitExprClass: {
3528 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3530 if (!SAE->isInstantiationDependent()) {
3532 // If the operand of a sizeof or alignof operator is not
3533 // instantiation-dependent it is encoded as an integer literal
3534 // reflecting the result of the operator.
3536 // If the result of the operator is implicitly converted to a known
3537 // integer type, that type is used for the literal; otherwise, the type
3538 // of std::size_t or std::ptrdiff_t is used.
3539 QualType T = (ImplicitlyConvertedToType.isNull() ||
3540 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3541 : ImplicitlyConvertedToType;
3542 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3543 mangleIntegerLiteral(T, V);
3547 switch(SAE->getKind()) {
3554 case UETT_VecStep: {
3555 DiagnosticsEngine &Diags = Context.getDiags();
3556 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3557 "cannot yet mangle vec_step expression");
3558 Diags.Report(DiagID);
3561 case UETT_OpenMPRequiredSimdAlign:
3562 DiagnosticsEngine &Diags = Context.getDiags();
3563 unsigned DiagID = Diags.getCustomDiagID(
3564 DiagnosticsEngine::Error,
3565 "cannot yet mangle __builtin_omp_required_simd_align expression");
3566 Diags.Report(DiagID);
3569 if (SAE->isArgumentType()) {
3571 mangleType(SAE->getArgumentType());
3574 mangleExpression(SAE->getArgumentExpr());
3579 case Expr::CXXThrowExprClass: {
3580 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3581 // <expression> ::= tw <expression> # throw expression
3583 if (TE->getSubExpr()) {
3585 mangleExpression(TE->getSubExpr());
3592 case Expr::CXXTypeidExprClass: {
3593 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3594 // <expression> ::= ti <type> # typeid (type)
3595 // ::= te <expression> # typeid (expression)
3596 if (TIE->isTypeOperand()) {
3598 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3601 mangleExpression(TIE->getExprOperand());
3606 case Expr::CXXDeleteExprClass: {
3607 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3608 // <expression> ::= [gs] dl <expression> # [::] delete expr
3609 // ::= [gs] da <expression> # [::] delete [] expr
3610 if (DE->isGlobalDelete()) Out << "gs";
3611 Out << (DE->isArrayForm() ? "da" : "dl");
3612 mangleExpression(DE->getArgument());
3616 case Expr::UnaryOperatorClass: {
3617 const UnaryOperator *UO = cast<UnaryOperator>(E);
3618 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3620 mangleExpression(UO->getSubExpr());
3624 case Expr::ArraySubscriptExprClass: {
3625 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3627 // Array subscript is treated as a syntactically weird form of
3630 mangleExpression(AE->getLHS());
3631 mangleExpression(AE->getRHS());
3635 case Expr::CompoundAssignOperatorClass: // fallthrough
3636 case Expr::BinaryOperatorClass: {
3637 const BinaryOperator *BO = cast<BinaryOperator>(E);
3638 if (BO->getOpcode() == BO_PtrMemD)
3641 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3643 mangleExpression(BO->getLHS());
3644 mangleExpression(BO->getRHS());
3648 case Expr::ConditionalOperatorClass: {
3649 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3650 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3651 mangleExpression(CO->getCond());
3652 mangleExpression(CO->getLHS(), Arity);
3653 mangleExpression(CO->getRHS(), Arity);
3657 case Expr::ImplicitCastExprClass: {
3658 ImplicitlyConvertedToType = E->getType();
3659 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3663 case Expr::ObjCBridgedCastExprClass: {
3664 // Mangle ownership casts as a vendor extended operator __bridge,
3665 // __bridge_transfer, or __bridge_retain.
3666 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3667 Out << "v1U" << Kind.size() << Kind;
3669 // Fall through to mangle the cast itself.
3671 case Expr::CStyleCastExprClass:
3672 mangleCastExpression(E, "cv");
3675 case Expr::CXXFunctionalCastExprClass: {
3676 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3677 // FIXME: Add isImplicit to CXXConstructExpr.
3678 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3679 if (CCE->getParenOrBraceRange().isInvalid())
3680 Sub = CCE->getArg(0)->IgnoreImplicit();
3681 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3682 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3683 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3685 mangleType(E->getType());
3686 mangleInitListElements(IL);
3689 mangleCastExpression(E, "cv");
3694 case Expr::CXXStaticCastExprClass:
3695 mangleCastExpression(E, "sc");
3697 case Expr::CXXDynamicCastExprClass:
3698 mangleCastExpression(E, "dc");
3700 case Expr::CXXReinterpretCastExprClass:
3701 mangleCastExpression(E, "rc");
3703 case Expr::CXXConstCastExprClass:
3704 mangleCastExpression(E, "cc");
3707 case Expr::CXXOperatorCallExprClass: {
3708 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3709 unsigned NumArgs = CE->getNumArgs();
3710 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3711 // Mangle the arguments.
3712 for (unsigned i = 0; i != NumArgs; ++i)
3713 mangleExpression(CE->getArg(i));
3717 case Expr::ParenExprClass:
3718 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3721 case Expr::DeclRefExprClass: {
3722 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3724 switch (D->getKind()) {
3726 // <expr-primary> ::= L <mangled-name> E # external name
3733 mangleFunctionParam(cast<ParmVarDecl>(D));
3736 case Decl::EnumConstant: {
3737 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3738 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3742 case Decl::NonTypeTemplateParm: {
3743 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3744 mangleTemplateParameter(PD->getIndex());
3753 case Expr::SubstNonTypeTemplateParmPackExprClass:
3754 // FIXME: not clear how to mangle this!
3755 // template <unsigned N...> class A {
3756 // template <class U...> void foo(U (&x)[N]...);
3758 Out << "_SUBSTPACK_";
3761 case Expr::FunctionParmPackExprClass: {
3762 // FIXME: not clear how to mangle this!
3763 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3764 Out << "v110_SUBSTPACK";
3765 mangleFunctionParam(FPPE->getParameterPack());
3769 case Expr::DependentScopeDeclRefExprClass: {
3770 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3771 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3773 // All the <unresolved-name> productions end in a
3774 // base-unresolved-name, where <template-args> are just tacked
3776 if (DRE->hasExplicitTemplateArgs())
3777 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
3781 case Expr::CXXBindTemporaryExprClass:
3782 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3785 case Expr::ExprWithCleanupsClass:
3786 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3789 case Expr::FloatingLiteralClass: {
3790 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3792 mangleType(FL->getType());
3793 mangleFloat(FL->getValue());
3798 case Expr::CharacterLiteralClass:
3800 mangleType(E->getType());
3801 Out << cast<CharacterLiteral>(E)->getValue();
3805 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3806 case Expr::ObjCBoolLiteralExprClass:
3808 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3812 case Expr::CXXBoolLiteralExprClass:
3814 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3818 case Expr::IntegerLiteralClass: {
3819 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3820 if (E->getType()->isSignedIntegerType())
3821 Value.setIsSigned(true);
3822 mangleIntegerLiteral(E->getType(), Value);
3826 case Expr::ImaginaryLiteralClass: {
3827 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3828 // Mangle as if a complex literal.
3829 // Proposal from David Vandevoorde, 2010.06.30.
3831 mangleType(E->getType());
3832 if (const FloatingLiteral *Imag =
3833 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3834 // Mangle a floating-point zero of the appropriate type.
3835 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3837 mangleFloat(Imag->getValue());
3840 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3841 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3842 Value.setIsSigned(true);
3843 mangleNumber(Value);
3849 case Expr::StringLiteralClass: {
3850 // Revised proposal from David Vandervoorde, 2010.07.15.
3852 assert(isa<ConstantArrayType>(E->getType()));
3853 mangleType(E->getType());
3858 case Expr::GNUNullExprClass:
3859 // FIXME: should this really be mangled the same as nullptr?
3862 case Expr::CXXNullPtrLiteralExprClass: {
3867 case Expr::PackExpansionExprClass:
3869 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3872 case Expr::SizeOfPackExprClass: {
3873 auto *SPE = cast<SizeOfPackExpr>(E);
3874 if (SPE->isPartiallySubstituted()) {
3876 for (const auto &A : SPE->getPartialArguments())
3877 mangleTemplateArg(A);
3883 const NamedDecl *Pack = SPE->getPack();
3884 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3885 mangleTemplateParameter(TTP->getIndex());
3886 else if (const NonTypeTemplateParmDecl *NTTP
3887 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3888 mangleTemplateParameter(NTTP->getIndex());
3889 else if (const TemplateTemplateParmDecl *TempTP
3890 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3891 mangleTemplateParameter(TempTP->getIndex());
3893 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3897 case Expr::MaterializeTemporaryExprClass: {
3898 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3902 case Expr::CXXFoldExprClass: {
3903 auto *FE = cast<CXXFoldExpr>(E);
3904 if (FE->isLeftFold())
3905 Out << (FE->getInit() ? "fL" : "fl");
3907 Out << (FE->getInit() ? "fR" : "fr");
3909 if (FE->getOperator() == BO_PtrMemD)
3913 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3917 mangleExpression(FE->getLHS());
3919 mangleExpression(FE->getRHS());
3923 case Expr::CXXThisExprClass:
3927 case Expr::CoawaitExprClass:
3928 // FIXME: Propose a non-vendor mangling.
3929 Out << "v18co_await";
3930 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3933 case Expr::CoyieldExprClass:
3934 // FIXME: Propose a non-vendor mangling.
3935 Out << "v18co_yield";
3936 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3941 /// Mangle an expression which refers to a parameter variable.
3943 /// <expression> ::= <function-param>
3944 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3945 /// <function-param> ::= fp <top-level CV-qualifiers>
3946 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3947 /// <function-param> ::= fL <L-1 non-negative number>
3948 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3949 /// <function-param> ::= fL <L-1 non-negative number>
3950 /// p <top-level CV-qualifiers>
3951 /// <I-1 non-negative number> _ # L > 0, I > 0
3953 /// L is the nesting depth of the parameter, defined as 1 if the
3954 /// parameter comes from the innermost function prototype scope
3955 /// enclosing the current context, 2 if from the next enclosing
3956 /// function prototype scope, and so on, with one special case: if
3957 /// we've processed the full parameter clause for the innermost
3958 /// function type, then L is one less. This definition conveniently
3959 /// makes it irrelevant whether a function's result type was written
3960 /// trailing or leading, but is otherwise overly complicated; the
3961 /// numbering was first designed without considering references to
3962 /// parameter in locations other than return types, and then the
3963 /// mangling had to be generalized without changing the existing
3966 /// I is the zero-based index of the parameter within its parameter
3967 /// declaration clause. Note that the original ABI document describes
3968 /// this using 1-based ordinals.
3969 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3970 unsigned parmDepth = parm->getFunctionScopeDepth();
3971 unsigned parmIndex = parm->getFunctionScopeIndex();
3974 // parmDepth does not include the declaring function prototype.
3975 // FunctionTypeDepth does account for that.
3976 assert(parmDepth < FunctionTypeDepth.getDepth());
3977 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3978 if (FunctionTypeDepth.isInResultType())
3981 if (nestingDepth == 0) {
3984 Out << "fL" << (nestingDepth - 1) << 'p';
3987 // Top-level qualifiers. We don't have to worry about arrays here,
3988 // because parameters declared as arrays should already have been
3989 // transformed to have pointer type. FIXME: apparently these don't
3990 // get mangled if used as an rvalue of a known non-class type?
3991 assert(!parm->getType()->isArrayType()
3992 && "parameter's type is still an array type?");
3993 mangleQualifiers(parm->getType().getQualifiers());
3996 if (parmIndex != 0) {
3997 Out << (parmIndex - 1);
4002 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4003 const CXXRecordDecl *InheritedFrom) {
4004 // <ctor-dtor-name> ::= C1 # complete object constructor
4005 // ::= C2 # base object constructor
4006 // ::= CI1 <type> # complete inheriting constructor
4007 // ::= CI2 <type> # base inheriting constructor
4009 // In addition, C5 is a comdat name with C1 and C2 in it.
4023 case Ctor_DefaultClosure:
4024 case Ctor_CopyingClosure:
4025 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4028 mangleName(InheritedFrom);
4031 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4032 // <ctor-dtor-name> ::= D0 # deleting destructor
4033 // ::= D1 # complete object destructor
4034 // ::= D2 # base object destructor
4036 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4053 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4054 unsigned NumTemplateArgs) {
4055 // <template-args> ::= I <template-arg>+ E
4057 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4058 mangleTemplateArg(TemplateArgs[i].getArgument());
4062 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4063 // <template-args> ::= I <template-arg>+ E
4065 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4066 mangleTemplateArg(AL[i]);
4070 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4071 unsigned NumTemplateArgs) {
4072 // <template-args> ::= I <template-arg>+ E
4074 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4075 mangleTemplateArg(TemplateArgs[i]);
4079 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4080 // <template-arg> ::= <type> # type or template
4081 // ::= X <expression> E # expression
4082 // ::= <expr-primary> # simple expressions
4083 // ::= J <template-arg>* E # argument pack
4084 if (!A.isInstantiationDependent() || A.isDependent())
4085 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4087 switch (A.getKind()) {
4088 case TemplateArgument::Null:
4089 llvm_unreachable("Cannot mangle NULL template argument");
4091 case TemplateArgument::Type:
4092 mangleType(A.getAsType());
4094 case TemplateArgument::Template:
4095 // This is mangled as <type>.
4096 mangleType(A.getAsTemplate());
4098 case TemplateArgument::TemplateExpansion:
4099 // <type> ::= Dp <type> # pack expansion (C++0x)
4101 mangleType(A.getAsTemplateOrTemplatePattern());
4103 case TemplateArgument::Expression: {
4104 // It's possible to end up with a DeclRefExpr here in certain
4105 // dependent cases, in which case we should mangle as a
4107 const Expr *E = A.getAsExpr()->IgnoreParens();
4108 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4109 const ValueDecl *D = DRE->getDecl();
4110 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4119 mangleExpression(E);
4123 case TemplateArgument::Integral:
4124 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4126 case TemplateArgument::Declaration: {
4127 // <expr-primary> ::= L <mangled-name> E # external name
4128 // Clang produces AST's where pointer-to-member-function expressions
4129 // and pointer-to-function expressions are represented as a declaration not
4130 // an expression. We compensate for it here to produce the correct mangling.
4131 ValueDecl *D = A.getAsDecl();
4132 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4133 if (compensateMangling) {
4135 mangleOperatorName(OO_Amp, 1);
4139 // References to external entities use the mangled name; if the name would
4140 // not normally be mangled then mangle it as unqualified.
4144 if (compensateMangling)
4149 case TemplateArgument::NullPtr: {
4150 // <expr-primary> ::= L <type> 0 E
4152 mangleType(A.getNullPtrType());
4156 case TemplateArgument::Pack: {
4157 // <template-arg> ::= J <template-arg>* E
4159 for (const auto &P : A.pack_elements())
4160 mangleTemplateArg(P);
4166 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4167 // <template-param> ::= T_ # first template parameter
4168 // ::= T <parameter-2 non-negative number> _
4172 Out << 'T' << (Index - 1) << '_';
4175 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4178 else if (SeqID > 1) {
4181 // <seq-id> is encoded in base-36, using digits and upper case letters.
4182 char Buffer[7]; // log(2**32) / log(36) ~= 7
4183 MutableArrayRef<char> BufferRef(Buffer);
4184 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4186 for (; SeqID != 0; SeqID /= 36) {
4187 unsigned C = SeqID % 36;
4188 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4191 Out.write(I.base(), I - BufferRef.rbegin());
4196 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4197 bool result = mangleSubstitution(tname);
4198 assert(result && "no existing substitution for template name");
4202 // <substitution> ::= S <seq-id> _
4204 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4205 // Try one of the standard substitutions first.
4206 if (mangleStandardSubstitution(ND))
4209 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4210 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4213 /// Determine whether the given type has any qualifiers that are relevant for
4215 static bool hasMangledSubstitutionQualifiers(QualType T) {
4216 Qualifiers Qs = T.getQualifiers();
4217 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4220 bool CXXNameMangler::mangleSubstitution(QualType T) {
4221 if (!hasMangledSubstitutionQualifiers(T)) {
4222 if (const RecordType *RT = T->getAs<RecordType>())
4223 return mangleSubstitution(RT->getDecl());
4226 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4228 return mangleSubstitution(TypePtr);
4231 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4232 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4233 return mangleSubstitution(TD);
4235 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4236 return mangleSubstitution(
4237 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4240 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4241 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4242 if (I == Substitutions.end())
4245 unsigned SeqID = I->second;
4252 static bool isCharType(QualType T) {
4256 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4257 T->isSpecificBuiltinType(BuiltinType::Char_U);
4260 /// Returns whether a given type is a template specialization of a given name
4261 /// with a single argument of type char.
4262 static bool isCharSpecialization(QualType T, const char *Name) {
4266 const RecordType *RT = T->getAs<RecordType>();
4270 const ClassTemplateSpecializationDecl *SD =
4271 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4275 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4278 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4279 if (TemplateArgs.size() != 1)
4282 if (!isCharType(TemplateArgs[0].getAsType()))
4285 return SD->getIdentifier()->getName() == Name;
4288 template <std::size_t StrLen>
4289 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4290 const char (&Str)[StrLen]) {
4291 if (!SD->getIdentifier()->isStr(Str))
4294 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4295 if (TemplateArgs.size() != 2)
4298 if (!isCharType(TemplateArgs[0].getAsType()))
4301 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4307 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4308 // <substitution> ::= St # ::std::
4309 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4316 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4317 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4320 // <substitution> ::= Sa # ::std::allocator
4321 if (TD->getIdentifier()->isStr("allocator")) {
4326 // <<substitution> ::= Sb # ::std::basic_string
4327 if (TD->getIdentifier()->isStr("basic_string")) {
4333 if (const ClassTemplateSpecializationDecl *SD =
4334 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4335 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4338 // <substitution> ::= Ss # ::std::basic_string<char,
4339 // ::std::char_traits<char>,
4340 // ::std::allocator<char> >
4341 if (SD->getIdentifier()->isStr("basic_string")) {
4342 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4344 if (TemplateArgs.size() != 3)
4347 if (!isCharType(TemplateArgs[0].getAsType()))
4350 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4353 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4360 // <substitution> ::= Si # ::std::basic_istream<char,
4361 // ::std::char_traits<char> >
4362 if (isStreamCharSpecialization(SD, "basic_istream")) {
4367 // <substitution> ::= So # ::std::basic_ostream<char,
4368 // ::std::char_traits<char> >
4369 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4374 // <substitution> ::= Sd # ::std::basic_iostream<char,
4375 // ::std::char_traits<char> >
4376 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4384 void CXXNameMangler::addSubstitution(QualType T) {
4385 if (!hasMangledSubstitutionQualifiers(T)) {
4386 if (const RecordType *RT = T->getAs<RecordType>()) {
4387 addSubstitution(RT->getDecl());
4392 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4393 addSubstitution(TypePtr);
4396 void CXXNameMangler::addSubstitution(TemplateName Template) {
4397 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4398 return addSubstitution(TD);
4400 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4401 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4404 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4405 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4406 Substitutions[Ptr] = SeqID++;
4409 CXXNameMangler::AbiTagList
4410 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4411 // When derived abi tags are disabled there is no need to make any list.
4412 if (DisableDerivedAbiTags)
4413 return AbiTagList();
4415 llvm::raw_null_ostream NullOutStream;
4416 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4417 TrackReturnTypeTags.disableDerivedAbiTags();
4419 const FunctionProtoType *Proto =
4420 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4421 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4422 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4423 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4425 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4428 CXXNameMangler::AbiTagList
4429 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4430 // When derived abi tags are disabled there is no need to make any list.
4431 if (DisableDerivedAbiTags)
4432 return AbiTagList();
4434 llvm::raw_null_ostream NullOutStream;
4435 CXXNameMangler TrackVariableType(*this, NullOutStream);
4436 TrackVariableType.disableDerivedAbiTags();
4438 TrackVariableType.mangleType(VD->getType());
4440 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4443 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4444 const VarDecl *VD) {
4445 llvm::raw_null_ostream NullOutStream;
4446 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4447 TrackAbiTags.mangle(VD);
4448 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4453 /// Mangles the name of the declaration D and emits that name to the given
4456 /// If the declaration D requires a mangled name, this routine will emit that
4457 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4458 /// and this routine will return false. In this case, the caller should just
4459 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4461 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4463 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4464 "Invalid mangleName() call, argument is not a variable or function!");
4465 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4466 "Invalid mangleName() call on 'structor decl!");
4468 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4469 getASTContext().getSourceManager(),
4470 "Mangling declaration");
4472 CXXNameMangler Mangler(*this, Out, D);
4476 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4479 CXXNameMangler Mangler(*this, Out, D, Type);
4483 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4486 CXXNameMangler Mangler(*this, Out, D, Type);
4490 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4492 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4496 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4498 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4502 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4503 const ThunkInfo &Thunk,
4505 // <special-name> ::= T <call-offset> <base encoding>
4506 // # base is the nominal target function of thunk
4507 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4508 // # base is the nominal target function of thunk
4509 // # first call-offset is 'this' adjustment
4510 // # second call-offset is result adjustment
4512 assert(!isa<CXXDestructorDecl>(MD) &&
4513 "Use mangleCXXDtor for destructor decls!");
4514 CXXNameMangler Mangler(*this, Out);
4515 Mangler.getStream() << "_ZT";
4516 if (!Thunk.Return.isEmpty())
4517 Mangler.getStream() << 'c';
4519 // Mangle the 'this' pointer adjustment.
4520 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4521 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4523 // Mangle the return pointer adjustment if there is one.
4524 if (!Thunk.Return.isEmpty())
4525 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4526 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4528 Mangler.mangleFunctionEncoding(MD);
4531 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4532 const CXXDestructorDecl *DD, CXXDtorType Type,
4533 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4534 // <special-name> ::= T <call-offset> <base encoding>
4535 // # base is the nominal target function of thunk
4536 CXXNameMangler Mangler(*this, Out, DD, Type);
4537 Mangler.getStream() << "_ZT";
4539 // Mangle the 'this' pointer adjustment.
4540 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4541 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4543 Mangler.mangleFunctionEncoding(DD);
4546 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4547 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4549 // <special-name> ::= GV <object name> # Guard variable for one-time
4551 CXXNameMangler Mangler(*this, Out);
4552 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4553 // be a bug that is fixed in trunk.
4554 Mangler.getStream() << "_ZGV";
4555 Mangler.mangleName(D);
4558 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4560 // These symbols are internal in the Itanium ABI, so the names don't matter.
4561 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4562 // avoid duplicate symbols.
4563 Out << "__cxx_global_var_init";
4566 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4568 // Prefix the mangling of D with __dtor_.
4569 CXXNameMangler Mangler(*this, Out);
4570 Mangler.getStream() << "__dtor_";
4571 if (shouldMangleDeclName(D))
4574 Mangler.getStream() << D->getName();
4577 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4578 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4579 CXXNameMangler Mangler(*this, Out);
4580 Mangler.getStream() << "__filt_";
4581 if (shouldMangleDeclName(EnclosingDecl))
4582 Mangler.mangle(EnclosingDecl);
4584 Mangler.getStream() << EnclosingDecl->getName();
4587 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4588 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4589 CXXNameMangler Mangler(*this, Out);
4590 Mangler.getStream() << "__fin_";
4591 if (shouldMangleDeclName(EnclosingDecl))
4592 Mangler.mangle(EnclosingDecl);
4594 Mangler.getStream() << EnclosingDecl->getName();
4597 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4599 // <special-name> ::= TH <object name>
4600 CXXNameMangler Mangler(*this, Out);
4601 Mangler.getStream() << "_ZTH";
4602 Mangler.mangleName(D);
4606 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4608 // <special-name> ::= TW <object name>
4609 CXXNameMangler Mangler(*this, Out);
4610 Mangler.getStream() << "_ZTW";
4611 Mangler.mangleName(D);
4614 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4615 unsigned ManglingNumber,
4617 // We match the GCC mangling here.
4618 // <special-name> ::= GR <object name>
4619 CXXNameMangler Mangler(*this, Out);
4620 Mangler.getStream() << "_ZGR";
4621 Mangler.mangleName(D);
4622 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4623 Mangler.mangleSeqID(ManglingNumber - 1);
4626 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4628 // <special-name> ::= TV <type> # virtual table
4629 CXXNameMangler Mangler(*this, Out);
4630 Mangler.getStream() << "_ZTV";
4631 Mangler.mangleNameOrStandardSubstitution(RD);
4634 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4636 // <special-name> ::= TT <type> # VTT structure
4637 CXXNameMangler Mangler(*this, Out);
4638 Mangler.getStream() << "_ZTT";
4639 Mangler.mangleNameOrStandardSubstitution(RD);
4642 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4644 const CXXRecordDecl *Type,
4646 // <special-name> ::= TC <type> <offset number> _ <base type>
4647 CXXNameMangler Mangler(*this, Out);
4648 Mangler.getStream() << "_ZTC";
4649 Mangler.mangleNameOrStandardSubstitution(RD);
4650 Mangler.getStream() << Offset;
4651 Mangler.getStream() << '_';
4652 Mangler.mangleNameOrStandardSubstitution(Type);
4655 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4656 // <special-name> ::= TI <type> # typeinfo structure
4657 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4658 CXXNameMangler Mangler(*this, Out);
4659 Mangler.getStream() << "_ZTI";
4660 Mangler.mangleType(Ty);
4663 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4665 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4666 CXXNameMangler Mangler(*this, Out);
4667 Mangler.getStream() << "_ZTS";
4668 Mangler.mangleType(Ty);
4671 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4672 mangleCXXRTTIName(Ty, Out);
4675 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4676 llvm_unreachable("Can't mangle string literals");
4679 ItaniumMangleContext *
4680 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4681 return new ItaniumMangleContextImpl(Context, Diags);