blob: 64f9ccd9967387f51ac23b6f5d4f9f108113bd55 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- 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//
David Majnemer98559942013-12-13 00:54:42 +000014// http://mentorembedded.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
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/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000024#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/ABI.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
35#define MANGLE_CHECKER 0
36
37#if MANGLE_CHECKER
38#include <cxxabi.h>
39#endif
40
41using namespace clang;
42
43namespace {
44
Justin Bognere8d762e2015-05-22 06:48:13 +000045/// Retrieve the declaration context that should be used when mangling the given
46/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000047static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
55 if (RD->isLambda())
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
59 }
Eli Friedman0cd23352013-07-10 01:33:19 +000060
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
66 }
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Eli Friedman95f50122013-07-02 17:52:28 +000068 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
71
David Majnemerf8c02e62015-02-18 19:08:11 +000072 if (const auto *VD = dyn_cast<VarDecl>(D))
73 if (VD->isExternC())
74 return VD->getASTContext().getTranslationUnitDecl();
75
76 if (const auto *FD = dyn_cast<FunctionDecl>(D))
77 if (FD->isExternC())
78 return FD->getASTContext().getTranslationUnitDecl();
79
Eli Friedman95f50122013-07-02 17:52:28 +000080 return DC;
Guy Benyei11169dd2012-12-18 14:30:41 +000081}
82
83static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
84 return getEffectiveDeclContext(cast<Decl>(DC));
85}
Eli Friedman95f50122013-07-02 17:52:28 +000086
87static bool isLocalContainerContext(const DeclContext *DC) {
88 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
89}
90
Eli Friedmaneecc09a2013-07-05 20:27:40 +000091static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000092 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000093 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000094 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000095 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000096 D = cast<Decl>(DC);
97 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000098 }
Craig Topper36250ad2014-05-12 05:36:57 +000099 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000100}
101
102static const FunctionDecl *getStructor(const FunctionDecl *fn) {
103 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
104 return ftd->getTemplatedDecl();
105
106 return fn;
107}
108
109static const NamedDecl *getStructor(const NamedDecl *decl) {
110 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
111 return (fn ? getStructor(fn) : decl);
112}
David Majnemer2206bf52014-03-05 08:57:59 +0000113
114static bool isLambda(const NamedDecl *ND) {
115 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
116 if (!Record)
117 return false;
118
119 return Record->isLambda();
120}
121
Guy Benyei11169dd2012-12-18 14:30:41 +0000122static const unsigned UnknownArity = ~0U;
123
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000124class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000125 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000127 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000128
Guy Benyei11169dd2012-12-18 14:30:41 +0000129public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000130 explicit ItaniumMangleContextImpl(ASTContext &Context,
131 DiagnosticsEngine &Diags)
132 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000133
Guy Benyei11169dd2012-12-18 14:30:41 +0000134 /// @name Mangler Entry Points
135 /// @{
136
Craig Toppercbce6e92014-03-11 06:22:39 +0000137 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000138 bool shouldMangleStringLiteral(const StringLiteral *) override {
139 return false;
140 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000141 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
142 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
143 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000144 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000146 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000147 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
148 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000149 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
150 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000152 const CXXRecordDecl *Type, raw_ostream &) override;
153 void mangleCXXRTTI(QualType T, raw_ostream &) override;
154 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
155 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000157 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160
Rafael Espindola1e4df922014-09-16 15:18:21 +0000161 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
162 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000163 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
164 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
165 void mangleDynamicAtExitDestructor(const VarDecl *D,
166 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000167 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
168 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000169 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000171 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
172 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
173 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000174
David Majnemer58e5bee2014-03-24 21:43:36 +0000175 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
176
Guy Benyei11169dd2012-12-18 14:30:41 +0000177 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000178 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000179 if (isLambda(ND))
180 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000181
182 // Anonymous tags are already numbered.
183 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
184 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
185 return false;
186 }
187
188 // Use the canonical number for externally visible decls.
189 if (ND->isExternallyVisible()) {
190 unsigned discriminator = getASTContext().getManglingNumber(ND);
191 if (discriminator == 1)
192 return false;
193 disc = discriminator - 2;
194 return true;
195 }
196
197 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000199 if (!discriminator) {
200 const DeclContext *DC = getEffectiveDeclContext(ND);
201 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
202 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 if (discriminator == 1)
204 return false;
205 disc = discriminator-2;
206 return true;
207 }
208 /// @}
209};
210
Justin Bognere8d762e2015-05-22 06:48:13 +0000211/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000212class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000213 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000214 raw_ostream &Out;
215
216 /// The "structor" is the top-level declaration being mangled, if
217 /// that's not a template specialization; otherwise it's the pattern
218 /// for that specialization.
219 const NamedDecl *Structor;
220 unsigned StructorType;
221
Justin Bognere8d762e2015-05-22 06:48:13 +0000222 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000223 unsigned SeqID;
224
225 class FunctionTypeDepthState {
226 unsigned Bits;
227
228 enum { InResultTypeMask = 1 };
229
230 public:
231 FunctionTypeDepthState() : Bits(0) {}
232
233 /// The number of function types we're inside.
234 unsigned getDepth() const {
235 return Bits >> 1;
236 }
237
238 /// True if we're in the return type of the innermost function type.
239 bool isInResultType() const {
240 return Bits & InResultTypeMask;
241 }
242
243 FunctionTypeDepthState push() {
244 FunctionTypeDepthState tmp = *this;
245 Bits = (Bits & ~InResultTypeMask) + 2;
246 return tmp;
247 }
248
249 void enterResultType() {
250 Bits |= InResultTypeMask;
251 }
252
253 void leaveResultType() {
254 Bits &= ~InResultTypeMask;
255 }
256
257 void pop(FunctionTypeDepthState saved) {
258 assert(getDepth() == saved.getDepth() + 1);
259 Bits = saved.Bits;
260 }
261
262 } FunctionTypeDepth;
263
264 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
265
266 ASTContext &getASTContext() const { return Context.getASTContext(); }
267
268public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000269 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000270 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000271 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
272 SeqID(0) {
273 // These can't be mangled without a ctor type or dtor type.
274 assert(!D || (!isa<CXXDestructorDecl>(D) &&
275 !isa<CXXConstructorDecl>(D)));
276 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000277 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000278 const CXXConstructorDecl *D, CXXCtorType Type)
279 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
280 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000281 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000282 const CXXDestructorDecl *D, CXXDtorType Type)
283 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
284 SeqID(0) { }
285
286#if MANGLE_CHECKER
287 ~CXXNameMangler() {
288 if (Out.str()[0] == '\01')
289 return;
290
291 int status = 0;
292 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
293 assert(status == 0 && "Could not demangle mangled name!");
294 free(result);
295 }
296#endif
297 raw_ostream &getStream() { return Out; }
298
David Majnemer7ff7eb72015-02-18 07:47:09 +0000299 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
301 void mangleNumber(const llvm::APSInt &I);
302 void mangleNumber(int64_t Number);
303 void mangleFloat(const llvm::APFloat &F);
304 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000305 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 void mangleName(const NamedDecl *ND);
307 void mangleType(QualType T);
308 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
309
310private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000311
Guy Benyei11169dd2012-12-18 14:30:41 +0000312 bool mangleSubstitution(const NamedDecl *ND);
313 bool mangleSubstitution(QualType T);
314 bool mangleSubstitution(TemplateName Template);
315 bool mangleSubstitution(uintptr_t Ptr);
316
317 void mangleExistingSubstitution(QualType type);
318 void mangleExistingSubstitution(TemplateName name);
319
320 bool mangleStandardSubstitution(const NamedDecl *ND);
321
322 void addSubstitution(const NamedDecl *ND) {
323 ND = cast<NamedDecl>(ND->getCanonicalDecl());
324
325 addSubstitution(reinterpret_cast<uintptr_t>(ND));
326 }
327 void addSubstitution(QualType T);
328 void addSubstitution(TemplateName Template);
329 void addSubstitution(uintptr_t Ptr);
330
331 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 bool recursive = false);
333 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 DeclarationName name,
335 unsigned KnownArity = UnknownArity);
336
337 void mangleName(const TemplateDecl *TD,
338 const TemplateArgument *TemplateArgs,
339 unsigned NumTemplateArgs);
340 void mangleUnqualifiedName(const NamedDecl *ND) {
341 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
342 }
343 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
344 unsigned KnownArity);
345 void mangleUnscopedName(const NamedDecl *ND);
346 void mangleUnscopedTemplateName(const TemplateDecl *ND);
347 void mangleUnscopedTemplateName(TemplateName);
348 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000349 void mangleLocalName(const Decl *D);
350 void mangleBlockForPrefix(const BlockDecl *Block);
351 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 void mangleLambda(const CXXRecordDecl *Lambda);
353 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
354 bool NoFunction=false);
355 void mangleNestedName(const TemplateDecl *TD,
356 const TemplateArgument *TemplateArgs,
357 unsigned NumTemplateArgs);
358 void manglePrefix(NestedNameSpecifier *qualifier);
359 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
360 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000361 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000363 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
364 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000365 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
367 void mangleQualifiers(Qualifiers Quals);
368 void mangleRefQualifier(RefQualifierKind RefQualifier);
369
370 void mangleObjCMethodName(const ObjCMethodDecl *MD);
371
372 // Declare manglers for every type class.
373#define ABSTRACT_TYPE(CLASS, PARENT)
374#define NON_CANONICAL_TYPE(CLASS, PARENT)
375#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
376#include "clang/AST/TypeNodes.def"
377
378 void mangleType(const TagType*);
379 void mangleType(TemplateName);
380 void mangleBareFunctionType(const FunctionType *T,
381 bool MangleReturnType);
382 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000383 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000384
385 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000386 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 void mangleMemberExpr(const Expr *base, bool isArrow,
388 NestedNameSpecifier *qualifier,
389 NamedDecl *firstQualifierLookup,
390 DeclarationName name,
391 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000392 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000393 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000394 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
395 void mangleCXXCtorType(CXXCtorType T);
396 void mangleCXXDtorType(CXXDtorType T);
397
398 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
399 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
400 unsigned NumTemplateArgs);
401 void mangleTemplateArgs(const TemplateArgumentList &AL);
402 void mangleTemplateArg(TemplateArgument A);
403
404 void mangleTemplateParameter(unsigned Index);
405
406 void mangleFunctionParam(const ParmVarDecl *parm);
407};
408
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000409}
Guy Benyei11169dd2012-12-18 14:30:41 +0000410
Rafael Espindola002667c2013-10-16 01:40:34 +0000411bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000412 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000413 if (FD) {
414 LanguageLinkage L = FD->getLanguageLinkage();
415 // Overloadable functions need mangling.
416 if (FD->hasAttr<OverloadableAttr>())
417 return true;
418
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000419 // "main" is not mangled.
420 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000421 return false;
422
423 // C++ functions and those whose names are not a simple identifier need
424 // mangling.
425 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
426 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000427
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000428 // C functions are not mangled.
429 if (L == CLanguageLinkage)
430 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000431 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000432
433 // Otherwise, no mangling is done outside C++ mode.
434 if (!getASTContext().getLangOpts().CPlusPlus)
435 return false;
436
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000437 const VarDecl *VD = dyn_cast<VarDecl>(D);
438 if (VD) {
439 // C variables are not mangled.
440 if (VD->isExternC())
441 return false;
442
443 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000444 const DeclContext *DC = getEffectiveDeclContext(D);
445 // Check for extern variable declared locally.
446 if (DC->isFunctionOrMethod() && D->hasLinkage())
447 while (!DC->isNamespace() && !DC->isTranslationUnit())
448 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000449 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
450 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 return false;
452 }
453
Guy Benyei11169dd2012-12-18 14:30:41 +0000454 return true;
455}
456
David Majnemer7ff7eb72015-02-18 07:47:09 +0000457void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 // <mangled-name> ::= _Z <encoding>
459 // ::= <data name>
460 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000461 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
463 mangleFunctionEncoding(FD);
464 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
465 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000466 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
467 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 else
469 mangleName(cast<FieldDecl>(D));
470}
471
472void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
473 // <encoding> ::= <function name> <bare-function-type>
474 mangleName(FD);
475
476 // Don't mangle in the type if this isn't a decl we should typically mangle.
477 if (!Context.shouldMangleDeclName(FD))
478 return;
479
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000480 if (FD->hasAttr<EnableIfAttr>()) {
481 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
482 Out << "Ua9enable_ifI";
483 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
484 // it here.
485 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
486 E = FD->getAttrs().rend();
487 I != E; ++I) {
488 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
489 if (!EIA)
490 continue;
491 Out << 'X';
492 mangleExpression(EIA->getCond());
493 Out << 'E';
494 }
495 Out << 'E';
496 FunctionTypeDepth.pop(Saved);
497 }
498
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 // Whether the mangling of a function type includes the return type depends on
500 // the context and the nature of the function. The rules for deciding whether
501 // the return type is included are:
502 //
503 // 1. Template functions (names or types) have return types encoded, with
504 // the exceptions listed below.
505 // 2. Function types not appearing as part of a function name mangling,
506 // e.g. parameters, pointer types, etc., have return type encoded, with the
507 // exceptions listed below.
508 // 3. Non-template function names do not have return types encoded.
509 //
510 // The exceptions mentioned in (1) and (2) above, for which the return type is
511 // never included, are
512 // 1. Constructors.
513 // 2. Destructors.
514 // 3. Conversion operator functions, e.g. operator int.
515 bool MangleReturnType = false;
516 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
517 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
518 isa<CXXConversionDecl>(FD)))
519 MangleReturnType = true;
520
521 // Mangle the type of the primary template.
522 FD = PrimaryTemplate->getTemplatedDecl();
523 }
524
525 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
526 MangleReturnType);
527}
528
529static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
530 while (isa<LinkageSpecDecl>(DC)) {
531 DC = getEffectiveParentContext(DC);
532 }
533
534 return DC;
535}
536
Justin Bognere8d762e2015-05-22 06:48:13 +0000537/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000538static bool isStd(const NamespaceDecl *NS) {
539 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
540 ->isTranslationUnit())
541 return false;
542
543 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
544 return II && II->isStr("std");
545}
546
547// isStdNamespace - Return whether a given decl context is a toplevel 'std'
548// namespace.
549static bool isStdNamespace(const DeclContext *DC) {
550 if (!DC->isNamespace())
551 return false;
552
553 return isStd(cast<NamespaceDecl>(DC));
554}
555
556static const TemplateDecl *
557isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
558 // Check if we have a function template.
559 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
560 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
561 TemplateArgs = FD->getTemplateSpecializationArgs();
562 return TD;
563 }
564 }
565
566 // Check if we have a class template.
567 if (const ClassTemplateSpecializationDecl *Spec =
568 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
569 TemplateArgs = &Spec->getTemplateArgs();
570 return Spec->getSpecializedTemplate();
571 }
572
Larisse Voufo39a1e502013-08-06 01:03:05 +0000573 // Check if we have a variable template.
574 if (const VarTemplateSpecializationDecl *Spec =
575 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
576 TemplateArgs = &Spec->getTemplateArgs();
577 return Spec->getSpecializedTemplate();
578 }
579
Craig Topper36250ad2014-05-12 05:36:57 +0000580 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000581}
582
Guy Benyei11169dd2012-12-18 14:30:41 +0000583void CXXNameMangler::mangleName(const NamedDecl *ND) {
584 // <name> ::= <nested-name>
585 // ::= <unscoped-name>
586 // ::= <unscoped-template-name> <template-args>
587 // ::= <local-name>
588 //
589 const DeclContext *DC = getEffectiveDeclContext(ND);
590
591 // If this is an extern variable declared locally, the relevant DeclContext
592 // is that of the containing namespace, or the translation unit.
593 // FIXME: This is a hack; extern variables declared locally should have
594 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000595 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000596 while (!DC->isNamespace() && !DC->isTranslationUnit())
597 DC = getEffectiveParentContext(DC);
598 else if (GetLocalClassDecl(ND)) {
599 mangleLocalName(ND);
600 return;
601 }
602
603 DC = IgnoreLinkageSpecDecls(DC);
604
605 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
606 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000607 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
609 mangleUnscopedTemplateName(TD);
610 mangleTemplateArgs(*TemplateArgs);
611 return;
612 }
613
614 mangleUnscopedName(ND);
615 return;
616 }
617
Eli Friedman95f50122013-07-02 17:52:28 +0000618 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000619 mangleLocalName(ND);
620 return;
621 }
622
623 mangleNestedName(ND, DC);
624}
625void CXXNameMangler::mangleName(const TemplateDecl *TD,
626 const TemplateArgument *TemplateArgs,
627 unsigned NumTemplateArgs) {
628 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
629
630 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
631 mangleUnscopedTemplateName(TD);
632 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
633 } else {
634 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
635 }
636}
637
638void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
639 // <unscoped-name> ::= <unqualified-name>
640 // ::= St <unqualified-name> # ::std::
641
642 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
643 Out << "St";
644
645 mangleUnqualifiedName(ND);
646}
647
648void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
649 // <unscoped-template-name> ::= <unscoped-name>
650 // ::= <substitution>
651 if (mangleSubstitution(ND))
652 return;
653
654 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000655 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000656 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000657 else
658 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000659
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 addSubstitution(ND);
661}
662
663void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
664 // <unscoped-template-name> ::= <unscoped-name>
665 // ::= <substitution>
666 if (TemplateDecl *TD = Template.getAsTemplateDecl())
667 return mangleUnscopedTemplateName(TD);
668
669 if (mangleSubstitution(Template))
670 return;
671
672 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
673 assert(Dependent && "Not a dependent template name?");
674 if (const IdentifierInfo *Id = Dependent->getIdentifier())
675 mangleSourceName(Id);
676 else
677 mangleOperatorName(Dependent->getOperator(), UnknownArity);
678
679 addSubstitution(Template);
680}
681
682void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
683 // ABI:
684 // Floating-point literals are encoded using a fixed-length
685 // lowercase hexadecimal string corresponding to the internal
686 // representation (IEEE on Itanium), high-order bytes first,
687 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
688 // on Itanium.
689 // The 'without leading zeroes' thing seems to be an editorial
690 // mistake; see the discussion on cxx-abi-dev beginning on
691 // 2012-01-16.
692
693 // Our requirements here are just barely weird enough to justify
694 // using a custom algorithm instead of post-processing APInt::toString().
695
696 llvm::APInt valueBits = f.bitcastToAPInt();
697 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
698 assert(numCharacters != 0);
699
700 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000701 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000702
703 // Fill the buffer left-to-right.
704 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
705 // The bit-index of the next hex digit.
706 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
707
708 // Project out 4 bits starting at 'digitIndex'.
709 llvm::integerPart hexDigit
710 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
711 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
712 hexDigit &= 0xF;
713
714 // Map that over to a lowercase hex digit.
715 static const char charForHex[16] = {
716 '0', '1', '2', '3', '4', '5', '6', '7',
717 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
718 };
719 buffer[stringIndex] = charForHex[hexDigit];
720 }
721
722 Out.write(buffer.data(), numCharacters);
723}
724
725void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
726 if (Value.isSigned() && Value.isNegative()) {
727 Out << 'n';
728 Value.abs().print(Out, /*signed*/ false);
729 } else {
730 Value.print(Out, /*signed*/ false);
731 }
732}
733
734void CXXNameMangler::mangleNumber(int64_t Number) {
735 // <number> ::= [n] <non-negative decimal integer>
736 if (Number < 0) {
737 Out << 'n';
738 Number = -Number;
739 }
740
741 Out << Number;
742}
743
744void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
745 // <call-offset> ::= h <nv-offset> _
746 // ::= v <v-offset> _
747 // <nv-offset> ::= <offset number> # non-virtual base override
748 // <v-offset> ::= <offset number> _ <virtual offset number>
749 // # virtual base override, with vcall offset
750 if (!Virtual) {
751 Out << 'h';
752 mangleNumber(NonVirtual);
753 Out << '_';
754 return;
755 }
756
757 Out << 'v';
758 mangleNumber(NonVirtual);
759 Out << '_';
760 mangleNumber(Virtual);
761 Out << '_';
762}
763
764void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000765 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000766 if (!mangleSubstitution(QualType(TST, 0))) {
767 mangleTemplatePrefix(TST->getTemplateName());
768
769 // FIXME: GCC does not appear to mangle the template arguments when
770 // the template in question is a dependent template name. Should we
771 // emulate that badness?
772 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
773 addSubstitution(QualType(TST, 0));
774 }
David Majnemera88b3592015-02-18 02:28:01 +0000775 } else if (const auto *DTST =
776 type->getAs<DependentTemplateSpecializationType>()) {
777 if (!mangleSubstitution(QualType(DTST, 0))) {
778 TemplateName Template = getASTContext().getDependentTemplateName(
779 DTST->getQualifier(), DTST->getIdentifier());
780 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000781
David Majnemera88b3592015-02-18 02:28:01 +0000782 // FIXME: GCC does not appear to mangle the template arguments when
783 // the template in question is a dependent template name. Should we
784 // emulate that badness?
785 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
786 addSubstitution(QualType(DTST, 0));
787 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 } else {
789 // We use the QualType mangle type variant here because it handles
790 // substitutions.
791 mangleType(type);
792 }
793}
794
795/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
796///
Guy Benyei11169dd2012-12-18 14:30:41 +0000797/// \param recursive - true if this is being called recursively,
798/// i.e. if there is more prefix "to the right".
799void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 bool recursive) {
801
802 // x, ::x
803 // <unresolved-name> ::= [gs] <base-unresolved-name>
804
805 // T::x / decltype(p)::x
806 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
807
808 // T::N::x /decltype(p)::N::x
809 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
810 // <base-unresolved-name>
811
812 // A::x, N::y, A<T>::z; "gs" means leading "::"
813 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
814 // <base-unresolved-name>
815
816 switch (qualifier->getKind()) {
817 case NestedNameSpecifier::Global:
818 Out << "gs";
819
820 // We want an 'sr' unless this is the entire NNS.
821 if (recursive)
822 Out << "sr";
823
824 // We never want an 'E' here.
825 return;
826
Nikola Smiljanic67860242014-09-26 00:28:20 +0000827 case NestedNameSpecifier::Super:
828 llvm_unreachable("Can't mangle __super specifier");
829
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 case NestedNameSpecifier::Namespace:
831 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000832 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 /*recursive*/ true);
834 else
835 Out << "sr";
836 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
837 break;
838 case NestedNameSpecifier::NamespaceAlias:
839 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000840 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 /*recursive*/ true);
842 else
843 Out << "sr";
844 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
845 break;
846
847 case NestedNameSpecifier::TypeSpec:
848 case NestedNameSpecifier::TypeSpecWithTemplate: {
849 const Type *type = qualifier->getAsType();
850
851 // We only want to use an unresolved-type encoding if this is one of:
852 // - a decltype
853 // - a template type parameter
854 // - a template template parameter with arguments
855 // In all of these cases, we should have no prefix.
856 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000857 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 /*recursive*/ true);
859 } else {
860 // Otherwise, all the cases want this.
861 Out << "sr";
862 }
863
David Majnemerb8014dd2015-02-19 02:16:16 +0000864 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 return;
866
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 break;
868 }
869
870 case NestedNameSpecifier::Identifier:
871 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000872 if (qualifier->getPrefix())
873 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000875 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000877
878 mangleSourceName(qualifier->getAsIdentifier());
879 break;
880 }
881
882 // If this was the innermost part of the NNS, and we fell out to
883 // here, append an 'E'.
884 if (!recursive)
885 Out << 'E';
886}
887
888/// Mangle an unresolved-name, which is generally used for names which
889/// weren't resolved to specific entities.
890void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000891 DeclarationName name,
892 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000893 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000894 switch (name.getNameKind()) {
895 // <base-unresolved-name> ::= <simple-id>
896 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000897 mangleSourceName(name.getAsIdentifierInfo());
898 break;
899 // <base-unresolved-name> ::= dn <destructor-name>
900 case DeclarationName::CXXDestructorName:
901 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000902 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000903 break;
904 // <base-unresolved-name> ::= on <operator-name>
905 case DeclarationName::CXXConversionFunctionName:
906 case DeclarationName::CXXLiteralOperatorName:
907 case DeclarationName::CXXOperatorName:
908 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000909 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000910 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000911 case DeclarationName::CXXConstructorName:
912 llvm_unreachable("Can't mangle a constructor name!");
913 case DeclarationName::CXXUsingDirective:
914 llvm_unreachable("Can't mangle a using directive name!");
915 case DeclarationName::ObjCMultiArgSelector:
916 case DeclarationName::ObjCOneArgSelector:
917 case DeclarationName::ObjCZeroArgSelector:
918 llvm_unreachable("Can't mangle Objective-C selector names here!");
919 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000920}
921
Guy Benyei11169dd2012-12-18 14:30:41 +0000922void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
923 DeclarationName Name,
924 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000925 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 // <unqualified-name> ::= <operator-name>
927 // ::= <ctor-dtor-name>
928 // ::= <source-name>
929 switch (Name.getNameKind()) {
930 case DeclarationName::Identifier: {
931 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
932 // We must avoid conflicts between internally- and externally-
933 // linked variable and function declaration names in the same TU:
934 // void test() { extern void foo(); }
935 // static void foo();
936 // This naming convention is the same as that followed by GCC,
937 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000938 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 getEffectiveDeclContext(ND)->isFileContext())
940 Out << 'L';
941
942 mangleSourceName(II);
943 break;
944 }
945
946 // Otherwise, an anonymous entity. We must have a declaration.
947 assert(ND && "mangling empty name without declaration");
948
949 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
950 if (NS->isAnonymousNamespace()) {
951 // This is how gcc mangles these names.
952 Out << "12_GLOBAL__N_1";
953 break;
954 }
955 }
956
957 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
958 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000959 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000961
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 // Itanium C++ ABI 5.1.2:
963 //
964 // For the purposes of mangling, the name of an anonymous union is
965 // considered to be the name of the first named data member found by a
966 // pre-order, depth-first, declaration-order walk of the data members of
967 // the anonymous union. If there is no such data member (i.e., if all of
968 // the data members in the union are unnamed), then there is no way for
969 // a program to refer to the anonymous union, and there is therefore no
970 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000971 assert(RD->isAnonymousStructOrUnion()
972 && "Expected anonymous struct or union!");
973 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000974
975 // It's actually possible for various reasons for us to get here
976 // with an empty anonymous struct / union. Fortunately, it
977 // doesn't really matter what name we generate.
978 if (!FD) break;
979 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000980
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 mangleSourceName(FD->getIdentifier());
982 break;
983 }
John McCall924046f2013-04-10 06:08:21 +0000984
985 // Class extensions have no name as a category, and it's possible
986 // for them to be the semantic parent of certain declarations
987 // (primarily, tag decls defined within declarations). Such
988 // declarations will always have internal linkage, so the name
989 // doesn't really matter, but we shouldn't crash on them. For
990 // safety, just handle all ObjC containers here.
991 if (isa<ObjCContainerDecl>(ND))
992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993
994 // We must have an anonymous struct.
995 const TagDecl *TD = cast<TagDecl>(ND);
996 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
997 assert(TD->getDeclContext() == D->getDeclContext() &&
998 "Typedef should not be in another decl context!");
999 assert(D->getDeclName().getAsIdentifierInfo() &&
1000 "Typedef was not named!");
1001 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1002 break;
1003 }
1004
1005 // <unnamed-type-name> ::= <closure-type-name>
1006 //
1007 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1008 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1009 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1010 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1011 mangleLambda(Record);
1012 break;
1013 }
1014 }
1015
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001016 if (TD->isExternallyVisible()) {
1017 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001019 if (UnnamedMangle > 1)
1020 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 Out << '_';
1022 break;
1023 }
1024
1025 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001026 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001027
1028 // Mangle it as a source name in the form
1029 // [n] $_<id>
1030 // where n is the length of the string.
1031 SmallString<8> Str;
1032 Str += "$_";
1033 Str += llvm::utostr(AnonStructId);
1034
1035 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001036 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 break;
1038 }
1039
1040 case DeclarationName::ObjCZeroArgSelector:
1041 case DeclarationName::ObjCOneArgSelector:
1042 case DeclarationName::ObjCMultiArgSelector:
1043 llvm_unreachable("Can't mangle Objective-C selector names here!");
1044
1045 case DeclarationName::CXXConstructorName:
1046 if (ND == Structor)
1047 // If the named decl is the C++ constructor we're mangling, use the type
1048 // we were given.
1049 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1050 else
1051 // Otherwise, use the complete constructor name. This is relevant if a
1052 // class with a constructor is declared within a constructor.
1053 mangleCXXCtorType(Ctor_Complete);
1054 break;
1055
1056 case DeclarationName::CXXDestructorName:
1057 if (ND == Structor)
1058 // If the named decl is the C++ destructor we're mangling, use the type we
1059 // were given.
1060 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1061 else
1062 // Otherwise, use the complete destructor name. This is relevant if a
1063 // class with a destructor is declared within a destructor.
1064 mangleCXXDtorType(Dtor_Complete);
1065 break;
1066
David Majnemera88b3592015-02-18 02:28:01 +00001067 case DeclarationName::CXXOperatorName:
1068 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 Arity = cast<FunctionDecl>(ND)->getNumParams();
1070
David Majnemera88b3592015-02-18 02:28:01 +00001071 // If we have a member function, we need to include the 'this' pointer.
1072 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1073 if (!MD->isStatic())
1074 Arity++;
1075 }
1076 // FALLTHROUGH
1077 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001078 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001079 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 break;
1081
1082 case DeclarationName::CXXUsingDirective:
1083 llvm_unreachable("Can't mangle a using directive name!");
1084 }
1085}
1086
1087void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1088 // <source-name> ::= <positive length number> <identifier>
1089 // <number> ::= [n] <non-negative decimal integer>
1090 // <identifier> ::= <unqualified source code identifier>
1091 Out << II->getLength() << II->getName();
1092}
1093
1094void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1095 const DeclContext *DC,
1096 bool NoFunction) {
1097 // <nested-name>
1098 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1099 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1100 // <template-args> E
1101
1102 Out << 'N';
1103 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001104 Qualifiers MethodQuals =
1105 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1106 // We do not consider restrict a distinguishing attribute for overloading
1107 // purposes so we must not mangle it.
1108 MethodQuals.removeRestrict();
1109 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 mangleRefQualifier(Method->getRefQualifier());
1111 }
1112
1113 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001114 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001116 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 mangleTemplateArgs(*TemplateArgs);
1118 }
1119 else {
1120 manglePrefix(DC, NoFunction);
1121 mangleUnqualifiedName(ND);
1122 }
1123
1124 Out << 'E';
1125}
1126void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1127 const TemplateArgument *TemplateArgs,
1128 unsigned NumTemplateArgs) {
1129 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1130
1131 Out << 'N';
1132
1133 mangleTemplatePrefix(TD);
1134 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1135
1136 Out << 'E';
1137}
1138
Eli Friedman95f50122013-07-02 17:52:28 +00001139void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1141 // := Z <function encoding> E s [<discriminator>]
1142 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1143 // _ <entity name>
1144 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001145 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001146 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001147 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001148
1149 Out << 'Z';
1150
Eli Friedman92821742013-07-02 02:01:18 +00001151 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1152 mangleObjCMethodName(MD);
1153 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001154 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001155 else
1156 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001157
Eli Friedman92821742013-07-02 02:01:18 +00001158 Out << 'E';
1159
1160 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 // The parameter number is omitted for the last parameter, 0 for the
1162 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1163 // <entity name> will of course contain a <closure-type-name>: Its
1164 // numbering will be local to the particular argument in which it appears
1165 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001166 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1167 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001169 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 if (const FunctionDecl *Func
1171 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1172 Out << 'd';
1173 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1174 if (Num > 1)
1175 mangleNumber(Num - 2);
1176 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 }
1178 }
1179 }
1180
1181 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001182 // equality ok because RD derived from ND above
1183 if (D == RD) {
1184 mangleUnqualifiedName(RD);
1185 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1186 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1187 mangleUnqualifiedBlock(BD);
1188 } else {
1189 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001190 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001191 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001192 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1193 // Mangle a block in a default parameter; see above explanation for
1194 // lambdas.
1195 if (const ParmVarDecl *Parm
1196 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1197 if (const FunctionDecl *Func
1198 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1199 Out << 'd';
1200 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1201 if (Num > 1)
1202 mangleNumber(Num - 2);
1203 Out << '_';
1204 }
1205 }
1206
1207 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001208 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001209 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001211
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001212 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1213 unsigned disc;
1214 if (Context.getNextDiscriminator(ND, disc)) {
1215 if (disc < 10)
1216 Out << '_' << disc;
1217 else
1218 Out << "__" << disc << '_';
1219 }
1220 }
Eli Friedman95f50122013-07-02 17:52:28 +00001221}
1222
1223void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1224 if (GetLocalClassDecl(Block)) {
1225 mangleLocalName(Block);
1226 return;
1227 }
1228 const DeclContext *DC = getEffectiveDeclContext(Block);
1229 if (isLocalContainerContext(DC)) {
1230 mangleLocalName(Block);
1231 return;
1232 }
1233 manglePrefix(getEffectiveDeclContext(Block));
1234 mangleUnqualifiedBlock(Block);
1235}
1236
1237void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1238 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1239 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1240 Context->getDeclContext()->isRecord()) {
1241 if (const IdentifierInfo *Name
1242 = cast<NamedDecl>(Context)->getIdentifier()) {
1243 mangleSourceName(Name);
1244 Out << 'M';
1245 }
1246 }
1247 }
1248
1249 // If we have a block mangling number, use it.
1250 unsigned Number = Block->getBlockManglingNumber();
1251 // Otherwise, just make up a number. It doesn't matter what it is because
1252 // the symbol in question isn't externally visible.
1253 if (!Number)
1254 Number = Context.getBlockId(Block, false);
1255 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001256 if (Number > 0)
1257 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001258 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001259}
1260
1261void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1262 // If the context of a closure type is an initializer for a class member
1263 // (static or nonstatic), it is encoded in a qualified name with a final
1264 // <prefix> of the form:
1265 //
1266 // <data-member-prefix> := <member source-name> M
1267 //
1268 // Technically, the data-member-prefix is part of the <prefix>. However,
1269 // since a closure type will always be mangled with a prefix, it's easier
1270 // to emit that last part of the prefix here.
1271 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1272 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1273 Context->getDeclContext()->isRecord()) {
1274 if (const IdentifierInfo *Name
1275 = cast<NamedDecl>(Context)->getIdentifier()) {
1276 mangleSourceName(Name);
1277 Out << 'M';
1278 }
1279 }
1280 }
1281
1282 Out << "Ul";
1283 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1284 getAs<FunctionProtoType>();
1285 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1286 Out << "E";
1287
1288 // The number is omitted for the first closure type with a given
1289 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1290 // (in lexical order) with that same <lambda-sig> and context.
1291 //
1292 // The AST keeps track of the number for us.
1293 unsigned Number = Lambda->getLambdaManglingNumber();
1294 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1295 if (Number > 1)
1296 mangleNumber(Number - 2);
1297 Out << '_';
1298}
1299
1300void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1301 switch (qualifier->getKind()) {
1302 case NestedNameSpecifier::Global:
1303 // nothing
1304 return;
1305
Nikola Smiljanic67860242014-09-26 00:28:20 +00001306 case NestedNameSpecifier::Super:
1307 llvm_unreachable("Can't mangle __super specifier");
1308
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 case NestedNameSpecifier::Namespace:
1310 mangleName(qualifier->getAsNamespace());
1311 return;
1312
1313 case NestedNameSpecifier::NamespaceAlias:
1314 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1315 return;
1316
1317 case NestedNameSpecifier::TypeSpec:
1318 case NestedNameSpecifier::TypeSpecWithTemplate:
1319 manglePrefix(QualType(qualifier->getAsType(), 0));
1320 return;
1321
1322 case NestedNameSpecifier::Identifier:
1323 // Member expressions can have these without prefixes, but that
1324 // should end up in mangleUnresolvedPrefix instead.
1325 assert(qualifier->getPrefix());
1326 manglePrefix(qualifier->getPrefix());
1327
1328 mangleSourceName(qualifier->getAsIdentifier());
1329 return;
1330 }
1331
1332 llvm_unreachable("unexpected nested name specifier");
1333}
1334
1335void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1336 // <prefix> ::= <prefix> <unqualified-name>
1337 // ::= <template-prefix> <template-args>
1338 // ::= <template-param>
1339 // ::= # empty
1340 // ::= <substitution>
1341
1342 DC = IgnoreLinkageSpecDecls(DC);
1343
1344 if (DC->isTranslationUnit())
1345 return;
1346
Eli Friedman95f50122013-07-02 17:52:28 +00001347 if (NoFunction && isLocalContainerContext(DC))
1348 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001349
Eli Friedman95f50122013-07-02 17:52:28 +00001350 assert(!isLocalContainerContext(DC));
1351
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 const NamedDecl *ND = cast<NamedDecl>(DC);
1353 if (mangleSubstitution(ND))
1354 return;
1355
1356 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001357 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1359 mangleTemplatePrefix(TD);
1360 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001361 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1363 mangleUnqualifiedName(ND);
1364 }
1365
1366 addSubstitution(ND);
1367}
1368
1369void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1370 // <template-prefix> ::= <prefix> <template unqualified-name>
1371 // ::= <template-param>
1372 // ::= <substitution>
1373 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1374 return mangleTemplatePrefix(TD);
1375
1376 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1377 manglePrefix(Qualified->getQualifier());
1378
1379 if (OverloadedTemplateStorage *Overloaded
1380 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001381 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 UnknownArity);
1383 return;
1384 }
1385
1386 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1387 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001388 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1389 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 mangleUnscopedTemplateName(Template);
1391}
1392
Eli Friedman86af13f02013-07-05 18:41:30 +00001393void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1394 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 // <template-prefix> ::= <prefix> <template unqualified-name>
1396 // ::= <template-param>
1397 // ::= <substitution>
1398 // <template-template-param> ::= <template-param>
1399 // <substitution>
1400
1401 if (mangleSubstitution(ND))
1402 return;
1403
1404 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001405 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001407 } else {
1408 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1409 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 }
1411
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 addSubstitution(ND);
1413}
1414
1415/// Mangles a template name under the production <type>. Required for
1416/// template template arguments.
1417/// <type> ::= <class-enum-type>
1418/// ::= <template-param>
1419/// ::= <substitution>
1420void CXXNameMangler::mangleType(TemplateName TN) {
1421 if (mangleSubstitution(TN))
1422 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001423
1424 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001425
1426 switch (TN.getKind()) {
1427 case TemplateName::QualifiedTemplate:
1428 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1429 goto HaveDecl;
1430
1431 case TemplateName::Template:
1432 TD = TN.getAsTemplateDecl();
1433 goto HaveDecl;
1434
1435 HaveDecl:
1436 if (isa<TemplateTemplateParmDecl>(TD))
1437 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1438 else
1439 mangleName(TD);
1440 break;
1441
1442 case TemplateName::OverloadedTemplate:
1443 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1444
1445 case TemplateName::DependentTemplate: {
1446 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1447 assert(Dependent->isIdentifier());
1448
1449 // <class-enum-type> ::= <name>
1450 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001451 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001452 mangleSourceName(Dependent->getIdentifier());
1453 break;
1454 }
1455
1456 case TemplateName::SubstTemplateTemplateParm: {
1457 // Substituted template parameters are mangled as the substituted
1458 // template. This will check for the substitution twice, which is
1459 // fine, but we have to return early so that we don't try to *add*
1460 // the substitution twice.
1461 SubstTemplateTemplateParmStorage *subst
1462 = TN.getAsSubstTemplateTemplateParm();
1463 mangleType(subst->getReplacement());
1464 return;
1465 }
1466
1467 case TemplateName::SubstTemplateTemplateParmPack: {
1468 // FIXME: not clear how to mangle this!
1469 // template <template <class> class T...> class A {
1470 // template <template <class> class U...> void foo(B<T,U> x...);
1471 // };
1472 Out << "_SUBSTPACK_";
1473 break;
1474 }
1475 }
1476
1477 addSubstitution(TN);
1478}
1479
David Majnemerb8014dd2015-02-19 02:16:16 +00001480bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1481 StringRef Prefix) {
1482 // Only certain other types are valid as prefixes; enumerate them.
1483 switch (Ty->getTypeClass()) {
1484 case Type::Builtin:
1485 case Type::Complex:
1486 case Type::Adjusted:
1487 case Type::Decayed:
1488 case Type::Pointer:
1489 case Type::BlockPointer:
1490 case Type::LValueReference:
1491 case Type::RValueReference:
1492 case Type::MemberPointer:
1493 case Type::ConstantArray:
1494 case Type::IncompleteArray:
1495 case Type::VariableArray:
1496 case Type::DependentSizedArray:
1497 case Type::DependentSizedExtVector:
1498 case Type::Vector:
1499 case Type::ExtVector:
1500 case Type::FunctionProto:
1501 case Type::FunctionNoProto:
1502 case Type::Paren:
1503 case Type::Attributed:
1504 case Type::Auto:
1505 case Type::PackExpansion:
1506 case Type::ObjCObject:
1507 case Type::ObjCInterface:
1508 case Type::ObjCObjectPointer:
1509 case Type::Atomic:
1510 llvm_unreachable("type is illegal as a nested name specifier");
1511
1512 case Type::SubstTemplateTypeParmPack:
1513 // FIXME: not clear how to mangle this!
1514 // template <class T...> class A {
1515 // template <class U...> void foo(decltype(T::foo(U())) x...);
1516 // };
1517 Out << "_SUBSTPACK_";
1518 break;
1519
1520 // <unresolved-type> ::= <template-param>
1521 // ::= <decltype>
1522 // ::= <template-template-param> <template-args>
1523 // (this last is not official yet)
1524 case Type::TypeOfExpr:
1525 case Type::TypeOf:
1526 case Type::Decltype:
1527 case Type::TemplateTypeParm:
1528 case Type::UnaryTransform:
1529 case Type::SubstTemplateTypeParm:
1530 unresolvedType:
1531 // Some callers want a prefix before the mangled type.
1532 Out << Prefix;
1533
1534 // This seems to do everything we want. It's not really
1535 // sanctioned for a substituted template parameter, though.
1536 mangleType(Ty);
1537
1538 // We never want to print 'E' directly after an unresolved-type,
1539 // so we return directly.
1540 return true;
1541
1542 case Type::Typedef:
1543 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1544 break;
1545
1546 case Type::UnresolvedUsing:
1547 mangleSourceName(
1548 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1549 break;
1550
1551 case Type::Enum:
1552 case Type::Record:
1553 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1554 break;
1555
1556 case Type::TemplateSpecialization: {
1557 const TemplateSpecializationType *TST =
1558 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001559 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001560 switch (TN.getKind()) {
1561 case TemplateName::Template:
1562 case TemplateName::QualifiedTemplate: {
1563 TemplateDecl *TD = TN.getAsTemplateDecl();
1564
1565 // If the base is a template template parameter, this is an
1566 // unresolved type.
1567 assert(TD && "no template for template specialization type");
1568 if (isa<TemplateTemplateParmDecl>(TD))
1569 goto unresolvedType;
1570
1571 mangleSourceName(TD->getIdentifier());
1572 break;
David Majnemera88b3592015-02-18 02:28:01 +00001573 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001574
1575 case TemplateName::OverloadedTemplate:
1576 case TemplateName::DependentTemplate:
1577 llvm_unreachable("invalid base for a template specialization type");
1578
1579 case TemplateName::SubstTemplateTemplateParm: {
1580 SubstTemplateTemplateParmStorage *subst =
1581 TN.getAsSubstTemplateTemplateParm();
1582 mangleExistingSubstitution(subst->getReplacement());
1583 break;
1584 }
1585
1586 case TemplateName::SubstTemplateTemplateParmPack: {
1587 // FIXME: not clear how to mangle this!
1588 // template <template <class U> class T...> class A {
1589 // template <class U...> void foo(decltype(T<U>::foo) x...);
1590 // };
1591 Out << "_SUBSTPACK_";
1592 break;
1593 }
1594 }
1595
David Majnemera88b3592015-02-18 02:28:01 +00001596 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001597 break;
David Majnemera88b3592015-02-18 02:28:01 +00001598 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001599
1600 case Type::InjectedClassName:
1601 mangleSourceName(
1602 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1603 break;
1604
1605 case Type::DependentName:
1606 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1607 break;
1608
1609 case Type::DependentTemplateSpecialization: {
1610 const DependentTemplateSpecializationType *DTST =
1611 cast<DependentTemplateSpecializationType>(Ty);
1612 mangleSourceName(DTST->getIdentifier());
1613 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1614 break;
1615 }
1616
1617 case Type::Elaborated:
1618 return mangleUnresolvedTypeOrSimpleId(
1619 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1620 }
1621
1622 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001623}
1624
1625void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1626 switch (Name.getNameKind()) {
1627 case DeclarationName::CXXConstructorName:
1628 case DeclarationName::CXXDestructorName:
1629 case DeclarationName::CXXUsingDirective:
1630 case DeclarationName::Identifier:
1631 case DeclarationName::ObjCMultiArgSelector:
1632 case DeclarationName::ObjCOneArgSelector:
1633 case DeclarationName::ObjCZeroArgSelector:
1634 llvm_unreachable("Not an operator name");
1635
1636 case DeclarationName::CXXConversionFunctionName:
1637 // <operator-name> ::= cv <type> # (cast)
1638 Out << "cv";
1639 mangleType(Name.getCXXNameType());
1640 break;
1641
1642 case DeclarationName::CXXLiteralOperatorName:
1643 Out << "li";
1644 mangleSourceName(Name.getCXXLiteralIdentifier());
1645 return;
1646
1647 case DeclarationName::CXXOperatorName:
1648 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1649 break;
1650 }
1651}
1652
1653
1654
Guy Benyei11169dd2012-12-18 14:30:41 +00001655void
1656CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1657 switch (OO) {
1658 // <operator-name> ::= nw # new
1659 case OO_New: Out << "nw"; break;
1660 // ::= na # new[]
1661 case OO_Array_New: Out << "na"; break;
1662 // ::= dl # delete
1663 case OO_Delete: Out << "dl"; break;
1664 // ::= da # delete[]
1665 case OO_Array_Delete: Out << "da"; break;
1666 // ::= ps # + (unary)
1667 // ::= pl # + (binary or unknown)
1668 case OO_Plus:
1669 Out << (Arity == 1? "ps" : "pl"); break;
1670 // ::= ng # - (unary)
1671 // ::= mi # - (binary or unknown)
1672 case OO_Minus:
1673 Out << (Arity == 1? "ng" : "mi"); break;
1674 // ::= ad # & (unary)
1675 // ::= an # & (binary or unknown)
1676 case OO_Amp:
1677 Out << (Arity == 1? "ad" : "an"); break;
1678 // ::= de # * (unary)
1679 // ::= ml # * (binary or unknown)
1680 case OO_Star:
1681 // Use binary when unknown.
1682 Out << (Arity == 1? "de" : "ml"); break;
1683 // ::= co # ~
1684 case OO_Tilde: Out << "co"; break;
1685 // ::= dv # /
1686 case OO_Slash: Out << "dv"; break;
1687 // ::= rm # %
1688 case OO_Percent: Out << "rm"; break;
1689 // ::= or # |
1690 case OO_Pipe: Out << "or"; break;
1691 // ::= eo # ^
1692 case OO_Caret: Out << "eo"; break;
1693 // ::= aS # =
1694 case OO_Equal: Out << "aS"; break;
1695 // ::= pL # +=
1696 case OO_PlusEqual: Out << "pL"; break;
1697 // ::= mI # -=
1698 case OO_MinusEqual: Out << "mI"; break;
1699 // ::= mL # *=
1700 case OO_StarEqual: Out << "mL"; break;
1701 // ::= dV # /=
1702 case OO_SlashEqual: Out << "dV"; break;
1703 // ::= rM # %=
1704 case OO_PercentEqual: Out << "rM"; break;
1705 // ::= aN # &=
1706 case OO_AmpEqual: Out << "aN"; break;
1707 // ::= oR # |=
1708 case OO_PipeEqual: Out << "oR"; break;
1709 // ::= eO # ^=
1710 case OO_CaretEqual: Out << "eO"; break;
1711 // ::= ls # <<
1712 case OO_LessLess: Out << "ls"; break;
1713 // ::= rs # >>
1714 case OO_GreaterGreater: Out << "rs"; break;
1715 // ::= lS # <<=
1716 case OO_LessLessEqual: Out << "lS"; break;
1717 // ::= rS # >>=
1718 case OO_GreaterGreaterEqual: Out << "rS"; break;
1719 // ::= eq # ==
1720 case OO_EqualEqual: Out << "eq"; break;
1721 // ::= ne # !=
1722 case OO_ExclaimEqual: Out << "ne"; break;
1723 // ::= lt # <
1724 case OO_Less: Out << "lt"; break;
1725 // ::= gt # >
1726 case OO_Greater: Out << "gt"; break;
1727 // ::= le # <=
1728 case OO_LessEqual: Out << "le"; break;
1729 // ::= ge # >=
1730 case OO_GreaterEqual: Out << "ge"; break;
1731 // ::= nt # !
1732 case OO_Exclaim: Out << "nt"; break;
1733 // ::= aa # &&
1734 case OO_AmpAmp: Out << "aa"; break;
1735 // ::= oo # ||
1736 case OO_PipePipe: Out << "oo"; break;
1737 // ::= pp # ++
1738 case OO_PlusPlus: Out << "pp"; break;
1739 // ::= mm # --
1740 case OO_MinusMinus: Out << "mm"; break;
1741 // ::= cm # ,
1742 case OO_Comma: Out << "cm"; break;
1743 // ::= pm # ->*
1744 case OO_ArrowStar: Out << "pm"; break;
1745 // ::= pt # ->
1746 case OO_Arrow: Out << "pt"; break;
1747 // ::= cl # ()
1748 case OO_Call: Out << "cl"; break;
1749 // ::= ix # []
1750 case OO_Subscript: Out << "ix"; break;
1751
1752 // ::= qu # ?
1753 // The conditional operator can't be overloaded, but we still handle it when
1754 // mangling expressions.
1755 case OO_Conditional: Out << "qu"; break;
1756
1757 case OO_None:
1758 case NUM_OVERLOADED_OPERATORS:
1759 llvm_unreachable("Not an overloaded operator");
1760 }
1761}
1762
1763void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1764 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1765 if (Quals.hasRestrict())
1766 Out << 'r';
1767 if (Quals.hasVolatile())
1768 Out << 'V';
1769 if (Quals.hasConst())
1770 Out << 'K';
1771
1772 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001773 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 //
David Tweed31d09b02013-09-13 12:04:22 +00001775 // <type> ::= U <target-addrspace>
1776 // <type> ::= U <OpenCL-addrspace>
1777 // <type> ::= U <CUDA-addrspace>
1778
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001780 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001781
1782 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1783 // <target-addrspace> ::= "AS" <address-space-number>
1784 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1785 ASString = "AS" + llvm::utostr_32(TargetAS);
1786 } else {
1787 switch (AS) {
1788 default: llvm_unreachable("Not a language specific address space");
1789 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1790 case LangAS::opencl_global: ASString = "CLglobal"; break;
1791 case LangAS::opencl_local: ASString = "CLlocal"; break;
1792 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1793 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1794 case LangAS::cuda_device: ASString = "CUdevice"; break;
1795 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1796 case LangAS::cuda_shared: ASString = "CUshared"; break;
1797 }
1798 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 Out << 'U' << ASString.size() << ASString;
1800 }
1801
1802 StringRef LifetimeName;
1803 switch (Quals.getObjCLifetime()) {
1804 // Objective-C ARC Extension:
1805 //
1806 // <type> ::= U "__strong"
1807 // <type> ::= U "__weak"
1808 // <type> ::= U "__autoreleasing"
1809 case Qualifiers::OCL_None:
1810 break;
1811
1812 case Qualifiers::OCL_Weak:
1813 LifetimeName = "__weak";
1814 break;
1815
1816 case Qualifiers::OCL_Strong:
1817 LifetimeName = "__strong";
1818 break;
1819
1820 case Qualifiers::OCL_Autoreleasing:
1821 LifetimeName = "__autoreleasing";
1822 break;
1823
1824 case Qualifiers::OCL_ExplicitNone:
1825 // The __unsafe_unretained qualifier is *not* mangled, so that
1826 // __unsafe_unretained types in ARC produce the same manglings as the
1827 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1828 // better ABI compatibility.
1829 //
1830 // It's safe to do this because unqualified 'id' won't show up
1831 // in any type signatures that need to be mangled.
1832 break;
1833 }
1834 if (!LifetimeName.empty())
1835 Out << 'U' << LifetimeName.size() << LifetimeName;
1836}
1837
1838void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1839 // <ref-qualifier> ::= R # lvalue reference
1840 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 switch (RefQualifier) {
1842 case RQ_None:
1843 break;
1844
1845 case RQ_LValue:
1846 Out << 'R';
1847 break;
1848
1849 case RQ_RValue:
1850 Out << 'O';
1851 break;
1852 }
1853}
1854
1855void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1856 Context.mangleObjCMethodName(MD, Out);
1857}
1858
David Majnemereea02ee2014-11-28 22:22:46 +00001859static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1860 if (Quals)
1861 return true;
1862 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1863 return true;
1864 if (Ty->isOpenCLSpecificType())
1865 return true;
1866 if (Ty->isBuiltinType())
1867 return false;
1868
1869 return true;
1870}
1871
Guy Benyei11169dd2012-12-18 14:30:41 +00001872void CXXNameMangler::mangleType(QualType T) {
1873 // If our type is instantiation-dependent but not dependent, we mangle
1874 // it as it was written in the source, removing any top-level sugar.
1875 // Otherwise, use the canonical type.
1876 //
1877 // FIXME: This is an approximation of the instantiation-dependent name
1878 // mangling rules, since we should really be using the type as written and
1879 // augmented via semantic analysis (i.e., with implicit conversions and
1880 // default template arguments) for any instantiation-dependent type.
1881 // Unfortunately, that requires several changes to our AST:
1882 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1883 // uniqued, so that we can handle substitutions properly
1884 // - Default template arguments will need to be represented in the
1885 // TemplateSpecializationType, since they need to be mangled even though
1886 // they aren't written.
1887 // - Conversions on non-type template arguments need to be expressed, since
1888 // they can affect the mangling of sizeof/alignof.
1889 if (!T->isInstantiationDependentType() || T->isDependentType())
1890 T = T.getCanonicalType();
1891 else {
1892 // Desugar any types that are purely sugar.
1893 do {
1894 // Don't desugar through template specialization types that aren't
1895 // type aliases. We need to mangle the template arguments as written.
1896 if (const TemplateSpecializationType *TST
1897 = dyn_cast<TemplateSpecializationType>(T))
1898 if (!TST->isTypeAlias())
1899 break;
1900
1901 QualType Desugared
1902 = T.getSingleStepDesugaredType(Context.getASTContext());
1903 if (Desugared == T)
1904 break;
1905
1906 T = Desugared;
1907 } while (true);
1908 }
1909 SplitQualType split = T.split();
1910 Qualifiers quals = split.Quals;
1911 const Type *ty = split.Ty;
1912
David Majnemereea02ee2014-11-28 22:22:46 +00001913 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001914 if (isSubstitutable && mangleSubstitution(T))
1915 return;
1916
1917 // If we're mangling a qualified array type, push the qualifiers to
1918 // the element type.
1919 if (quals && isa<ArrayType>(T)) {
1920 ty = Context.getASTContext().getAsArrayType(T);
1921 quals = Qualifiers();
1922
1923 // Note that we don't update T: we want to add the
1924 // substitution at the original type.
1925 }
1926
1927 if (quals) {
1928 mangleQualifiers(quals);
1929 // Recurse: even if the qualified type isn't yet substitutable,
1930 // the unqualified type might be.
1931 mangleType(QualType(ty, 0));
1932 } else {
1933 switch (ty->getTypeClass()) {
1934#define ABSTRACT_TYPE(CLASS, PARENT)
1935#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1936 case Type::CLASS: \
1937 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1938 return;
1939#define TYPE(CLASS, PARENT) \
1940 case Type::CLASS: \
1941 mangleType(static_cast<const CLASS##Type*>(ty)); \
1942 break;
1943#include "clang/AST/TypeNodes.def"
1944 }
1945 }
1946
1947 // Add the substitution.
1948 if (isSubstitutable)
1949 addSubstitution(T);
1950}
1951
1952void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1953 if (!mangleStandardSubstitution(ND))
1954 mangleName(ND);
1955}
1956
1957void CXXNameMangler::mangleType(const BuiltinType *T) {
1958 // <type> ::= <builtin-type>
1959 // <builtin-type> ::= v # void
1960 // ::= w # wchar_t
1961 // ::= b # bool
1962 // ::= c # char
1963 // ::= a # signed char
1964 // ::= h # unsigned char
1965 // ::= s # short
1966 // ::= t # unsigned short
1967 // ::= i # int
1968 // ::= j # unsigned int
1969 // ::= l # long
1970 // ::= m # unsigned long
1971 // ::= x # long long, __int64
1972 // ::= y # unsigned long long, __int64
1973 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001974 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001975 // ::= f # float
1976 // ::= d # double
1977 // ::= e # long double, __float80
1978 // UNSUPPORTED: ::= g # __float128
1979 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1980 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1981 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1982 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1983 // ::= Di # char32_t
1984 // ::= Ds # char16_t
1985 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1986 // ::= u <source-name> # vendor extended type
1987 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00001988 case BuiltinType::Void:
1989 Out << 'v';
1990 break;
1991 case BuiltinType::Bool:
1992 Out << 'b';
1993 break;
1994 case BuiltinType::Char_U:
1995 case BuiltinType::Char_S:
1996 Out << 'c';
1997 break;
1998 case BuiltinType::UChar:
1999 Out << 'h';
2000 break;
2001 case BuiltinType::UShort:
2002 Out << 't';
2003 break;
2004 case BuiltinType::UInt:
2005 Out << 'j';
2006 break;
2007 case BuiltinType::ULong:
2008 Out << 'm';
2009 break;
2010 case BuiltinType::ULongLong:
2011 Out << 'y';
2012 break;
2013 case BuiltinType::UInt128:
2014 Out << 'o';
2015 break;
2016 case BuiltinType::SChar:
2017 Out << 'a';
2018 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002020 case BuiltinType::WChar_U:
2021 Out << 'w';
2022 break;
2023 case BuiltinType::Char16:
2024 Out << "Ds";
2025 break;
2026 case BuiltinType::Char32:
2027 Out << "Di";
2028 break;
2029 case BuiltinType::Short:
2030 Out << 's';
2031 break;
2032 case BuiltinType::Int:
2033 Out << 'i';
2034 break;
2035 case BuiltinType::Long:
2036 Out << 'l';
2037 break;
2038 case BuiltinType::LongLong:
2039 Out << 'x';
2040 break;
2041 case BuiltinType::Int128:
2042 Out << 'n';
2043 break;
2044 case BuiltinType::Half:
2045 Out << "Dh";
2046 break;
2047 case BuiltinType::Float:
2048 Out << 'f';
2049 break;
2050 case BuiltinType::Double:
2051 Out << 'd';
2052 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002053 case BuiltinType::LongDouble:
2054 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2055 ? 'g'
2056 : 'e');
2057 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002058 case BuiltinType::NullPtr:
2059 Out << "Dn";
2060 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002061
2062#define BUILTIN_TYPE(Id, SingletonId)
2063#define PLACEHOLDER_TYPE(Id, SingletonId) \
2064 case BuiltinType::Id:
2065#include "clang/AST/BuiltinTypes.def"
2066 case BuiltinType::Dependent:
2067 llvm_unreachable("mangling a placeholder type");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002068 case BuiltinType::ObjCId:
2069 Out << "11objc_object";
2070 break;
2071 case BuiltinType::ObjCClass:
2072 Out << "10objc_class";
2073 break;
2074 case BuiltinType::ObjCSel:
2075 Out << "13objc_selector";
2076 break;
2077 case BuiltinType::OCLImage1d:
2078 Out << "11ocl_image1d";
2079 break;
2080 case BuiltinType::OCLImage1dArray:
2081 Out << "16ocl_image1darray";
2082 break;
2083 case BuiltinType::OCLImage1dBuffer:
2084 Out << "17ocl_image1dbuffer";
2085 break;
2086 case BuiltinType::OCLImage2d:
2087 Out << "11ocl_image2d";
2088 break;
2089 case BuiltinType::OCLImage2dArray:
2090 Out << "16ocl_image2darray";
2091 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002092 case BuiltinType::OCLImage2dDepth:
2093 Out << "16ocl_image2ddepth";
2094 break;
2095 case BuiltinType::OCLImage2dArrayDepth:
2096 Out << "21ocl_image2darraydepth";
2097 break;
2098 case BuiltinType::OCLImage2dMSAA:
2099 Out << "15ocl_image2dmsaa";
2100 break;
2101 case BuiltinType::OCLImage2dArrayMSAA:
2102 Out << "20ocl_image2darraymsaa";
2103 break;
2104 case BuiltinType::OCLImage2dMSAADepth:
2105 Out << "20ocl_image2dmsaadepth";
2106 break;
2107 case BuiltinType::OCLImage2dArrayMSAADepth:
2108 Out << "35ocl_image2darraymsaadepth";
2109 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002110 case BuiltinType::OCLImage3d:
2111 Out << "11ocl_image3d";
2112 break;
2113 case BuiltinType::OCLSampler:
2114 Out << "11ocl_sampler";
2115 break;
2116 case BuiltinType::OCLEvent:
2117 Out << "9ocl_event";
2118 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002119 case BuiltinType::OCLClkEvent:
2120 Out << "12ocl_clkevent";
2121 break;
2122 case BuiltinType::OCLQueue:
2123 Out << "9ocl_queue";
2124 break;
2125 case BuiltinType::OCLNDRange:
2126 Out << "11ocl_ndrange";
2127 break;
2128 case BuiltinType::OCLReserveID:
2129 Out << "13ocl_reserveid";
2130 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 }
2132}
2133
2134// <type> ::= <function-type>
2135// <function-type> ::= [<CV-qualifiers>] F [Y]
2136// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002137void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2138 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2139 // e.g. "const" in "int (A::*)() const".
2140 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2141
2142 Out << 'F';
2143
2144 // FIXME: We don't have enough information in the AST to produce the 'Y'
2145 // encoding for extern "C" function types.
2146 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2147
2148 // Mangle the ref-qualifier, if present.
2149 mangleRefQualifier(T->getRefQualifier());
2150
2151 Out << 'E';
2152}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002153
Guy Benyei11169dd2012-12-18 14:30:41 +00002154void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002155 // Function types without prototypes can arise when mangling a function type
2156 // within an overloadable function in C. We mangle these as the absence of any
2157 // parameter types (not even an empty parameter list).
2158 Out << 'F';
2159
2160 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2161
2162 FunctionTypeDepth.enterResultType();
2163 mangleType(T->getReturnType());
2164 FunctionTypeDepth.leaveResultType();
2165
2166 FunctionTypeDepth.pop(saved);
2167 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002168}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002169
Guy Benyei11169dd2012-12-18 14:30:41 +00002170void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2171 bool MangleReturnType) {
2172 // We should never be mangling something without a prototype.
2173 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2174
2175 // Record that we're in a function type. See mangleFunctionParam
2176 // for details on what we're trying to achieve here.
2177 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2178
2179 // <bare-function-type> ::= <signature type>+
2180 if (MangleReturnType) {
2181 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002182 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 FunctionTypeDepth.leaveResultType();
2184 }
2185
Alp Toker9cacbab2014-01-20 20:26:09 +00002186 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 // <builtin-type> ::= v # void
2188 Out << 'v';
2189
2190 FunctionTypeDepth.pop(saved);
2191 return;
2192 }
2193
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002194 for (const auto &Arg : Proto->param_types())
2195 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002196
2197 FunctionTypeDepth.pop(saved);
2198
2199 // <builtin-type> ::= z # ellipsis
2200 if (Proto->isVariadic())
2201 Out << 'z';
2202}
2203
2204// <type> ::= <class-enum-type>
2205// <class-enum-type> ::= <name>
2206void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2207 mangleName(T->getDecl());
2208}
2209
2210// <type> ::= <class-enum-type>
2211// <class-enum-type> ::= <name>
2212void CXXNameMangler::mangleType(const EnumType *T) {
2213 mangleType(static_cast<const TagType*>(T));
2214}
2215void CXXNameMangler::mangleType(const RecordType *T) {
2216 mangleType(static_cast<const TagType*>(T));
2217}
2218void CXXNameMangler::mangleType(const TagType *T) {
2219 mangleName(T->getDecl());
2220}
2221
2222// <type> ::= <array-type>
2223// <array-type> ::= A <positive dimension number> _ <element type>
2224// ::= A [<dimension expression>] _ <element type>
2225void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2226 Out << 'A' << T->getSize() << '_';
2227 mangleType(T->getElementType());
2228}
2229void CXXNameMangler::mangleType(const VariableArrayType *T) {
2230 Out << 'A';
2231 // decayed vla types (size 0) will just be skipped.
2232 if (T->getSizeExpr())
2233 mangleExpression(T->getSizeExpr());
2234 Out << '_';
2235 mangleType(T->getElementType());
2236}
2237void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2238 Out << 'A';
2239 mangleExpression(T->getSizeExpr());
2240 Out << '_';
2241 mangleType(T->getElementType());
2242}
2243void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2244 Out << "A_";
2245 mangleType(T->getElementType());
2246}
2247
2248// <type> ::= <pointer-to-member-type>
2249// <pointer-to-member-type> ::= M <class type> <member type>
2250void CXXNameMangler::mangleType(const MemberPointerType *T) {
2251 Out << 'M';
2252 mangleType(QualType(T->getClass(), 0));
2253 QualType PointeeType = T->getPointeeType();
2254 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2255 mangleType(FPT);
2256
2257 // Itanium C++ ABI 5.1.8:
2258 //
2259 // The type of a non-static member function is considered to be different,
2260 // for the purposes of substitution, from the type of a namespace-scope or
2261 // static member function whose type appears similar. The types of two
2262 // non-static member functions are considered to be different, for the
2263 // purposes of substitution, if the functions are members of different
2264 // classes. In other words, for the purposes of substitution, the class of
2265 // which the function is a member is considered part of the type of
2266 // function.
2267
2268 // Given that we already substitute member function pointers as a
2269 // whole, the net effect of this rule is just to unconditionally
2270 // suppress substitution on the function type in a member pointer.
2271 // We increment the SeqID here to emulate adding an entry to the
2272 // substitution table.
2273 ++SeqID;
2274 } else
2275 mangleType(PointeeType);
2276}
2277
2278// <type> ::= <template-param>
2279void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2280 mangleTemplateParameter(T->getIndex());
2281}
2282
2283// <type> ::= <template-param>
2284void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2285 // FIXME: not clear how to mangle this!
2286 // template <class T...> class A {
2287 // template <class U...> void foo(T(*)(U) x...);
2288 // };
2289 Out << "_SUBSTPACK_";
2290}
2291
2292// <type> ::= P <type> # pointer-to
2293void CXXNameMangler::mangleType(const PointerType *T) {
2294 Out << 'P';
2295 mangleType(T->getPointeeType());
2296}
2297void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2298 Out << 'P';
2299 mangleType(T->getPointeeType());
2300}
2301
2302// <type> ::= R <type> # reference-to
2303void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2304 Out << 'R';
2305 mangleType(T->getPointeeType());
2306}
2307
2308// <type> ::= O <type> # rvalue reference-to (C++0x)
2309void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2310 Out << 'O';
2311 mangleType(T->getPointeeType());
2312}
2313
2314// <type> ::= C <type> # complex pair (C 2000)
2315void CXXNameMangler::mangleType(const ComplexType *T) {
2316 Out << 'C';
2317 mangleType(T->getElementType());
2318}
2319
2320// ARM's ABI for Neon vector types specifies that they should be mangled as
2321// if they are structs (to match ARM's initial implementation). The
2322// vector type must be one of the special types predefined by ARM.
2323void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2324 QualType EltType = T->getElementType();
2325 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002326 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2328 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002329 case BuiltinType::SChar:
2330 case BuiltinType::UChar:
2331 EltName = "poly8_t";
2332 break;
2333 case BuiltinType::Short:
2334 case BuiltinType::UShort:
2335 EltName = "poly16_t";
2336 break;
2337 case BuiltinType::ULongLong:
2338 EltName = "poly64_t";
2339 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2341 }
2342 } else {
2343 switch (cast<BuiltinType>(EltType)->getKind()) {
2344 case BuiltinType::SChar: EltName = "int8_t"; break;
2345 case BuiltinType::UChar: EltName = "uint8_t"; break;
2346 case BuiltinType::Short: EltName = "int16_t"; break;
2347 case BuiltinType::UShort: EltName = "uint16_t"; break;
2348 case BuiltinType::Int: EltName = "int32_t"; break;
2349 case BuiltinType::UInt: EltName = "uint32_t"; break;
2350 case BuiltinType::LongLong: EltName = "int64_t"; break;
2351 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002352 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002354 case BuiltinType::Half: EltName = "float16_t";break;
2355 default:
2356 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 }
2358 }
Craig Topper36250ad2014-05-12 05:36:57 +00002359 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 unsigned BitSize = (T->getNumElements() *
2361 getASTContext().getTypeSize(EltType));
2362 if (BitSize == 64)
2363 BaseName = "__simd64_";
2364 else {
2365 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2366 BaseName = "__simd128_";
2367 }
2368 Out << strlen(BaseName) + strlen(EltName);
2369 Out << BaseName << EltName;
2370}
2371
Tim Northover2fe823a2013-08-01 09:23:19 +00002372static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2373 switch (EltType->getKind()) {
2374 case BuiltinType::SChar:
2375 return "Int8";
2376 case BuiltinType::Short:
2377 return "Int16";
2378 case BuiltinType::Int:
2379 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002380 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002381 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002382 return "Int64";
2383 case BuiltinType::UChar:
2384 return "Uint8";
2385 case BuiltinType::UShort:
2386 return "Uint16";
2387 case BuiltinType::UInt:
2388 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002389 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002390 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002391 return "Uint64";
2392 case BuiltinType::Half:
2393 return "Float16";
2394 case BuiltinType::Float:
2395 return "Float32";
2396 case BuiltinType::Double:
2397 return "Float64";
2398 default:
2399 llvm_unreachable("Unexpected vector element base type");
2400 }
2401}
2402
2403// AArch64's ABI for Neon vector types specifies that they should be mangled as
2404// the equivalent internal name. The vector type must be one of the special
2405// types predefined by ARM.
2406void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2407 QualType EltType = T->getElementType();
2408 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2409 unsigned BitSize =
2410 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002411 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002412
2413 assert((BitSize == 64 || BitSize == 128) &&
2414 "Neon vector type not 64 or 128 bits");
2415
Tim Northover2fe823a2013-08-01 09:23:19 +00002416 StringRef EltName;
2417 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2418 switch (cast<BuiltinType>(EltType)->getKind()) {
2419 case BuiltinType::UChar:
2420 EltName = "Poly8";
2421 break;
2422 case BuiltinType::UShort:
2423 EltName = "Poly16";
2424 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002425 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002426 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002427 EltName = "Poly64";
2428 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002429 default:
2430 llvm_unreachable("unexpected Neon polynomial vector element type");
2431 }
2432 } else
2433 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2434
2435 std::string TypeName =
2436 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2437 Out << TypeName.length() << TypeName;
2438}
2439
Guy Benyei11169dd2012-12-18 14:30:41 +00002440// GNU extension: vector types
2441// <type> ::= <vector-type>
2442// <vector-type> ::= Dv <positive dimension number> _
2443// <extended element type>
2444// ::= Dv [<dimension expression>] _ <element type>
2445// <extended element type> ::= <element type>
2446// ::= p # AltiVec vector pixel
2447// ::= b # Altivec vector bool
2448void CXXNameMangler::mangleType(const VectorType *T) {
2449 if ((T->getVectorKind() == VectorType::NeonVector ||
2450 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002451 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002452 llvm::Triple::ArchType Arch =
2453 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002454 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002455 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002456 mangleAArch64NeonVectorType(T);
2457 else
2458 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 return;
2460 }
2461 Out << "Dv" << T->getNumElements() << '_';
2462 if (T->getVectorKind() == VectorType::AltiVecPixel)
2463 Out << 'p';
2464 else if (T->getVectorKind() == VectorType::AltiVecBool)
2465 Out << 'b';
2466 else
2467 mangleType(T->getElementType());
2468}
2469void CXXNameMangler::mangleType(const ExtVectorType *T) {
2470 mangleType(static_cast<const VectorType*>(T));
2471}
2472void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2473 Out << "Dv";
2474 mangleExpression(T->getSizeExpr());
2475 Out << '_';
2476 mangleType(T->getElementType());
2477}
2478
2479void CXXNameMangler::mangleType(const PackExpansionType *T) {
2480 // <type> ::= Dp <type> # pack expansion (C++0x)
2481 Out << "Dp";
2482 mangleType(T->getPattern());
2483}
2484
2485void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2486 mangleSourceName(T->getDecl()->getIdentifier());
2487}
2488
2489void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002490 // Treat __kindof as a vendor extended type qualifier.
2491 if (T->isKindOfType())
2492 Out << "U8__kindof";
2493
Eli Friedman5f508952013-06-18 22:41:37 +00002494 if (!T->qual_empty()) {
2495 // Mangle protocol qualifiers.
2496 SmallString<64> QualStr;
2497 llvm::raw_svector_ostream QualOS(QualStr);
2498 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002499 for (const auto *I : T->quals()) {
2500 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002501 QualOS << name.size() << name;
2502 }
Eli Friedman5f508952013-06-18 22:41:37 +00002503 Out << 'U' << QualStr.size() << QualStr;
2504 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002505
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002507
2508 if (T->isSpecialized()) {
2509 // Mangle type arguments as I <type>+ E
2510 Out << 'I';
2511 for (auto typeArg : T->getTypeArgs())
2512 mangleType(typeArg);
2513 Out << 'E';
2514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002515}
2516
2517void CXXNameMangler::mangleType(const BlockPointerType *T) {
2518 Out << "U13block_pointer";
2519 mangleType(T->getPointeeType());
2520}
2521
2522void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2523 // Mangle injected class name types as if the user had written the
2524 // specialization out fully. It may not actually be possible to see
2525 // this mangling, though.
2526 mangleType(T->getInjectedSpecializationType());
2527}
2528
2529void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2530 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2531 mangleName(TD, T->getArgs(), T->getNumArgs());
2532 } else {
2533 if (mangleSubstitution(QualType(T, 0)))
2534 return;
2535
2536 mangleTemplatePrefix(T->getTemplateName());
2537
2538 // FIXME: GCC does not appear to mangle the template arguments when
2539 // the template in question is a dependent template name. Should we
2540 // emulate that badness?
2541 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2542 addSubstitution(QualType(T, 0));
2543 }
2544}
2545
2546void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002547 // Proposal by cxx-abi-dev, 2014-03-26
2548 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2549 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002550 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002551 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002552 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002553 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002554 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002555 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002556 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002557 switch (T->getKeyword()) {
2558 case ETK_Typename:
2559 break;
2560 case ETK_Struct:
2561 case ETK_Class:
2562 case ETK_Interface:
2563 Out << "Ts";
2564 break;
2565 case ETK_Union:
2566 Out << "Tu";
2567 break;
2568 case ETK_Enum:
2569 Out << "Te";
2570 break;
2571 default:
2572 llvm_unreachable("unexpected keyword for dependent type name");
2573 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002574 // Typename types are always nested
2575 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002577 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 Out << 'E';
2579}
2580
2581void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2582 // Dependently-scoped template types are nested if they have a prefix.
2583 Out << 'N';
2584
2585 // TODO: avoid making this TemplateName.
2586 TemplateName Prefix =
2587 getASTContext().getDependentTemplateName(T->getQualifier(),
2588 T->getIdentifier());
2589 mangleTemplatePrefix(Prefix);
2590
2591 // FIXME: GCC does not appear to mangle the template arguments when
2592 // the template in question is a dependent template name. Should we
2593 // emulate that badness?
2594 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2595 Out << 'E';
2596}
2597
2598void CXXNameMangler::mangleType(const TypeOfType *T) {
2599 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2600 // "extension with parameters" mangling.
2601 Out << "u6typeof";
2602}
2603
2604void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2605 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2606 // "extension with parameters" mangling.
2607 Out << "u6typeof";
2608}
2609
2610void CXXNameMangler::mangleType(const DecltypeType *T) {
2611 Expr *E = T->getUnderlyingExpr();
2612
2613 // type ::= Dt <expression> E # decltype of an id-expression
2614 // # or class member access
2615 // ::= DT <expression> E # decltype of an expression
2616
2617 // This purports to be an exhaustive list of id-expressions and
2618 // class member accesses. Note that we do not ignore parentheses;
2619 // parentheses change the semantics of decltype for these
2620 // expressions (and cause the mangler to use the other form).
2621 if (isa<DeclRefExpr>(E) ||
2622 isa<MemberExpr>(E) ||
2623 isa<UnresolvedLookupExpr>(E) ||
2624 isa<DependentScopeDeclRefExpr>(E) ||
2625 isa<CXXDependentScopeMemberExpr>(E) ||
2626 isa<UnresolvedMemberExpr>(E))
2627 Out << "Dt";
2628 else
2629 Out << "DT";
2630 mangleExpression(E);
2631 Out << 'E';
2632}
2633
2634void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2635 // If this is dependent, we need to record that. If not, we simply
2636 // mangle it as the underlying type since they are equivalent.
2637 if (T->isDependentType()) {
2638 Out << 'U';
2639
2640 switch (T->getUTTKind()) {
2641 case UnaryTransformType::EnumUnderlyingType:
2642 Out << "3eut";
2643 break;
2644 }
2645 }
2646
2647 mangleType(T->getUnderlyingType());
2648}
2649
2650void CXXNameMangler::mangleType(const AutoType *T) {
2651 QualType D = T->getDeducedType();
2652 // <builtin-type> ::= Da # dependent auto
2653 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002654 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 else
2656 mangleType(D);
2657}
2658
2659void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002660 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 // (Until there's a standardized mangling...)
2662 Out << "U7_Atomic";
2663 mangleType(T->getValueType());
2664}
2665
2666void CXXNameMangler::mangleIntegerLiteral(QualType T,
2667 const llvm::APSInt &Value) {
2668 // <expr-primary> ::= L <type> <value number> E # integer literal
2669 Out << 'L';
2670
2671 mangleType(T);
2672 if (T->isBooleanType()) {
2673 // Boolean values are encoded as 0/1.
2674 Out << (Value.getBoolValue() ? '1' : '0');
2675 } else {
2676 mangleNumber(Value);
2677 }
2678 Out << 'E';
2679
2680}
2681
David Majnemer1dabfdc2015-02-14 13:23:54 +00002682void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2683 // Ignore member expressions involving anonymous unions.
2684 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2685 if (!RT->getDecl()->isAnonymousStructOrUnion())
2686 break;
2687 const auto *ME = dyn_cast<MemberExpr>(Base);
2688 if (!ME)
2689 break;
2690 Base = ME->getBase();
2691 IsArrow = ME->isArrow();
2692 }
2693
2694 if (Base->isImplicitCXXThis()) {
2695 // Note: GCC mangles member expressions to the implicit 'this' as
2696 // *this., whereas we represent them as this->. The Itanium C++ ABI
2697 // does not specify anything here, so we follow GCC.
2698 Out << "dtdefpT";
2699 } else {
2700 Out << (IsArrow ? "pt" : "dt");
2701 mangleExpression(Base);
2702 }
2703}
2704
Guy Benyei11169dd2012-12-18 14:30:41 +00002705/// Mangles a member expression.
2706void CXXNameMangler::mangleMemberExpr(const Expr *base,
2707 bool isArrow,
2708 NestedNameSpecifier *qualifier,
2709 NamedDecl *firstQualifierLookup,
2710 DeclarationName member,
2711 unsigned arity) {
2712 // <expression> ::= dt <expression> <unresolved-name>
2713 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002714 if (base)
2715 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002716 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002717}
2718
2719/// Look at the callee of the given call expression and determine if
2720/// it's a parenthesized id-expression which would have triggered ADL
2721/// otherwise.
2722static bool isParenthesizedADLCallee(const CallExpr *call) {
2723 const Expr *callee = call->getCallee();
2724 const Expr *fn = callee->IgnoreParens();
2725
2726 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2727 // too, but for those to appear in the callee, it would have to be
2728 // parenthesized.
2729 if (callee == fn) return false;
2730
2731 // Must be an unresolved lookup.
2732 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2733 if (!lookup) return false;
2734
2735 assert(!lookup->requiresADL());
2736
2737 // Must be an unqualified lookup.
2738 if (lookup->getQualifier()) return false;
2739
2740 // Must not have found a class member. Note that if one is a class
2741 // member, they're all class members.
2742 if (lookup->getNumDecls() > 0 &&
2743 (*lookup->decls_begin())->isCXXClassMember())
2744 return false;
2745
2746 // Otherwise, ADL would have been triggered.
2747 return true;
2748}
2749
David Majnemer9c775c72014-09-23 04:27:55 +00002750void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2751 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2752 Out << CastEncoding;
2753 mangleType(ECE->getType());
2754 mangleExpression(ECE->getSubExpr());
2755}
2756
Richard Smith520449d2015-02-05 06:15:50 +00002757void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2758 if (auto *Syntactic = InitList->getSyntacticForm())
2759 InitList = Syntactic;
2760 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2761 mangleExpression(InitList->getInit(i));
2762}
2763
Guy Benyei11169dd2012-12-18 14:30:41 +00002764void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2765 // <expression> ::= <unary operator-name> <expression>
2766 // ::= <binary operator-name> <expression> <expression>
2767 // ::= <trinary operator-name> <expression> <expression> <expression>
2768 // ::= cv <type> expression # conversion with one argument
2769 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002770 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2771 // ::= sc <type> <expression> # static_cast<type> (expression)
2772 // ::= cc <type> <expression> # const_cast<type> (expression)
2773 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 // ::= st <type> # sizeof (a type)
2775 // ::= at <type> # alignof (a type)
2776 // ::= <template-param>
2777 // ::= <function-param>
2778 // ::= sr <type> <unqualified-name> # dependent name
2779 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2780 // ::= ds <expression> <expression> # expr.*expr
2781 // ::= sZ <template-param> # size of a parameter pack
2782 // ::= sZ <function-param> # size of a function parameter pack
2783 // ::= <expr-primary>
2784 // <expr-primary> ::= L <type> <value number> E # integer literal
2785 // ::= L <type <value float> E # floating literal
2786 // ::= L <mangled-name> E # external name
2787 // ::= fpT # 'this' expression
2788 QualType ImplicitlyConvertedToType;
2789
2790recurse:
2791 switch (E->getStmtClass()) {
2792 case Expr::NoStmtClass:
2793#define ABSTRACT_STMT(Type)
2794#define EXPR(Type, Base)
2795#define STMT(Type, Base) \
2796 case Expr::Type##Class:
2797#include "clang/AST/StmtNodes.inc"
2798 // fallthrough
2799
2800 // These all can only appear in local or variable-initialization
2801 // contexts and so should never appear in a mangling.
2802 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002803 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002805 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 case Expr::ParenListExprClass:
2807 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002808 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002809 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002810 case Expr::OMPArraySectionExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 llvm_unreachable("unexpected statement kind");
2812
2813 // FIXME: invent manglings for all these.
2814 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 case Expr::ChooseExprClass:
2816 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002817 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 case Expr::ExtVectorElementExprClass:
2819 case Expr::GenericSelectionExprClass:
2820 case Expr::ObjCEncodeExprClass:
2821 case Expr::ObjCIsaExprClass:
2822 case Expr::ObjCIvarRefExprClass:
2823 case Expr::ObjCMessageExprClass:
2824 case Expr::ObjCPropertyRefExprClass:
2825 case Expr::ObjCProtocolExprClass:
2826 case Expr::ObjCSelectorExprClass:
2827 case Expr::ObjCStringLiteralClass:
2828 case Expr::ObjCBoxedExprClass:
2829 case Expr::ObjCArrayLiteralClass:
2830 case Expr::ObjCDictionaryLiteralClass:
2831 case Expr::ObjCSubscriptRefExprClass:
2832 case Expr::ObjCIndirectCopyRestoreExprClass:
2833 case Expr::OffsetOfExprClass:
2834 case Expr::PredefinedExprClass:
2835 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002836 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 case Expr::TypeTraitExprClass:
2839 case Expr::ArrayTypeTraitExprClass:
2840 case Expr::ExpressionTraitExprClass:
2841 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 case Expr::CUDAKernelCallExprClass:
2843 case Expr::AsTypeExprClass:
2844 case Expr::PseudoObjectExprClass:
2845 case Expr::AtomicExprClass:
2846 {
2847 // As bad as this diagnostic is, it's better than crashing.
2848 DiagnosticsEngine &Diags = Context.getDiags();
2849 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2850 "cannot yet mangle expression type %0");
2851 Diags.Report(E->getExprLoc(), DiagID)
2852 << E->getStmtClassName() << E->getSourceRange();
2853 break;
2854 }
2855
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002856 case Expr::CXXUuidofExprClass: {
2857 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2858 if (UE->isTypeOperand()) {
2859 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2860 Out << "u8__uuidoft";
2861 mangleType(UuidT);
2862 } else {
2863 Expr *UuidExp = UE->getExprOperand();
2864 Out << "u8__uuidofz";
2865 mangleExpression(UuidExp, Arity);
2866 }
2867 break;
2868 }
2869
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 // Even gcc-4.5 doesn't mangle this.
2871 case Expr::BinaryConditionalOperatorClass: {
2872 DiagnosticsEngine &Diags = Context.getDiags();
2873 unsigned DiagID =
2874 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2875 "?: operator with omitted middle operand cannot be mangled");
2876 Diags.Report(E->getExprLoc(), DiagID)
2877 << E->getStmtClassName() << E->getSourceRange();
2878 break;
2879 }
2880
2881 // These are used for internal purposes and cannot be meaningfully mangled.
2882 case Expr::OpaqueValueExprClass:
2883 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2884
2885 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002887 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 Out << "E";
2889 break;
2890 }
2891
2892 case Expr::CXXDefaultArgExprClass:
2893 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2894 break;
2895
Richard Smith852c9db2013-04-20 22:23:05 +00002896 case Expr::CXXDefaultInitExprClass:
2897 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2898 break;
2899
Richard Smithcc1b96d2013-06-12 22:31:48 +00002900 case Expr::CXXStdInitializerListExprClass:
2901 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2902 break;
2903
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 case Expr::SubstNonTypeTemplateParmExprClass:
2905 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2906 Arity);
2907 break;
2908
2909 case Expr::UserDefinedLiteralClass:
2910 // We follow g++'s approach of mangling a UDL as a call to the literal
2911 // operator.
2912 case Expr::CXXMemberCallExprClass: // fallthrough
2913 case Expr::CallExprClass: {
2914 const CallExpr *CE = cast<CallExpr>(E);
2915
2916 // <expression> ::= cp <simple-id> <expression>* E
2917 // We use this mangling only when the call would use ADL except
2918 // for being parenthesized. Per discussion with David
2919 // Vandervoorde, 2011.04.25.
2920 if (isParenthesizedADLCallee(CE)) {
2921 Out << "cp";
2922 // The callee here is a parenthesized UnresolvedLookupExpr with
2923 // no qualifier and should always get mangled as a <simple-id>
2924 // anyway.
2925
2926 // <expression> ::= cl <expression>* E
2927 } else {
2928 Out << "cl";
2929 }
2930
David Majnemer67a8ec62015-02-19 21:41:48 +00002931 unsigned CallArity = CE->getNumArgs();
2932 for (const Expr *Arg : CE->arguments())
2933 if (isa<PackExpansionExpr>(Arg))
2934 CallArity = UnknownArity;
2935
2936 mangleExpression(CE->getCallee(), CallArity);
2937 for (const Expr *Arg : CE->arguments())
2938 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 Out << 'E';
2940 break;
2941 }
2942
2943 case Expr::CXXNewExprClass: {
2944 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2945 if (New->isGlobalNew()) Out << "gs";
2946 Out << (New->isArray() ? "na" : "nw");
2947 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2948 E = New->placement_arg_end(); I != E; ++I)
2949 mangleExpression(*I);
2950 Out << '_';
2951 mangleType(New->getAllocatedType());
2952 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2954 Out << "il";
2955 else
2956 Out << "pi";
2957 const Expr *Init = New->getInitializer();
2958 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2959 // Directly inline the initializers.
2960 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2961 E = CCE->arg_end();
2962 I != E; ++I)
2963 mangleExpression(*I);
2964 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2965 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2966 mangleExpression(PLE->getExpr(i));
2967 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2968 isa<InitListExpr>(Init)) {
2969 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002970 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 } else
2972 mangleExpression(Init);
2973 }
2974 Out << 'E';
2975 break;
2976 }
2977
David Majnemer1dabfdc2015-02-14 13:23:54 +00002978 case Expr::CXXPseudoDestructorExprClass: {
2979 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2980 if (const Expr *Base = PDE->getBase())
2981 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00002982 NestedNameSpecifier *Qualifier = PDE->getQualifier();
2983 QualType ScopeType;
2984 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
2985 if (Qualifier) {
2986 mangleUnresolvedPrefix(Qualifier,
2987 /*Recursive=*/true);
2988 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
2989 Out << 'E';
2990 } else {
2991 Out << "sr";
2992 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
2993 Out << 'E';
2994 }
2995 } else if (Qualifier) {
2996 mangleUnresolvedPrefix(Qualifier);
2997 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00002998 // <base-unresolved-name> ::= dn <destructor-name>
2999 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003000 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003001 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003002 break;
3003 }
3004
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 case Expr::MemberExprClass: {
3006 const MemberExpr *ME = cast<MemberExpr>(E);
3007 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003008 ME->getQualifier(), nullptr,
3009 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 break;
3011 }
3012
3013 case Expr::UnresolvedMemberExprClass: {
3014 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003015 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3016 ME->isArrow(), ME->getQualifier(), nullptr,
3017 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 if (ME->hasExplicitTemplateArgs())
3019 mangleTemplateArgs(ME->getExplicitTemplateArgs());
3020 break;
3021 }
3022
3023 case Expr::CXXDependentScopeMemberExprClass: {
3024 const CXXDependentScopeMemberExpr *ME
3025 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003026 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3027 ME->isArrow(), ME->getQualifier(),
3028 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 ME->getMember(), Arity);
3030 if (ME->hasExplicitTemplateArgs())
3031 mangleTemplateArgs(ME->getExplicitTemplateArgs());
3032 break;
3033 }
3034
3035 case Expr::UnresolvedLookupExprClass: {
3036 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003037 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003038
3039 // All the <unresolved-name> productions end in a
3040 // base-unresolved-name, where <template-args> are just tacked
3041 // onto the end.
3042 if (ULE->hasExplicitTemplateArgs())
3043 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
3044 break;
3045 }
3046
3047 case Expr::CXXUnresolvedConstructExprClass: {
3048 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3049 unsigned N = CE->arg_size();
3050
3051 Out << "cv";
3052 mangleType(CE->getType());
3053 if (N != 1) Out << '_';
3054 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3055 if (N != 1) Out << 'E';
3056 break;
3057 }
3058
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003060 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003061 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003062 assert(
3063 CE->getNumArgs() >= 1 &&
3064 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3065 "implicit CXXConstructExpr must have one argument");
3066 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3067 }
3068 Out << "il";
3069 for (auto *E : CE->arguments())
3070 mangleExpression(E);
3071 Out << "E";
3072 break;
3073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003074
Richard Smith520449d2015-02-05 06:15:50 +00003075 case Expr::CXXTemporaryObjectExprClass: {
3076 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3077 unsigned N = CE->getNumArgs();
3078 bool List = CE->isListInitialization();
3079
3080 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 Out << "tl";
3082 else
3083 Out << "cv";
3084 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003085 if (!List && N != 1)
3086 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003087 if (CE->isStdInitListInitialization()) {
3088 // We implicitly created a std::initializer_list<T> for the first argument
3089 // of a constructor of type U in an expression of the form U{a, b, c}.
3090 // Strip all the semantic gunk off the initializer list.
3091 auto *SILE =
3092 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3093 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3094 mangleInitListElements(ILE);
3095 } else {
3096 for (auto *E : CE->arguments())
3097 mangleExpression(E);
3098 }
Richard Smith520449d2015-02-05 06:15:50 +00003099 if (List || N != 1)
3100 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 break;
3102 }
3103
3104 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003105 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003107 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 break;
3109
3110 case Expr::CXXNoexceptExprClass:
3111 Out << "nx";
3112 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3113 break;
3114
3115 case Expr::UnaryExprOrTypeTraitExprClass: {
3116 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3117
3118 if (!SAE->isInstantiationDependent()) {
3119 // Itanium C++ ABI:
3120 // If the operand of a sizeof or alignof operator is not
3121 // instantiation-dependent it is encoded as an integer literal
3122 // reflecting the result of the operator.
3123 //
3124 // If the result of the operator is implicitly converted to a known
3125 // integer type, that type is used for the literal; otherwise, the type
3126 // of std::size_t or std::ptrdiff_t is used.
3127 QualType T = (ImplicitlyConvertedToType.isNull() ||
3128 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3129 : ImplicitlyConvertedToType;
3130 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3131 mangleIntegerLiteral(T, V);
3132 break;
3133 }
3134
3135 switch(SAE->getKind()) {
3136 case UETT_SizeOf:
3137 Out << 's';
3138 break;
3139 case UETT_AlignOf:
3140 Out << 'a';
3141 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003142 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 DiagnosticsEngine &Diags = Context.getDiags();
3144 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3145 "cannot yet mangle vec_step expression");
3146 Diags.Report(DiagID);
3147 return;
3148 }
Alexey Bataev00396512015-07-02 03:40:19 +00003149 case UETT_OpenMPRequiredSimdAlign:
3150 DiagnosticsEngine &Diags = Context.getDiags();
3151 unsigned DiagID = Diags.getCustomDiagID(
3152 DiagnosticsEngine::Error,
3153 "cannot yet mangle __builtin_omp_required_simd_align expression");
3154 Diags.Report(DiagID);
3155 return;
3156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 if (SAE->isArgumentType()) {
3158 Out << 't';
3159 mangleType(SAE->getArgumentType());
3160 } else {
3161 Out << 'z';
3162 mangleExpression(SAE->getArgumentExpr());
3163 }
3164 break;
3165 }
3166
3167 case Expr::CXXThrowExprClass: {
3168 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003169 // <expression> ::= tw <expression> # throw expression
3170 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 if (TE->getSubExpr()) {
3172 Out << "tw";
3173 mangleExpression(TE->getSubExpr());
3174 } else {
3175 Out << "tr";
3176 }
3177 break;
3178 }
3179
3180 case Expr::CXXTypeidExprClass: {
3181 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003182 // <expression> ::= ti <type> # typeid (type)
3183 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 if (TIE->isTypeOperand()) {
3185 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003186 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 } else {
3188 Out << "te";
3189 mangleExpression(TIE->getExprOperand());
3190 }
3191 break;
3192 }
3193
3194 case Expr::CXXDeleteExprClass: {
3195 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003196 // <expression> ::= [gs] dl <expression> # [::] delete expr
3197 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 if (DE->isGlobalDelete()) Out << "gs";
3199 Out << (DE->isArrayForm() ? "da" : "dl");
3200 mangleExpression(DE->getArgument());
3201 break;
3202 }
3203
3204 case Expr::UnaryOperatorClass: {
3205 const UnaryOperator *UO = cast<UnaryOperator>(E);
3206 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3207 /*Arity=*/1);
3208 mangleExpression(UO->getSubExpr());
3209 break;
3210 }
3211
3212 case Expr::ArraySubscriptExprClass: {
3213 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3214
3215 // Array subscript is treated as a syntactically weird form of
3216 // binary operator.
3217 Out << "ix";
3218 mangleExpression(AE->getLHS());
3219 mangleExpression(AE->getRHS());
3220 break;
3221 }
3222
3223 case Expr::CompoundAssignOperatorClass: // fallthrough
3224 case Expr::BinaryOperatorClass: {
3225 const BinaryOperator *BO = cast<BinaryOperator>(E);
3226 if (BO->getOpcode() == BO_PtrMemD)
3227 Out << "ds";
3228 else
3229 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3230 /*Arity=*/2);
3231 mangleExpression(BO->getLHS());
3232 mangleExpression(BO->getRHS());
3233 break;
3234 }
3235
3236 case Expr::ConditionalOperatorClass: {
3237 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3238 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3239 mangleExpression(CO->getCond());
3240 mangleExpression(CO->getLHS(), Arity);
3241 mangleExpression(CO->getRHS(), Arity);
3242 break;
3243 }
3244
3245 case Expr::ImplicitCastExprClass: {
3246 ImplicitlyConvertedToType = E->getType();
3247 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3248 goto recurse;
3249 }
3250
3251 case Expr::ObjCBridgedCastExprClass: {
3252 // Mangle ownership casts as a vendor extended operator __bridge,
3253 // __bridge_transfer, or __bridge_retain.
3254 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3255 Out << "v1U" << Kind.size() << Kind;
3256 }
3257 // Fall through to mangle the cast itself.
3258
3259 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003260 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003262
Richard Smith520449d2015-02-05 06:15:50 +00003263 case Expr::CXXFunctionalCastExprClass: {
3264 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3265 // FIXME: Add isImplicit to CXXConstructExpr.
3266 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3267 if (CCE->getParenOrBraceRange().isInvalid())
3268 Sub = CCE->getArg(0)->IgnoreImplicit();
3269 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3270 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3271 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3272 Out << "tl";
3273 mangleType(E->getType());
3274 mangleInitListElements(IL);
3275 Out << "E";
3276 } else {
3277 mangleCastExpression(E, "cv");
3278 }
3279 break;
3280 }
3281
David Majnemer9c775c72014-09-23 04:27:55 +00003282 case Expr::CXXStaticCastExprClass:
3283 mangleCastExpression(E, "sc");
3284 break;
3285 case Expr::CXXDynamicCastExprClass:
3286 mangleCastExpression(E, "dc");
3287 break;
3288 case Expr::CXXReinterpretCastExprClass:
3289 mangleCastExpression(E, "rc");
3290 break;
3291 case Expr::CXXConstCastExprClass:
3292 mangleCastExpression(E, "cc");
3293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003294
3295 case Expr::CXXOperatorCallExprClass: {
3296 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3297 unsigned NumArgs = CE->getNumArgs();
3298 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3299 // Mangle the arguments.
3300 for (unsigned i = 0; i != NumArgs; ++i)
3301 mangleExpression(CE->getArg(i));
3302 break;
3303 }
3304
3305 case Expr::ParenExprClass:
3306 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3307 break;
3308
3309 case Expr::DeclRefExprClass: {
3310 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3311
3312 switch (D->getKind()) {
3313 default:
3314 // <expr-primary> ::= L <mangled-name> E # external name
3315 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003316 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 Out << 'E';
3318 break;
3319
3320 case Decl::ParmVar:
3321 mangleFunctionParam(cast<ParmVarDecl>(D));
3322 break;
3323
3324 case Decl::EnumConstant: {
3325 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3326 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3327 break;
3328 }
3329
3330 case Decl::NonTypeTemplateParm: {
3331 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3332 mangleTemplateParameter(PD->getIndex());
3333 break;
3334 }
3335
3336 }
3337
3338 break;
3339 }
3340
3341 case Expr::SubstNonTypeTemplateParmPackExprClass:
3342 // FIXME: not clear how to mangle this!
3343 // template <unsigned N...> class A {
3344 // template <class U...> void foo(U (&x)[N]...);
3345 // };
3346 Out << "_SUBSTPACK_";
3347 break;
3348
3349 case Expr::FunctionParmPackExprClass: {
3350 // FIXME: not clear how to mangle this!
3351 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3352 Out << "v110_SUBSTPACK";
3353 mangleFunctionParam(FPPE->getParameterPack());
3354 break;
3355 }
3356
3357 case Expr::DependentScopeDeclRefExprClass: {
3358 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003359 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003360
3361 // All the <unresolved-name> productions end in a
3362 // base-unresolved-name, where <template-args> are just tacked
3363 // onto the end.
3364 if (DRE->hasExplicitTemplateArgs())
3365 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3366 break;
3367 }
3368
3369 case Expr::CXXBindTemporaryExprClass:
3370 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3371 break;
3372
3373 case Expr::ExprWithCleanupsClass:
3374 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3375 break;
3376
3377 case Expr::FloatingLiteralClass: {
3378 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3379 Out << 'L';
3380 mangleType(FL->getType());
3381 mangleFloat(FL->getValue());
3382 Out << 'E';
3383 break;
3384 }
3385
3386 case Expr::CharacterLiteralClass:
3387 Out << 'L';
3388 mangleType(E->getType());
3389 Out << cast<CharacterLiteral>(E)->getValue();
3390 Out << 'E';
3391 break;
3392
3393 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3394 case Expr::ObjCBoolLiteralExprClass:
3395 Out << "Lb";
3396 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3397 Out << 'E';
3398 break;
3399
3400 case Expr::CXXBoolLiteralExprClass:
3401 Out << "Lb";
3402 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3403 Out << 'E';
3404 break;
3405
3406 case Expr::IntegerLiteralClass: {
3407 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3408 if (E->getType()->isSignedIntegerType())
3409 Value.setIsSigned(true);
3410 mangleIntegerLiteral(E->getType(), Value);
3411 break;
3412 }
3413
3414 case Expr::ImaginaryLiteralClass: {
3415 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3416 // Mangle as if a complex literal.
3417 // Proposal from David Vandevoorde, 2010.06.30.
3418 Out << 'L';
3419 mangleType(E->getType());
3420 if (const FloatingLiteral *Imag =
3421 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3422 // Mangle a floating-point zero of the appropriate type.
3423 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3424 Out << '_';
3425 mangleFloat(Imag->getValue());
3426 } else {
3427 Out << "0_";
3428 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3429 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3430 Value.setIsSigned(true);
3431 mangleNumber(Value);
3432 }
3433 Out << 'E';
3434 break;
3435 }
3436
3437 case Expr::StringLiteralClass: {
3438 // Revised proposal from David Vandervoorde, 2010.07.15.
3439 Out << 'L';
3440 assert(isa<ConstantArrayType>(E->getType()));
3441 mangleType(E->getType());
3442 Out << 'E';
3443 break;
3444 }
3445
3446 case Expr::GNUNullExprClass:
3447 // FIXME: should this really be mangled the same as nullptr?
3448 // fallthrough
3449
3450 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003451 Out << "LDnE";
3452 break;
3453 }
3454
3455 case Expr::PackExpansionExprClass:
3456 Out << "sp";
3457 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3458 break;
3459
3460 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003461 auto *SPE = cast<SizeOfPackExpr>(E);
3462 if (SPE->isPartiallySubstituted()) {
3463 Out << "sP";
3464 for (const auto &A : SPE->getPartialArguments())
3465 mangleTemplateArg(A);
3466 Out << "E";
3467 break;
3468 }
3469
Guy Benyei11169dd2012-12-18 14:30:41 +00003470 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003471 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3473 mangleTemplateParameter(TTP->getIndex());
3474 else if (const NonTypeTemplateParmDecl *NTTP
3475 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3476 mangleTemplateParameter(NTTP->getIndex());
3477 else if (const TemplateTemplateParmDecl *TempTP
3478 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3479 mangleTemplateParameter(TempTP->getIndex());
3480 else
3481 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3482 break;
3483 }
Richard Smith0f0af192014-11-08 05:07:16 +00003484
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 case Expr::MaterializeTemporaryExprClass: {
3486 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3487 break;
3488 }
Richard Smith0f0af192014-11-08 05:07:16 +00003489
3490 case Expr::CXXFoldExprClass: {
3491 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003492 if (FE->isLeftFold())
3493 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003494 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003495 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003496
3497 if (FE->getOperator() == BO_PtrMemD)
3498 Out << "ds";
3499 else
3500 mangleOperatorName(
3501 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3502 /*Arity=*/2);
3503
3504 if (FE->getLHS())
3505 mangleExpression(FE->getLHS());
3506 if (FE->getRHS())
3507 mangleExpression(FE->getRHS());
3508 break;
3509 }
3510
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 case Expr::CXXThisExprClass:
3512 Out << "fpT";
3513 break;
3514 }
3515}
3516
3517/// Mangle an expression which refers to a parameter variable.
3518///
3519/// <expression> ::= <function-param>
3520/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3521/// <function-param> ::= fp <top-level CV-qualifiers>
3522/// <parameter-2 non-negative number> _ # L == 0, I > 0
3523/// <function-param> ::= fL <L-1 non-negative number>
3524/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3525/// <function-param> ::= fL <L-1 non-negative number>
3526/// p <top-level CV-qualifiers>
3527/// <I-1 non-negative number> _ # L > 0, I > 0
3528///
3529/// L is the nesting depth of the parameter, defined as 1 if the
3530/// parameter comes from the innermost function prototype scope
3531/// enclosing the current context, 2 if from the next enclosing
3532/// function prototype scope, and so on, with one special case: if
3533/// we've processed the full parameter clause for the innermost
3534/// function type, then L is one less. This definition conveniently
3535/// makes it irrelevant whether a function's result type was written
3536/// trailing or leading, but is otherwise overly complicated; the
3537/// numbering was first designed without considering references to
3538/// parameter in locations other than return types, and then the
3539/// mangling had to be generalized without changing the existing
3540/// manglings.
3541///
3542/// I is the zero-based index of the parameter within its parameter
3543/// declaration clause. Note that the original ABI document describes
3544/// this using 1-based ordinals.
3545void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3546 unsigned parmDepth = parm->getFunctionScopeDepth();
3547 unsigned parmIndex = parm->getFunctionScopeIndex();
3548
3549 // Compute 'L'.
3550 // parmDepth does not include the declaring function prototype.
3551 // FunctionTypeDepth does account for that.
3552 assert(parmDepth < FunctionTypeDepth.getDepth());
3553 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3554 if (FunctionTypeDepth.isInResultType())
3555 nestingDepth--;
3556
3557 if (nestingDepth == 0) {
3558 Out << "fp";
3559 } else {
3560 Out << "fL" << (nestingDepth - 1) << 'p';
3561 }
3562
3563 // Top-level qualifiers. We don't have to worry about arrays here,
3564 // because parameters declared as arrays should already have been
3565 // transformed to have pointer type. FIXME: apparently these don't
3566 // get mangled if used as an rvalue of a known non-class type?
3567 assert(!parm->getType()->isArrayType()
3568 && "parameter's type is still an array type?");
3569 mangleQualifiers(parm->getType().getQualifiers());
3570
3571 // Parameter index.
3572 if (parmIndex != 0) {
3573 Out << (parmIndex - 1);
3574 }
3575 Out << '_';
3576}
3577
3578void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3579 // <ctor-dtor-name> ::= C1 # complete object constructor
3580 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003582 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 switch (T) {
3584 case Ctor_Complete:
3585 Out << "C1";
3586 break;
3587 case Ctor_Base:
3588 Out << "C2";
3589 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003590 case Ctor_Comdat:
3591 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003593 case Ctor_DefaultClosure:
3594 case Ctor_CopyingClosure:
3595 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 }
3597}
3598
3599void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3600 // <ctor-dtor-name> ::= D0 # deleting destructor
3601 // ::= D1 # complete object destructor
3602 // ::= D2 # base object destructor
3603 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003604 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 switch (T) {
3606 case Dtor_Deleting:
3607 Out << "D0";
3608 break;
3609 case Dtor_Complete:
3610 Out << "D1";
3611 break;
3612 case Dtor_Base:
3613 Out << "D2";
3614 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003615 case Dtor_Comdat:
3616 Out << "D5";
3617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 }
3619}
3620
3621void CXXNameMangler::mangleTemplateArgs(
3622 const ASTTemplateArgumentListInfo &TemplateArgs) {
3623 // <template-args> ::= I <template-arg>+ E
3624 Out << 'I';
3625 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3626 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3627 Out << 'E';
3628}
3629
3630void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3631 // <template-args> ::= I <template-arg>+ E
3632 Out << 'I';
3633 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3634 mangleTemplateArg(AL[i]);
3635 Out << 'E';
3636}
3637
3638void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3639 unsigned NumTemplateArgs) {
3640 // <template-args> ::= I <template-arg>+ E
3641 Out << 'I';
3642 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3643 mangleTemplateArg(TemplateArgs[i]);
3644 Out << 'E';
3645}
3646
3647void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3648 // <template-arg> ::= <type> # type or template
3649 // ::= X <expression> E # expression
3650 // ::= <expr-primary> # simple expressions
3651 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 if (!A.isInstantiationDependent() || A.isDependent())
3653 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3654
3655 switch (A.getKind()) {
3656 case TemplateArgument::Null:
3657 llvm_unreachable("Cannot mangle NULL template argument");
3658
3659 case TemplateArgument::Type:
3660 mangleType(A.getAsType());
3661 break;
3662 case TemplateArgument::Template:
3663 // This is mangled as <type>.
3664 mangleType(A.getAsTemplate());
3665 break;
3666 case TemplateArgument::TemplateExpansion:
3667 // <type> ::= Dp <type> # pack expansion (C++0x)
3668 Out << "Dp";
3669 mangleType(A.getAsTemplateOrTemplatePattern());
3670 break;
3671 case TemplateArgument::Expression: {
3672 // It's possible to end up with a DeclRefExpr here in certain
3673 // dependent cases, in which case we should mangle as a
3674 // declaration.
3675 const Expr *E = A.getAsExpr()->IgnoreParens();
3676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3677 const ValueDecl *D = DRE->getDecl();
3678 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003679 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003680 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 Out << 'E';
3682 break;
3683 }
3684 }
3685
3686 Out << 'X';
3687 mangleExpression(E);
3688 Out << 'E';
3689 break;
3690 }
3691 case TemplateArgument::Integral:
3692 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3693 break;
3694 case TemplateArgument::Declaration: {
3695 // <expr-primary> ::= L <mangled-name> E # external name
3696 // Clang produces AST's where pointer-to-member-function expressions
3697 // and pointer-to-function expressions are represented as a declaration not
3698 // an expression. We compensate for it here to produce the correct mangling.
3699 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003700 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 if (compensateMangling) {
3702 Out << 'X';
3703 mangleOperatorName(OO_Amp, 1);
3704 }
3705
3706 Out << 'L';
3707 // References to external entities use the mangled name; if the name would
3708 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003709 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 Out << 'E';
3711
3712 if (compensateMangling)
3713 Out << 'E';
3714
3715 break;
3716 }
3717 case TemplateArgument::NullPtr: {
3718 // <expr-primary> ::= L <type> 0 E
3719 Out << 'L';
3720 mangleType(A.getNullPtrType());
3721 Out << "0E";
3722 break;
3723 }
3724 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003725 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003727 for (const auto &P : A.pack_elements())
3728 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 Out << 'E';
3730 }
3731 }
3732}
3733
3734void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3735 // <template-param> ::= T_ # first template parameter
3736 // ::= T <parameter-2 non-negative number> _
3737 if (Index == 0)
3738 Out << "T_";
3739 else
3740 Out << 'T' << (Index - 1) << '_';
3741}
3742
David Majnemer3b3bdb52014-05-06 22:49:16 +00003743void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3744 if (SeqID == 1)
3745 Out << '0';
3746 else if (SeqID > 1) {
3747 SeqID--;
3748
3749 // <seq-id> is encoded in base-36, using digits and upper case letters.
3750 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003751 MutableArrayRef<char> BufferRef(Buffer);
3752 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003753
3754 for (; SeqID != 0; SeqID /= 36) {
3755 unsigned C = SeqID % 36;
3756 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3757 }
3758
3759 Out.write(I.base(), I - BufferRef.rbegin());
3760 }
3761 Out << '_';
3762}
3763
Guy Benyei11169dd2012-12-18 14:30:41 +00003764void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3765 bool result = mangleSubstitution(type);
3766 assert(result && "no existing substitution for type");
3767 (void) result;
3768}
3769
3770void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3771 bool result = mangleSubstitution(tname);
3772 assert(result && "no existing substitution for template name");
3773 (void) result;
3774}
3775
3776// <substitution> ::= S <seq-id> _
3777// ::= S_
3778bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3779 // Try one of the standard substitutions first.
3780 if (mangleStandardSubstitution(ND))
3781 return true;
3782
3783 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3784 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3785}
3786
Justin Bognere8d762e2015-05-22 06:48:13 +00003787/// Determine whether the given type has any qualifiers that are relevant for
3788/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003789static bool hasMangledSubstitutionQualifiers(QualType T) {
3790 Qualifiers Qs = T.getQualifiers();
3791 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3792}
3793
3794bool CXXNameMangler::mangleSubstitution(QualType T) {
3795 if (!hasMangledSubstitutionQualifiers(T)) {
3796 if (const RecordType *RT = T->getAs<RecordType>())
3797 return mangleSubstitution(RT->getDecl());
3798 }
3799
3800 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3801
3802 return mangleSubstitution(TypePtr);
3803}
3804
3805bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3806 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3807 return mangleSubstitution(TD);
3808
3809 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3810 return mangleSubstitution(
3811 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3812}
3813
3814bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3815 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3816 if (I == Substitutions.end())
3817 return false;
3818
3819 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003820 Out << 'S';
3821 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003822
3823 return true;
3824}
3825
3826static bool isCharType(QualType T) {
3827 if (T.isNull())
3828 return false;
3829
3830 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3831 T->isSpecificBuiltinType(BuiltinType::Char_U);
3832}
3833
Justin Bognere8d762e2015-05-22 06:48:13 +00003834/// Returns whether a given type is a template specialization of a given name
3835/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003836static bool isCharSpecialization(QualType T, const char *Name) {
3837 if (T.isNull())
3838 return false;
3839
3840 const RecordType *RT = T->getAs<RecordType>();
3841 if (!RT)
3842 return false;
3843
3844 const ClassTemplateSpecializationDecl *SD =
3845 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3846 if (!SD)
3847 return false;
3848
3849 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3850 return false;
3851
3852 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3853 if (TemplateArgs.size() != 1)
3854 return false;
3855
3856 if (!isCharType(TemplateArgs[0].getAsType()))
3857 return false;
3858
3859 return SD->getIdentifier()->getName() == Name;
3860}
3861
3862template <std::size_t StrLen>
3863static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3864 const char (&Str)[StrLen]) {
3865 if (!SD->getIdentifier()->isStr(Str))
3866 return false;
3867
3868 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3869 if (TemplateArgs.size() != 2)
3870 return false;
3871
3872 if (!isCharType(TemplateArgs[0].getAsType()))
3873 return false;
3874
3875 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3876 return false;
3877
3878 return true;
3879}
3880
3881bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3882 // <substitution> ::= St # ::std::
3883 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3884 if (isStd(NS)) {
3885 Out << "St";
3886 return true;
3887 }
3888 }
3889
3890 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3891 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3892 return false;
3893
3894 // <substitution> ::= Sa # ::std::allocator
3895 if (TD->getIdentifier()->isStr("allocator")) {
3896 Out << "Sa";
3897 return true;
3898 }
3899
3900 // <<substitution> ::= Sb # ::std::basic_string
3901 if (TD->getIdentifier()->isStr("basic_string")) {
3902 Out << "Sb";
3903 return true;
3904 }
3905 }
3906
3907 if (const ClassTemplateSpecializationDecl *SD =
3908 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3909 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3910 return false;
3911
3912 // <substitution> ::= Ss # ::std::basic_string<char,
3913 // ::std::char_traits<char>,
3914 // ::std::allocator<char> >
3915 if (SD->getIdentifier()->isStr("basic_string")) {
3916 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3917
3918 if (TemplateArgs.size() != 3)
3919 return false;
3920
3921 if (!isCharType(TemplateArgs[0].getAsType()))
3922 return false;
3923
3924 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3925 return false;
3926
3927 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3928 return false;
3929
3930 Out << "Ss";
3931 return true;
3932 }
3933
3934 // <substitution> ::= Si # ::std::basic_istream<char,
3935 // ::std::char_traits<char> >
3936 if (isStreamCharSpecialization(SD, "basic_istream")) {
3937 Out << "Si";
3938 return true;
3939 }
3940
3941 // <substitution> ::= So # ::std::basic_ostream<char,
3942 // ::std::char_traits<char> >
3943 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3944 Out << "So";
3945 return true;
3946 }
3947
3948 // <substitution> ::= Sd # ::std::basic_iostream<char,
3949 // ::std::char_traits<char> >
3950 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3951 Out << "Sd";
3952 return true;
3953 }
3954 }
3955 return false;
3956}
3957
3958void CXXNameMangler::addSubstitution(QualType T) {
3959 if (!hasMangledSubstitutionQualifiers(T)) {
3960 if (const RecordType *RT = T->getAs<RecordType>()) {
3961 addSubstitution(RT->getDecl());
3962 return;
3963 }
3964 }
3965
3966 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3967 addSubstitution(TypePtr);
3968}
3969
3970void CXXNameMangler::addSubstitution(TemplateName Template) {
3971 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3972 return addSubstitution(TD);
3973
3974 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3975 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3976}
3977
3978void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3979 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3980 Substitutions[Ptr] = SeqID++;
3981}
3982
3983//
3984
Justin Bognere8d762e2015-05-22 06:48:13 +00003985/// Mangles the name of the declaration D and emits that name to the given
3986/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00003987///
3988/// If the declaration D requires a mangled name, this routine will emit that
3989/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3990/// and this routine will return false. In this case, the caller should just
3991/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3992/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003993void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3994 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3996 "Invalid mangleName() call, argument is not a variable or function!");
3997 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3998 "Invalid mangleName() call on 'structor decl!");
3999
4000 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4001 getASTContext().getSourceManager(),
4002 "Mangling declaration");
4003
4004 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004005 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006}
4007
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004008void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4009 CXXCtorType Type,
4010 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 CXXNameMangler Mangler(*this, Out, D, Type);
4012 Mangler.mangle(D);
4013}
4014
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004015void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4016 CXXDtorType Type,
4017 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 CXXNameMangler Mangler(*this, Out, D, Type);
4019 Mangler.mangle(D);
4020}
4021
Rafael Espindola1e4df922014-09-16 15:18:21 +00004022void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4023 raw_ostream &Out) {
4024 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4025 Mangler.mangle(D);
4026}
4027
4028void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4029 raw_ostream &Out) {
4030 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4031 Mangler.mangle(D);
4032}
4033
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004034void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4035 const ThunkInfo &Thunk,
4036 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 // <special-name> ::= T <call-offset> <base encoding>
4038 // # base is the nominal target function of thunk
4039 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4040 // # base is the nominal target function of thunk
4041 // # first call-offset is 'this' adjustment
4042 // # second call-offset is result adjustment
4043
4044 assert(!isa<CXXDestructorDecl>(MD) &&
4045 "Use mangleCXXDtor for destructor decls!");
4046 CXXNameMangler Mangler(*this, Out);
4047 Mangler.getStream() << "_ZT";
4048 if (!Thunk.Return.isEmpty())
4049 Mangler.getStream() << 'c';
4050
4051 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004052 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4053 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4054
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 // Mangle the return pointer adjustment if there is one.
4056 if (!Thunk.Return.isEmpty())
4057 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004058 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4059
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 Mangler.mangleFunctionEncoding(MD);
4061}
4062
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004063void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4064 const CXXDestructorDecl *DD, CXXDtorType Type,
4065 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 // <special-name> ::= T <call-offset> <base encoding>
4067 // # base is the nominal target function of thunk
4068 CXXNameMangler Mangler(*this, Out, DD, Type);
4069 Mangler.getStream() << "_ZT";
4070
4071 // Mangle the 'this' pointer adjustment.
4072 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004073 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
4075 Mangler.mangleFunctionEncoding(DD);
4076}
4077
Justin Bognere8d762e2015-05-22 06:48:13 +00004078/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004079void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4080 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 // <special-name> ::= GV <object name> # Guard variable for one-time
4082 // # initialization
4083 CXXNameMangler Mangler(*this, Out);
4084 Mangler.getStream() << "_ZGV";
4085 Mangler.mangleName(D);
4086}
4087
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004088void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4089 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004090 // These symbols are internal in the Itanium ABI, so the names don't matter.
4091 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4092 // avoid duplicate symbols.
4093 Out << "__cxx_global_var_init";
4094}
4095
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004096void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4097 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004098 // Prefix the mangling of D with __dtor_.
4099 CXXNameMangler Mangler(*this, Out);
4100 Mangler.getStream() << "__dtor_";
4101 if (shouldMangleDeclName(D))
4102 Mangler.mangle(D);
4103 else
4104 Mangler.getStream() << D->getName();
4105}
4106
Reid Kleckner1d59f992015-01-22 01:36:17 +00004107void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4108 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4109 CXXNameMangler Mangler(*this, Out);
4110 Mangler.getStream() << "__filt_";
4111 if (shouldMangleDeclName(EnclosingDecl))
4112 Mangler.mangle(EnclosingDecl);
4113 else
4114 Mangler.getStream() << EnclosingDecl->getName();
4115}
4116
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004117void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4118 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4119 CXXNameMangler Mangler(*this, Out);
4120 Mangler.getStream() << "__fin_";
4121 if (shouldMangleDeclName(EnclosingDecl))
4122 Mangler.mangle(EnclosingDecl);
4123 else
4124 Mangler.getStream() << EnclosingDecl->getName();
4125}
4126
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004127void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4128 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004129 // <special-name> ::= TH <object name>
4130 CXXNameMangler Mangler(*this, Out);
4131 Mangler.getStream() << "_ZTH";
4132 Mangler.mangleName(D);
4133}
4134
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004135void
4136ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4137 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004138 // <special-name> ::= TW <object name>
4139 CXXNameMangler Mangler(*this, Out);
4140 Mangler.getStream() << "_ZTW";
4141 Mangler.mangleName(D);
4142}
4143
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004144void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004145 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004146 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 // We match the GCC mangling here.
4148 // <special-name> ::= GR <object name>
4149 CXXNameMangler Mangler(*this, Out);
4150 Mangler.getStream() << "_ZGR";
4151 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004152 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004153 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004154}
4155
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004156void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4157 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 // <special-name> ::= TV <type> # virtual table
4159 CXXNameMangler Mangler(*this, Out);
4160 Mangler.getStream() << "_ZTV";
4161 Mangler.mangleNameOrStandardSubstitution(RD);
4162}
4163
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004164void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4165 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 // <special-name> ::= TT <type> # VTT structure
4167 CXXNameMangler Mangler(*this, Out);
4168 Mangler.getStream() << "_ZTT";
4169 Mangler.mangleNameOrStandardSubstitution(RD);
4170}
4171
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004172void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4173 int64_t Offset,
4174 const CXXRecordDecl *Type,
4175 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 // <special-name> ::= TC <type> <offset number> _ <base type>
4177 CXXNameMangler Mangler(*this, Out);
4178 Mangler.getStream() << "_ZTC";
4179 Mangler.mangleNameOrStandardSubstitution(RD);
4180 Mangler.getStream() << Offset;
4181 Mangler.getStream() << '_';
4182 Mangler.mangleNameOrStandardSubstitution(Type);
4183}
4184
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004185void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 // <special-name> ::= TI <type> # typeinfo structure
4187 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4188 CXXNameMangler Mangler(*this, Out);
4189 Mangler.getStream() << "_ZTI";
4190 Mangler.mangleType(Ty);
4191}
4192
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004193void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4194 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4196 CXXNameMangler Mangler(*this, Out);
4197 Mangler.getStream() << "_ZTS";
4198 Mangler.mangleType(Ty);
4199}
4200
Reid Klecknercc99e262013-11-19 23:23:00 +00004201void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4202 mangleCXXRTTIName(Ty, Out);
4203}
4204
David Majnemer58e5bee2014-03-24 21:43:36 +00004205void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4206 llvm_unreachable("Can't mangle string literals");
4207}
4208
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004209ItaniumMangleContext *
4210ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4211 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004212}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004213