1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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):
13 //
14 // http://mentorembedded.github.io/cxx-abi/abi.html#mangling
15 //
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"
35
36 #define MANGLE_CHECKER 0
37
38 #if MANGLE_CHECKER
39 #include <cxxabi.h>
40 #endif
41
42 using namespace clang;
43
44 namespace {
45
46 /// Retrieve the declaration context that should be used when mangling the given
47 /// declaration.
getEffectiveDeclContext(const Decl * D)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)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
61
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();
67 }
68
69 const DeclContext *DC = D->getDeclContext();
70 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
73
74 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
82 return DC->getRedeclContext();
83 }
84
getEffectiveParentContext(const DeclContext * DC)85 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87 }
88
isLocalContainerContext(const DeclContext * DC)89 static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91 }
92
GetLocalClassDecl(const Decl * D)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);
98 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
100 }
101 return nullptr;
102 }
103
getStructor(const FunctionDecl * fn)104 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109 }
110
getStructor(const NamedDecl * decl)111 static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114 }
115
isLambda(const NamedDecl * ND)116 static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122 }
123
124 static const unsigned UnknownArity = ~0U;
125
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;
130
131 public:
ItaniumMangleContextImpl(ASTContext & Context,DiagnosticsEngine & Diags)132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
135
136 /// @name Mangler Entry Points
137 /// @{
138
139 bool shouldMangleCXXName(const NamedDecl *D) override;
shouldMangleStringLiteral(const StringLiteral *)140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
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;
162
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;
176
177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
getNextDiscriminator(const NamedDecl * ND,unsigned & disc)179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180 // Lambda closure types are already numbered.
181 if (isLambda(ND))
182 return false;
183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
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())];
204 }
205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211 };
212
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215 ItaniumMangleContextImpl &Context;
216 raw_ostream &Out;
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;
223
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;
229
230 /// The next substitution sequence number.
231 unsigned SeqID;
232
233 class FunctionTypeDepthState {
234 unsigned Bits;
235
236 enum { InResultTypeMask = 1 };
237
238 public:
FunctionTypeDepthState()239 FunctionTypeDepthState() : Bits(0) {}
240
241 /// The number of function types we're inside.
getDepth() const242 unsigned getDepth() const {
243 return Bits >> 1;
244 }
245
246 /// True if we're in the return type of the innermost function type.
isInResultType() const247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
249 }
250
push()251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
254 return tmp;
255 }
256
enterResultType()257 void enterResultType() {
258 Bits |= InResultTypeMask;
259 }
260
leaveResultType()261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
263 }
264
pop(FunctionTypeDepthState saved)265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
267 Bits = saved.Bits;
268 }
269
270 } FunctionTypeDepth;
271
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;
277
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
280 // track.
281 class AbiTagState final {
282 public:
AbiTagState(AbiTagState * & Head)283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284 Parent = LinkHead;
285 LinkHead = this;
286 }
287
288 // No copy, no move.
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
291
~AbiTagState()292 ~AbiTagState() { pop(); }
293
write(raw_ostream & Out,const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)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)) {
298 assert(
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());
305 }
306 // Don't emit abi tags for namespaces.
307 return;
308 }
309 }
310
311 AbiTagList TagList;
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());
317 }
318
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
324 }
325
326 std::sort(TagList.begin(), TagList.end());
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
getUsedAbiTags() const332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
setUsedAbiTags(const AbiTagList & AbiTags)333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
getEmittedAbiTags() const337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
getSortedUniqueUsedAbiTags()341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
pop()357 void pop() {
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
360 if (Parent) {
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());
366 }
367 LinkHead = Parent;
368 }
369
writeSortedUniqueAbiTags(raw_ostream & Out,const AbiTagList & AbiTags)370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
384
getASTContext() const385 ASTContext &getASTContext() const { return Context.getASTContext(); }
386
387 public:
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const NamedDecl * D=nullptr,bool NullOut_=false)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)));
395 }
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const CXXConstructorDecl * D,CXXCtorType Type)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) { }
CXXNameMangler(ItaniumMangleContextImpl & C,raw_ostream & Out_,const CXXDestructorDecl * D,CXXDtorType Type)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) { }
404
CXXNameMangler(CXXNameMangler & Outer,raw_ostream & Out_)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) {}
409
CXXNameMangler(CXXNameMangler & Outer,llvm::raw_null_ostream & Out_)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) {}
414
415 #if MANGLE_CHECKER
~CXXNameMangler()416 ~CXXNameMangler() {
417 if (Out.str()[0] == '\01')
418 return;
419
420 int status = 0;
421 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
422 assert(status == 0 && "Could not demangle mangled name!");
423 free(result);
424 }
425 #endif
getStream()426 raw_ostream &getStream() { return Out; }
427
disableDerivedAbiTags()428 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
429 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
430
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);
441
442 private:
443
444 bool mangleSubstitution(const NamedDecl *ND);
445 bool mangleSubstitution(QualType T);
446 bool mangleSubstitution(TemplateName Template);
447 bool mangleSubstitution(uintptr_t Ptr);
448
449 void mangleExistingSubstitution(TemplateName name);
450
451 bool mangleStandardSubstitution(const NamedDecl *ND);
452
addSubstitution(const NamedDecl * ND)453 void addSubstitution(const NamedDecl *ND) {
454 ND = cast<NamedDecl>(ND->getCanonicalDecl());
455
456 addSubstitution(reinterpret_cast<uintptr_t>(ND));
457 }
458 void addSubstitution(QualType T);
459 void addSubstitution(TemplateName Template);
460 void addSubstitution(uintptr_t Ptr);
461
462 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
463 bool recursive = false);
464 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
465 DeclarationName name,
466 unsigned KnownArity = UnknownArity);
467
468 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
469
470 void mangleNameWithAbiTags(const NamedDecl *ND,
471 const AbiTagList *AdditionalAbiTags);
472 void mangleTemplateName(const TemplateDecl *TD,
473 const TemplateArgument *TemplateArgs,
474 unsigned NumTemplateArgs);
mangleUnqualifiedName(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)475 void mangleUnqualifiedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags) {
477 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
478 AdditionalAbiTags);
479 }
480 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
481 unsigned KnownArity,
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);
515
516 void mangleObjCMethodName(const ObjCMethodDecl *MD);
517
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"
523
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);
533
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);
546
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);
553
554 void mangleTemplateParameter(unsigned Index);
555
556 void mangleFunctionParam(const ParmVarDecl *parm);
557
558 void writeAbiTags(const NamedDecl *ND,
559 const AbiTagList *AdditionalAbiTags);
560
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);
565 };
566
567 }
568
shouldMangleCXXName(const NamedDecl * D)569 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
570 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
571 if (FD) {
572 LanguageLinkage L = FD->getLanguageLinkage();
573 // Overloadable functions need mangling.
574 if (FD->hasAttr<OverloadableAttr>())
575 return true;
576
577 // "main" is not mangled.
578 if (FD->isMain())
579 return false;
580
581 // C++ functions and those whose names are not a simple identifier need
582 // mangling.
583 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
584 return true;
585
586 // C functions are not mangled.
587 if (L == CLanguageLinkage)
588 return false;
589 }
590
591 // Otherwise, no mangling is done outside C++ mode.
592 if (!getASTContext().getLangOpts().CPlusPlus)
593 return false;
594
595 const VarDecl *VD = dyn_cast<VarDecl>(D);
596 if (VD) {
597 // C variables are not mangled.
598 if (VD->isExternC())
599 return false;
600
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))
610 return false;
611 }
612
613 return true;
614 }
615
writeAbiTags(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)616 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
617 const AbiTagList *AdditionalAbiTags) {
618 assert(AbiTags && "require AbiTagState");
619 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
620 }
621
mangleSourceNameWithAbiTags(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)622 void CXXNameMangler::mangleSourceNameWithAbiTags(
623 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
624 mangleSourceName(ND->getIdentifier());
625 writeAbiTags(ND, AdditionalAbiTags);
626 }
627
mangle(const NamedDecl * D)628 void CXXNameMangler::mangle(const NamedDecl *D) {
629 // <mangled-name> ::= _Z <encoding>
630 // ::= <data name>
631 // ::= <special-name>
632 Out << "_Z";
633 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
634 mangleFunctionEncoding(FD);
635 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
636 mangleName(VD);
637 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
638 mangleName(IFD->getAnonField());
639 else
640 mangleName(cast<FieldDecl>(D));
641 }
642
mangleFunctionEncoding(const FunctionDecl * FD)643 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
644 // <encoding> ::= <function name> <bare-function-type>
645
646 // Don't mangle in the type if this isn't a decl we should typically mangle.
647 if (!Context.shouldMangleDeclName(FD)) {
648 mangleName(FD);
649 return;
650 }
651
652 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
653 if (ReturnTypeAbiTags.empty()) {
654 // There are no tags for return type, the simplest case.
655 mangleName(FD);
656 mangleFunctionEncodingBareType(FD);
657 return;
658 }
659
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);
669
670 // Remember length of the function name in the buffer.
671 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
672 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
673
674 // Get tags from return type that are not present in function name or
675 // encoding.
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());
684
685 // Output name with implicit tags and function encoding from temporary buffer.
686 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
687 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
688 }
689
mangleFunctionEncodingBareType(const FunctionDecl * FD)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
695 // it here.
696 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
697 E = FD->getAttrs().rend();
698 I != E; ++I) {
699 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
700 if (!EIA)
701 continue;
702 Out << 'X';
703 mangleExpression(EIA->getCond());
704 Out << 'E';
705 }
706 Out << 'E';
707 FunctionTypeDepth.pop(Saved);
708 }
709
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();
715
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:
719 //
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.
726 //
727 // The exceptions mentioned in (1) and (2) above, for which the return type is
728 // never included, are
729 // 1. Constructors.
730 // 2. Destructors.
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;
737
738 // Mangle the type of the primary template.
739 FD = PrimaryTemplate->getTemplatedDecl();
740 }
741
742 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
743 MangleReturnType, FD);
744 }
745
IgnoreLinkageSpecDecls(const DeclContext * DC)746 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
747 while (isa<LinkageSpecDecl>(DC)) {
748 DC = getEffectiveParentContext(DC);
749 }
750
751 return DC;
752 }
753
754 /// Return whether a given namespace is the 'std' namespace.
isStd(const NamespaceDecl * NS)755 static bool isStd(const NamespaceDecl *NS) {
756 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
757 ->isTranslationUnit())
758 return false;
759
760 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
761 return II && II->isStr("std");
762 }
763
764 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
765 // namespace.
isStdNamespace(const DeclContext * DC)766 static bool isStdNamespace(const DeclContext *DC) {
767 if (!DC->isNamespace())
768 return false;
769
770 return isStd(cast<NamespaceDecl>(DC));
771 }
772
773 static const TemplateDecl *
isTemplate(const NamedDecl * ND,const TemplateArgumentList * & TemplateArgs)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();
779 return TD;
780 }
781 }
782
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();
788 }
789
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();
795 }
796
797 return nullptr;
798 }
799
mangleName(const NamedDecl * ND)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);
807 return;
808 }
809
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);
815
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());
825
826 // Output name with implicit tags.
827 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
828 } else {
829 mangleNameWithAbiTags(ND, nullptr);
830 }
831 }
832
mangleNameWithAbiTags(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)833 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
834 const AbiTagList *AdditionalAbiTags) {
835 // <name> ::= <nested-name>
836 // ::= <unscoped-name>
837 // ::= <unscoped-template-name> <template-args>
838 // ::= <local-name>
839 //
840 const DeclContext *DC = getEffectiveDeclContext(ND);
841
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);
851 return;
852 }
853
854 DC = IgnoreLinkageSpecDecls(DC);
855
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);
862 return;
863 }
864
865 mangleUnscopedName(ND, AdditionalAbiTags);
866 return;
867 }
868
869 if (isLocalContainerContext(DC)) {
870 mangleLocalName(ND, AdditionalAbiTags);
871 return;
872 }
873
874 mangleNestedName(ND, DC, AdditionalAbiTags);
875 }
876
mangleTemplateName(const TemplateDecl * TD,const TemplateArgument * TemplateArgs,unsigned NumTemplateArgs)877 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
878 const TemplateArgument *TemplateArgs,
879 unsigned NumTemplateArgs) {
880 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
881
882 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
883 mangleUnscopedTemplateName(TD, nullptr);
884 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
885 } else {
886 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
887 }
888 }
889
mangleUnscopedName(const NamedDecl * ND,const AbiTagList * AdditionalAbiTags)890 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
891 const AbiTagList *AdditionalAbiTags) {
892 // <unscoped-name> ::= <unqualified-name>
893 // ::= St <unqualified-name> # ::std::
894
895 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
896 Out << "St";
897
898 mangleUnqualifiedName(ND, AdditionalAbiTags);
899 }
900
mangleUnscopedTemplateName(const TemplateDecl * ND,const AbiTagList * AdditionalAbiTags)901 void CXXNameMangler::mangleUnscopedTemplateName(
902 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
903 // <unscoped-template-name> ::= <unscoped-name>
904 // ::= <substitution>
905 if (mangleSubstitution(ND))
906 return;
907
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);
915 } else {
916 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
917 }
918
919 addSubstitution(ND);
920 }
921
mangleUnscopedTemplateName(TemplateName Template,const AbiTagList * 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);
928
929 if (mangleSubstitution(Template))
930 return;
931
932 assert(!AdditionalAbiTags &&
933 "dependent template name cannot have abi tags");
934
935 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
936 assert(Dependent && "Not a dependent template name?");
937 if (const IdentifierInfo *Id = Dependent->getIdentifier())
938 mangleSourceName(Id);
939 else
940 mangleOperatorName(Dependent->getOperator(), UnknownArity);
941
942 addSubstitution(Template);
943 }
944
mangleFloat(const llvm::APFloat & f)945 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
946 // ABI:
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
951 // on Itanium.
952 // The 'without leading zeroes' thing seems to be an editorial
953 // mistake; see the discussion on cxx-abi-dev beginning on
954 // 2012-01-16.
955
956 // Our requirements here are just barely weird enough to justify
957 // using a custom algorithm instead of post-processing APInt::toString().
958
959 llvm::APInt valueBits = f.bitcastToAPInt();
960 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
961 assert(numCharacters != 0);
962
963 // Allocate a buffer of the right number of characters.
964 SmallVector<char, 20> buffer(numCharacters);
965
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);
970
971 // Project out 4 bits starting at 'digitIndex'.
972 llvm::integerPart hexDigit
973 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
974 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
975 hexDigit &= 0xF;
976
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'
981 };
982 buffer[stringIndex] = charForHex[hexDigit];
983 }
984
985 Out.write(buffer.data(), numCharacters);
986 }
987
mangleNumber(const llvm::APSInt & Value)988 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
989 if (Value.isSigned() && Value.isNegative()) {
990 Out << 'n';
991 Value.abs().print(Out, /*signed*/ false);
992 } else {
993 Value.print(Out, /*signed*/ false);
994 }
995 }
996
mangleNumber(int64_t Number)997 void CXXNameMangler::mangleNumber(int64_t Number) {
998 // <number> ::= [n] <non-negative decimal integer>
999 if (Number < 0) {
1000 Out << 'n';
1001 Number = -Number;
1002 }
1003
1004 Out << Number;
1005 }
1006
mangleCallOffset(int64_t NonVirtual,int64_t Virtual)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
1013 if (!Virtual) {
1014 Out << 'h';
1015 mangleNumber(NonVirtual);
1016 Out << '_';
1017 return;
1018 }
1019
1020 Out << 'v';
1021 mangleNumber(NonVirtual);
1022 Out << '_';
1023 mangleNumber(Virtual);
1024 Out << '_';
1025 }
1026
manglePrefix(QualType type)1027 void CXXNameMangler::manglePrefix(QualType type) {
1028 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1029 if (!mangleSubstitution(QualType(TST, 0))) {
1030 mangleTemplatePrefix(TST->getTemplateName());
1031
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));
1037 }
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);
1044
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));
1050 }
1051 } else {
1052 // We use the QualType mangle type variant here because it handles
1053 // substitutions.
1054 mangleType(type);
1055 }
1056 }
1057
1058 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1059 ///
1060 /// \param recursive - true if this is being called recursively,
1061 /// i.e. if there is more prefix "to the right".
mangleUnresolvedPrefix(NestedNameSpecifier * qualifier,bool recursive)1062 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1063 bool recursive) {
1064
1065 // x, ::x
1066 // <unresolved-name> ::= [gs] <base-unresolved-name>
1067
1068 // T::x / decltype(p)::x
1069 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1070
1071 // T::N::x /decltype(p)::N::x
1072 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1073 // <base-unresolved-name>
1074
1075 // A::x, N::y, A<T>::z; "gs" means leading "::"
1076 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1077 // <base-unresolved-name>
1078
1079 switch (qualifier->getKind()) {
1080 case NestedNameSpecifier::Global:
1081 Out << "gs";
1082
1083 // We want an 'sr' unless this is the entire NNS.
1084 if (recursive)
1085 Out << "sr";
1086
1087 // We never want an 'E' here.
1088 return;
1089
1090 case NestedNameSpecifier::Super:
1091 llvm_unreachable("Can't mangle __super specifier");
1092
1093 case NestedNameSpecifier::Namespace:
1094 if (qualifier->getPrefix())
1095 mangleUnresolvedPrefix(qualifier->getPrefix(),
1096 /*recursive*/ true);
1097 else
1098 Out << "sr";
1099 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1100 break;
1101 case NestedNameSpecifier::NamespaceAlias:
1102 if (qualifier->getPrefix())
1103 mangleUnresolvedPrefix(qualifier->getPrefix(),
1104 /*recursive*/ true);
1105 else
1106 Out << "sr";
1107 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1108 break;
1109
1110 case NestedNameSpecifier::TypeSpec:
1111 case NestedNameSpecifier::TypeSpecWithTemplate: {
1112 const Type *type = qualifier->getAsType();
1113
1114 // We only want to use an unresolved-type encoding if this is one of:
1115 // - a decltype
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);
1122 } else {
1123 // Otherwise, all the cases want this.
1124 Out << "sr";
1125 }
1126
1127 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1128 return;
1129
1130 break;
1131 }
1132
1133 case NestedNameSpecifier::Identifier:
1134 // Member expressions can have these without prefixes.
1135 if (qualifier->getPrefix())
1136 mangleUnresolvedPrefix(qualifier->getPrefix(),
1137 /*recursive*/ true);
1138 else
1139 Out << "sr";
1140
1141 mangleSourceName(qualifier->getAsIdentifier());
1142 // An Identifier has no type information, so we can't emit abi tags for it.
1143 break;
1144 }
1145
1146 // If this was the innermost part of the NNS, and we fell out to
1147 // here, append an 'E'.
1148 if (!recursive)
1149 Out << 'E';
1150 }
1151
1152 /// Mangle an unresolved-name, which is generally used for names which
1153 /// weren't resolved to specific entities.
mangleUnresolvedName(NestedNameSpecifier * qualifier,DeclarationName name,unsigned knownArity)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());
1162 break;
1163 // <base-unresolved-name> ::= dn <destructor-name>
1164 case DeclarationName::CXXDestructorName:
1165 Out << "dn";
1166 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1167 break;
1168 // <base-unresolved-name> ::= on <operator-name>
1169 case DeclarationName::CXXConversionFunctionName:
1170 case DeclarationName::CXXLiteralOperatorName:
1171 case DeclarationName::CXXOperatorName:
1172 Out << "on";
1173 mangleOperatorName(name, knownArity);
1174 break;
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!");
1183 }
1184 }
1185
mangleUnqualifiedName(const NamedDecl * ND,DeclarationName Name,unsigned KnownArity,const AbiTagList * AdditionalAbiTags)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())
1205 Out << 'L';
1206
1207 mangleSourceName(II);
1208 writeAbiTags(ND, AdditionalAbiTags);
1209 break;
1210 }
1211
1212 // Otherwise, an anonymous entity. We must have a declaration.
1213 assert(ND && "mangling empty name without declaration");
1214
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";
1219 break;
1220 }
1221 }
1222
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());
1227
1228 // Itanium C++ ABI 5.1.2:
1229 //
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();
1240
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.
1244 if (!FD) break;
1245 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1246
1247 mangleSourceName(FD->getIdentifier());
1248 // Not emitting abi tags: internal name anyway.
1249 break;
1250 }
1251
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))
1259 break;
1260
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
1271 // from typedef.
1272 writeAbiTags(TD, nullptr);
1273 break;
1274 }
1275
1276 // <unnamed-type-name> ::= <closure-type-name>
1277 //
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);
1285 break;
1286 }
1287 }
1288
1289 if (TD->isExternallyVisible()) {
1290 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1291 Out << "Ut";
1292 if (UnnamedMangle > 1)
1293 Out << UnnamedMangle - 2;
1294 Out << '_';
1295 writeAbiTags(TD, AdditionalAbiTags);
1296 break;
1297 }
1298
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);
1302
1303 // Mangle it as a source name in the form
1304 // [n] $_<id>
1305 // where n is the length of the string.
1306 SmallString<8> Str;
1307 Str += "$_";
1308 Str += llvm::utostr(AnonStructId);
1309
1310 Out << Str.size();
1311 Out << Str;
1312 break;
1313 }
1314
1315 case DeclarationName::ObjCZeroArgSelector:
1316 case DeclarationName::ObjCOneArgSelector:
1317 case DeclarationName::ObjCMultiArgSelector:
1318 llvm_unreachable("Can't mangle Objective-C selector names here!");
1319
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();
1328 }
1329
1330 if (ND == Structor)
1331 // If the named decl is the C++ constructor we're mangling, use the type
1332 // we were given.
1333 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1334 else
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);
1338
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);
1343
1344 writeAbiTags(ND, AdditionalAbiTags);
1345 break;
1346 }
1347
1348 case DeclarationName::CXXDestructorName:
1349 if (ND == Structor)
1350 // If the named decl is the C++ destructor we're mangling, use the type we
1351 // were given.
1352 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1353 else
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);
1358 break;
1359
1360 case DeclarationName::CXXOperatorName:
1361 if (ND && Arity == UnknownArity) {
1362 Arity = cast<FunctionDecl>(ND)->getNumParams();
1363
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())
1367 Arity++;
1368 }
1369 // FALLTHROUGH
1370 case DeclarationName::CXXConversionFunctionName:
1371 case DeclarationName::CXXLiteralOperatorName:
1372 mangleOperatorName(Name, Arity);
1373 writeAbiTags(ND, AdditionalAbiTags);
1374 break;
1375
1376 case DeclarationName::CXXUsingDirective:
1377 llvm_unreachable("Can't mangle a using directive name!");
1378 }
1379 }
1380
mangleSourceName(const IdentifierInfo * II)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();
1386 }
1387
mangleNestedName(const NamedDecl * ND,const DeclContext * DC,const AbiTagList * AdditionalAbiTags,bool NoFunction)1388 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1389 const DeclContext *DC,
1390 const AbiTagList *AdditionalAbiTags,
1391 bool NoFunction) {
1392 // <nested-name>
1393 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1394 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1395 // <template-args> E
1396
1397 Out << 'N';
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());
1406 }
1407
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);
1413 }
1414 else {
1415 manglePrefix(DC, NoFunction);
1416 mangleUnqualifiedName(ND, AdditionalAbiTags);
1417 }
1418
1419 Out << 'E';
1420 }
mangleNestedName(const TemplateDecl * TD,const TemplateArgument * TemplateArgs,unsigned NumTemplateArgs)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
1425
1426 Out << 'N';
1427
1428 mangleTemplatePrefix(TD);
1429 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1430
1431 Out << 'E';
1432 }
1433
mangleLocalName(const Decl * D,const AbiTagList * AdditionalAbiTags)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> ]
1439 // _ <entity name>
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);
1444
1445 Out << 'Z';
1446
1447 {
1448 AbiTagState LocalAbiTags(AbiTags);
1449
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);
1454 else
1455 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1456
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());
1460 }
1461
1462 Out << 'E';
1463
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.
1466
1467 if (RD) {
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())) {
1479 Out << 'd';
1480 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1481 if (Num > 1)
1482 mangleNumber(Num - 2);
1483 Out << '_';
1484 }
1485 }
1486 }
1487
1488 // Mangle the name relative to the closest enclosing function.
1489 // equality ok because RD derived from ND above
1490 if (D == RD) {
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);
1496 } else {
1497 const NamedDecl *ND = cast<NamedDecl>(D);
1498 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1499 true /*NoFunction*/);
1500 }
1501 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1502 // Mangle a block in a default parameter; see above explanation for
1503 // lambdas.
1504 if (const ParmVarDecl *Parm
1505 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1506 if (const FunctionDecl *Func
1507 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1508 Out << 'd';
1509 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1510 if (Num > 1)
1511 mangleNumber(Num - 2);
1512 Out << '_';
1513 }
1514 }
1515
1516 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1517 mangleUnqualifiedBlock(BD);
1518 } else {
1519 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1520 }
1521
1522 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1523 unsigned disc;
1524 if (Context.getNextDiscriminator(ND, disc)) {
1525 if (disc < 10)
1526 Out << '_' << disc;
1527 else
1528 Out << "__" << disc << '_';
1529 }
1530 }
1531 }
1532
mangleBlockForPrefix(const BlockDecl * Block)1533 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1534 if (GetLocalClassDecl(Block)) {
1535 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1536 return;
1537 }
1538 const DeclContext *DC = getEffectiveDeclContext(Block);
1539 if (isLocalContainerContext(DC)) {
1540 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1541 return;
1542 }
1543 manglePrefix(getEffectiveDeclContext(Block));
1544 mangleUnqualifiedBlock(Block);
1545 }
1546
mangleUnqualifiedBlock(const BlockDecl * 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);
1554 Out << 'M';
1555 }
1556 }
1557 }
1558
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.
1563 if (!Number)
1564 Number = Context.getBlockId(Block, false);
1565 Out << "Ub";
1566 if (Number > 0)
1567 Out << Number - 1;
1568 Out << '_';
1569 }
1570
mangleLambda(const CXXRecordDecl * Lambda)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:
1575 //
1576 // <data-member-prefix> := <member source-name> M
1577 //
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);
1587 Out << 'M';
1588 }
1589 }
1590 }
1591
1592 Out << "Ul";
1593 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1594 getAs<FunctionProtoType>();
1595 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1596 Lambda->getLambdaStaticInvoker());
1597 Out << "E";
1598
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.
1602 //
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");
1606 if (Number > 1)
1607 mangleNumber(Number - 2);
1608 Out << '_';
1609 }
1610
manglePrefix(NestedNameSpecifier * qualifier)1611 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1612 switch (qualifier->getKind()) {
1613 case NestedNameSpecifier::Global:
1614 // nothing
1615 return;
1616
1617 case NestedNameSpecifier::Super:
1618 llvm_unreachable("Can't mangle __super specifier");
1619
1620 case NestedNameSpecifier::Namespace:
1621 mangleName(qualifier->getAsNamespace());
1622 return;
1623
1624 case NestedNameSpecifier::NamespaceAlias:
1625 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1626 return;
1627
1628 case NestedNameSpecifier::TypeSpec:
1629 case NestedNameSpecifier::TypeSpecWithTemplate:
1630 manglePrefix(QualType(qualifier->getAsType(), 0));
1631 return;
1632
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());
1638
1639 mangleSourceName(qualifier->getAsIdentifier());
1640 return;
1641 }
1642
1643 llvm_unreachable("unexpected nested name specifier");
1644 }
1645
manglePrefix(const DeclContext * DC,bool NoFunction)1646 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1647 // <prefix> ::= <prefix> <unqualified-name>
1648 // ::= <template-prefix> <template-args>
1649 // ::= <template-param>
1650 // ::= # empty
1651 // ::= <substitution>
1652
1653 DC = IgnoreLinkageSpecDecls(DC);
1654
1655 if (DC->isTranslationUnit())
1656 return;
1657
1658 if (NoFunction && isLocalContainerContext(DC))
1659 return;
1660
1661 assert(!isLocalContainerContext(DC));
1662
1663 const NamedDecl *ND = cast<NamedDecl>(DC);
1664 if (mangleSubstitution(ND))
1665 return;
1666
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);
1672 } else {
1673 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1674 mangleUnqualifiedName(ND, nullptr);
1675 }
1676
1677 addSubstitution(ND);
1678 }
1679
mangleTemplatePrefix(TemplateName Template)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);
1686
1687 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1688 manglePrefix(Qualified->getQualifier());
1689
1690 if (OverloadedTemplateStorage *Overloaded
1691 = Template.getAsOverloadedTemplate()) {
1692 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1693 UnknownArity, nullptr);
1694 return;
1695 }
1696
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);
1702 }
1703
mangleTemplatePrefix(const TemplateDecl * ND,bool NoFunction)1704 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1705 bool NoFunction) {
1706 // <template-prefix> ::= <prefix> <template unqualified-name>
1707 // ::= <template-param>
1708 // ::= <substitution>
1709 // <template-template-param> ::= <template-param>
1710 // <substitution>
1711
1712 if (mangleSubstitution(ND))
1713 return;
1714
1715 // <template-template-param> ::= <template-param>
1716 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1717 mangleTemplateParameter(TTP->getIndex());
1718 } else {
1719 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1720 if (isa<BuiltinTemplateDecl>(ND))
1721 mangleUnqualifiedName(ND, nullptr);
1722 else
1723 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1724 }
1725
1726 addSubstitution(ND);
1727 }
1728
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>
mangleType(TemplateName TN)1734 void CXXNameMangler::mangleType(TemplateName TN) {
1735 if (mangleSubstitution(TN))
1736 return;
1737
1738 TemplateDecl *TD = nullptr;
1739
1740 switch (TN.getKind()) {
1741 case TemplateName::QualifiedTemplate:
1742 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1743 goto HaveDecl;
1744
1745 case TemplateName::Template:
1746 TD = TN.getAsTemplateDecl();
1747 goto HaveDecl;
1748
1749 HaveDecl:
1750 if (isa<TemplateTemplateParmDecl>(TD))
1751 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1752 else
1753 mangleName(TD);
1754 break;
1755
1756 case TemplateName::OverloadedTemplate:
1757 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1758
1759 case TemplateName::DependentTemplate: {
1760 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1761 assert(Dependent->isIdentifier());
1762
1763 // <class-enum-type> ::= <name>
1764 // <name> ::= <nested-name>
1765 mangleUnresolvedPrefix(Dependent->getQualifier());
1766 mangleSourceName(Dependent->getIdentifier());
1767 break;
1768 }
1769
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());
1778 return;
1779 }
1780
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...);
1785 // };
1786 Out << "_SUBSTPACK_";
1787 break;
1788 }
1789 }
1790
1791 addSubstitution(TN);
1792 }
1793
mangleUnresolvedTypeOrSimpleId(QualType Ty,StringRef Prefix)1794 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1795 StringRef Prefix) {
1796 // Only certain other types are valid as prefixes; enumerate them.
1797 switch (Ty->getTypeClass()) {
1798 case Type::Builtin:
1799 case Type::Complex:
1800 case Type::Adjusted:
1801 case Type::Decayed:
1802 case Type::Pointer:
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:
1812 case Type::Vector:
1813 case Type::ExtVector:
1814 case Type::FunctionProto:
1815 case Type::FunctionNoProto:
1816 case Type::Paren:
1817 case Type::Attributed:
1818 case Type::Auto:
1819 case Type::PackExpansion:
1820 case Type::ObjCObject:
1821 case Type::ObjCInterface:
1822 case Type::ObjCObjectPointer:
1823 case Type::Atomic:
1824 case Type::Pipe:
1825 llvm_unreachable("type is illegal as a nested name specifier");
1826
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...);
1831 // };
1832 Out << "_SUBSTPACK_";
1833 break;
1834
1835 // <unresolved-type> ::= <template-param>
1836 // ::= <decltype>
1837 // ::= <template-template-param> <template-args>
1838 // (this last is not official yet)
1839 case Type::TypeOfExpr:
1840 case Type::TypeOf:
1841 case Type::Decltype:
1842 case Type::TemplateTypeParm:
1843 case Type::UnaryTransform:
1844 case Type::SubstTemplateTypeParm:
1845 unresolvedType:
1846 // Some callers want a prefix before the mangled type.
1847 Out << Prefix;
1848
1849 // This seems to do everything we want. It's not really
1850 // sanctioned for a substituted template parameter, though.
1851 mangleType(Ty);
1852
1853 // We never want to print 'E' directly after an unresolved-type,
1854 // so we return directly.
1855 return true;
1856
1857 case Type::Typedef:
1858 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
1859 break;
1860
1861 case Type::UnresolvedUsing:
1862 mangleSourceNameWithAbiTags(
1863 cast<UnresolvedUsingType>(Ty)->getDecl());
1864 break;
1865
1866 case Type::Enum:
1867 case Type::Record:
1868 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
1869 break;
1870
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();
1879
1880 // If the base is a template template parameter, this is an
1881 // unresolved type.
1882 assert(TD && "no template for template specialization type");
1883 if (isa<TemplateTemplateParmDecl>(TD))
1884 goto unresolvedType;
1885
1886 mangleSourceNameWithAbiTags(TD);
1887 break;
1888 }
1889
1890 case TemplateName::OverloadedTemplate:
1891 case TemplateName::DependentTemplate:
1892 llvm_unreachable("invalid base for a template specialization type");
1893
1894 case TemplateName::SubstTemplateTemplateParm: {
1895 SubstTemplateTemplateParmStorage *subst =
1896 TN.getAsSubstTemplateTemplateParm();
1897 mangleExistingSubstitution(subst->getReplacement());
1898 break;
1899 }
1900
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...);
1905 // };
1906 Out << "_SUBSTPACK_";
1907 break;
1908 }
1909 }
1910
1911 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1912 break;
1913 }
1914
1915 case Type::InjectedClassName:
1916 mangleSourceNameWithAbiTags(
1917 cast<InjectedClassNameType>(Ty)->getDecl());
1918 break;
1919
1920 case Type::DependentName:
1921 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1922 break;
1923
1924 case Type::DependentTemplateSpecialization: {
1925 const DependentTemplateSpecializationType *DTST =
1926 cast<DependentTemplateSpecializationType>(Ty);
1927 mangleSourceName(DTST->getIdentifier());
1928 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1929 break;
1930 }
1931
1932 case Type::Elaborated:
1933 return mangleUnresolvedTypeOrSimpleId(
1934 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1935 }
1936
1937 return false;
1938 }
1939
mangleOperatorName(DeclarationName Name,unsigned Arity)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");
1950
1951 case DeclarationName::CXXConversionFunctionName:
1952 // <operator-name> ::= cv <type> # (cast)
1953 Out << "cv";
1954 mangleType(Name.getCXXNameType());
1955 break;
1956
1957 case DeclarationName::CXXLiteralOperatorName:
1958 Out << "li";
1959 mangleSourceName(Name.getCXXLiteralIdentifier());
1960 return;
1961
1962 case DeclarationName::CXXOperatorName:
1963 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1964 break;
1965 }
1966 }
1967
1968 void
mangleOperatorName(OverloadedOperatorKind OO,unsigned Arity)1969 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1970 switch (OO) {
1971 // <operator-name> ::= nw # new
1972 case OO_New: Out << "nw"; break;
1973 // ::= na # new[]
1974 case OO_Array_New: Out << "na"; break;
1975 // ::= dl # delete
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)
1981 case OO_Plus:
1982 Out << (Arity == 1? "ps" : "pl"); break;
1983 // ::= ng # - (unary)
1984 // ::= mi # - (binary or unknown)
1985 case OO_Minus:
1986 Out << (Arity == 1? "ng" : "mi"); break;
1987 // ::= ad # & (unary)
1988 // ::= an # & (binary or unknown)
1989 case OO_Amp:
1990 Out << (Arity == 1? "ad" : "an"); break;
1991 // ::= de # * (unary)
1992 // ::= ml # * (binary or unknown)
1993 case OO_Star:
1994 // Use binary when unknown.
1995 Out << (Arity == 1? "de" : "ml"); break;
1996 // ::= co # ~
1997 case OO_Tilde: Out << "co"; break;
1998 // ::= dv # /
1999 case OO_Slash: Out << "dv"; break;
2000 // ::= rm # %
2001 case OO_Percent: Out << "rm"; break;
2002 // ::= or # |
2003 case OO_Pipe: Out << "or"; break;
2004 // ::= eo # ^
2005 case OO_Caret: Out << "eo"; break;
2006 // ::= aS # =
2007 case OO_Equal: Out << "aS"; break;
2008 // ::= pL # +=
2009 case OO_PlusEqual: Out << "pL"; break;
2010 // ::= mI # -=
2011 case OO_MinusEqual: Out << "mI"; break;
2012 // ::= mL # *=
2013 case OO_StarEqual: Out << "mL"; break;
2014 // ::= dV # /=
2015 case OO_SlashEqual: Out << "dV"; break;
2016 // ::= rM # %=
2017 case OO_PercentEqual: Out << "rM"; break;
2018 // ::= aN # &=
2019 case OO_AmpEqual: Out << "aN"; break;
2020 // ::= oR # |=
2021 case OO_PipeEqual: Out << "oR"; break;
2022 // ::= eO # ^=
2023 case OO_CaretEqual: Out << "eO"; break;
2024 // ::= ls # <<
2025 case OO_LessLess: Out << "ls"; break;
2026 // ::= rs # >>
2027 case OO_GreaterGreater: Out << "rs"; break;
2028 // ::= lS # <<=
2029 case OO_LessLessEqual: Out << "lS"; break;
2030 // ::= rS # >>=
2031 case OO_GreaterGreaterEqual: Out << "rS"; break;
2032 // ::= eq # ==
2033 case OO_EqualEqual: Out << "eq"; break;
2034 // ::= ne # !=
2035 case OO_ExclaimEqual: Out << "ne"; break;
2036 // ::= lt # <
2037 case OO_Less: Out << "lt"; break;
2038 // ::= gt # >
2039 case OO_Greater: Out << "gt"; break;
2040 // ::= le # <=
2041 case OO_LessEqual: Out << "le"; break;
2042 // ::= ge # >=
2043 case OO_GreaterEqual: Out << "ge"; break;
2044 // ::= nt # !
2045 case OO_Exclaim: Out << "nt"; break;
2046 // ::= aa # &&
2047 case OO_AmpAmp: Out << "aa"; break;
2048 // ::= oo # ||
2049 case OO_PipePipe: Out << "oo"; break;
2050 // ::= pp # ++
2051 case OO_PlusPlus: Out << "pp"; break;
2052 // ::= mm # --
2053 case OO_MinusMinus: Out << "mm"; break;
2054 // ::= cm # ,
2055 case OO_Comma: Out << "cm"; break;
2056 // ::= pm # ->*
2057 case OO_ArrowStar: Out << "pm"; break;
2058 // ::= pt # ->
2059 case OO_Arrow: Out << "pt"; break;
2060 // ::= cl # ()
2061 case OO_Call: Out << "cl"; break;
2062 // ::= ix # []
2063 case OO_Subscript: Out << "ix"; break;
2064
2065 // ::= qu # ?
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;
2072
2073 case OO_None:
2074 case NUM_OVERLOADED_OPERATORS:
2075 llvm_unreachable("Not an overloaded operator");
2076 }
2077 }
2078
mangleQualifiers(Qualifiers Quals)2079 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
2080 // Vendor qualifiers come first.
2081
2082 // Address space qualifiers start with an ordinary letter.
2083 if (Quals.hasAddressSpace()) {
2084 // Address space extension:
2085 //
2086 // <type> ::= U <target-addrspace>
2087 // <type> ::= U <OpenCL-addrspace>
2088 // <type> ::= U <CUDA-addrspace>
2089
2090 SmallString<64> ASString;
2091 unsigned AS = Quals.getAddressSpace();
2092
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);
2097 } else {
2098 switch (AS) {
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;
2108 }
2109 }
2110 mangleVendorQualifier(ASString);
2111 }
2112
2113 // The ARC ownership qualifiers start with underscores.
2114 switch (Quals.getObjCLifetime()) {
2115 // Objective-C ARC Extension:
2116 //
2117 // <type> ::= U "__strong"
2118 // <type> ::= U "__weak"
2119 // <type> ::= U "__autoreleasing"
2120 case Qualifiers::OCL_None:
2121 break;
2122
2123 case Qualifiers::OCL_Weak:
2124 mangleVendorQualifier("__weak");
2125 break;
2126
2127 case Qualifiers::OCL_Strong:
2128 mangleVendorQualifier("__strong");
2129 break;
2130
2131 case Qualifiers::OCL_Autoreleasing:
2132 mangleVendorQualifier("__autoreleasing");
2133 break;
2134
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.
2140 //
2141 // It's safe to do this because unqualified 'id' won't show up
2142 // in any type signatures that need to be mangled.
2143 break;
2144 }
2145
2146 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2147 if (Quals.hasRestrict())
2148 Out << 'r';
2149 if (Quals.hasVolatile())
2150 Out << 'V';
2151 if (Quals.hasConst())
2152 Out << 'K';
2153 }
2154
mangleVendorQualifier(StringRef name)2155 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2156 Out << 'U' << name.size() << name;
2157 }
2158
mangleRefQualifier(RefQualifierKind RefQualifier)2159 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2160 // <ref-qualifier> ::= R # lvalue reference
2161 // ::= O # rvalue-reference
2162 switch (RefQualifier) {
2163 case RQ_None:
2164 break;
2165
2166 case RQ_LValue:
2167 Out << 'R';
2168 break;
2169
2170 case RQ_RValue:
2171 Out << 'O';
2172 break;
2173 }
2174 }
2175
mangleObjCMethodName(const ObjCMethodDecl * MD)2176 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2177 Context.mangleObjCMethodName(MD, Out);
2178 }
2179
isTypeSubstitutable(Qualifiers Quals,const Type * Ty)2180 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2181 if (Quals)
2182 return true;
2183 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2184 return true;
2185 if (Ty->isOpenCLSpecificType())
2186 return true;
2187 if (Ty->isBuiltinType())
2188 return false;
2189
2190 return true;
2191 }
2192
mangleType(QualType T)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.
2197 //
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();
2212 else {
2213 // Desugar any types that are purely sugar.
2214 do {
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())
2220 break;
2221
2222 QualType Desugared
2223 = T.getSingleStepDesugaredType(Context.getASTContext());
2224 if (Desugared == T)
2225 break;
2226
2227 T = Desugared;
2228 } while (true);
2229 }
2230 SplitQualType split = T.split();
2231 Qualifiers quals = split.Quals;
2232 const Type *ty = split.Ty;
2233
2234 bool isSubstitutable = isTypeSubstitutable(quals, ty);
2235 if (isSubstitutable && mangleSubstitution(T))
2236 return;
2237
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();
2243
2244 // Note that we don't update T: we want to add the
2245 // substitution at the original type.
2246 }
2247
2248 if (quals) {
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));
2253 } else {
2254 switch (ty->getTypeClass()) {
2255 #define ABSTRACT_TYPE(CLASS, PARENT)
2256 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2257 case Type::CLASS: \
2258 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2259 return;
2260 #define TYPE(CLASS, PARENT) \
2261 case Type::CLASS: \
2262 mangleType(static_cast<const CLASS##Type*>(ty)); \
2263 break;
2264 #include "clang/AST/TypeNodes.def"
2265 }
2266 }
2267
2268 // Add the substitution.
2269 if (isSubstitutable)
2270 addSubstitution(T);
2271 }
2272
mangleNameOrStandardSubstitution(const NamedDecl * ND)2273 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2274 if (!mangleStandardSubstitution(ND))
2275 mangleName(ND);
2276 }
2277
mangleType(const BuiltinType * T)2278 void CXXNameMangler::mangleType(const BuiltinType *T) {
2279 // <type> ::= <builtin-type>
2280 // <builtin-type> ::= v # void
2281 // ::= w # wchar_t
2282 // ::= b # bool
2283 // ::= c # char
2284 // ::= a # signed char
2285 // ::= h # unsigned char
2286 // ::= s # short
2287 // ::= t # unsigned short
2288 // ::= i # int
2289 // ::= j # unsigned int
2290 // ::= l # long
2291 // ::= m # unsigned long
2292 // ::= x # long long, __int64
2293 // ::= y # unsigned long long, __int64
2294 // ::= n # __int128
2295 // ::= o # unsigned __int128
2296 // ::= f # float
2297 // ::= d # double
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:
2311 Out << 'v';
2312 break;
2313 case BuiltinType::Bool:
2314 Out << 'b';
2315 break;
2316 case BuiltinType::Char_U:
2317 case BuiltinType::Char_S:
2318 Out << 'c';
2319 break;
2320 case BuiltinType::UChar:
2321 Out << 'h';
2322 break;
2323 case BuiltinType::UShort:
2324 Out << 't';
2325 break;
2326 case BuiltinType::UInt:
2327 Out << 'j';
2328 break;
2329 case BuiltinType::ULong:
2330 Out << 'm';
2331 break;
2332 case BuiltinType::ULongLong:
2333 Out << 'y';
2334 break;
2335 case BuiltinType::UInt128:
2336 Out << 'o';
2337 break;
2338 case BuiltinType::SChar:
2339 Out << 'a';
2340 break;
2341 case BuiltinType::WChar_S:
2342 case BuiltinType::WChar_U:
2343 Out << 'w';
2344 break;
2345 case BuiltinType::Char16:
2346 Out << "Ds";
2347 break;
2348 case BuiltinType::Char32:
2349 Out << "Di";
2350 break;
2351 case BuiltinType::Short:
2352 Out << 's';
2353 break;
2354 case BuiltinType::Int:
2355 Out << 'i';
2356 break;
2357 case BuiltinType::Long:
2358 Out << 'l';
2359 break;
2360 case BuiltinType::LongLong:
2361 Out << 'x';
2362 break;
2363 case BuiltinType::Int128:
2364 Out << 'n';
2365 break;
2366 case BuiltinType::Half:
2367 Out << "Dh";
2368 break;
2369 case BuiltinType::Float:
2370 Out << 'f';
2371 break;
2372 case BuiltinType::Double:
2373 Out << 'd';
2374 break;
2375 case BuiltinType::LongDouble:
2376 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2377 ? 'g'
2378 : 'e');
2379 break;
2380 case BuiltinType::Float128:
2381 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2382 Out << "U10__float128"; // Match the GCC mangling
2383 else
2384 Out << 'g';
2385 break;
2386 case BuiltinType::NullPtr:
2387 Out << "Dn";
2388 break;
2389
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:
2395 if (!NullOut)
2396 llvm_unreachable("mangling a placeholder type");
2397 break;
2398 case BuiltinType::ObjCId:
2399 Out << "11objc_object";
2400 break;
2401 case BuiltinType::ObjCClass:
2402 Out << "10objc_class";
2403 break;
2404 case BuiltinType::ObjCSel:
2405 Out << "13objc_selector";
2406 break;
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; \
2411 break;
2412 #include "clang/Basic/OpenCLImageTypes.def"
2413 case BuiltinType::OCLSampler:
2414 Out << "11ocl_sampler";
2415 break;
2416 case BuiltinType::OCLEvent:
2417 Out << "9ocl_event";
2418 break;
2419 case BuiltinType::OCLClkEvent:
2420 Out << "12ocl_clkevent";
2421 break;
2422 case BuiltinType::OCLQueue:
2423 Out << "9ocl_queue";
2424 break;
2425 case BuiltinType::OCLNDRange:
2426 Out << "11ocl_ndrange";
2427 break;
2428 case BuiltinType::OCLReserveID:
2429 Out << "13ocl_reserveid";
2430 break;
2431 }
2432 }
2433
getCallingConvQualifierName(CallingConv CC)2434 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2435 switch (CC) {
2436 case CC_C:
2437 return "";
2438
2439 case CC_X86StdCall:
2440 case CC_X86FastCall:
2441 case CC_X86ThisCall:
2442 case CC_X86VectorCall:
2443 case CC_X86Pascal:
2444 case CC_X86_64Win64:
2445 case CC_X86_64SysV:
2446 case CC_AAPCS:
2447 case CC_AAPCS_VFP:
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.
2454 return "";
2455
2456 case CC_Swift:
2457 return "swiftcall";
2458 }
2459 llvm_unreachable("bad calling convention");
2460 }
2461
mangleExtFunctionInfo(const FunctionType * T)2462 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2463 // Fast path.
2464 if (T->getExtInfo() == FunctionType::ExtInfo())
2465 return;
2466
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);
2474
2475 // FIXME: regparm
2476 // FIXME: noreturn
2477 }
2478
2479 void
mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI)2480 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2481 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2482
2483 // Note that these are *not* substitution candidates. Demanglers might
2484 // have trouble with this if the parameter type is fully substituted.
2485
2486 switch (PI.getABI()) {
2487 case ParameterABI::Ordinary:
2488 break;
2489
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()));
2495 break;
2496 }
2497
2498 if (PI.isConsumed())
2499 mangleVendorQualifier("ns_consumed");
2500 }
2501
2502 // <type> ::= <function-type>
2503 // <function-type> ::= [<CV-qualifiers>] F [Y]
2504 // <bare-function-type> [<ref-qualifier>] E
mangleType(const FunctionProtoType * T)2505 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2506 mangleExtFunctionInfo(T);
2507
2508 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2509 // e.g. "const" in "int (A::*)() const".
2510 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2511
2512 Out << 'F';
2513
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);
2517
2518 // Mangle the ref-qualifier, if present.
2519 mangleRefQualifier(T->getRefQualifier());
2520
2521 Out << 'E';
2522 }
2523
mangleType(const FunctionNoProtoType * T)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).
2528 Out << 'F';
2529
2530 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2531
2532 FunctionTypeDepth.enterResultType();
2533 mangleType(T->getReturnType());
2534 FunctionTypeDepth.leaveResultType();
2535
2536 FunctionTypeDepth.pop(saved);
2537 Out << 'E';
2538 }
2539
mangleBareFunctionType(const FunctionProtoType * Proto,bool MangleReturnType,const FunctionDecl * FD)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();
2546
2547 // <bare-function-type> ::= <signature type>+
2548 if (MangleReturnType) {
2549 FunctionTypeDepth.enterResultType();
2550
2551 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2552 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2553 mangleVendorQualifier("ns_returns_retained");
2554
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);
2561 }
2562 mangleType(ReturnTy);
2563
2564 FunctionTypeDepth.leaveResultType();
2565 }
2566
2567 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2568 // <builtin-type> ::= v # void
2569 Out << 'v';
2570
2571 FunctionTypeDepth.pop(saved);
2572 return;
2573 }
2574
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));
2580 }
2581
2582 // Mangle the type.
2583 QualType ParamTy = Proto->getParamType(I);
2584 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2585
2586 if (FD) {
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();
2591 }
2592 }
2593 }
2594
2595 FunctionTypeDepth.pop(saved);
2596
2597 // <builtin-type> ::= z # ellipsis
2598 if (Proto->isVariadic())
2599 Out << 'z';
2600 }
2601
2602 // <type> ::= <class-enum-type>
2603 // <class-enum-type> ::= <name>
mangleType(const UnresolvedUsingType * T)2604 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2605 mangleName(T->getDecl());
2606 }
2607
2608 // <type> ::= <class-enum-type>
2609 // <class-enum-type> ::= <name>
mangleType(const EnumType * T)2610 void CXXNameMangler::mangleType(const EnumType *T) {
2611 mangleType(static_cast<const TagType*>(T));
2612 }
mangleType(const RecordType * T)2613 void CXXNameMangler::mangleType(const RecordType *T) {
2614 mangleType(static_cast<const TagType*>(T));
2615 }
mangleType(const TagType * T)2616 void CXXNameMangler::mangleType(const TagType *T) {
2617 mangleName(T->getDecl());
2618 }
2619
2620 // <type> ::= <array-type>
2621 // <array-type> ::= A <positive dimension number> _ <element type>
2622 // ::= A [<dimension expression>] _ <element type>
mangleType(const ConstantArrayType * T)2623 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2624 Out << 'A' << T->getSize() << '_';
2625 mangleType(T->getElementType());
2626 }
mangleType(const VariableArrayType * T)2627 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2628 Out << 'A';
2629 // decayed vla types (size 0) will just be skipped.
2630 if (T->getSizeExpr())
2631 mangleExpression(T->getSizeExpr());
2632 Out << '_';
2633 mangleType(T->getElementType());
2634 }
mangleType(const DependentSizedArrayType * T)2635 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2636 Out << 'A';
2637 mangleExpression(T->getSizeExpr());
2638 Out << '_';
2639 mangleType(T->getElementType());
2640 }
mangleType(const IncompleteArrayType * T)2641 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2642 Out << "A_";
2643 mangleType(T->getElementType());
2644 }
2645
2646 // <type> ::= <pointer-to-member-type>
2647 // <pointer-to-member-type> ::= M <class type> <member type>
mangleType(const MemberPointerType * T)2648 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2649 Out << 'M';
2650 mangleType(QualType(T->getClass(), 0));
2651 QualType PointeeType = T->getPointeeType();
2652 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2653 mangleType(FPT);
2654
2655 // Itanium C++ ABI 5.1.8:
2656 //
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
2664 // function.
2665
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.
2671 ++SeqID;
2672 } else
2673 mangleType(PointeeType);
2674 }
2675
2676 // <type> ::= <template-param>
mangleType(const TemplateTypeParmType * T)2677 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2678 mangleTemplateParameter(T->getIndex());
2679 }
2680
2681 // <type> ::= <template-param>
mangleType(const SubstTemplateTypeParmPackType * T)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...);
2686 // };
2687 Out << "_SUBSTPACK_";
2688 }
2689
2690 // <type> ::= P <type> # pointer-to
mangleType(const PointerType * T)2691 void CXXNameMangler::mangleType(const PointerType *T) {
2692 Out << 'P';
2693 mangleType(T->getPointeeType());
2694 }
mangleType(const ObjCObjectPointerType * T)2695 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2696 Out << 'P';
2697 mangleType(T->getPointeeType());
2698 }
2699
2700 // <type> ::= R <type> # reference-to
mangleType(const LValueReferenceType * T)2701 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2702 Out << 'R';
2703 mangleType(T->getPointeeType());
2704 }
2705
2706 // <type> ::= O <type> # rvalue reference-to (C++0x)
mangleType(const RValueReferenceType * T)2707 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2708 Out << 'O';
2709 mangleType(T->getPointeeType());
2710 }
2711
2712 // <type> ::= C <type> # complex pair (C 2000)
mangleType(const ComplexType * T)2713 void CXXNameMangler::mangleType(const ComplexType *T) {
2714 Out << 'C';
2715 mangleType(T->getElementType());
2716 }
2717
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.
mangleNeonVectorType(const VectorType * T)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";
2730 break;
2731 case BuiltinType::Short:
2732 case BuiltinType::UShort:
2733 EltName = "poly16_t";
2734 break;
2735 case BuiltinType::ULongLong:
2736 EltName = "poly64_t";
2737 break;
2738 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2739 }
2740 } else {
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;
2753 default:
2754 llvm_unreachable("unexpected Neon vector element type");
2755 }
2756 }
2757 const char *BaseName = nullptr;
2758 unsigned BitSize = (T->getNumElements() *
2759 getASTContext().getTypeSize(EltType));
2760 if (BitSize == 64)
2761 BaseName = "__simd64_";
2762 else {
2763 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2764 BaseName = "__simd128_";
2765 }
2766 Out << strlen(BaseName) + strlen(EltName);
2767 Out << BaseName << EltName;
2768 }
2769
mangleAArch64VectorBase(const BuiltinType * EltType)2770 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2771 switch (EltType->getKind()) {
2772 case BuiltinType::SChar:
2773 return "Int8";
2774 case BuiltinType::Short:
2775 return "Int16";
2776 case BuiltinType::Int:
2777 return "Int32";
2778 case BuiltinType::Long:
2779 case BuiltinType::LongLong:
2780 return "Int64";
2781 case BuiltinType::UChar:
2782 return "Uint8";
2783 case BuiltinType::UShort:
2784 return "Uint16";
2785 case BuiltinType::UInt:
2786 return "Uint32";
2787 case BuiltinType::ULong:
2788 case BuiltinType::ULongLong:
2789 return "Uint64";
2790 case BuiltinType::Half:
2791 return "Float16";
2792 case BuiltinType::Float:
2793 return "Float32";
2794 case BuiltinType::Double:
2795 return "Float64";
2796 default:
2797 llvm_unreachable("Unexpected vector element base type");
2798 }
2799 }
2800
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.
mangleAArch64NeonVectorType(const VectorType * T)2804 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2805 QualType EltType = T->getElementType();
2806 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2807 unsigned BitSize =
2808 (T->getNumElements() * getASTContext().getTypeSize(EltType));
2809 (void)BitSize; // Silence warning.
2810
2811 assert((BitSize == 64 || BitSize == 128) &&
2812 "Neon vector type not 64 or 128 bits");
2813
2814 StringRef EltName;
2815 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2816 switch (cast<BuiltinType>(EltType)->getKind()) {
2817 case BuiltinType::UChar:
2818 EltName = "Poly8";
2819 break;
2820 case BuiltinType::UShort:
2821 EltName = "Poly16";
2822 break;
2823 case BuiltinType::ULong:
2824 case BuiltinType::ULongLong:
2825 EltName = "Poly64";
2826 break;
2827 default:
2828 llvm_unreachable("unexpected Neon polynomial vector element type");
2829 }
2830 } else
2831 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2832
2833 std::string TypeName =
2834 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2835 Out << TypeName.length() << TypeName;
2836 }
2837
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
mangleType(const VectorType * T)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);
2855 else
2856 mangleNeonVectorType(T);
2857 return;
2858 }
2859 Out << "Dv" << T->getNumElements() << '_';
2860 if (T->getVectorKind() == VectorType::AltiVecPixel)
2861 Out << 'p';
2862 else if (T->getVectorKind() == VectorType::AltiVecBool)
2863 Out << 'b';
2864 else
2865 mangleType(T->getElementType());
2866 }
mangleType(const ExtVectorType * T)2867 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2868 mangleType(static_cast<const VectorType*>(T));
2869 }
mangleType(const DependentSizedExtVectorType * T)2870 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2871 Out << "Dv";
2872 mangleExpression(T->getSizeExpr());
2873 Out << '_';
2874 mangleType(T->getElementType());
2875 }
2876
mangleType(const PackExpansionType * T)2877 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2878 // <type> ::= Dp <type> # pack expansion (C++0x)
2879 Out << "Dp";
2880 mangleType(T->getPattern());
2881 }
2882
mangleType(const ObjCInterfaceType * T)2883 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2884 mangleSourceName(T->getDecl()->getIdentifier());
2885 }
2886
mangleType(const ObjCObjectType * T)2887 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2888 // Treat __kindof as a vendor extended type qualifier.
2889 if (T->isKindOfType())
2890 Out << "U8__kindof";
2891
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;
2900 }
2901 Out << 'U' << QualStr.size() << QualStr;
2902 }
2903
2904 mangleType(T->getBaseType());
2905
2906 if (T->isSpecialized()) {
2907 // Mangle type arguments as I <type>+ E
2908 Out << 'I';
2909 for (auto typeArg : T->getTypeArgs())
2910 mangleType(typeArg);
2911 Out << 'E';
2912 }
2913 }
2914
mangleType(const BlockPointerType * T)2915 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2916 Out << "U13block_pointer";
2917 mangleType(T->getPointeeType());
2918 }
2919
mangleType(const InjectedClassNameType * T)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());
2925 }
2926
mangleType(const TemplateSpecializationType * T)2927 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2928 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2929 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
2930 } else {
2931 if (mangleSubstitution(QualType(T, 0)))
2932 return;
2933
2934 mangleTemplatePrefix(T->getTemplateName());
2935
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));
2941 }
2942 }
2943
mangleType(const DependentNameType * T)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
2948 // # 'typename'
2949 // ::= Ts <name> # dependent elaborated type specifier using
2950 // # 'struct' or 'class'
2951 // ::= Tu <name> # dependent elaborated type specifier using
2952 // # 'union'
2953 // ::= Te <name> # dependent elaborated type specifier using
2954 // # 'enum'
2955 switch (T->getKeyword()) {
2956 case ETK_Typename:
2957 break;
2958 case ETK_Struct:
2959 case ETK_Class:
2960 case ETK_Interface:
2961 Out << "Ts";
2962 break;
2963 case ETK_Union:
2964 Out << "Tu";
2965 break;
2966 case ETK_Enum:
2967 Out << "Te";
2968 break;
2969 default:
2970 llvm_unreachable("unexpected keyword for dependent type name");
2971 }
2972 // Typename types are always nested
2973 Out << 'N';
2974 manglePrefix(T->getQualifier());
2975 mangleSourceName(T->getIdentifier());
2976 Out << 'E';
2977 }
2978
mangleType(const DependentTemplateSpecializationType * T)2979 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2980 // Dependently-scoped template types are nested if they have a prefix.
2981 Out << 'N';
2982
2983 // TODO: avoid making this TemplateName.
2984 TemplateName Prefix =
2985 getASTContext().getDependentTemplateName(T->getQualifier(),
2986 T->getIdentifier());
2987 mangleTemplatePrefix(Prefix);
2988
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());
2993 Out << 'E';
2994 }
2995
mangleType(const TypeOfType * T)2996 void CXXNameMangler::mangleType(const TypeOfType *T) {
2997 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2998 // "extension with parameters" mangling.
2999 Out << "u6typeof";
3000 }
3001
mangleType(const TypeOfExprType * T)3002 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3003 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3004 // "extension with parameters" mangling.
3005 Out << "u6typeof";
3006 }
3007
mangleType(const DecltypeType * T)3008 void CXXNameMangler::mangleType(const DecltypeType *T) {
3009 Expr *E = T->getUnderlyingExpr();
3010
3011 // type ::= Dt <expression> E # decltype of an id-expression
3012 // # or class member access
3013 // ::= DT <expression> E # decltype of an expression
3014
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))
3025 Out << "Dt";
3026 else
3027 Out << "DT";
3028 mangleExpression(E);
3029 Out << 'E';
3030 }
3031
mangleType(const UnaryTransformType * T)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()) {
3036 Out << 'U';
3037
3038 switch (T->getUTTKind()) {
3039 case UnaryTransformType::EnumUnderlyingType:
3040 Out << "3eut";
3041 break;
3042 }
3043 }
3044
3045 mangleType(T->getBaseType());
3046 }
3047
mangleType(const AutoType * T)3048 void CXXNameMangler::mangleType(const AutoType *T) {
3049 QualType D = T->getDeducedType();
3050 // <builtin-type> ::= Da # dependent auto
3051 if (D.isNull()) {
3052 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3053 "shouldn't need to mangle __auto_type!");
3054 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3055 } else
3056 mangleType(D);
3057 }
3058
mangleType(const AtomicType * T)3059 void CXXNameMangler::mangleType(const AtomicType *T) {
3060 // <type> ::= U <source-name> <type> # vendor extended type qualifier
3061 // (Until there's a standardized mangling...)
3062 Out << "U7_Atomic";
3063 mangleType(T->getValueType());
3064 }
3065
mangleType(const PipeType * T)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
3070 Out << "8ocl_pipe";
3071 }
3072
mangleIntegerLiteral(QualType T,const llvm::APSInt & Value)3073 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3074 const llvm::APSInt &Value) {
3075 // <expr-primary> ::= L <type> <value number> E # integer literal
3076 Out << 'L';
3077
3078 mangleType(T);
3079 if (T->isBooleanType()) {
3080 // Boolean values are encoded as 0/1.
3081 Out << (Value.getBoolValue() ? '1' : '0');
3082 } else {
3083 mangleNumber(Value);
3084 }
3085 Out << 'E';
3086
3087 }
3088
mangleMemberExprBase(const Expr * Base,bool IsArrow)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())
3093 break;
3094 const auto *ME = dyn_cast<MemberExpr>(Base);
3095 if (!ME)
3096 break;
3097 Base = ME->getBase();
3098 IsArrow = ME->isArrow();
3099 }
3100
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.
3105 Out << "dtdefpT";
3106 } else {
3107 Out << (IsArrow ? "pt" : "dt");
3108 mangleExpression(Base);
3109 }
3110 }
3111
3112 /// Mangles a member expression.
mangleMemberExpr(const Expr * base,bool isArrow,NestedNameSpecifier * qualifier,NamedDecl * firstQualifierLookup,DeclarationName member,unsigned arity)3113 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3114 bool isArrow,
3115 NestedNameSpecifier *qualifier,
3116 NamedDecl *firstQualifierLookup,
3117 DeclarationName member,
3118 unsigned arity) {
3119 // <expression> ::= dt <expression> <unresolved-name>
3120 // ::= pt <expression> <unresolved-name>
3121 if (base)
3122 mangleMemberExprBase(base, isArrow);
3123 mangleUnresolvedName(qualifier, member, arity);
3124 }
3125
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
3128 /// otherwise.
isParenthesizedADLCallee(const CallExpr * call)3129 static bool isParenthesizedADLCallee(const CallExpr *call) {
3130 const Expr *callee = call->getCallee();
3131 const Expr *fn = callee->IgnoreParens();
3132
3133 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3134 // too, but for those to appear in the callee, it would have to be
3135 // parenthesized.
3136 if (callee == fn) return false;
3137
3138 // Must be an unresolved lookup.
3139 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3140 if (!lookup) return false;
3141
3142 assert(!lookup->requiresADL());
3143
3144 // Must be an unqualified lookup.
3145 if (lookup->getQualifier()) return false;
3146
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())
3151 return false;
3152
3153 // Otherwise, ADL would have been triggered.
3154 return true;
3155 }
3156
mangleCastExpression(const Expr * E,StringRef CastEncoding)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());
3162 }
3163
mangleInitListElements(const InitListExpr * InitList)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));
3169 }
3170
mangleExpression(const Expr * E,unsigned Arity)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;
3196
3197 recurse:
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"
3205 // fallthrough
3206
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");
3221
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::OffsetOfExprClass:
3243 case Expr::PredefinedExprClass:
3244 case Expr::ShuffleVectorExprClass:
3245 case Expr::ConvertVectorExprClass:
3246 case Expr::StmtExprClass:
3247 case Expr::TypeTraitExprClass:
3248 case Expr::ArrayTypeTraitExprClass:
3249 case Expr::ExpressionTraitExprClass:
3250 case Expr::VAArgExprClass:
3251 case Expr::CUDAKernelCallExprClass:
3252 case Expr::AsTypeExprClass:
3253 case Expr::PseudoObjectExprClass:
3254 case Expr::AtomicExprClass:
3255 {
3256 if (!NullOut) {
3257 // As bad as this diagnostic is, it's better than crashing.
3258 DiagnosticsEngine &Diags = Context.getDiags();
3259 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3260 "cannot yet mangle expression type %0");
3261 Diags.Report(E->getExprLoc(), DiagID)
3262 << E->getStmtClassName() << E->getSourceRange();
3263 }
3264 break;
3265 }
3266
3267 case Expr::CXXUuidofExprClass: {
3268 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3269 if (UE->isTypeOperand()) {
3270 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3271 Out << "u8__uuidoft";
3272 mangleType(UuidT);
3273 } else {
3274 Expr *UuidExp = UE->getExprOperand();
3275 Out << "u8__uuidofz";
3276 mangleExpression(UuidExp, Arity);
3277 }
3278 break;
3279 }
3280
3281 // Even gcc-4.5 doesn't mangle this.
3282 case Expr::BinaryConditionalOperatorClass: {
3283 DiagnosticsEngine &Diags = Context.getDiags();
3284 unsigned DiagID =
3285 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3286 "?: operator with omitted middle operand cannot be mangled");
3287 Diags.Report(E->getExprLoc(), DiagID)
3288 << E->getStmtClassName() << E->getSourceRange();
3289 break;
3290 }
3291
3292 // These are used for internal purposes and cannot be meaningfully mangled.
3293 case Expr::OpaqueValueExprClass:
3294 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3295
3296 case Expr::InitListExprClass: {
3297 Out << "il";
3298 mangleInitListElements(cast<InitListExpr>(E));
3299 Out << "E";
3300 break;
3301 }
3302
3303 case Expr::CXXDefaultArgExprClass:
3304 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3305 break;
3306
3307 case Expr::CXXDefaultInitExprClass:
3308 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3309 break;
3310
3311 case Expr::CXXStdInitializerListExprClass:
3312 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3313 break;
3314
3315 case Expr::SubstNonTypeTemplateParmExprClass:
3316 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3317 Arity);
3318 break;
3319
3320 case Expr::UserDefinedLiteralClass:
3321 // We follow g++'s approach of mangling a UDL as a call to the literal
3322 // operator.
3323 case Expr::CXXMemberCallExprClass: // fallthrough
3324 case Expr::CallExprClass: {
3325 const CallExpr *CE = cast<CallExpr>(E);
3326
3327 // <expression> ::= cp <simple-id> <expression>* E
3328 // We use this mangling only when the call would use ADL except
3329 // for being parenthesized. Per discussion with David
3330 // Vandervoorde, 2011.04.25.
3331 if (isParenthesizedADLCallee(CE)) {
3332 Out << "cp";
3333 // The callee here is a parenthesized UnresolvedLookupExpr with
3334 // no qualifier and should always get mangled as a <simple-id>
3335 // anyway.
3336
3337 // <expression> ::= cl <expression>* E
3338 } else {
3339 Out << "cl";
3340 }
3341
3342 unsigned CallArity = CE->getNumArgs();
3343 for (const Expr *Arg : CE->arguments())
3344 if (isa<PackExpansionExpr>(Arg))
3345 CallArity = UnknownArity;
3346
3347 mangleExpression(CE->getCallee(), CallArity);
3348 for (const Expr *Arg : CE->arguments())
3349 mangleExpression(Arg);
3350 Out << 'E';
3351 break;
3352 }
3353
3354 case Expr::CXXNewExprClass: {
3355 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3356 if (New->isGlobalNew()) Out << "gs";
3357 Out << (New->isArray() ? "na" : "nw");
3358 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3359 E = New->placement_arg_end(); I != E; ++I)
3360 mangleExpression(*I);
3361 Out << '_';
3362 mangleType(New->getAllocatedType());
3363 if (New->hasInitializer()) {
3364 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3365 Out << "il";
3366 else
3367 Out << "pi";
3368 const Expr *Init = New->getInitializer();
3369 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3370 // Directly inline the initializers.
3371 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3372 E = CCE->arg_end();
3373 I != E; ++I)
3374 mangleExpression(*I);
3375 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3376 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3377 mangleExpression(PLE->getExpr(i));
3378 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3379 isa<InitListExpr>(Init)) {
3380 // Only take InitListExprs apart for list-initialization.
3381 mangleInitListElements(cast<InitListExpr>(Init));
3382 } else
3383 mangleExpression(Init);
3384 }
3385 Out << 'E';
3386 break;
3387 }
3388
3389 case Expr::CXXPseudoDestructorExprClass: {
3390 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3391 if (const Expr *Base = PDE->getBase())
3392 mangleMemberExprBase(Base, PDE->isArrow());
3393 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3394 QualType ScopeType;
3395 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3396 if (Qualifier) {
3397 mangleUnresolvedPrefix(Qualifier,
3398 /*Recursive=*/true);
3399 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3400 Out << 'E';
3401 } else {
3402 Out << "sr";
3403 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3404 Out << 'E';
3405 }
3406 } else if (Qualifier) {
3407 mangleUnresolvedPrefix(Qualifier);
3408 }
3409 // <base-unresolved-name> ::= dn <destructor-name>
3410 Out << "dn";
3411 QualType DestroyedType = PDE->getDestroyedType();
3412 mangleUnresolvedTypeOrSimpleId(DestroyedType);
3413 break;
3414 }
3415
3416 case Expr::MemberExprClass: {
3417 const MemberExpr *ME = cast<MemberExpr>(E);
3418 mangleMemberExpr(ME->getBase(), ME->isArrow(),
3419 ME->getQualifier(), nullptr,
3420 ME->getMemberDecl()->getDeclName(), Arity);
3421 break;
3422 }
3423
3424 case Expr::UnresolvedMemberExprClass: {
3425 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3426 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3427 ME->isArrow(), ME->getQualifier(), nullptr,
3428 ME->getMemberName(), Arity);
3429 if (ME->hasExplicitTemplateArgs())
3430 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3431 break;
3432 }
3433
3434 case Expr::CXXDependentScopeMemberExprClass: {
3435 const CXXDependentScopeMemberExpr *ME
3436 = cast<CXXDependentScopeMemberExpr>(E);
3437 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3438 ME->isArrow(), ME->getQualifier(),
3439 ME->getFirstQualifierFoundInScope(),
3440 ME->getMember(), Arity);
3441 if (ME->hasExplicitTemplateArgs())
3442 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3443 break;
3444 }
3445
3446 case Expr::UnresolvedLookupExprClass: {
3447 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3448 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3449
3450 // All the <unresolved-name> productions end in a
3451 // base-unresolved-name, where <template-args> are just tacked
3452 // onto the end.
3453 if (ULE->hasExplicitTemplateArgs())
3454 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
3455 break;
3456 }
3457
3458 case Expr::CXXUnresolvedConstructExprClass: {
3459 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3460 unsigned N = CE->arg_size();
3461
3462 Out << "cv";
3463 mangleType(CE->getType());
3464 if (N != 1) Out << '_';
3465 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3466 if (N != 1) Out << 'E';
3467 break;
3468 }
3469
3470 case Expr::CXXConstructExprClass: {
3471 const auto *CE = cast<CXXConstructExpr>(E);
3472 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3473 assert(
3474 CE->getNumArgs() >= 1 &&
3475 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3476 "implicit CXXConstructExpr must have one argument");
3477 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3478 }
3479 Out << "il";
3480 for (auto *E : CE->arguments())
3481 mangleExpression(E);
3482 Out << "E";
3483 break;
3484 }
3485
3486 case Expr::CXXTemporaryObjectExprClass: {
3487 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3488 unsigned N = CE->getNumArgs();
3489 bool List = CE->isListInitialization();
3490
3491 if (List)
3492 Out << "tl";
3493 else
3494 Out << "cv";
3495 mangleType(CE->getType());
3496 if (!List && N != 1)
3497 Out << '_';
3498 if (CE->isStdInitListInitialization()) {
3499 // We implicitly created a std::initializer_list<T> for the first argument
3500 // of a constructor of type U in an expression of the form U{a, b, c}.
3501 // Strip all the semantic gunk off the initializer list.
3502 auto *SILE =
3503 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3504 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3505 mangleInitListElements(ILE);
3506 } else {
3507 for (auto *E : CE->arguments())
3508 mangleExpression(E);
3509 }
3510 if (List || N != 1)
3511 Out << 'E';
3512 break;
3513 }
3514
3515 case Expr::CXXScalarValueInitExprClass:
3516 Out << "cv";
3517 mangleType(E->getType());
3518 Out << "_E";
3519 break;
3520
3521 case Expr::CXXNoexceptExprClass:
3522 Out << "nx";
3523 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3524 break;
3525
3526 case Expr::UnaryExprOrTypeTraitExprClass: {
3527 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3528
3529 if (!SAE->isInstantiationDependent()) {
3530 // Itanium C++ ABI:
3531 // If the operand of a sizeof or alignof operator is not
3532 // instantiation-dependent it is encoded as an integer literal
3533 // reflecting the result of the operator.
3534 //
3535 // If the result of the operator is implicitly converted to a known
3536 // integer type, that type is used for the literal; otherwise, the type
3537 // of std::size_t or std::ptrdiff_t is used.
3538 QualType T = (ImplicitlyConvertedToType.isNull() ||
3539 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3540 : ImplicitlyConvertedToType;
3541 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3542 mangleIntegerLiteral(T, V);
3543 break;
3544 }
3545
3546 switch(SAE->getKind()) {
3547 case UETT_SizeOf:
3548 Out << 's';
3549 break;
3550 case UETT_AlignOf:
3551 Out << 'a';
3552 break;
3553 case UETT_VecStep: {
3554 DiagnosticsEngine &Diags = Context.getDiags();
3555 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3556 "cannot yet mangle vec_step expression");
3557 Diags.Report(DiagID);
3558 return;
3559 }
3560 case UETT_OpenMPRequiredSimdAlign:
3561 DiagnosticsEngine &Diags = Context.getDiags();
3562 unsigned DiagID = Diags.getCustomDiagID(
3563 DiagnosticsEngine::Error,
3564 "cannot yet mangle __builtin_omp_required_simd_align expression");
3565 Diags.Report(DiagID);
3566 return;
3567 }
3568 if (SAE->isArgumentType()) {
3569 Out << 't';
3570 mangleType(SAE->getArgumentType());
3571 } else {
3572 Out << 'z';
3573 mangleExpression(SAE->getArgumentExpr());
3574 }
3575 break;
3576 }
3577
3578 case Expr::CXXThrowExprClass: {
3579 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3580 // <expression> ::= tw <expression> # throw expression
3581 // ::= tr # rethrow
3582 if (TE->getSubExpr()) {
3583 Out << "tw";
3584 mangleExpression(TE->getSubExpr());
3585 } else {
3586 Out << "tr";
3587 }
3588 break;
3589 }
3590
3591 case Expr::CXXTypeidExprClass: {
3592 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3593 // <expression> ::= ti <type> # typeid (type)
3594 // ::= te <expression> # typeid (expression)
3595 if (TIE->isTypeOperand()) {
3596 Out << "ti";
3597 mangleType(TIE->getTypeOperand(Context.getASTContext()));
3598 } else {
3599 Out << "te";
3600 mangleExpression(TIE->getExprOperand());
3601 }
3602 break;
3603 }
3604
3605 case Expr::CXXDeleteExprClass: {
3606 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3607 // <expression> ::= [gs] dl <expression> # [::] delete expr
3608 // ::= [gs] da <expression> # [::] delete [] expr
3609 if (DE->isGlobalDelete()) Out << "gs";
3610 Out << (DE->isArrayForm() ? "da" : "dl");
3611 mangleExpression(DE->getArgument());
3612 break;
3613 }
3614
3615 case Expr::UnaryOperatorClass: {
3616 const UnaryOperator *UO = cast<UnaryOperator>(E);
3617 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3618 /*Arity=*/1);
3619 mangleExpression(UO->getSubExpr());
3620 break;
3621 }
3622
3623 case Expr::ArraySubscriptExprClass: {
3624 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3625
3626 // Array subscript is treated as a syntactically weird form of
3627 // binary operator.
3628 Out << "ix";
3629 mangleExpression(AE->getLHS());
3630 mangleExpression(AE->getRHS());
3631 break;
3632 }
3633
3634 case Expr::CompoundAssignOperatorClass: // fallthrough
3635 case Expr::BinaryOperatorClass: {
3636 const BinaryOperator *BO = cast<BinaryOperator>(E);
3637 if (BO->getOpcode() == BO_PtrMemD)
3638 Out << "ds";
3639 else
3640 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3641 /*Arity=*/2);
3642 mangleExpression(BO->getLHS());
3643 mangleExpression(BO->getRHS());
3644 break;
3645 }
3646
3647 case Expr::ConditionalOperatorClass: {
3648 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3649 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3650 mangleExpression(CO->getCond());
3651 mangleExpression(CO->getLHS(), Arity);
3652 mangleExpression(CO->getRHS(), Arity);
3653 break;
3654 }
3655
3656 case Expr::ImplicitCastExprClass: {
3657 ImplicitlyConvertedToType = E->getType();
3658 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3659 goto recurse;
3660 }
3661
3662 case Expr::ObjCBridgedCastExprClass: {
3663 // Mangle ownership casts as a vendor extended operator __bridge,
3664 // __bridge_transfer, or __bridge_retain.
3665 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3666 Out << "v1U" << Kind.size() << Kind;
3667 }
3668 // Fall through to mangle the cast itself.
3669
3670 case Expr::CStyleCastExprClass:
3671 mangleCastExpression(E, "cv");
3672 break;
3673
3674 case Expr::CXXFunctionalCastExprClass: {
3675 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3676 // FIXME: Add isImplicit to CXXConstructExpr.
3677 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3678 if (CCE->getParenOrBraceRange().isInvalid())
3679 Sub = CCE->getArg(0)->IgnoreImplicit();
3680 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3681 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3682 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3683 Out << "tl";
3684 mangleType(E->getType());
3685 mangleInitListElements(IL);
3686 Out << "E";
3687 } else {
3688 mangleCastExpression(E, "cv");
3689 }
3690 break;
3691 }
3692
3693 case Expr::CXXStaticCastExprClass:
3694 mangleCastExpression(E, "sc");
3695 break;
3696 case Expr::CXXDynamicCastExprClass:
3697 mangleCastExpression(E, "dc");
3698 break;
3699 case Expr::CXXReinterpretCastExprClass:
3700 mangleCastExpression(E, "rc");
3701 break;
3702 case Expr::CXXConstCastExprClass:
3703 mangleCastExpression(E, "cc");
3704 break;
3705
3706 case Expr::CXXOperatorCallExprClass: {
3707 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3708 unsigned NumArgs = CE->getNumArgs();
3709 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3710 // Mangle the arguments.
3711 for (unsigned i = 0; i != NumArgs; ++i)
3712 mangleExpression(CE->getArg(i));
3713 break;
3714 }
3715
3716 case Expr::ParenExprClass:
3717 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3718 break;
3719
3720 case Expr::DeclRefExprClass: {
3721 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3722
3723 switch (D->getKind()) {
3724 default:
3725 // <expr-primary> ::= L <mangled-name> E # external name
3726 Out << 'L';
3727 mangle(D);
3728 Out << 'E';
3729 break;
3730
3731 case Decl::ParmVar:
3732 mangleFunctionParam(cast<ParmVarDecl>(D));
3733 break;
3734
3735 case Decl::EnumConstant: {
3736 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3737 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3738 break;
3739 }
3740
3741 case Decl::NonTypeTemplateParm: {
3742 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3743 mangleTemplateParameter(PD->getIndex());
3744 break;
3745 }
3746
3747 }
3748
3749 break;
3750 }
3751
3752 case Expr::SubstNonTypeTemplateParmPackExprClass:
3753 // FIXME: not clear how to mangle this!
3754 // template <unsigned N...> class A {
3755 // template <class U...> void foo(U (&x)[N]...);
3756 // };
3757 Out << "_SUBSTPACK_";
3758 break;
3759
3760 case Expr::FunctionParmPackExprClass: {
3761 // FIXME: not clear how to mangle this!
3762 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3763 Out << "v110_SUBSTPACK";
3764 mangleFunctionParam(FPPE->getParameterPack());
3765 break;
3766 }
3767
3768 case Expr::DependentScopeDeclRefExprClass: {
3769 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3770 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3771
3772 // All the <unresolved-name> productions end in a
3773 // base-unresolved-name, where <template-args> are just tacked
3774 // onto the end.
3775 if (DRE->hasExplicitTemplateArgs())
3776 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
3777 break;
3778 }
3779
3780 case Expr::CXXBindTemporaryExprClass:
3781 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3782 break;
3783
3784 case Expr::ExprWithCleanupsClass:
3785 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3786 break;
3787
3788 case Expr::FloatingLiteralClass: {
3789 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3790 Out << 'L';
3791 mangleType(FL->getType());
3792 mangleFloat(FL->getValue());
3793 Out << 'E';
3794 break;
3795 }
3796
3797 case Expr::CharacterLiteralClass:
3798 Out << 'L';
3799 mangleType(E->getType());
3800 Out << cast<CharacterLiteral>(E)->getValue();
3801 Out << 'E';
3802 break;
3803
3804 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3805 case Expr::ObjCBoolLiteralExprClass:
3806 Out << "Lb";
3807 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3808 Out << 'E';
3809 break;
3810
3811 case Expr::CXXBoolLiteralExprClass:
3812 Out << "Lb";
3813 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3814 Out << 'E';
3815 break;
3816
3817 case Expr::IntegerLiteralClass: {
3818 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3819 if (E->getType()->isSignedIntegerType())
3820 Value.setIsSigned(true);
3821 mangleIntegerLiteral(E->getType(), Value);
3822 break;
3823 }
3824
3825 case Expr::ImaginaryLiteralClass: {
3826 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3827 // Mangle as if a complex literal.
3828 // Proposal from David Vandevoorde, 2010.06.30.
3829 Out << 'L';
3830 mangleType(E->getType());
3831 if (const FloatingLiteral *Imag =
3832 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3833 // Mangle a floating-point zero of the appropriate type.
3834 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3835 Out << '_';
3836 mangleFloat(Imag->getValue());
3837 } else {
3838 Out << "0_";
3839 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3840 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3841 Value.setIsSigned(true);
3842 mangleNumber(Value);
3843 }
3844 Out << 'E';
3845 break;
3846 }
3847
3848 case Expr::StringLiteralClass: {
3849 // Revised proposal from David Vandervoorde, 2010.07.15.
3850 Out << 'L';
3851 assert(isa<ConstantArrayType>(E->getType()));
3852 mangleType(E->getType());
3853 Out << 'E';
3854 break;
3855 }
3856
3857 case Expr::GNUNullExprClass:
3858 // FIXME: should this really be mangled the same as nullptr?
3859 // fallthrough
3860
3861 case Expr::CXXNullPtrLiteralExprClass: {
3862 Out << "LDnE";
3863 break;
3864 }
3865
3866 case Expr::PackExpansionExprClass:
3867 Out << "sp";
3868 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3869 break;
3870
3871 case Expr::SizeOfPackExprClass: {
3872 auto *SPE = cast<SizeOfPackExpr>(E);
3873 if (SPE->isPartiallySubstituted()) {
3874 Out << "sP";
3875 for (const auto &A : SPE->getPartialArguments())
3876 mangleTemplateArg(A);
3877 Out << "E";
3878 break;
3879 }
3880
3881 Out << "sZ";
3882 const NamedDecl *Pack = SPE->getPack();
3883 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3884 mangleTemplateParameter(TTP->getIndex());
3885 else if (const NonTypeTemplateParmDecl *NTTP
3886 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3887 mangleTemplateParameter(NTTP->getIndex());
3888 else if (const TemplateTemplateParmDecl *TempTP
3889 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3890 mangleTemplateParameter(TempTP->getIndex());
3891 else
3892 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3893 break;
3894 }
3895
3896 case Expr::MaterializeTemporaryExprClass: {
3897 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3898 break;
3899 }
3900
3901 case Expr::CXXFoldExprClass: {
3902 auto *FE = cast<CXXFoldExpr>(E);
3903 if (FE->isLeftFold())
3904 Out << (FE->getInit() ? "fL" : "fl");
3905 else
3906 Out << (FE->getInit() ? "fR" : "fr");
3907
3908 if (FE->getOperator() == BO_PtrMemD)
3909 Out << "ds";
3910 else
3911 mangleOperatorName(
3912 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3913 /*Arity=*/2);
3914
3915 if (FE->getLHS())
3916 mangleExpression(FE->getLHS());
3917 if (FE->getRHS())
3918 mangleExpression(FE->getRHS());
3919 break;
3920 }
3921
3922 case Expr::CXXThisExprClass:
3923 Out << "fpT";
3924 break;
3925
3926 case Expr::CoawaitExprClass:
3927 // FIXME: Propose a non-vendor mangling.
3928 Out << "v18co_await";
3929 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3930 break;
3931
3932 case Expr::CoyieldExprClass:
3933 // FIXME: Propose a non-vendor mangling.
3934 Out << "v18co_yield";
3935 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3936 break;
3937 }
3938 }
3939
3940 /// Mangle an expression which refers to a parameter variable.
3941 ///
3942 /// <expression> ::= <function-param>
3943 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3944 /// <function-param> ::= fp <top-level CV-qualifiers>
3945 /// <parameter-2 non-negative number> _ # L == 0, I > 0
3946 /// <function-param> ::= fL <L-1 non-negative number>
3947 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
3948 /// <function-param> ::= fL <L-1 non-negative number>
3949 /// p <top-level CV-qualifiers>
3950 /// <I-1 non-negative number> _ # L > 0, I > 0
3951 ///
3952 /// L is the nesting depth of the parameter, defined as 1 if the
3953 /// parameter comes from the innermost function prototype scope
3954 /// enclosing the current context, 2 if from the next enclosing
3955 /// function prototype scope, and so on, with one special case: if
3956 /// we've processed the full parameter clause for the innermost
3957 /// function type, then L is one less. This definition conveniently
3958 /// makes it irrelevant whether a function's result type was written
3959 /// trailing or leading, but is otherwise overly complicated; the
3960 /// numbering was first designed without considering references to
3961 /// parameter in locations other than return types, and then the
3962 /// mangling had to be generalized without changing the existing
3963 /// manglings.
3964 ///
3965 /// I is the zero-based index of the parameter within its parameter
3966 /// declaration clause. Note that the original ABI document describes
3967 /// this using 1-based ordinals.
mangleFunctionParam(const ParmVarDecl * parm)3968 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3969 unsigned parmDepth = parm->getFunctionScopeDepth();
3970 unsigned parmIndex = parm->getFunctionScopeIndex();
3971
3972 // Compute 'L'.
3973 // parmDepth does not include the declaring function prototype.
3974 // FunctionTypeDepth does account for that.
3975 assert(parmDepth < FunctionTypeDepth.getDepth());
3976 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3977 if (FunctionTypeDepth.isInResultType())
3978 nestingDepth--;
3979
3980 if (nestingDepth == 0) {
3981 Out << "fp";
3982 } else {
3983 Out << "fL" << (nestingDepth - 1) << 'p';
3984 }
3985
3986 // Top-level qualifiers. We don't have to worry about arrays here,
3987 // because parameters declared as arrays should already have been
3988 // transformed to have pointer type. FIXME: apparently these don't
3989 // get mangled if used as an rvalue of a known non-class type?
3990 assert(!parm->getType()->isArrayType()
3991 && "parameter's type is still an array type?");
3992 mangleQualifiers(parm->getType().getQualifiers());
3993
3994 // Parameter index.
3995 if (parmIndex != 0) {
3996 Out << (parmIndex - 1);
3997 }
3998 Out << '_';
3999 }
4000
mangleCXXCtorType(CXXCtorType T,const CXXRecordDecl * InheritedFrom)4001 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4002 const CXXRecordDecl *InheritedFrom) {
4003 // <ctor-dtor-name> ::= C1 # complete object constructor
4004 // ::= C2 # base object constructor
4005 // ::= CI1 <type> # complete inheriting constructor
4006 // ::= CI2 <type> # base inheriting constructor
4007 //
4008 // In addition, C5 is a comdat name with C1 and C2 in it.
4009 Out << 'C';
4010 if (InheritedFrom)
4011 Out << 'I';
4012 switch (T) {
4013 case Ctor_Complete:
4014 Out << '1';
4015 break;
4016 case Ctor_Base:
4017 Out << '2';
4018 break;
4019 case Ctor_Comdat:
4020 Out << '5';
4021 break;
4022 case Ctor_DefaultClosure:
4023 case Ctor_CopyingClosure:
4024 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4025 }
4026 if (InheritedFrom)
4027 mangleName(InheritedFrom);
4028 }
4029
mangleCXXDtorType(CXXDtorType T)4030 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4031 // <ctor-dtor-name> ::= D0 # deleting destructor
4032 // ::= D1 # complete object destructor
4033 // ::= D2 # base object destructor
4034 //
4035 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4036 switch (T) {
4037 case Dtor_Deleting:
4038 Out << "D0";
4039 break;
4040 case Dtor_Complete:
4041 Out << "D1";
4042 break;
4043 case Dtor_Base:
4044 Out << "D2";
4045 break;
4046 case Dtor_Comdat:
4047 Out << "D5";
4048 break;
4049 }
4050 }
4051
mangleTemplateArgs(const TemplateArgumentLoc * TemplateArgs,unsigned NumTemplateArgs)4052 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4053 unsigned NumTemplateArgs) {
4054 // <template-args> ::= I <template-arg>+ E
4055 Out << 'I';
4056 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4057 mangleTemplateArg(TemplateArgs[i].getArgument());
4058 Out << 'E';
4059 }
4060
mangleTemplateArgs(const TemplateArgumentList & AL)4061 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4062 // <template-args> ::= I <template-arg>+ E
4063 Out << 'I';
4064 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4065 mangleTemplateArg(AL[i]);
4066 Out << 'E';
4067 }
4068
mangleTemplateArgs(const TemplateArgument * TemplateArgs,unsigned NumTemplateArgs)4069 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4070 unsigned NumTemplateArgs) {
4071 // <template-args> ::= I <template-arg>+ E
4072 Out << 'I';
4073 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4074 mangleTemplateArg(TemplateArgs[i]);
4075 Out << 'E';
4076 }
4077
mangleTemplateArg(TemplateArgument A)4078 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4079 // <template-arg> ::= <type> # type or template
4080 // ::= X <expression> E # expression
4081 // ::= <expr-primary> # simple expressions
4082 // ::= J <template-arg>* E # argument pack
4083 if (!A.isInstantiationDependent() || A.isDependent())
4084 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4085
4086 switch (A.getKind()) {
4087 case TemplateArgument::Null:
4088 llvm_unreachable("Cannot mangle NULL template argument");
4089
4090 case TemplateArgument::Type:
4091 mangleType(A.getAsType());
4092 break;
4093 case TemplateArgument::Template:
4094 // This is mangled as <type>.
4095 mangleType(A.getAsTemplate());
4096 break;
4097 case TemplateArgument::TemplateExpansion:
4098 // <type> ::= Dp <type> # pack expansion (C++0x)
4099 Out << "Dp";
4100 mangleType(A.getAsTemplateOrTemplatePattern());
4101 break;
4102 case TemplateArgument::Expression: {
4103 // It's possible to end up with a DeclRefExpr here in certain
4104 // dependent cases, in which case we should mangle as a
4105 // declaration.
4106 const Expr *E = A.getAsExpr()->IgnoreParens();
4107 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4108 const ValueDecl *D = DRE->getDecl();
4109 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4110 Out << 'L';
4111 mangle(D);
4112 Out << 'E';
4113 break;
4114 }
4115 }
4116
4117 Out << 'X';
4118 mangleExpression(E);
4119 Out << 'E';
4120 break;
4121 }
4122 case TemplateArgument::Integral:
4123 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4124 break;
4125 case TemplateArgument::Declaration: {
4126 // <expr-primary> ::= L <mangled-name> E # external name
4127 // Clang produces AST's where pointer-to-member-function expressions
4128 // and pointer-to-function expressions are represented as a declaration not
4129 // an expression. We compensate for it here to produce the correct mangling.
4130 ValueDecl *D = A.getAsDecl();
4131 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4132 if (compensateMangling) {
4133 Out << 'X';
4134 mangleOperatorName(OO_Amp, 1);
4135 }
4136
4137 Out << 'L';
4138 // References to external entities use the mangled name; if the name would
4139 // not normally be mangled then mangle it as unqualified.
4140 mangle(D);
4141 Out << 'E';
4142
4143 if (compensateMangling)
4144 Out << 'E';
4145
4146 break;
4147 }
4148 case TemplateArgument::NullPtr: {
4149 // <expr-primary> ::= L <type> 0 E
4150 Out << 'L';
4151 mangleType(A.getNullPtrType());
4152 Out << "0E";
4153 break;
4154 }
4155 case TemplateArgument::Pack: {
4156 // <template-arg> ::= J <template-arg>* E
4157 Out << 'J';
4158 for (const auto &P : A.pack_elements())
4159 mangleTemplateArg(P);
4160 Out << 'E';
4161 }
4162 }
4163 }
4164
mangleTemplateParameter(unsigned Index)4165 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4166 // <template-param> ::= T_ # first template parameter
4167 // ::= T <parameter-2 non-negative number> _
4168 if (Index == 0)
4169 Out << "T_";
4170 else
4171 Out << 'T' << (Index - 1) << '_';
4172 }
4173
mangleSeqID(unsigned SeqID)4174 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4175 if (SeqID == 1)
4176 Out << '0';
4177 else if (SeqID > 1) {
4178 SeqID--;
4179
4180 // <seq-id> is encoded in base-36, using digits and upper case letters.
4181 char Buffer[7]; // log(2**32) / log(36) ~= 7
4182 MutableArrayRef<char> BufferRef(Buffer);
4183 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4184
4185 for (; SeqID != 0; SeqID /= 36) {
4186 unsigned C = SeqID % 36;
4187 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4188 }
4189
4190 Out.write(I.base(), I - BufferRef.rbegin());
4191 }
4192 Out << '_';
4193 }
4194
mangleExistingSubstitution(TemplateName tname)4195 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4196 bool result = mangleSubstitution(tname);
4197 assert(result && "no existing substitution for template name");
4198 (void) result;
4199 }
4200
4201 // <substitution> ::= S <seq-id> _
4202 // ::= S_
mangleSubstitution(const NamedDecl * ND)4203 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4204 // Try one of the standard substitutions first.
4205 if (mangleStandardSubstitution(ND))
4206 return true;
4207
4208 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4209 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4210 }
4211
4212 /// Determine whether the given type has any qualifiers that are relevant for
4213 /// substitutions.
hasMangledSubstitutionQualifiers(QualType T)4214 static bool hasMangledSubstitutionQualifiers(QualType T) {
4215 Qualifiers Qs = T.getQualifiers();
4216 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4217 }
4218
mangleSubstitution(QualType T)4219 bool CXXNameMangler::mangleSubstitution(QualType T) {
4220 if (!hasMangledSubstitutionQualifiers(T)) {
4221 if (const RecordType *RT = T->getAs<RecordType>())
4222 return mangleSubstitution(RT->getDecl());
4223 }
4224
4225 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4226
4227 return mangleSubstitution(TypePtr);
4228 }
4229
mangleSubstitution(TemplateName Template)4230 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4231 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4232 return mangleSubstitution(TD);
4233
4234 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4235 return mangleSubstitution(
4236 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4237 }
4238
mangleSubstitution(uintptr_t Ptr)4239 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4240 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4241 if (I == Substitutions.end())
4242 return false;
4243
4244 unsigned SeqID = I->second;
4245 Out << 'S';
4246 mangleSeqID(SeqID);
4247
4248 return true;
4249 }
4250
isCharType(QualType T)4251 static bool isCharType(QualType T) {
4252 if (T.isNull())
4253 return false;
4254
4255 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4256 T->isSpecificBuiltinType(BuiltinType::Char_U);
4257 }
4258
4259 /// Returns whether a given type is a template specialization of a given name
4260 /// with a single argument of type char.
isCharSpecialization(QualType T,const char * Name)4261 static bool isCharSpecialization(QualType T, const char *Name) {
4262 if (T.isNull())
4263 return false;
4264
4265 const RecordType *RT = T->getAs<RecordType>();
4266 if (!RT)
4267 return false;
4268
4269 const ClassTemplateSpecializationDecl *SD =
4270 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4271 if (!SD)
4272 return false;
4273
4274 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4275 return false;
4276
4277 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4278 if (TemplateArgs.size() != 1)
4279 return false;
4280
4281 if (!isCharType(TemplateArgs[0].getAsType()))
4282 return false;
4283
4284 return SD->getIdentifier()->getName() == Name;
4285 }
4286
4287 template <std::size_t StrLen>
isStreamCharSpecialization(const ClassTemplateSpecializationDecl * SD,const char (& Str)[StrLen])4288 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4289 const char (&Str)[StrLen]) {
4290 if (!SD->getIdentifier()->isStr(Str))
4291 return false;
4292
4293 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4294 if (TemplateArgs.size() != 2)
4295 return false;
4296
4297 if (!isCharType(TemplateArgs[0].getAsType()))
4298 return false;
4299
4300 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4301 return false;
4302
4303 return true;
4304 }
4305
mangleStandardSubstitution(const NamedDecl * ND)4306 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4307 // <substitution> ::= St # ::std::
4308 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4309 if (isStd(NS)) {
4310 Out << "St";
4311 return true;
4312 }
4313 }
4314
4315 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4316 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4317 return false;
4318
4319 // <substitution> ::= Sa # ::std::allocator
4320 if (TD->getIdentifier()->isStr("allocator")) {
4321 Out << "Sa";
4322 return true;
4323 }
4324
4325 // <<substitution> ::= Sb # ::std::basic_string
4326 if (TD->getIdentifier()->isStr("basic_string")) {
4327 Out << "Sb";
4328 return true;
4329 }
4330 }
4331
4332 if (const ClassTemplateSpecializationDecl *SD =
4333 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4334 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4335 return false;
4336
4337 // <substitution> ::= Ss # ::std::basic_string<char,
4338 // ::std::char_traits<char>,
4339 // ::std::allocator<char> >
4340 if (SD->getIdentifier()->isStr("basic_string")) {
4341 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4342
4343 if (TemplateArgs.size() != 3)
4344 return false;
4345
4346 if (!isCharType(TemplateArgs[0].getAsType()))
4347 return false;
4348
4349 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4350 return false;
4351
4352 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4353 return false;
4354
4355 Out << "Ss";
4356 return true;
4357 }
4358
4359 // <substitution> ::= Si # ::std::basic_istream<char,
4360 // ::std::char_traits<char> >
4361 if (isStreamCharSpecialization(SD, "basic_istream")) {
4362 Out << "Si";
4363 return true;
4364 }
4365
4366 // <substitution> ::= So # ::std::basic_ostream<char,
4367 // ::std::char_traits<char> >
4368 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4369 Out << "So";
4370 return true;
4371 }
4372
4373 // <substitution> ::= Sd # ::std::basic_iostream<char,
4374 // ::std::char_traits<char> >
4375 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4376 Out << "Sd";
4377 return true;
4378 }
4379 }
4380 return false;
4381 }
4382
addSubstitution(QualType T)4383 void CXXNameMangler::addSubstitution(QualType T) {
4384 if (!hasMangledSubstitutionQualifiers(T)) {
4385 if (const RecordType *RT = T->getAs<RecordType>()) {
4386 addSubstitution(RT->getDecl());
4387 return;
4388 }
4389 }
4390
4391 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4392 addSubstitution(TypePtr);
4393 }
4394
addSubstitution(TemplateName Template)4395 void CXXNameMangler::addSubstitution(TemplateName Template) {
4396 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4397 return addSubstitution(TD);
4398
4399 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4400 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4401 }
4402
addSubstitution(uintptr_t Ptr)4403 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4404 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4405 Substitutions[Ptr] = SeqID++;
4406 }
4407
4408 CXXNameMangler::AbiTagList
makeFunctionReturnTypeTags(const FunctionDecl * FD)4409 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4410 // When derived abi tags are disabled there is no need to make any list.
4411 if (DisableDerivedAbiTags)
4412 return AbiTagList();
4413
4414 llvm::raw_null_ostream NullOutStream;
4415 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4416 TrackReturnTypeTags.disableDerivedAbiTags();
4417
4418 const FunctionProtoType *Proto =
4419 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4420 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4421 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4422 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4423
4424 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4425 }
4426
4427 CXXNameMangler::AbiTagList
makeVariableTypeTags(const VarDecl * VD)4428 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4429 // When derived abi tags are disabled there is no need to make any list.
4430 if (DisableDerivedAbiTags)
4431 return AbiTagList();
4432
4433 llvm::raw_null_ostream NullOutStream;
4434 CXXNameMangler TrackVariableType(*this, NullOutStream);
4435 TrackVariableType.disableDerivedAbiTags();
4436
4437 TrackVariableType.mangleType(VD->getType());
4438
4439 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4440 }
4441
shouldHaveAbiTags(ItaniumMangleContextImpl & C,const VarDecl * VD)4442 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4443 const VarDecl *VD) {
4444 llvm::raw_null_ostream NullOutStream;
4445 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4446 TrackAbiTags.mangle(VD);
4447 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4448 }
4449
4450 //
4451
4452 /// Mangles the name of the declaration D and emits that name to the given
4453 /// output stream.
4454 ///
4455 /// If the declaration D requires a mangled name, this routine will emit that
4456 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4457 /// and this routine will return false. In this case, the caller should just
4458 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4459 /// name.
mangleCXXName(const NamedDecl * D,raw_ostream & Out)4460 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4461 raw_ostream &Out) {
4462 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4463 "Invalid mangleName() call, argument is not a variable or function!");
4464 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4465 "Invalid mangleName() call on 'structor decl!");
4466
4467 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4468 getASTContext().getSourceManager(),
4469 "Mangling declaration");
4470
4471 CXXNameMangler Mangler(*this, Out, D);
4472 Mangler.mangle(D);
4473 }
4474
mangleCXXCtor(const CXXConstructorDecl * D,CXXCtorType Type,raw_ostream & Out)4475 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4476 CXXCtorType Type,
4477 raw_ostream &Out) {
4478 CXXNameMangler Mangler(*this, Out, D, Type);
4479 Mangler.mangle(D);
4480 }
4481
mangleCXXDtor(const CXXDestructorDecl * D,CXXDtorType Type,raw_ostream & Out)4482 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4483 CXXDtorType Type,
4484 raw_ostream &Out) {
4485 CXXNameMangler Mangler(*this, Out, D, Type);
4486 Mangler.mangle(D);
4487 }
4488
mangleCXXCtorComdat(const CXXConstructorDecl * D,raw_ostream & Out)4489 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4490 raw_ostream &Out) {
4491 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4492 Mangler.mangle(D);
4493 }
4494
mangleCXXDtorComdat(const CXXDestructorDecl * D,raw_ostream & Out)4495 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4496 raw_ostream &Out) {
4497 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4498 Mangler.mangle(D);
4499 }
4500
mangleThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk,raw_ostream & Out)4501 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4502 const ThunkInfo &Thunk,
4503 raw_ostream &Out) {
4504 // <special-name> ::= T <call-offset> <base encoding>
4505 // # base is the nominal target function of thunk
4506 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4507 // # base is the nominal target function of thunk
4508 // # first call-offset is 'this' adjustment
4509 // # second call-offset is result adjustment
4510
4511 assert(!isa<CXXDestructorDecl>(MD) &&
4512 "Use mangleCXXDtor for destructor decls!");
4513 CXXNameMangler Mangler(*this, Out);
4514 Mangler.getStream() << "_ZT";
4515 if (!Thunk.Return.isEmpty())
4516 Mangler.getStream() << 'c';
4517
4518 // Mangle the 'this' pointer adjustment.
4519 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4520 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4521
4522 // Mangle the return pointer adjustment if there is one.
4523 if (!Thunk.Return.isEmpty())
4524 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4525 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4526
4527 Mangler.mangleFunctionEncoding(MD);
4528 }
4529
mangleCXXDtorThunk(const CXXDestructorDecl * DD,CXXDtorType Type,const ThisAdjustment & ThisAdjustment,raw_ostream & Out)4530 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4531 const CXXDestructorDecl *DD, CXXDtorType Type,
4532 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4533 // <special-name> ::= T <call-offset> <base encoding>
4534 // # base is the nominal target function of thunk
4535 CXXNameMangler Mangler(*this, Out, DD, Type);
4536 Mangler.getStream() << "_ZT";
4537
4538 // Mangle the 'this' pointer adjustment.
4539 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4540 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4541
4542 Mangler.mangleFunctionEncoding(DD);
4543 }
4544
4545 /// Returns the mangled name for a guard variable for the passed in VarDecl.
mangleStaticGuardVariable(const VarDecl * D,raw_ostream & Out)4546 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4547 raw_ostream &Out) {
4548 // <special-name> ::= GV <object name> # Guard variable for one-time
4549 // # initialization
4550 CXXNameMangler Mangler(*this, Out);
4551 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4552 // be a bug that is fixed in trunk.
4553 Mangler.getStream() << "_ZGV";
4554 Mangler.mangleName(D);
4555 }
4556
mangleDynamicInitializer(const VarDecl * MD,raw_ostream & Out)4557 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4558 raw_ostream &Out) {
4559 // These symbols are internal in the Itanium ABI, so the names don't matter.
4560 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4561 // avoid duplicate symbols.
4562 Out << "__cxx_global_var_init";
4563 }
4564
mangleDynamicAtExitDestructor(const VarDecl * D,raw_ostream & Out)4565 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4566 raw_ostream &Out) {
4567 // Prefix the mangling of D with __dtor_.
4568 CXXNameMangler Mangler(*this, Out);
4569 Mangler.getStream() << "__dtor_";
4570 if (shouldMangleDeclName(D))
4571 Mangler.mangle(D);
4572 else
4573 Mangler.getStream() << D->getName();
4574 }
4575
mangleSEHFilterExpression(const NamedDecl * EnclosingDecl,raw_ostream & Out)4576 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4577 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4578 CXXNameMangler Mangler(*this, Out);
4579 Mangler.getStream() << "__filt_";
4580 if (shouldMangleDeclName(EnclosingDecl))
4581 Mangler.mangle(EnclosingDecl);
4582 else
4583 Mangler.getStream() << EnclosingDecl->getName();
4584 }
4585
mangleSEHFinallyBlock(const NamedDecl * EnclosingDecl,raw_ostream & Out)4586 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4587 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4588 CXXNameMangler Mangler(*this, Out);
4589 Mangler.getStream() << "__fin_";
4590 if (shouldMangleDeclName(EnclosingDecl))
4591 Mangler.mangle(EnclosingDecl);
4592 else
4593 Mangler.getStream() << EnclosingDecl->getName();
4594 }
4595
mangleItaniumThreadLocalInit(const VarDecl * D,raw_ostream & Out)4596 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4597 raw_ostream &Out) {
4598 // <special-name> ::= TH <object name>
4599 CXXNameMangler Mangler(*this, Out);
4600 Mangler.getStream() << "_ZTH";
4601 Mangler.mangleName(D);
4602 }
4603
4604 void
mangleItaniumThreadLocalWrapper(const VarDecl * D,raw_ostream & Out)4605 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4606 raw_ostream &Out) {
4607 // <special-name> ::= TW <object name>
4608 CXXNameMangler Mangler(*this, Out);
4609 Mangler.getStream() << "_ZTW";
4610 Mangler.mangleName(D);
4611 }
4612
mangleReferenceTemporary(const VarDecl * D,unsigned ManglingNumber,raw_ostream & Out)4613 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4614 unsigned ManglingNumber,
4615 raw_ostream &Out) {
4616 // We match the GCC mangling here.
4617 // <special-name> ::= GR <object name>
4618 CXXNameMangler Mangler(*this, Out);
4619 Mangler.getStream() << "_ZGR";
4620 Mangler.mangleName(D);
4621 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4622 Mangler.mangleSeqID(ManglingNumber - 1);
4623 }
4624
mangleCXXVTable(const CXXRecordDecl * RD,raw_ostream & Out)4625 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4626 raw_ostream &Out) {
4627 // <special-name> ::= TV <type> # virtual table
4628 CXXNameMangler Mangler(*this, Out);
4629 Mangler.getStream() << "_ZTV";
4630 Mangler.mangleNameOrStandardSubstitution(RD);
4631 }
4632
mangleCXXVTT(const CXXRecordDecl * RD,raw_ostream & Out)4633 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4634 raw_ostream &Out) {
4635 // <special-name> ::= TT <type> # VTT structure
4636 CXXNameMangler Mangler(*this, Out);
4637 Mangler.getStream() << "_ZTT";
4638 Mangler.mangleNameOrStandardSubstitution(RD);
4639 }
4640
mangleCXXCtorVTable(const CXXRecordDecl * RD,int64_t Offset,const CXXRecordDecl * Type,raw_ostream & Out)4641 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4642 int64_t Offset,
4643 const CXXRecordDecl *Type,
4644 raw_ostream &Out) {
4645 // <special-name> ::= TC <type> <offset number> _ <base type>
4646 CXXNameMangler Mangler(*this, Out);
4647 Mangler.getStream() << "_ZTC";
4648 Mangler.mangleNameOrStandardSubstitution(RD);
4649 Mangler.getStream() << Offset;
4650 Mangler.getStream() << '_';
4651 Mangler.mangleNameOrStandardSubstitution(Type);
4652 }
4653
mangleCXXRTTI(QualType Ty,raw_ostream & Out)4654 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4655 // <special-name> ::= TI <type> # typeinfo structure
4656 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4657 CXXNameMangler Mangler(*this, Out);
4658 Mangler.getStream() << "_ZTI";
4659 Mangler.mangleType(Ty);
4660 }
4661
mangleCXXRTTIName(QualType Ty,raw_ostream & Out)4662 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4663 raw_ostream &Out) {
4664 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4665 CXXNameMangler Mangler(*this, Out);
4666 Mangler.getStream() << "_ZTS";
4667 Mangler.mangleType(Ty);
4668 }
4669
mangleTypeName(QualType Ty,raw_ostream & Out)4670 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4671 mangleCXXRTTIName(Ty, Out);
4672 }
4673
mangleStringLiteral(const StringLiteral *,raw_ostream &)4674 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4675 llvm_unreachable("Can't mangle string literals");
4676 }
4677
4678 ItaniumMangleContext *
create(ASTContext & Context,DiagnosticsEngine & Diags)4679 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4680 return new ItaniumMangleContextImpl(Context, Diags);
4681 }
4682