blob: 1e777a51d9fabb7228416755c115df89e41dd88f [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
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000177 void mangleCXXVTableBitSet(const CXXRecordDecl *RD, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
217
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
223
Justin Bognere8d762e2015-05-22 06:48:13 +0000224 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225 unsigned SeqID;
226
227 class FunctionTypeDepthState {
228 unsigned Bits;
229
230 enum { InResultTypeMask = 1 };
231
232 public:
233 FunctionTypeDepthState() : Bits(0) {}
234
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
237 return Bits >> 1;
238 }
239
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
243 }
244
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
248 return tmp;
249 }
250
251 void enterResultType() {
252 Bits |= InResultTypeMask;
253 }
254
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
257 }
258
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
261 Bits = saved.Bits;
262 }
263
264 } FunctionTypeDepth;
265
266 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
267
268 ASTContext &getASTContext() const { return Context.getASTContext(); }
269
270public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000271 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000272 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000273 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
274 SeqID(0) {
275 // These can't be mangled without a ctor type or dtor type.
276 assert(!D || (!isa<CXXDestructorDecl>(D) &&
277 !isa<CXXConstructorDecl>(D)));
278 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 const CXXConstructorDecl *D, CXXCtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000283 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000284 const CXXDestructorDecl *D, CXXDtorType Type)
285 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
286 SeqID(0) { }
287
288#if MANGLE_CHECKER
289 ~CXXNameMangler() {
290 if (Out.str()[0] == '\01')
291 return;
292
293 int status = 0;
294 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
295 assert(status == 0 && "Could not demangle mangled name!");
296 free(result);
297 }
298#endif
299 raw_ostream &getStream() { return Out; }
300
David Majnemer7ff7eb72015-02-18 07:47:09 +0000301 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
303 void mangleNumber(const llvm::APSInt &I);
304 void mangleNumber(int64_t Number);
305 void mangleFloat(const llvm::APFloat &F);
306 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000307 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 void mangleName(const NamedDecl *ND);
309 void mangleType(QualType T);
310 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
311
312private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000313
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 bool mangleSubstitution(const NamedDecl *ND);
315 bool mangleSubstitution(QualType T);
316 bool mangleSubstitution(TemplateName Template);
317 bool mangleSubstitution(uintptr_t Ptr);
318
319 void mangleExistingSubstitution(QualType type);
320 void mangleExistingSubstitution(TemplateName name);
321
322 bool mangleStandardSubstitution(const NamedDecl *ND);
323
324 void addSubstitution(const NamedDecl *ND) {
325 ND = cast<NamedDecl>(ND->getCanonicalDecl());
326
327 addSubstitution(reinterpret_cast<uintptr_t>(ND));
328 }
329 void addSubstitution(QualType T);
330 void addSubstitution(TemplateName Template);
331 void addSubstitution(uintptr_t Ptr);
332
333 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 bool recursive = false);
335 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000336 DeclarationName name,
337 unsigned KnownArity = UnknownArity);
338
339 void mangleName(const TemplateDecl *TD,
340 const TemplateArgument *TemplateArgs,
341 unsigned NumTemplateArgs);
342 void mangleUnqualifiedName(const NamedDecl *ND) {
343 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
344 }
345 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
346 unsigned KnownArity);
347 void mangleUnscopedName(const NamedDecl *ND);
348 void mangleUnscopedTemplateName(const TemplateDecl *ND);
349 void mangleUnscopedTemplateName(TemplateName);
350 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000351 void mangleLocalName(const Decl *D);
352 void mangleBlockForPrefix(const BlockDecl *Block);
353 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 void mangleLambda(const CXXRecordDecl *Lambda);
355 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
356 bool NoFunction=false);
357 void mangleNestedName(const TemplateDecl *TD,
358 const TemplateArgument *TemplateArgs,
359 unsigned NumTemplateArgs);
360 void manglePrefix(NestedNameSpecifier *qualifier);
361 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
362 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000363 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000365 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
366 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000367 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
369 void mangleQualifiers(Qualifiers Quals);
370 void mangleRefQualifier(RefQualifierKind RefQualifier);
371
372 void mangleObjCMethodName(const ObjCMethodDecl *MD);
373
374 // Declare manglers for every type class.
375#define ABSTRACT_TYPE(CLASS, PARENT)
376#define NON_CANONICAL_TYPE(CLASS, PARENT)
377#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
378#include "clang/AST/TypeNodes.def"
379
380 void mangleType(const TagType*);
381 void mangleType(TemplateName);
382 void mangleBareFunctionType(const FunctionType *T,
383 bool MangleReturnType);
384 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000385 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000386
387 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000388 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000389 void mangleMemberExpr(const Expr *base, bool isArrow,
390 NestedNameSpecifier *qualifier,
391 NamedDecl *firstQualifierLookup,
392 DeclarationName name,
393 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000394 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000395 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000396 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
397 void mangleCXXCtorType(CXXCtorType T);
398 void mangleCXXDtorType(CXXDtorType T);
399
400 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
401 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
402 unsigned NumTemplateArgs);
403 void mangleTemplateArgs(const TemplateArgumentList &AL);
404 void mangleTemplateArg(TemplateArgument A);
405
406 void mangleTemplateParameter(unsigned Index);
407
408 void mangleFunctionParam(const ParmVarDecl *parm);
409};
410
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000411}
Guy Benyei11169dd2012-12-18 14:30:41 +0000412
Rafael Espindola002667c2013-10-16 01:40:34 +0000413bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000414 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000415 if (FD) {
416 LanguageLinkage L = FD->getLanguageLinkage();
417 // Overloadable functions need mangling.
418 if (FD->hasAttr<OverloadableAttr>())
419 return true;
420
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000421 // "main" is not mangled.
422 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000423 return false;
424
425 // C++ functions and those whose names are not a simple identifier need
426 // mangling.
427 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
428 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000429
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000430 // C functions are not mangled.
431 if (L == CLanguageLinkage)
432 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000433 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000434
435 // Otherwise, no mangling is done outside C++ mode.
436 if (!getASTContext().getLangOpts().CPlusPlus)
437 return false;
438
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000439 const VarDecl *VD = dyn_cast<VarDecl>(D);
440 if (VD) {
441 // C variables are not mangled.
442 if (VD->isExternC())
443 return false;
444
445 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 const DeclContext *DC = getEffectiveDeclContext(D);
447 // Check for extern variable declared locally.
448 if (DC->isFunctionOrMethod() && D->hasLinkage())
449 while (!DC->isNamespace() && !DC->isTranslationUnit())
450 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000451 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
452 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 return false;
454 }
455
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 return true;
457}
458
David Majnemer7ff7eb72015-02-18 07:47:09 +0000459void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 // <mangled-name> ::= _Z <encoding>
461 // ::= <data name>
462 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000463 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
465 mangleFunctionEncoding(FD);
466 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
467 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000468 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
469 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 else
471 mangleName(cast<FieldDecl>(D));
472}
473
474void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
475 // <encoding> ::= <function name> <bare-function-type>
476 mangleName(FD);
477
478 // Don't mangle in the type if this isn't a decl we should typically mangle.
479 if (!Context.shouldMangleDeclName(FD))
480 return;
481
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000482 if (FD->hasAttr<EnableIfAttr>()) {
483 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
484 Out << "Ua9enable_ifI";
485 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
486 // it here.
487 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
488 E = FD->getAttrs().rend();
489 I != E; ++I) {
490 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
491 if (!EIA)
492 continue;
493 Out << 'X';
494 mangleExpression(EIA->getCond());
495 Out << 'E';
496 }
497 Out << 'E';
498 FunctionTypeDepth.pop(Saved);
499 }
500
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 // Whether the mangling of a function type includes the return type depends on
502 // the context and the nature of the function. The rules for deciding whether
503 // the return type is included are:
504 //
505 // 1. Template functions (names or types) have return types encoded, with
506 // the exceptions listed below.
507 // 2. Function types not appearing as part of a function name mangling,
508 // e.g. parameters, pointer types, etc., have return type encoded, with the
509 // exceptions listed below.
510 // 3. Non-template function names do not have return types encoded.
511 //
512 // The exceptions mentioned in (1) and (2) above, for which the return type is
513 // never included, are
514 // 1. Constructors.
515 // 2. Destructors.
516 // 3. Conversion operator functions, e.g. operator int.
517 bool MangleReturnType = false;
518 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
519 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
520 isa<CXXConversionDecl>(FD)))
521 MangleReturnType = true;
522
523 // Mangle the type of the primary template.
524 FD = PrimaryTemplate->getTemplatedDecl();
525 }
526
527 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
528 MangleReturnType);
529}
530
531static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
532 while (isa<LinkageSpecDecl>(DC)) {
533 DC = getEffectiveParentContext(DC);
534 }
535
536 return DC;
537}
538
Justin Bognere8d762e2015-05-22 06:48:13 +0000539/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000540static bool isStd(const NamespaceDecl *NS) {
541 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
542 ->isTranslationUnit())
543 return false;
544
545 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
546 return II && II->isStr("std");
547}
548
549// isStdNamespace - Return whether a given decl context is a toplevel 'std'
550// namespace.
551static bool isStdNamespace(const DeclContext *DC) {
552 if (!DC->isNamespace())
553 return false;
554
555 return isStd(cast<NamespaceDecl>(DC));
556}
557
558static const TemplateDecl *
559isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
560 // Check if we have a function template.
561 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
562 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
563 TemplateArgs = FD->getTemplateSpecializationArgs();
564 return TD;
565 }
566 }
567
568 // Check if we have a class template.
569 if (const ClassTemplateSpecializationDecl *Spec =
570 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
571 TemplateArgs = &Spec->getTemplateArgs();
572 return Spec->getSpecializedTemplate();
573 }
574
Larisse Voufo39a1e502013-08-06 01:03:05 +0000575 // Check if we have a variable template.
576 if (const VarTemplateSpecializationDecl *Spec =
577 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
578 TemplateArgs = &Spec->getTemplateArgs();
579 return Spec->getSpecializedTemplate();
580 }
581
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000583}
584
Guy Benyei11169dd2012-12-18 14:30:41 +0000585void CXXNameMangler::mangleName(const NamedDecl *ND) {
586 // <name> ::= <nested-name>
587 // ::= <unscoped-name>
588 // ::= <unscoped-template-name> <template-args>
589 // ::= <local-name>
590 //
591 const DeclContext *DC = getEffectiveDeclContext(ND);
592
593 // If this is an extern variable declared locally, the relevant DeclContext
594 // is that of the containing namespace, or the translation unit.
595 // FIXME: This is a hack; extern variables declared locally should have
596 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000597 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000598 while (!DC->isNamespace() && !DC->isTranslationUnit())
599 DC = getEffectiveParentContext(DC);
600 else if (GetLocalClassDecl(ND)) {
601 mangleLocalName(ND);
602 return;
603 }
604
605 DC = IgnoreLinkageSpecDecls(DC);
606
607 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
608 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000609 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
611 mangleUnscopedTemplateName(TD);
612 mangleTemplateArgs(*TemplateArgs);
613 return;
614 }
615
616 mangleUnscopedName(ND);
617 return;
618 }
619
Eli Friedman95f50122013-07-02 17:52:28 +0000620 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 mangleLocalName(ND);
622 return;
623 }
624
625 mangleNestedName(ND, DC);
626}
627void CXXNameMangler::mangleName(const TemplateDecl *TD,
628 const TemplateArgument *TemplateArgs,
629 unsigned NumTemplateArgs) {
630 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
631
632 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
633 mangleUnscopedTemplateName(TD);
634 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
635 } else {
636 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
637 }
638}
639
640void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
641 // <unscoped-name> ::= <unqualified-name>
642 // ::= St <unqualified-name> # ::std::
643
644 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
645 Out << "St";
646
647 mangleUnqualifiedName(ND);
648}
649
650void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
651 // <unscoped-template-name> ::= <unscoped-name>
652 // ::= <substitution>
653 if (mangleSubstitution(ND))
654 return;
655
656 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000657 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000659 else
660 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000661
Guy Benyei11169dd2012-12-18 14:30:41 +0000662 addSubstitution(ND);
663}
664
665void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
666 // <unscoped-template-name> ::= <unscoped-name>
667 // ::= <substitution>
668 if (TemplateDecl *TD = Template.getAsTemplateDecl())
669 return mangleUnscopedTemplateName(TD);
670
671 if (mangleSubstitution(Template))
672 return;
673
674 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
675 assert(Dependent && "Not a dependent template name?");
676 if (const IdentifierInfo *Id = Dependent->getIdentifier())
677 mangleSourceName(Id);
678 else
679 mangleOperatorName(Dependent->getOperator(), UnknownArity);
680
681 addSubstitution(Template);
682}
683
684void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
685 // ABI:
686 // Floating-point literals are encoded using a fixed-length
687 // lowercase hexadecimal string corresponding to the internal
688 // representation (IEEE on Itanium), high-order bytes first,
689 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
690 // on Itanium.
691 // The 'without leading zeroes' thing seems to be an editorial
692 // mistake; see the discussion on cxx-abi-dev beginning on
693 // 2012-01-16.
694
695 // Our requirements here are just barely weird enough to justify
696 // using a custom algorithm instead of post-processing APInt::toString().
697
698 llvm::APInt valueBits = f.bitcastToAPInt();
699 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
700 assert(numCharacters != 0);
701
702 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000703 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000704
705 // Fill the buffer left-to-right.
706 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
707 // The bit-index of the next hex digit.
708 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
709
710 // Project out 4 bits starting at 'digitIndex'.
711 llvm::integerPart hexDigit
712 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
713 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
714 hexDigit &= 0xF;
715
716 // Map that over to a lowercase hex digit.
717 static const char charForHex[16] = {
718 '0', '1', '2', '3', '4', '5', '6', '7',
719 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
720 };
721 buffer[stringIndex] = charForHex[hexDigit];
722 }
723
724 Out.write(buffer.data(), numCharacters);
725}
726
727void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
728 if (Value.isSigned() && Value.isNegative()) {
729 Out << 'n';
730 Value.abs().print(Out, /*signed*/ false);
731 } else {
732 Value.print(Out, /*signed*/ false);
733 }
734}
735
736void CXXNameMangler::mangleNumber(int64_t Number) {
737 // <number> ::= [n] <non-negative decimal integer>
738 if (Number < 0) {
739 Out << 'n';
740 Number = -Number;
741 }
742
743 Out << Number;
744}
745
746void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
747 // <call-offset> ::= h <nv-offset> _
748 // ::= v <v-offset> _
749 // <nv-offset> ::= <offset number> # non-virtual base override
750 // <v-offset> ::= <offset number> _ <virtual offset number>
751 // # virtual base override, with vcall offset
752 if (!Virtual) {
753 Out << 'h';
754 mangleNumber(NonVirtual);
755 Out << '_';
756 return;
757 }
758
759 Out << 'v';
760 mangleNumber(NonVirtual);
761 Out << '_';
762 mangleNumber(Virtual);
763 Out << '_';
764}
765
766void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000767 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 if (!mangleSubstitution(QualType(TST, 0))) {
769 mangleTemplatePrefix(TST->getTemplateName());
770
771 // FIXME: GCC does not appear to mangle the template arguments when
772 // the template in question is a dependent template name. Should we
773 // emulate that badness?
774 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
775 addSubstitution(QualType(TST, 0));
776 }
David Majnemera88b3592015-02-18 02:28:01 +0000777 } else if (const auto *DTST =
778 type->getAs<DependentTemplateSpecializationType>()) {
779 if (!mangleSubstitution(QualType(DTST, 0))) {
780 TemplateName Template = getASTContext().getDependentTemplateName(
781 DTST->getQualifier(), DTST->getIdentifier());
782 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000783
David Majnemera88b3592015-02-18 02:28:01 +0000784 // FIXME: GCC does not appear to mangle the template arguments when
785 // the template in question is a dependent template name. Should we
786 // emulate that badness?
787 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
788 addSubstitution(QualType(DTST, 0));
789 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 } else {
791 // We use the QualType mangle type variant here because it handles
792 // substitutions.
793 mangleType(type);
794 }
795}
796
797/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
798///
Guy Benyei11169dd2012-12-18 14:30:41 +0000799/// \param recursive - true if this is being called recursively,
800/// i.e. if there is more prefix "to the right".
801void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000802 bool recursive) {
803
804 // x, ::x
805 // <unresolved-name> ::= [gs] <base-unresolved-name>
806
807 // T::x / decltype(p)::x
808 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
809
810 // T::N::x /decltype(p)::N::x
811 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
812 // <base-unresolved-name>
813
814 // A::x, N::y, A<T>::z; "gs" means leading "::"
815 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
816 // <base-unresolved-name>
817
818 switch (qualifier->getKind()) {
819 case NestedNameSpecifier::Global:
820 Out << "gs";
821
822 // We want an 'sr' unless this is the entire NNS.
823 if (recursive)
824 Out << "sr";
825
826 // We never want an 'E' here.
827 return;
828
Nikola Smiljanic67860242014-09-26 00:28:20 +0000829 case NestedNameSpecifier::Super:
830 llvm_unreachable("Can't mangle __super specifier");
831
Guy Benyei11169dd2012-12-18 14:30:41 +0000832 case NestedNameSpecifier::Namespace:
833 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000834 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 /*recursive*/ true);
836 else
837 Out << "sr";
838 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
839 break;
840 case NestedNameSpecifier::NamespaceAlias:
841 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000842 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 /*recursive*/ true);
844 else
845 Out << "sr";
846 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
847 break;
848
849 case NestedNameSpecifier::TypeSpec:
850 case NestedNameSpecifier::TypeSpecWithTemplate: {
851 const Type *type = qualifier->getAsType();
852
853 // We only want to use an unresolved-type encoding if this is one of:
854 // - a decltype
855 // - a template type parameter
856 // - a template template parameter with arguments
857 // In all of these cases, we should have no prefix.
858 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000859 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 /*recursive*/ true);
861 } else {
862 // Otherwise, all the cases want this.
863 Out << "sr";
864 }
865
David Majnemerb8014dd2015-02-19 02:16:16 +0000866 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 return;
868
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 break;
870 }
871
872 case NestedNameSpecifier::Identifier:
873 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000874 if (qualifier->getPrefix())
875 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000877 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000879
880 mangleSourceName(qualifier->getAsIdentifier());
881 break;
882 }
883
884 // If this was the innermost part of the NNS, and we fell out to
885 // here, append an 'E'.
886 if (!recursive)
887 Out << 'E';
888}
889
890/// Mangle an unresolved-name, which is generally used for names which
891/// weren't resolved to specific entities.
892void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000893 DeclarationName name,
894 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000895 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000896 switch (name.getNameKind()) {
897 // <base-unresolved-name> ::= <simple-id>
898 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000899 mangleSourceName(name.getAsIdentifierInfo());
900 break;
901 // <base-unresolved-name> ::= dn <destructor-name>
902 case DeclarationName::CXXDestructorName:
903 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000904 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000905 break;
906 // <base-unresolved-name> ::= on <operator-name>
907 case DeclarationName::CXXConversionFunctionName:
908 case DeclarationName::CXXLiteralOperatorName:
909 case DeclarationName::CXXOperatorName:
910 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000911 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000912 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000913 case DeclarationName::CXXConstructorName:
914 llvm_unreachable("Can't mangle a constructor name!");
915 case DeclarationName::CXXUsingDirective:
916 llvm_unreachable("Can't mangle a using directive name!");
917 case DeclarationName::ObjCMultiArgSelector:
918 case DeclarationName::ObjCOneArgSelector:
919 case DeclarationName::ObjCZeroArgSelector:
920 llvm_unreachable("Can't mangle Objective-C selector names here!");
921 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000922}
923
Guy Benyei11169dd2012-12-18 14:30:41 +0000924void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
925 DeclarationName Name,
926 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000927 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 // <unqualified-name> ::= <operator-name>
929 // ::= <ctor-dtor-name>
930 // ::= <source-name>
931 switch (Name.getNameKind()) {
932 case DeclarationName::Identifier: {
933 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
934 // We must avoid conflicts between internally- and externally-
935 // linked variable and function declaration names in the same TU:
936 // void test() { extern void foo(); }
937 // static void foo();
938 // This naming convention is the same as that followed by GCC,
939 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000940 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 getEffectiveDeclContext(ND)->isFileContext())
942 Out << 'L';
943
944 mangleSourceName(II);
945 break;
946 }
947
948 // Otherwise, an anonymous entity. We must have a declaration.
949 assert(ND && "mangling empty name without declaration");
950
951 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
952 if (NS->isAnonymousNamespace()) {
953 // This is how gcc mangles these names.
954 Out << "12_GLOBAL__N_1";
955 break;
956 }
957 }
958
959 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
960 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000961 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 // Itanium C++ ABI 5.1.2:
965 //
966 // For the purposes of mangling, the name of an anonymous union is
967 // considered to be the name of the first named data member found by a
968 // pre-order, depth-first, declaration-order walk of the data members of
969 // the anonymous union. If there is no such data member (i.e., if all of
970 // the data members in the union are unnamed), then there is no way for
971 // a program to refer to the anonymous union, and there is therefore no
972 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000973 assert(RD->isAnonymousStructOrUnion()
974 && "Expected anonymous struct or union!");
975 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
977 // It's actually possible for various reasons for us to get here
978 // with an empty anonymous struct / union. Fortunately, it
979 // doesn't really matter what name we generate.
980 if (!FD) break;
981 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000982
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 mangleSourceName(FD->getIdentifier());
984 break;
985 }
John McCall924046f2013-04-10 06:08:21 +0000986
987 // Class extensions have no name as a category, and it's possible
988 // for them to be the semantic parent of certain declarations
989 // (primarily, tag decls defined within declarations). Such
990 // declarations will always have internal linkage, so the name
991 // doesn't really matter, but we shouldn't crash on them. For
992 // safety, just handle all ObjC containers here.
993 if (isa<ObjCContainerDecl>(ND))
994 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000995
996 // We must have an anonymous struct.
997 const TagDecl *TD = cast<TagDecl>(ND);
998 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
999 assert(TD->getDeclContext() == D->getDeclContext() &&
1000 "Typedef should not be in another decl context!");
1001 assert(D->getDeclName().getAsIdentifierInfo() &&
1002 "Typedef was not named!");
1003 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1004 break;
1005 }
1006
1007 // <unnamed-type-name> ::= <closure-type-name>
1008 //
1009 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1010 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1011 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1012 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1013 mangleLambda(Record);
1014 break;
1015 }
1016 }
1017
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001018 if (TD->isExternallyVisible()) {
1019 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001021 if (UnnamedMangle > 1)
1022 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 Out << '_';
1024 break;
1025 }
1026
1027 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001028 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001029
1030 // Mangle it as a source name in the form
1031 // [n] $_<id>
1032 // where n is the length of the string.
1033 SmallString<8> Str;
1034 Str += "$_";
1035 Str += llvm::utostr(AnonStructId);
1036
1037 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001038 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 break;
1040 }
1041
1042 case DeclarationName::ObjCZeroArgSelector:
1043 case DeclarationName::ObjCOneArgSelector:
1044 case DeclarationName::ObjCMultiArgSelector:
1045 llvm_unreachable("Can't mangle Objective-C selector names here!");
1046
1047 case DeclarationName::CXXConstructorName:
1048 if (ND == Structor)
1049 // If the named decl is the C++ constructor we're mangling, use the type
1050 // we were given.
1051 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1052 else
1053 // Otherwise, use the complete constructor name. This is relevant if a
1054 // class with a constructor is declared within a constructor.
1055 mangleCXXCtorType(Ctor_Complete);
1056 break;
1057
1058 case DeclarationName::CXXDestructorName:
1059 if (ND == Structor)
1060 // If the named decl is the C++ destructor we're mangling, use the type we
1061 // were given.
1062 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1063 else
1064 // Otherwise, use the complete destructor name. This is relevant if a
1065 // class with a destructor is declared within a destructor.
1066 mangleCXXDtorType(Dtor_Complete);
1067 break;
1068
David Majnemera88b3592015-02-18 02:28:01 +00001069 case DeclarationName::CXXOperatorName:
1070 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 Arity = cast<FunctionDecl>(ND)->getNumParams();
1072
David Majnemera88b3592015-02-18 02:28:01 +00001073 // If we have a member function, we need to include the 'this' pointer.
1074 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1075 if (!MD->isStatic())
1076 Arity++;
1077 }
1078 // FALLTHROUGH
1079 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001081 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001082 break;
1083
1084 case DeclarationName::CXXUsingDirective:
1085 llvm_unreachable("Can't mangle a using directive name!");
1086 }
1087}
1088
1089void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1090 // <source-name> ::= <positive length number> <identifier>
1091 // <number> ::= [n] <non-negative decimal integer>
1092 // <identifier> ::= <unqualified source code identifier>
1093 Out << II->getLength() << II->getName();
1094}
1095
1096void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1097 const DeclContext *DC,
1098 bool NoFunction) {
1099 // <nested-name>
1100 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1101 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1102 // <template-args> E
1103
1104 Out << 'N';
1105 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001106 Qualifiers MethodQuals =
1107 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1108 // We do not consider restrict a distinguishing attribute for overloading
1109 // purposes so we must not mangle it.
1110 MethodQuals.removeRestrict();
1111 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 mangleRefQualifier(Method->getRefQualifier());
1113 }
1114
1115 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001116 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001118 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001119 mangleTemplateArgs(*TemplateArgs);
1120 }
1121 else {
1122 manglePrefix(DC, NoFunction);
1123 mangleUnqualifiedName(ND);
1124 }
1125
1126 Out << 'E';
1127}
1128void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1129 const TemplateArgument *TemplateArgs,
1130 unsigned NumTemplateArgs) {
1131 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1132
1133 Out << 'N';
1134
1135 mangleTemplatePrefix(TD);
1136 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1137
1138 Out << 'E';
1139}
1140
Eli Friedman95f50122013-07-02 17:52:28 +00001141void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1143 // := Z <function encoding> E s [<discriminator>]
1144 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1145 // _ <entity name>
1146 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001147 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001148 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001149 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001150
1151 Out << 'Z';
1152
Eli Friedman92821742013-07-02 02:01:18 +00001153 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1154 mangleObjCMethodName(MD);
1155 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001156 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001157 else
1158 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001159
Eli Friedman92821742013-07-02 02:01:18 +00001160 Out << 'E';
1161
1162 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 // The parameter number is omitted for the last parameter, 0 for the
1164 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1165 // <entity name> will of course contain a <closure-type-name>: Its
1166 // numbering will be local to the particular argument in which it appears
1167 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001168 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1169 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001171 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 if (const FunctionDecl *Func
1173 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1174 Out << 'd';
1175 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1176 if (Num > 1)
1177 mangleNumber(Num - 2);
1178 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 }
1180 }
1181 }
1182
1183 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001184 // equality ok because RD derived from ND above
1185 if (D == RD) {
1186 mangleUnqualifiedName(RD);
1187 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1188 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1189 mangleUnqualifiedBlock(BD);
1190 } else {
1191 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001192 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001193 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001194 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1195 // Mangle a block in a default parameter; see above explanation for
1196 // lambdas.
1197 if (const ParmVarDecl *Parm
1198 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1199 if (const FunctionDecl *Func
1200 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1201 Out << 'd';
1202 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1203 if (Num > 1)
1204 mangleNumber(Num - 2);
1205 Out << '_';
1206 }
1207 }
1208
1209 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001210 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001211 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001213
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001214 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1215 unsigned disc;
1216 if (Context.getNextDiscriminator(ND, disc)) {
1217 if (disc < 10)
1218 Out << '_' << disc;
1219 else
1220 Out << "__" << disc << '_';
1221 }
1222 }
Eli Friedman95f50122013-07-02 17:52:28 +00001223}
1224
1225void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1226 if (GetLocalClassDecl(Block)) {
1227 mangleLocalName(Block);
1228 return;
1229 }
1230 const DeclContext *DC = getEffectiveDeclContext(Block);
1231 if (isLocalContainerContext(DC)) {
1232 mangleLocalName(Block);
1233 return;
1234 }
1235 manglePrefix(getEffectiveDeclContext(Block));
1236 mangleUnqualifiedBlock(Block);
1237}
1238
1239void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1240 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1241 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1242 Context->getDeclContext()->isRecord()) {
1243 if (const IdentifierInfo *Name
1244 = cast<NamedDecl>(Context)->getIdentifier()) {
1245 mangleSourceName(Name);
1246 Out << 'M';
1247 }
1248 }
1249 }
1250
1251 // If we have a block mangling number, use it.
1252 unsigned Number = Block->getBlockManglingNumber();
1253 // Otherwise, just make up a number. It doesn't matter what it is because
1254 // the symbol in question isn't externally visible.
1255 if (!Number)
1256 Number = Context.getBlockId(Block, false);
1257 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001258 if (Number > 0)
1259 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001260 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001261}
1262
1263void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1264 // If the context of a closure type is an initializer for a class member
1265 // (static or nonstatic), it is encoded in a qualified name with a final
1266 // <prefix> of the form:
1267 //
1268 // <data-member-prefix> := <member source-name> M
1269 //
1270 // Technically, the data-member-prefix is part of the <prefix>. However,
1271 // since a closure type will always be mangled with a prefix, it's easier
1272 // to emit that last part of the prefix here.
1273 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1274 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1275 Context->getDeclContext()->isRecord()) {
1276 if (const IdentifierInfo *Name
1277 = cast<NamedDecl>(Context)->getIdentifier()) {
1278 mangleSourceName(Name);
1279 Out << 'M';
1280 }
1281 }
1282 }
1283
1284 Out << "Ul";
1285 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1286 getAs<FunctionProtoType>();
1287 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1288 Out << "E";
1289
1290 // The number is omitted for the first closure type with a given
1291 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1292 // (in lexical order) with that same <lambda-sig> and context.
1293 //
1294 // The AST keeps track of the number for us.
1295 unsigned Number = Lambda->getLambdaManglingNumber();
1296 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1297 if (Number > 1)
1298 mangleNumber(Number - 2);
1299 Out << '_';
1300}
1301
1302void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1303 switch (qualifier->getKind()) {
1304 case NestedNameSpecifier::Global:
1305 // nothing
1306 return;
1307
Nikola Smiljanic67860242014-09-26 00:28:20 +00001308 case NestedNameSpecifier::Super:
1309 llvm_unreachable("Can't mangle __super specifier");
1310
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 case NestedNameSpecifier::Namespace:
1312 mangleName(qualifier->getAsNamespace());
1313 return;
1314
1315 case NestedNameSpecifier::NamespaceAlias:
1316 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1317 return;
1318
1319 case NestedNameSpecifier::TypeSpec:
1320 case NestedNameSpecifier::TypeSpecWithTemplate:
1321 manglePrefix(QualType(qualifier->getAsType(), 0));
1322 return;
1323
1324 case NestedNameSpecifier::Identifier:
1325 // Member expressions can have these without prefixes, but that
1326 // should end up in mangleUnresolvedPrefix instead.
1327 assert(qualifier->getPrefix());
1328 manglePrefix(qualifier->getPrefix());
1329
1330 mangleSourceName(qualifier->getAsIdentifier());
1331 return;
1332 }
1333
1334 llvm_unreachable("unexpected nested name specifier");
1335}
1336
1337void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1338 // <prefix> ::= <prefix> <unqualified-name>
1339 // ::= <template-prefix> <template-args>
1340 // ::= <template-param>
1341 // ::= # empty
1342 // ::= <substitution>
1343
1344 DC = IgnoreLinkageSpecDecls(DC);
1345
1346 if (DC->isTranslationUnit())
1347 return;
1348
Eli Friedman95f50122013-07-02 17:52:28 +00001349 if (NoFunction && isLocalContainerContext(DC))
1350 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001351
Eli Friedman95f50122013-07-02 17:52:28 +00001352 assert(!isLocalContainerContext(DC));
1353
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 const NamedDecl *ND = cast<NamedDecl>(DC);
1355 if (mangleSubstitution(ND))
1356 return;
1357
1358 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001359 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1361 mangleTemplatePrefix(TD);
1362 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001363 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001364 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1365 mangleUnqualifiedName(ND);
1366 }
1367
1368 addSubstitution(ND);
1369}
1370
1371void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1372 // <template-prefix> ::= <prefix> <template unqualified-name>
1373 // ::= <template-param>
1374 // ::= <substitution>
1375 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1376 return mangleTemplatePrefix(TD);
1377
1378 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1379 manglePrefix(Qualified->getQualifier());
1380
1381 if (OverloadedTemplateStorage *Overloaded
1382 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001383 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 UnknownArity);
1385 return;
1386 }
1387
1388 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1389 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001390 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1391 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 mangleUnscopedTemplateName(Template);
1393}
1394
Eli Friedman86af13f02013-07-05 18:41:30 +00001395void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1396 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 // <template-prefix> ::= <prefix> <template unqualified-name>
1398 // ::= <template-param>
1399 // ::= <substitution>
1400 // <template-template-param> ::= <template-param>
1401 // <substitution>
1402
1403 if (mangleSubstitution(ND))
1404 return;
1405
1406 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001407 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001409 } else {
1410 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1411 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 }
1413
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 addSubstitution(ND);
1415}
1416
1417/// Mangles a template name under the production <type>. Required for
1418/// template template arguments.
1419/// <type> ::= <class-enum-type>
1420/// ::= <template-param>
1421/// ::= <substitution>
1422void CXXNameMangler::mangleType(TemplateName TN) {
1423 if (mangleSubstitution(TN))
1424 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001425
1426 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427
1428 switch (TN.getKind()) {
1429 case TemplateName::QualifiedTemplate:
1430 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1431 goto HaveDecl;
1432
1433 case TemplateName::Template:
1434 TD = TN.getAsTemplateDecl();
1435 goto HaveDecl;
1436
1437 HaveDecl:
1438 if (isa<TemplateTemplateParmDecl>(TD))
1439 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1440 else
1441 mangleName(TD);
1442 break;
1443
1444 case TemplateName::OverloadedTemplate:
1445 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1446
1447 case TemplateName::DependentTemplate: {
1448 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1449 assert(Dependent->isIdentifier());
1450
1451 // <class-enum-type> ::= <name>
1452 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001453 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 mangleSourceName(Dependent->getIdentifier());
1455 break;
1456 }
1457
1458 case TemplateName::SubstTemplateTemplateParm: {
1459 // Substituted template parameters are mangled as the substituted
1460 // template. This will check for the substitution twice, which is
1461 // fine, but we have to return early so that we don't try to *add*
1462 // the substitution twice.
1463 SubstTemplateTemplateParmStorage *subst
1464 = TN.getAsSubstTemplateTemplateParm();
1465 mangleType(subst->getReplacement());
1466 return;
1467 }
1468
1469 case TemplateName::SubstTemplateTemplateParmPack: {
1470 // FIXME: not clear how to mangle this!
1471 // template <template <class> class T...> class A {
1472 // template <template <class> class U...> void foo(B<T,U> x...);
1473 // };
1474 Out << "_SUBSTPACK_";
1475 break;
1476 }
1477 }
1478
1479 addSubstitution(TN);
1480}
1481
David Majnemerb8014dd2015-02-19 02:16:16 +00001482bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1483 StringRef Prefix) {
1484 // Only certain other types are valid as prefixes; enumerate them.
1485 switch (Ty->getTypeClass()) {
1486 case Type::Builtin:
1487 case Type::Complex:
1488 case Type::Adjusted:
1489 case Type::Decayed:
1490 case Type::Pointer:
1491 case Type::BlockPointer:
1492 case Type::LValueReference:
1493 case Type::RValueReference:
1494 case Type::MemberPointer:
1495 case Type::ConstantArray:
1496 case Type::IncompleteArray:
1497 case Type::VariableArray:
1498 case Type::DependentSizedArray:
1499 case Type::DependentSizedExtVector:
1500 case Type::Vector:
1501 case Type::ExtVector:
1502 case Type::FunctionProto:
1503 case Type::FunctionNoProto:
1504 case Type::Paren:
1505 case Type::Attributed:
1506 case Type::Auto:
1507 case Type::PackExpansion:
1508 case Type::ObjCObject:
1509 case Type::ObjCInterface:
1510 case Type::ObjCObjectPointer:
1511 case Type::Atomic:
1512 llvm_unreachable("type is illegal as a nested name specifier");
1513
1514 case Type::SubstTemplateTypeParmPack:
1515 // FIXME: not clear how to mangle this!
1516 // template <class T...> class A {
1517 // template <class U...> void foo(decltype(T::foo(U())) x...);
1518 // };
1519 Out << "_SUBSTPACK_";
1520 break;
1521
1522 // <unresolved-type> ::= <template-param>
1523 // ::= <decltype>
1524 // ::= <template-template-param> <template-args>
1525 // (this last is not official yet)
1526 case Type::TypeOfExpr:
1527 case Type::TypeOf:
1528 case Type::Decltype:
1529 case Type::TemplateTypeParm:
1530 case Type::UnaryTransform:
1531 case Type::SubstTemplateTypeParm:
1532 unresolvedType:
1533 // Some callers want a prefix before the mangled type.
1534 Out << Prefix;
1535
1536 // This seems to do everything we want. It's not really
1537 // sanctioned for a substituted template parameter, though.
1538 mangleType(Ty);
1539
1540 // We never want to print 'E' directly after an unresolved-type,
1541 // so we return directly.
1542 return true;
1543
1544 case Type::Typedef:
1545 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1546 break;
1547
1548 case Type::UnresolvedUsing:
1549 mangleSourceName(
1550 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1551 break;
1552
1553 case Type::Enum:
1554 case Type::Record:
1555 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1556 break;
1557
1558 case Type::TemplateSpecialization: {
1559 const TemplateSpecializationType *TST =
1560 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001561 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001562 switch (TN.getKind()) {
1563 case TemplateName::Template:
1564 case TemplateName::QualifiedTemplate: {
1565 TemplateDecl *TD = TN.getAsTemplateDecl();
1566
1567 // If the base is a template template parameter, this is an
1568 // unresolved type.
1569 assert(TD && "no template for template specialization type");
1570 if (isa<TemplateTemplateParmDecl>(TD))
1571 goto unresolvedType;
1572
1573 mangleSourceName(TD->getIdentifier());
1574 break;
David Majnemera88b3592015-02-18 02:28:01 +00001575 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001576
1577 case TemplateName::OverloadedTemplate:
1578 case TemplateName::DependentTemplate:
1579 llvm_unreachable("invalid base for a template specialization type");
1580
1581 case TemplateName::SubstTemplateTemplateParm: {
1582 SubstTemplateTemplateParmStorage *subst =
1583 TN.getAsSubstTemplateTemplateParm();
1584 mangleExistingSubstitution(subst->getReplacement());
1585 break;
1586 }
1587
1588 case TemplateName::SubstTemplateTemplateParmPack: {
1589 // FIXME: not clear how to mangle this!
1590 // template <template <class U> class T...> class A {
1591 // template <class U...> void foo(decltype(T<U>::foo) x...);
1592 // };
1593 Out << "_SUBSTPACK_";
1594 break;
1595 }
1596 }
1597
David Majnemera88b3592015-02-18 02:28:01 +00001598 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001599 break;
David Majnemera88b3592015-02-18 02:28:01 +00001600 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001601
1602 case Type::InjectedClassName:
1603 mangleSourceName(
1604 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1605 break;
1606
1607 case Type::DependentName:
1608 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1609 break;
1610
1611 case Type::DependentTemplateSpecialization: {
1612 const DependentTemplateSpecializationType *DTST =
1613 cast<DependentTemplateSpecializationType>(Ty);
1614 mangleSourceName(DTST->getIdentifier());
1615 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1616 break;
1617 }
1618
1619 case Type::Elaborated:
1620 return mangleUnresolvedTypeOrSimpleId(
1621 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1622 }
1623
1624 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001625}
1626
1627void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1628 switch (Name.getNameKind()) {
1629 case DeclarationName::CXXConstructorName:
1630 case DeclarationName::CXXDestructorName:
1631 case DeclarationName::CXXUsingDirective:
1632 case DeclarationName::Identifier:
1633 case DeclarationName::ObjCMultiArgSelector:
1634 case DeclarationName::ObjCOneArgSelector:
1635 case DeclarationName::ObjCZeroArgSelector:
1636 llvm_unreachable("Not an operator name");
1637
1638 case DeclarationName::CXXConversionFunctionName:
1639 // <operator-name> ::= cv <type> # (cast)
1640 Out << "cv";
1641 mangleType(Name.getCXXNameType());
1642 break;
1643
1644 case DeclarationName::CXXLiteralOperatorName:
1645 Out << "li";
1646 mangleSourceName(Name.getCXXLiteralIdentifier());
1647 return;
1648
1649 case DeclarationName::CXXOperatorName:
1650 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1651 break;
1652 }
1653}
1654
1655
1656
Guy Benyei11169dd2012-12-18 14:30:41 +00001657void
1658CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1659 switch (OO) {
1660 // <operator-name> ::= nw # new
1661 case OO_New: Out << "nw"; break;
1662 // ::= na # new[]
1663 case OO_Array_New: Out << "na"; break;
1664 // ::= dl # delete
1665 case OO_Delete: Out << "dl"; break;
1666 // ::= da # delete[]
1667 case OO_Array_Delete: Out << "da"; break;
1668 // ::= ps # + (unary)
1669 // ::= pl # + (binary or unknown)
1670 case OO_Plus:
1671 Out << (Arity == 1? "ps" : "pl"); break;
1672 // ::= ng # - (unary)
1673 // ::= mi # - (binary or unknown)
1674 case OO_Minus:
1675 Out << (Arity == 1? "ng" : "mi"); break;
1676 // ::= ad # & (unary)
1677 // ::= an # & (binary or unknown)
1678 case OO_Amp:
1679 Out << (Arity == 1? "ad" : "an"); break;
1680 // ::= de # * (unary)
1681 // ::= ml # * (binary or unknown)
1682 case OO_Star:
1683 // Use binary when unknown.
1684 Out << (Arity == 1? "de" : "ml"); break;
1685 // ::= co # ~
1686 case OO_Tilde: Out << "co"; break;
1687 // ::= dv # /
1688 case OO_Slash: Out << "dv"; break;
1689 // ::= rm # %
1690 case OO_Percent: Out << "rm"; break;
1691 // ::= or # |
1692 case OO_Pipe: Out << "or"; break;
1693 // ::= eo # ^
1694 case OO_Caret: Out << "eo"; break;
1695 // ::= aS # =
1696 case OO_Equal: Out << "aS"; break;
1697 // ::= pL # +=
1698 case OO_PlusEqual: Out << "pL"; break;
1699 // ::= mI # -=
1700 case OO_MinusEqual: Out << "mI"; break;
1701 // ::= mL # *=
1702 case OO_StarEqual: Out << "mL"; break;
1703 // ::= dV # /=
1704 case OO_SlashEqual: Out << "dV"; break;
1705 // ::= rM # %=
1706 case OO_PercentEqual: Out << "rM"; break;
1707 // ::= aN # &=
1708 case OO_AmpEqual: Out << "aN"; break;
1709 // ::= oR # |=
1710 case OO_PipeEqual: Out << "oR"; break;
1711 // ::= eO # ^=
1712 case OO_CaretEqual: Out << "eO"; break;
1713 // ::= ls # <<
1714 case OO_LessLess: Out << "ls"; break;
1715 // ::= rs # >>
1716 case OO_GreaterGreater: Out << "rs"; break;
1717 // ::= lS # <<=
1718 case OO_LessLessEqual: Out << "lS"; break;
1719 // ::= rS # >>=
1720 case OO_GreaterGreaterEqual: Out << "rS"; break;
1721 // ::= eq # ==
1722 case OO_EqualEqual: Out << "eq"; break;
1723 // ::= ne # !=
1724 case OO_ExclaimEqual: Out << "ne"; break;
1725 // ::= lt # <
1726 case OO_Less: Out << "lt"; break;
1727 // ::= gt # >
1728 case OO_Greater: Out << "gt"; break;
1729 // ::= le # <=
1730 case OO_LessEqual: Out << "le"; break;
1731 // ::= ge # >=
1732 case OO_GreaterEqual: Out << "ge"; break;
1733 // ::= nt # !
1734 case OO_Exclaim: Out << "nt"; break;
1735 // ::= aa # &&
1736 case OO_AmpAmp: Out << "aa"; break;
1737 // ::= oo # ||
1738 case OO_PipePipe: Out << "oo"; break;
1739 // ::= pp # ++
1740 case OO_PlusPlus: Out << "pp"; break;
1741 // ::= mm # --
1742 case OO_MinusMinus: Out << "mm"; break;
1743 // ::= cm # ,
1744 case OO_Comma: Out << "cm"; break;
1745 // ::= pm # ->*
1746 case OO_ArrowStar: Out << "pm"; break;
1747 // ::= pt # ->
1748 case OO_Arrow: Out << "pt"; break;
1749 // ::= cl # ()
1750 case OO_Call: Out << "cl"; break;
1751 // ::= ix # []
1752 case OO_Subscript: Out << "ix"; break;
1753
1754 // ::= qu # ?
1755 // The conditional operator can't be overloaded, but we still handle it when
1756 // mangling expressions.
1757 case OO_Conditional: Out << "qu"; break;
1758
1759 case OO_None:
1760 case NUM_OVERLOADED_OPERATORS:
1761 llvm_unreachable("Not an overloaded operator");
1762 }
1763}
1764
1765void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1766 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1767 if (Quals.hasRestrict())
1768 Out << 'r';
1769 if (Quals.hasVolatile())
1770 Out << 'V';
1771 if (Quals.hasConst())
1772 Out << 'K';
1773
1774 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001775 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001776 //
David Tweed31d09b02013-09-13 12:04:22 +00001777 // <type> ::= U <target-addrspace>
1778 // <type> ::= U <OpenCL-addrspace>
1779 // <type> ::= U <CUDA-addrspace>
1780
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001782 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001783
1784 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1785 // <target-addrspace> ::= "AS" <address-space-number>
1786 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1787 ASString = "AS" + llvm::utostr_32(TargetAS);
1788 } else {
1789 switch (AS) {
1790 default: llvm_unreachable("Not a language specific address space");
1791 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1792 case LangAS::opencl_global: ASString = "CLglobal"; break;
1793 case LangAS::opencl_local: ASString = "CLlocal"; break;
1794 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1795 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1796 case LangAS::cuda_device: ASString = "CUdevice"; break;
1797 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1798 case LangAS::cuda_shared: ASString = "CUshared"; break;
1799 }
1800 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 Out << 'U' << ASString.size() << ASString;
1802 }
1803
1804 StringRef LifetimeName;
1805 switch (Quals.getObjCLifetime()) {
1806 // Objective-C ARC Extension:
1807 //
1808 // <type> ::= U "__strong"
1809 // <type> ::= U "__weak"
1810 // <type> ::= U "__autoreleasing"
1811 case Qualifiers::OCL_None:
1812 break;
1813
1814 case Qualifiers::OCL_Weak:
1815 LifetimeName = "__weak";
1816 break;
1817
1818 case Qualifiers::OCL_Strong:
1819 LifetimeName = "__strong";
1820 break;
1821
1822 case Qualifiers::OCL_Autoreleasing:
1823 LifetimeName = "__autoreleasing";
1824 break;
1825
1826 case Qualifiers::OCL_ExplicitNone:
1827 // The __unsafe_unretained qualifier is *not* mangled, so that
1828 // __unsafe_unretained types in ARC produce the same manglings as the
1829 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1830 // better ABI compatibility.
1831 //
1832 // It's safe to do this because unqualified 'id' won't show up
1833 // in any type signatures that need to be mangled.
1834 break;
1835 }
1836 if (!LifetimeName.empty())
1837 Out << 'U' << LifetimeName.size() << LifetimeName;
1838}
1839
1840void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1841 // <ref-qualifier> ::= R # lvalue reference
1842 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 switch (RefQualifier) {
1844 case RQ_None:
1845 break;
1846
1847 case RQ_LValue:
1848 Out << 'R';
1849 break;
1850
1851 case RQ_RValue:
1852 Out << 'O';
1853 break;
1854 }
1855}
1856
1857void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1858 Context.mangleObjCMethodName(MD, Out);
1859}
1860
David Majnemereea02ee2014-11-28 22:22:46 +00001861static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1862 if (Quals)
1863 return true;
1864 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1865 return true;
1866 if (Ty->isOpenCLSpecificType())
1867 return true;
1868 if (Ty->isBuiltinType())
1869 return false;
1870
1871 return true;
1872}
1873
Guy Benyei11169dd2012-12-18 14:30:41 +00001874void CXXNameMangler::mangleType(QualType T) {
1875 // If our type is instantiation-dependent but not dependent, we mangle
1876 // it as it was written in the source, removing any top-level sugar.
1877 // Otherwise, use the canonical type.
1878 //
1879 // FIXME: This is an approximation of the instantiation-dependent name
1880 // mangling rules, since we should really be using the type as written and
1881 // augmented via semantic analysis (i.e., with implicit conversions and
1882 // default template arguments) for any instantiation-dependent type.
1883 // Unfortunately, that requires several changes to our AST:
1884 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1885 // uniqued, so that we can handle substitutions properly
1886 // - Default template arguments will need to be represented in the
1887 // TemplateSpecializationType, since they need to be mangled even though
1888 // they aren't written.
1889 // - Conversions on non-type template arguments need to be expressed, since
1890 // they can affect the mangling of sizeof/alignof.
1891 if (!T->isInstantiationDependentType() || T->isDependentType())
1892 T = T.getCanonicalType();
1893 else {
1894 // Desugar any types that are purely sugar.
1895 do {
1896 // Don't desugar through template specialization types that aren't
1897 // type aliases. We need to mangle the template arguments as written.
1898 if (const TemplateSpecializationType *TST
1899 = dyn_cast<TemplateSpecializationType>(T))
1900 if (!TST->isTypeAlias())
1901 break;
1902
1903 QualType Desugared
1904 = T.getSingleStepDesugaredType(Context.getASTContext());
1905 if (Desugared == T)
1906 break;
1907
1908 T = Desugared;
1909 } while (true);
1910 }
1911 SplitQualType split = T.split();
1912 Qualifiers quals = split.Quals;
1913 const Type *ty = split.Ty;
1914
David Majnemereea02ee2014-11-28 22:22:46 +00001915 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001916 if (isSubstitutable && mangleSubstitution(T))
1917 return;
1918
1919 // If we're mangling a qualified array type, push the qualifiers to
1920 // the element type.
1921 if (quals && isa<ArrayType>(T)) {
1922 ty = Context.getASTContext().getAsArrayType(T);
1923 quals = Qualifiers();
1924
1925 // Note that we don't update T: we want to add the
1926 // substitution at the original type.
1927 }
1928
1929 if (quals) {
1930 mangleQualifiers(quals);
1931 // Recurse: even if the qualified type isn't yet substitutable,
1932 // the unqualified type might be.
1933 mangleType(QualType(ty, 0));
1934 } else {
1935 switch (ty->getTypeClass()) {
1936#define ABSTRACT_TYPE(CLASS, PARENT)
1937#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1938 case Type::CLASS: \
1939 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1940 return;
1941#define TYPE(CLASS, PARENT) \
1942 case Type::CLASS: \
1943 mangleType(static_cast<const CLASS##Type*>(ty)); \
1944 break;
1945#include "clang/AST/TypeNodes.def"
1946 }
1947 }
1948
1949 // Add the substitution.
1950 if (isSubstitutable)
1951 addSubstitution(T);
1952}
1953
1954void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1955 if (!mangleStandardSubstitution(ND))
1956 mangleName(ND);
1957}
1958
1959void CXXNameMangler::mangleType(const BuiltinType *T) {
1960 // <type> ::= <builtin-type>
1961 // <builtin-type> ::= v # void
1962 // ::= w # wchar_t
1963 // ::= b # bool
1964 // ::= c # char
1965 // ::= a # signed char
1966 // ::= h # unsigned char
1967 // ::= s # short
1968 // ::= t # unsigned short
1969 // ::= i # int
1970 // ::= j # unsigned int
1971 // ::= l # long
1972 // ::= m # unsigned long
1973 // ::= x # long long, __int64
1974 // ::= y # unsigned long long, __int64
1975 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001976 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001977 // ::= f # float
1978 // ::= d # double
1979 // ::= e # long double, __float80
1980 // UNSUPPORTED: ::= g # __float128
1981 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1982 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1983 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1984 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1985 // ::= Di # char32_t
1986 // ::= Ds # char16_t
1987 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1988 // ::= u <source-name> # vendor extended type
1989 switch (T->getKind()) {
1990 case BuiltinType::Void: Out << 'v'; break;
1991 case BuiltinType::Bool: Out << 'b'; break;
1992 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1993 case BuiltinType::UChar: Out << 'h'; break;
1994 case BuiltinType::UShort: Out << 't'; break;
1995 case BuiltinType::UInt: Out << 'j'; break;
1996 case BuiltinType::ULong: Out << 'm'; break;
1997 case BuiltinType::ULongLong: Out << 'y'; break;
1998 case BuiltinType::UInt128: Out << 'o'; break;
1999 case BuiltinType::SChar: Out << 'a'; break;
2000 case BuiltinType::WChar_S:
2001 case BuiltinType::WChar_U: Out << 'w'; break;
2002 case BuiltinType::Char16: Out << "Ds"; break;
2003 case BuiltinType::Char32: Out << "Di"; break;
2004 case BuiltinType::Short: Out << 's'; break;
2005 case BuiltinType::Int: Out << 'i'; break;
2006 case BuiltinType::Long: Out << 'l'; break;
2007 case BuiltinType::LongLong: Out << 'x'; break;
2008 case BuiltinType::Int128: Out << 'n'; break;
2009 case BuiltinType::Half: Out << "Dh"; break;
2010 case BuiltinType::Float: Out << 'f'; break;
2011 case BuiltinType::Double: Out << 'd'; break;
David Majnemer2617ea62015-06-09 18:05:33 +00002012 case BuiltinType::LongDouble:
2013 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2014 ? 'g'
2015 : 'e');
2016 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 case BuiltinType::NullPtr: Out << "Dn"; break;
2018
2019#define BUILTIN_TYPE(Id, SingletonId)
2020#define PLACEHOLDER_TYPE(Id, SingletonId) \
2021 case BuiltinType::Id:
2022#include "clang/AST/BuiltinTypes.def"
2023 case BuiltinType::Dependent:
2024 llvm_unreachable("mangling a placeholder type");
2025 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2026 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2027 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00002028 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2029 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2030 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2031 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2032 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2033 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00002034 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002035 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 }
2037}
2038
2039// <type> ::= <function-type>
2040// <function-type> ::= [<CV-qualifiers>] F [Y]
2041// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002042void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2043 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2044 // e.g. "const" in "int (A::*)() const".
2045 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2046
2047 Out << 'F';
2048
2049 // FIXME: We don't have enough information in the AST to produce the 'Y'
2050 // encoding for extern "C" function types.
2051 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2052
2053 // Mangle the ref-qualifier, if present.
2054 mangleRefQualifier(T->getRefQualifier());
2055
2056 Out << 'E';
2057}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002058
Guy Benyei11169dd2012-12-18 14:30:41 +00002059void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002060 // Function types without prototypes can arise when mangling a function type
2061 // within an overloadable function in C. We mangle these as the absence of any
2062 // parameter types (not even an empty parameter list).
2063 Out << 'F';
2064
2065 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2066
2067 FunctionTypeDepth.enterResultType();
2068 mangleType(T->getReturnType());
2069 FunctionTypeDepth.leaveResultType();
2070
2071 FunctionTypeDepth.pop(saved);
2072 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002073}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002074
Guy Benyei11169dd2012-12-18 14:30:41 +00002075void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2076 bool MangleReturnType) {
2077 // We should never be mangling something without a prototype.
2078 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2079
2080 // Record that we're in a function type. See mangleFunctionParam
2081 // for details on what we're trying to achieve here.
2082 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2083
2084 // <bare-function-type> ::= <signature type>+
2085 if (MangleReturnType) {
2086 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002087 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 FunctionTypeDepth.leaveResultType();
2089 }
2090
Alp Toker9cacbab2014-01-20 20:26:09 +00002091 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002092 // <builtin-type> ::= v # void
2093 Out << 'v';
2094
2095 FunctionTypeDepth.pop(saved);
2096 return;
2097 }
2098
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002099 for (const auto &Arg : Proto->param_types())
2100 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002101
2102 FunctionTypeDepth.pop(saved);
2103
2104 // <builtin-type> ::= z # ellipsis
2105 if (Proto->isVariadic())
2106 Out << 'z';
2107}
2108
2109// <type> ::= <class-enum-type>
2110// <class-enum-type> ::= <name>
2111void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2112 mangleName(T->getDecl());
2113}
2114
2115// <type> ::= <class-enum-type>
2116// <class-enum-type> ::= <name>
2117void CXXNameMangler::mangleType(const EnumType *T) {
2118 mangleType(static_cast<const TagType*>(T));
2119}
2120void CXXNameMangler::mangleType(const RecordType *T) {
2121 mangleType(static_cast<const TagType*>(T));
2122}
2123void CXXNameMangler::mangleType(const TagType *T) {
2124 mangleName(T->getDecl());
2125}
2126
2127// <type> ::= <array-type>
2128// <array-type> ::= A <positive dimension number> _ <element type>
2129// ::= A [<dimension expression>] _ <element type>
2130void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2131 Out << 'A' << T->getSize() << '_';
2132 mangleType(T->getElementType());
2133}
2134void CXXNameMangler::mangleType(const VariableArrayType *T) {
2135 Out << 'A';
2136 // decayed vla types (size 0) will just be skipped.
2137 if (T->getSizeExpr())
2138 mangleExpression(T->getSizeExpr());
2139 Out << '_';
2140 mangleType(T->getElementType());
2141}
2142void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2143 Out << 'A';
2144 mangleExpression(T->getSizeExpr());
2145 Out << '_';
2146 mangleType(T->getElementType());
2147}
2148void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2149 Out << "A_";
2150 mangleType(T->getElementType());
2151}
2152
2153// <type> ::= <pointer-to-member-type>
2154// <pointer-to-member-type> ::= M <class type> <member type>
2155void CXXNameMangler::mangleType(const MemberPointerType *T) {
2156 Out << 'M';
2157 mangleType(QualType(T->getClass(), 0));
2158 QualType PointeeType = T->getPointeeType();
2159 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2160 mangleType(FPT);
2161
2162 // Itanium C++ ABI 5.1.8:
2163 //
2164 // The type of a non-static member function is considered to be different,
2165 // for the purposes of substitution, from the type of a namespace-scope or
2166 // static member function whose type appears similar. The types of two
2167 // non-static member functions are considered to be different, for the
2168 // purposes of substitution, if the functions are members of different
2169 // classes. In other words, for the purposes of substitution, the class of
2170 // which the function is a member is considered part of the type of
2171 // function.
2172
2173 // Given that we already substitute member function pointers as a
2174 // whole, the net effect of this rule is just to unconditionally
2175 // suppress substitution on the function type in a member pointer.
2176 // We increment the SeqID here to emulate adding an entry to the
2177 // substitution table.
2178 ++SeqID;
2179 } else
2180 mangleType(PointeeType);
2181}
2182
2183// <type> ::= <template-param>
2184void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2185 mangleTemplateParameter(T->getIndex());
2186}
2187
2188// <type> ::= <template-param>
2189void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2190 // FIXME: not clear how to mangle this!
2191 // template <class T...> class A {
2192 // template <class U...> void foo(T(*)(U) x...);
2193 // };
2194 Out << "_SUBSTPACK_";
2195}
2196
2197// <type> ::= P <type> # pointer-to
2198void CXXNameMangler::mangleType(const PointerType *T) {
2199 Out << 'P';
2200 mangleType(T->getPointeeType());
2201}
2202void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2203 Out << 'P';
2204 mangleType(T->getPointeeType());
2205}
2206
2207// <type> ::= R <type> # reference-to
2208void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2209 Out << 'R';
2210 mangleType(T->getPointeeType());
2211}
2212
2213// <type> ::= O <type> # rvalue reference-to (C++0x)
2214void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2215 Out << 'O';
2216 mangleType(T->getPointeeType());
2217}
2218
2219// <type> ::= C <type> # complex pair (C 2000)
2220void CXXNameMangler::mangleType(const ComplexType *T) {
2221 Out << 'C';
2222 mangleType(T->getElementType());
2223}
2224
2225// ARM's ABI for Neon vector types specifies that they should be mangled as
2226// if they are structs (to match ARM's initial implementation). The
2227// vector type must be one of the special types predefined by ARM.
2228void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2229 QualType EltType = T->getElementType();
2230 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002231 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2233 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002234 case BuiltinType::SChar:
2235 case BuiltinType::UChar:
2236 EltName = "poly8_t";
2237 break;
2238 case BuiltinType::Short:
2239 case BuiltinType::UShort:
2240 EltName = "poly16_t";
2241 break;
2242 case BuiltinType::ULongLong:
2243 EltName = "poly64_t";
2244 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2246 }
2247 } else {
2248 switch (cast<BuiltinType>(EltType)->getKind()) {
2249 case BuiltinType::SChar: EltName = "int8_t"; break;
2250 case BuiltinType::UChar: EltName = "uint8_t"; break;
2251 case BuiltinType::Short: EltName = "int16_t"; break;
2252 case BuiltinType::UShort: EltName = "uint16_t"; break;
2253 case BuiltinType::Int: EltName = "int32_t"; break;
2254 case BuiltinType::UInt: EltName = "uint32_t"; break;
2255 case BuiltinType::LongLong: EltName = "int64_t"; break;
2256 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002257 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002259 case BuiltinType::Half: EltName = "float16_t";break;
2260 default:
2261 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 }
2263 }
Craig Topper36250ad2014-05-12 05:36:57 +00002264 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 unsigned BitSize = (T->getNumElements() *
2266 getASTContext().getTypeSize(EltType));
2267 if (BitSize == 64)
2268 BaseName = "__simd64_";
2269 else {
2270 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2271 BaseName = "__simd128_";
2272 }
2273 Out << strlen(BaseName) + strlen(EltName);
2274 Out << BaseName << EltName;
2275}
2276
Tim Northover2fe823a2013-08-01 09:23:19 +00002277static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2278 switch (EltType->getKind()) {
2279 case BuiltinType::SChar:
2280 return "Int8";
2281 case BuiltinType::Short:
2282 return "Int16";
2283 case BuiltinType::Int:
2284 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002285 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002286 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002287 return "Int64";
2288 case BuiltinType::UChar:
2289 return "Uint8";
2290 case BuiltinType::UShort:
2291 return "Uint16";
2292 case BuiltinType::UInt:
2293 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002294 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002295 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002296 return "Uint64";
2297 case BuiltinType::Half:
2298 return "Float16";
2299 case BuiltinType::Float:
2300 return "Float32";
2301 case BuiltinType::Double:
2302 return "Float64";
2303 default:
2304 llvm_unreachable("Unexpected vector element base type");
2305 }
2306}
2307
2308// AArch64's ABI for Neon vector types specifies that they should be mangled as
2309// the equivalent internal name. The vector type must be one of the special
2310// types predefined by ARM.
2311void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2312 QualType EltType = T->getElementType();
2313 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2314 unsigned BitSize =
2315 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002316 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002317
2318 assert((BitSize == 64 || BitSize == 128) &&
2319 "Neon vector type not 64 or 128 bits");
2320
Tim Northover2fe823a2013-08-01 09:23:19 +00002321 StringRef EltName;
2322 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2323 switch (cast<BuiltinType>(EltType)->getKind()) {
2324 case BuiltinType::UChar:
2325 EltName = "Poly8";
2326 break;
2327 case BuiltinType::UShort:
2328 EltName = "Poly16";
2329 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002330 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002331 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002332 EltName = "Poly64";
2333 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002334 default:
2335 llvm_unreachable("unexpected Neon polynomial vector element type");
2336 }
2337 } else
2338 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2339
2340 std::string TypeName =
2341 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2342 Out << TypeName.length() << TypeName;
2343}
2344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345// GNU extension: vector types
2346// <type> ::= <vector-type>
2347// <vector-type> ::= Dv <positive dimension number> _
2348// <extended element type>
2349// ::= Dv [<dimension expression>] _ <element type>
2350// <extended element type> ::= <element type>
2351// ::= p # AltiVec vector pixel
2352// ::= b # Altivec vector bool
2353void CXXNameMangler::mangleType(const VectorType *T) {
2354 if ((T->getVectorKind() == VectorType::NeonVector ||
2355 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002356 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002357 llvm::Triple::ArchType Arch =
2358 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002359 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002360 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002361 mangleAArch64NeonVectorType(T);
2362 else
2363 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002364 return;
2365 }
2366 Out << "Dv" << T->getNumElements() << '_';
2367 if (T->getVectorKind() == VectorType::AltiVecPixel)
2368 Out << 'p';
2369 else if (T->getVectorKind() == VectorType::AltiVecBool)
2370 Out << 'b';
2371 else
2372 mangleType(T->getElementType());
2373}
2374void CXXNameMangler::mangleType(const ExtVectorType *T) {
2375 mangleType(static_cast<const VectorType*>(T));
2376}
2377void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2378 Out << "Dv";
2379 mangleExpression(T->getSizeExpr());
2380 Out << '_';
2381 mangleType(T->getElementType());
2382}
2383
2384void CXXNameMangler::mangleType(const PackExpansionType *T) {
2385 // <type> ::= Dp <type> # pack expansion (C++0x)
2386 Out << "Dp";
2387 mangleType(T->getPattern());
2388}
2389
2390void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2391 mangleSourceName(T->getDecl()->getIdentifier());
2392}
2393
2394void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002395 // Treat __kindof as a vendor extended type qualifier.
2396 if (T->isKindOfType())
2397 Out << "U8__kindof";
2398
Eli Friedman5f508952013-06-18 22:41:37 +00002399 if (!T->qual_empty()) {
2400 // Mangle protocol qualifiers.
2401 SmallString<64> QualStr;
2402 llvm::raw_svector_ostream QualOS(QualStr);
2403 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002404 for (const auto *I : T->quals()) {
2405 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002406 QualOS << name.size() << name;
2407 }
Eli Friedman5f508952013-06-18 22:41:37 +00002408 Out << 'U' << QualStr.size() << QualStr;
2409 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002412
2413 if (T->isSpecialized()) {
2414 // Mangle type arguments as I <type>+ E
2415 Out << 'I';
2416 for (auto typeArg : T->getTypeArgs())
2417 mangleType(typeArg);
2418 Out << 'E';
2419 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002420}
2421
2422void CXXNameMangler::mangleType(const BlockPointerType *T) {
2423 Out << "U13block_pointer";
2424 mangleType(T->getPointeeType());
2425}
2426
2427void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2428 // Mangle injected class name types as if the user had written the
2429 // specialization out fully. It may not actually be possible to see
2430 // this mangling, though.
2431 mangleType(T->getInjectedSpecializationType());
2432}
2433
2434void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2435 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2436 mangleName(TD, T->getArgs(), T->getNumArgs());
2437 } else {
2438 if (mangleSubstitution(QualType(T, 0)))
2439 return;
2440
2441 mangleTemplatePrefix(T->getTemplateName());
2442
2443 // FIXME: GCC does not appear to mangle the template arguments when
2444 // the template in question is a dependent template name. Should we
2445 // emulate that badness?
2446 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2447 addSubstitution(QualType(T, 0));
2448 }
2449}
2450
2451void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002452 // Proposal by cxx-abi-dev, 2014-03-26
2453 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2454 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002455 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002456 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002457 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002458 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002459 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002460 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002461 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002462 switch (T->getKeyword()) {
2463 case ETK_Typename:
2464 break;
2465 case ETK_Struct:
2466 case ETK_Class:
2467 case ETK_Interface:
2468 Out << "Ts";
2469 break;
2470 case ETK_Union:
2471 Out << "Tu";
2472 break;
2473 case ETK_Enum:
2474 Out << "Te";
2475 break;
2476 default:
2477 llvm_unreachable("unexpected keyword for dependent type name");
2478 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002479 // Typename types are always nested
2480 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002482 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 Out << 'E';
2484}
2485
2486void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2487 // Dependently-scoped template types are nested if they have a prefix.
2488 Out << 'N';
2489
2490 // TODO: avoid making this TemplateName.
2491 TemplateName Prefix =
2492 getASTContext().getDependentTemplateName(T->getQualifier(),
2493 T->getIdentifier());
2494 mangleTemplatePrefix(Prefix);
2495
2496 // FIXME: GCC does not appear to mangle the template arguments when
2497 // the template in question is a dependent template name. Should we
2498 // emulate that badness?
2499 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2500 Out << 'E';
2501}
2502
2503void CXXNameMangler::mangleType(const TypeOfType *T) {
2504 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2505 // "extension with parameters" mangling.
2506 Out << "u6typeof";
2507}
2508
2509void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2510 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2511 // "extension with parameters" mangling.
2512 Out << "u6typeof";
2513}
2514
2515void CXXNameMangler::mangleType(const DecltypeType *T) {
2516 Expr *E = T->getUnderlyingExpr();
2517
2518 // type ::= Dt <expression> E # decltype of an id-expression
2519 // # or class member access
2520 // ::= DT <expression> E # decltype of an expression
2521
2522 // This purports to be an exhaustive list of id-expressions and
2523 // class member accesses. Note that we do not ignore parentheses;
2524 // parentheses change the semantics of decltype for these
2525 // expressions (and cause the mangler to use the other form).
2526 if (isa<DeclRefExpr>(E) ||
2527 isa<MemberExpr>(E) ||
2528 isa<UnresolvedLookupExpr>(E) ||
2529 isa<DependentScopeDeclRefExpr>(E) ||
2530 isa<CXXDependentScopeMemberExpr>(E) ||
2531 isa<UnresolvedMemberExpr>(E))
2532 Out << "Dt";
2533 else
2534 Out << "DT";
2535 mangleExpression(E);
2536 Out << 'E';
2537}
2538
2539void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2540 // If this is dependent, we need to record that. If not, we simply
2541 // mangle it as the underlying type since they are equivalent.
2542 if (T->isDependentType()) {
2543 Out << 'U';
2544
2545 switch (T->getUTTKind()) {
2546 case UnaryTransformType::EnumUnderlyingType:
2547 Out << "3eut";
2548 break;
2549 }
2550 }
2551
2552 mangleType(T->getUnderlyingType());
2553}
2554
2555void CXXNameMangler::mangleType(const AutoType *T) {
2556 QualType D = T->getDeducedType();
2557 // <builtin-type> ::= Da # dependent auto
2558 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002559 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 else
2561 mangleType(D);
2562}
2563
2564void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002565 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 // (Until there's a standardized mangling...)
2567 Out << "U7_Atomic";
2568 mangleType(T->getValueType());
2569}
2570
2571void CXXNameMangler::mangleIntegerLiteral(QualType T,
2572 const llvm::APSInt &Value) {
2573 // <expr-primary> ::= L <type> <value number> E # integer literal
2574 Out << 'L';
2575
2576 mangleType(T);
2577 if (T->isBooleanType()) {
2578 // Boolean values are encoded as 0/1.
2579 Out << (Value.getBoolValue() ? '1' : '0');
2580 } else {
2581 mangleNumber(Value);
2582 }
2583 Out << 'E';
2584
2585}
2586
David Majnemer1dabfdc2015-02-14 13:23:54 +00002587void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2588 // Ignore member expressions involving anonymous unions.
2589 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2590 if (!RT->getDecl()->isAnonymousStructOrUnion())
2591 break;
2592 const auto *ME = dyn_cast<MemberExpr>(Base);
2593 if (!ME)
2594 break;
2595 Base = ME->getBase();
2596 IsArrow = ME->isArrow();
2597 }
2598
2599 if (Base->isImplicitCXXThis()) {
2600 // Note: GCC mangles member expressions to the implicit 'this' as
2601 // *this., whereas we represent them as this->. The Itanium C++ ABI
2602 // does not specify anything here, so we follow GCC.
2603 Out << "dtdefpT";
2604 } else {
2605 Out << (IsArrow ? "pt" : "dt");
2606 mangleExpression(Base);
2607 }
2608}
2609
Guy Benyei11169dd2012-12-18 14:30:41 +00002610/// Mangles a member expression.
2611void CXXNameMangler::mangleMemberExpr(const Expr *base,
2612 bool isArrow,
2613 NestedNameSpecifier *qualifier,
2614 NamedDecl *firstQualifierLookup,
2615 DeclarationName member,
2616 unsigned arity) {
2617 // <expression> ::= dt <expression> <unresolved-name>
2618 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002619 if (base)
2620 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002621 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002622}
2623
2624/// Look at the callee of the given call expression and determine if
2625/// it's a parenthesized id-expression which would have triggered ADL
2626/// otherwise.
2627static bool isParenthesizedADLCallee(const CallExpr *call) {
2628 const Expr *callee = call->getCallee();
2629 const Expr *fn = callee->IgnoreParens();
2630
2631 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2632 // too, but for those to appear in the callee, it would have to be
2633 // parenthesized.
2634 if (callee == fn) return false;
2635
2636 // Must be an unresolved lookup.
2637 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2638 if (!lookup) return false;
2639
2640 assert(!lookup->requiresADL());
2641
2642 // Must be an unqualified lookup.
2643 if (lookup->getQualifier()) return false;
2644
2645 // Must not have found a class member. Note that if one is a class
2646 // member, they're all class members.
2647 if (lookup->getNumDecls() > 0 &&
2648 (*lookup->decls_begin())->isCXXClassMember())
2649 return false;
2650
2651 // Otherwise, ADL would have been triggered.
2652 return true;
2653}
2654
David Majnemer9c775c72014-09-23 04:27:55 +00002655void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2656 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2657 Out << CastEncoding;
2658 mangleType(ECE->getType());
2659 mangleExpression(ECE->getSubExpr());
2660}
2661
Richard Smith520449d2015-02-05 06:15:50 +00002662void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2663 if (auto *Syntactic = InitList->getSyntacticForm())
2664 InitList = Syntactic;
2665 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2666 mangleExpression(InitList->getInit(i));
2667}
2668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2670 // <expression> ::= <unary operator-name> <expression>
2671 // ::= <binary operator-name> <expression> <expression>
2672 // ::= <trinary operator-name> <expression> <expression> <expression>
2673 // ::= cv <type> expression # conversion with one argument
2674 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002675 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2676 // ::= sc <type> <expression> # static_cast<type> (expression)
2677 // ::= cc <type> <expression> # const_cast<type> (expression)
2678 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 // ::= st <type> # sizeof (a type)
2680 // ::= at <type> # alignof (a type)
2681 // ::= <template-param>
2682 // ::= <function-param>
2683 // ::= sr <type> <unqualified-name> # dependent name
2684 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2685 // ::= ds <expression> <expression> # expr.*expr
2686 // ::= sZ <template-param> # size of a parameter pack
2687 // ::= sZ <function-param> # size of a function parameter pack
2688 // ::= <expr-primary>
2689 // <expr-primary> ::= L <type> <value number> E # integer literal
2690 // ::= L <type <value float> E # floating literal
2691 // ::= L <mangled-name> E # external name
2692 // ::= fpT # 'this' expression
2693 QualType ImplicitlyConvertedToType;
2694
2695recurse:
2696 switch (E->getStmtClass()) {
2697 case Expr::NoStmtClass:
2698#define ABSTRACT_STMT(Type)
2699#define EXPR(Type, Base)
2700#define STMT(Type, Base) \
2701 case Expr::Type##Class:
2702#include "clang/AST/StmtNodes.inc"
2703 // fallthrough
2704
2705 // These all can only appear in local or variable-initialization
2706 // contexts and so should never appear in a mangling.
2707 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002708 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002710 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 case Expr::ParenListExprClass:
2712 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002713 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002714 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 llvm_unreachable("unexpected statement kind");
2716
2717 // FIXME: invent manglings for all these.
2718 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 case Expr::ChooseExprClass:
2720 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002721 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 case Expr::ExtVectorElementExprClass:
2723 case Expr::GenericSelectionExprClass:
2724 case Expr::ObjCEncodeExprClass:
2725 case Expr::ObjCIsaExprClass:
2726 case Expr::ObjCIvarRefExprClass:
2727 case Expr::ObjCMessageExprClass:
2728 case Expr::ObjCPropertyRefExprClass:
2729 case Expr::ObjCProtocolExprClass:
2730 case Expr::ObjCSelectorExprClass:
2731 case Expr::ObjCStringLiteralClass:
2732 case Expr::ObjCBoxedExprClass:
2733 case Expr::ObjCArrayLiteralClass:
2734 case Expr::ObjCDictionaryLiteralClass:
2735 case Expr::ObjCSubscriptRefExprClass:
2736 case Expr::ObjCIndirectCopyRestoreExprClass:
2737 case Expr::OffsetOfExprClass:
2738 case Expr::PredefinedExprClass:
2739 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002740 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 case Expr::TypeTraitExprClass:
2743 case Expr::ArrayTypeTraitExprClass:
2744 case Expr::ExpressionTraitExprClass:
2745 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 case Expr::CUDAKernelCallExprClass:
2747 case Expr::AsTypeExprClass:
2748 case Expr::PseudoObjectExprClass:
2749 case Expr::AtomicExprClass:
2750 {
2751 // As bad as this diagnostic is, it's better than crashing.
2752 DiagnosticsEngine &Diags = Context.getDiags();
2753 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2754 "cannot yet mangle expression type %0");
2755 Diags.Report(E->getExprLoc(), DiagID)
2756 << E->getStmtClassName() << E->getSourceRange();
2757 break;
2758 }
2759
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002760 case Expr::CXXUuidofExprClass: {
2761 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2762 if (UE->isTypeOperand()) {
2763 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2764 Out << "u8__uuidoft";
2765 mangleType(UuidT);
2766 } else {
2767 Expr *UuidExp = UE->getExprOperand();
2768 Out << "u8__uuidofz";
2769 mangleExpression(UuidExp, Arity);
2770 }
2771 break;
2772 }
2773
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 // Even gcc-4.5 doesn't mangle this.
2775 case Expr::BinaryConditionalOperatorClass: {
2776 DiagnosticsEngine &Diags = Context.getDiags();
2777 unsigned DiagID =
2778 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2779 "?: operator with omitted middle operand cannot be mangled");
2780 Diags.Report(E->getExprLoc(), DiagID)
2781 << E->getStmtClassName() << E->getSourceRange();
2782 break;
2783 }
2784
2785 // These are used for internal purposes and cannot be meaningfully mangled.
2786 case Expr::OpaqueValueExprClass:
2787 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2788
2789 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002791 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 Out << "E";
2793 break;
2794 }
2795
2796 case Expr::CXXDefaultArgExprClass:
2797 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2798 break;
2799
Richard Smith852c9db2013-04-20 22:23:05 +00002800 case Expr::CXXDefaultInitExprClass:
2801 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2802 break;
2803
Richard Smithcc1b96d2013-06-12 22:31:48 +00002804 case Expr::CXXStdInitializerListExprClass:
2805 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2806 break;
2807
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 case Expr::SubstNonTypeTemplateParmExprClass:
2809 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2810 Arity);
2811 break;
2812
2813 case Expr::UserDefinedLiteralClass:
2814 // We follow g++'s approach of mangling a UDL as a call to the literal
2815 // operator.
2816 case Expr::CXXMemberCallExprClass: // fallthrough
2817 case Expr::CallExprClass: {
2818 const CallExpr *CE = cast<CallExpr>(E);
2819
2820 // <expression> ::= cp <simple-id> <expression>* E
2821 // We use this mangling only when the call would use ADL except
2822 // for being parenthesized. Per discussion with David
2823 // Vandervoorde, 2011.04.25.
2824 if (isParenthesizedADLCallee(CE)) {
2825 Out << "cp";
2826 // The callee here is a parenthesized UnresolvedLookupExpr with
2827 // no qualifier and should always get mangled as a <simple-id>
2828 // anyway.
2829
2830 // <expression> ::= cl <expression>* E
2831 } else {
2832 Out << "cl";
2833 }
2834
David Majnemer67a8ec62015-02-19 21:41:48 +00002835 unsigned CallArity = CE->getNumArgs();
2836 for (const Expr *Arg : CE->arguments())
2837 if (isa<PackExpansionExpr>(Arg))
2838 CallArity = UnknownArity;
2839
2840 mangleExpression(CE->getCallee(), CallArity);
2841 for (const Expr *Arg : CE->arguments())
2842 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 Out << 'E';
2844 break;
2845 }
2846
2847 case Expr::CXXNewExprClass: {
2848 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2849 if (New->isGlobalNew()) Out << "gs";
2850 Out << (New->isArray() ? "na" : "nw");
2851 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2852 E = New->placement_arg_end(); I != E; ++I)
2853 mangleExpression(*I);
2854 Out << '_';
2855 mangleType(New->getAllocatedType());
2856 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2858 Out << "il";
2859 else
2860 Out << "pi";
2861 const Expr *Init = New->getInitializer();
2862 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2863 // Directly inline the initializers.
2864 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2865 E = CCE->arg_end();
2866 I != E; ++I)
2867 mangleExpression(*I);
2868 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2869 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2870 mangleExpression(PLE->getExpr(i));
2871 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2872 isa<InitListExpr>(Init)) {
2873 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002874 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 } else
2876 mangleExpression(Init);
2877 }
2878 Out << 'E';
2879 break;
2880 }
2881
David Majnemer1dabfdc2015-02-14 13:23:54 +00002882 case Expr::CXXPseudoDestructorExprClass: {
2883 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2884 if (const Expr *Base = PDE->getBase())
2885 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00002886 NestedNameSpecifier *Qualifier = PDE->getQualifier();
2887 QualType ScopeType;
2888 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
2889 if (Qualifier) {
2890 mangleUnresolvedPrefix(Qualifier,
2891 /*Recursive=*/true);
2892 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
2893 Out << 'E';
2894 } else {
2895 Out << "sr";
2896 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
2897 Out << 'E';
2898 }
2899 } else if (Qualifier) {
2900 mangleUnresolvedPrefix(Qualifier);
2901 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00002902 // <base-unresolved-name> ::= dn <destructor-name>
2903 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00002904 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00002905 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00002906 break;
2907 }
2908
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 case Expr::MemberExprClass: {
2910 const MemberExpr *ME = cast<MemberExpr>(E);
2911 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002912 ME->getQualifier(), nullptr,
2913 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 break;
2915 }
2916
2917 case Expr::UnresolvedMemberExprClass: {
2918 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00002919 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
2920 ME->isArrow(), ME->getQualifier(), nullptr,
2921 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 if (ME->hasExplicitTemplateArgs())
2923 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2924 break;
2925 }
2926
2927 case Expr::CXXDependentScopeMemberExprClass: {
2928 const CXXDependentScopeMemberExpr *ME
2929 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00002930 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
2931 ME->isArrow(), ME->getQualifier(),
2932 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 ME->getMember(), Arity);
2934 if (ME->hasExplicitTemplateArgs())
2935 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2936 break;
2937 }
2938
2939 case Expr::UnresolvedLookupExprClass: {
2940 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00002941 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002942
2943 // All the <unresolved-name> productions end in a
2944 // base-unresolved-name, where <template-args> are just tacked
2945 // onto the end.
2946 if (ULE->hasExplicitTemplateArgs())
2947 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2948 break;
2949 }
2950
2951 case Expr::CXXUnresolvedConstructExprClass: {
2952 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2953 unsigned N = CE->arg_size();
2954
2955 Out << "cv";
2956 mangleType(CE->getType());
2957 if (N != 1) Out << '_';
2958 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2959 if (N != 1) Out << 'E';
2960 break;
2961 }
2962
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00002964 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00002965 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00002966 assert(
2967 CE->getNumArgs() >= 1 &&
2968 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2969 "implicit CXXConstructExpr must have one argument");
2970 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2971 }
2972 Out << "il";
2973 for (auto *E : CE->arguments())
2974 mangleExpression(E);
2975 Out << "E";
2976 break;
2977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002978
Richard Smith520449d2015-02-05 06:15:50 +00002979 case Expr::CXXTemporaryObjectExprClass: {
2980 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2981 unsigned N = CE->getNumArgs();
2982 bool List = CE->isListInitialization();
2983
2984 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 Out << "tl";
2986 else
2987 Out << "cv";
2988 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002989 if (!List && N != 1)
2990 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00002991 if (CE->isStdInitListInitialization()) {
2992 // We implicitly created a std::initializer_list<T> for the first argument
2993 // of a constructor of type U in an expression of the form U{a, b, c}.
2994 // Strip all the semantic gunk off the initializer list.
2995 auto *SILE =
2996 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2997 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2998 mangleInitListElements(ILE);
2999 } else {
3000 for (auto *E : CE->arguments())
3001 mangleExpression(E);
3002 }
Richard Smith520449d2015-02-05 06:15:50 +00003003 if (List || N != 1)
3004 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 break;
3006 }
3007
3008 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003009 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003011 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 break;
3013
3014 case Expr::CXXNoexceptExprClass:
3015 Out << "nx";
3016 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3017 break;
3018
3019 case Expr::UnaryExprOrTypeTraitExprClass: {
3020 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3021
3022 if (!SAE->isInstantiationDependent()) {
3023 // Itanium C++ ABI:
3024 // If the operand of a sizeof or alignof operator is not
3025 // instantiation-dependent it is encoded as an integer literal
3026 // reflecting the result of the operator.
3027 //
3028 // If the result of the operator is implicitly converted to a known
3029 // integer type, that type is used for the literal; otherwise, the type
3030 // of std::size_t or std::ptrdiff_t is used.
3031 QualType T = (ImplicitlyConvertedToType.isNull() ||
3032 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3033 : ImplicitlyConvertedToType;
3034 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3035 mangleIntegerLiteral(T, V);
3036 break;
3037 }
3038
3039 switch(SAE->getKind()) {
3040 case UETT_SizeOf:
3041 Out << 's';
3042 break;
3043 case UETT_AlignOf:
3044 Out << 'a';
3045 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003046 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 DiagnosticsEngine &Diags = Context.getDiags();
3048 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3049 "cannot yet mangle vec_step expression");
3050 Diags.Report(DiagID);
3051 return;
3052 }
Alexey Bataev00396512015-07-02 03:40:19 +00003053 case UETT_OpenMPRequiredSimdAlign:
3054 DiagnosticsEngine &Diags = Context.getDiags();
3055 unsigned DiagID = Diags.getCustomDiagID(
3056 DiagnosticsEngine::Error,
3057 "cannot yet mangle __builtin_omp_required_simd_align expression");
3058 Diags.Report(DiagID);
3059 return;
3060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 if (SAE->isArgumentType()) {
3062 Out << 't';
3063 mangleType(SAE->getArgumentType());
3064 } else {
3065 Out << 'z';
3066 mangleExpression(SAE->getArgumentExpr());
3067 }
3068 break;
3069 }
3070
3071 case Expr::CXXThrowExprClass: {
3072 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003073 // <expression> ::= tw <expression> # throw expression
3074 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 if (TE->getSubExpr()) {
3076 Out << "tw";
3077 mangleExpression(TE->getSubExpr());
3078 } else {
3079 Out << "tr";
3080 }
3081 break;
3082 }
3083
3084 case Expr::CXXTypeidExprClass: {
3085 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003086 // <expression> ::= ti <type> # typeid (type)
3087 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 if (TIE->isTypeOperand()) {
3089 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003090 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 } else {
3092 Out << "te";
3093 mangleExpression(TIE->getExprOperand());
3094 }
3095 break;
3096 }
3097
3098 case Expr::CXXDeleteExprClass: {
3099 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003100 // <expression> ::= [gs] dl <expression> # [::] delete expr
3101 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 if (DE->isGlobalDelete()) Out << "gs";
3103 Out << (DE->isArrayForm() ? "da" : "dl");
3104 mangleExpression(DE->getArgument());
3105 break;
3106 }
3107
3108 case Expr::UnaryOperatorClass: {
3109 const UnaryOperator *UO = cast<UnaryOperator>(E);
3110 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3111 /*Arity=*/1);
3112 mangleExpression(UO->getSubExpr());
3113 break;
3114 }
3115
3116 case Expr::ArraySubscriptExprClass: {
3117 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3118
3119 // Array subscript is treated as a syntactically weird form of
3120 // binary operator.
3121 Out << "ix";
3122 mangleExpression(AE->getLHS());
3123 mangleExpression(AE->getRHS());
3124 break;
3125 }
3126
3127 case Expr::CompoundAssignOperatorClass: // fallthrough
3128 case Expr::BinaryOperatorClass: {
3129 const BinaryOperator *BO = cast<BinaryOperator>(E);
3130 if (BO->getOpcode() == BO_PtrMemD)
3131 Out << "ds";
3132 else
3133 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3134 /*Arity=*/2);
3135 mangleExpression(BO->getLHS());
3136 mangleExpression(BO->getRHS());
3137 break;
3138 }
3139
3140 case Expr::ConditionalOperatorClass: {
3141 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3142 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3143 mangleExpression(CO->getCond());
3144 mangleExpression(CO->getLHS(), Arity);
3145 mangleExpression(CO->getRHS(), Arity);
3146 break;
3147 }
3148
3149 case Expr::ImplicitCastExprClass: {
3150 ImplicitlyConvertedToType = E->getType();
3151 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3152 goto recurse;
3153 }
3154
3155 case Expr::ObjCBridgedCastExprClass: {
3156 // Mangle ownership casts as a vendor extended operator __bridge,
3157 // __bridge_transfer, or __bridge_retain.
3158 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3159 Out << "v1U" << Kind.size() << Kind;
3160 }
3161 // Fall through to mangle the cast itself.
3162
3163 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003164 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003166
Richard Smith520449d2015-02-05 06:15:50 +00003167 case Expr::CXXFunctionalCastExprClass: {
3168 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3169 // FIXME: Add isImplicit to CXXConstructExpr.
3170 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3171 if (CCE->getParenOrBraceRange().isInvalid())
3172 Sub = CCE->getArg(0)->IgnoreImplicit();
3173 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3174 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3175 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3176 Out << "tl";
3177 mangleType(E->getType());
3178 mangleInitListElements(IL);
3179 Out << "E";
3180 } else {
3181 mangleCastExpression(E, "cv");
3182 }
3183 break;
3184 }
3185
David Majnemer9c775c72014-09-23 04:27:55 +00003186 case Expr::CXXStaticCastExprClass:
3187 mangleCastExpression(E, "sc");
3188 break;
3189 case Expr::CXXDynamicCastExprClass:
3190 mangleCastExpression(E, "dc");
3191 break;
3192 case Expr::CXXReinterpretCastExprClass:
3193 mangleCastExpression(E, "rc");
3194 break;
3195 case Expr::CXXConstCastExprClass:
3196 mangleCastExpression(E, "cc");
3197 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003198
3199 case Expr::CXXOperatorCallExprClass: {
3200 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3201 unsigned NumArgs = CE->getNumArgs();
3202 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3203 // Mangle the arguments.
3204 for (unsigned i = 0; i != NumArgs; ++i)
3205 mangleExpression(CE->getArg(i));
3206 break;
3207 }
3208
3209 case Expr::ParenExprClass:
3210 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3211 break;
3212
3213 case Expr::DeclRefExprClass: {
3214 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3215
3216 switch (D->getKind()) {
3217 default:
3218 // <expr-primary> ::= L <mangled-name> E # external name
3219 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003220 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 Out << 'E';
3222 break;
3223
3224 case Decl::ParmVar:
3225 mangleFunctionParam(cast<ParmVarDecl>(D));
3226 break;
3227
3228 case Decl::EnumConstant: {
3229 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3230 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3231 break;
3232 }
3233
3234 case Decl::NonTypeTemplateParm: {
3235 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3236 mangleTemplateParameter(PD->getIndex());
3237 break;
3238 }
3239
3240 }
3241
3242 break;
3243 }
3244
3245 case Expr::SubstNonTypeTemplateParmPackExprClass:
3246 // FIXME: not clear how to mangle this!
3247 // template <unsigned N...> class A {
3248 // template <class U...> void foo(U (&x)[N]...);
3249 // };
3250 Out << "_SUBSTPACK_";
3251 break;
3252
3253 case Expr::FunctionParmPackExprClass: {
3254 // FIXME: not clear how to mangle this!
3255 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3256 Out << "v110_SUBSTPACK";
3257 mangleFunctionParam(FPPE->getParameterPack());
3258 break;
3259 }
3260
3261 case Expr::DependentScopeDeclRefExprClass: {
3262 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003263 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003264
3265 // All the <unresolved-name> productions end in a
3266 // base-unresolved-name, where <template-args> are just tacked
3267 // onto the end.
3268 if (DRE->hasExplicitTemplateArgs())
3269 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3270 break;
3271 }
3272
3273 case Expr::CXXBindTemporaryExprClass:
3274 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3275 break;
3276
3277 case Expr::ExprWithCleanupsClass:
3278 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3279 break;
3280
3281 case Expr::FloatingLiteralClass: {
3282 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3283 Out << 'L';
3284 mangleType(FL->getType());
3285 mangleFloat(FL->getValue());
3286 Out << 'E';
3287 break;
3288 }
3289
3290 case Expr::CharacterLiteralClass:
3291 Out << 'L';
3292 mangleType(E->getType());
3293 Out << cast<CharacterLiteral>(E)->getValue();
3294 Out << 'E';
3295 break;
3296
3297 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3298 case Expr::ObjCBoolLiteralExprClass:
3299 Out << "Lb";
3300 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3301 Out << 'E';
3302 break;
3303
3304 case Expr::CXXBoolLiteralExprClass:
3305 Out << "Lb";
3306 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3307 Out << 'E';
3308 break;
3309
3310 case Expr::IntegerLiteralClass: {
3311 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3312 if (E->getType()->isSignedIntegerType())
3313 Value.setIsSigned(true);
3314 mangleIntegerLiteral(E->getType(), Value);
3315 break;
3316 }
3317
3318 case Expr::ImaginaryLiteralClass: {
3319 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3320 // Mangle as if a complex literal.
3321 // Proposal from David Vandevoorde, 2010.06.30.
3322 Out << 'L';
3323 mangleType(E->getType());
3324 if (const FloatingLiteral *Imag =
3325 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3326 // Mangle a floating-point zero of the appropriate type.
3327 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3328 Out << '_';
3329 mangleFloat(Imag->getValue());
3330 } else {
3331 Out << "0_";
3332 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3333 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3334 Value.setIsSigned(true);
3335 mangleNumber(Value);
3336 }
3337 Out << 'E';
3338 break;
3339 }
3340
3341 case Expr::StringLiteralClass: {
3342 // Revised proposal from David Vandervoorde, 2010.07.15.
3343 Out << 'L';
3344 assert(isa<ConstantArrayType>(E->getType()));
3345 mangleType(E->getType());
3346 Out << 'E';
3347 break;
3348 }
3349
3350 case Expr::GNUNullExprClass:
3351 // FIXME: should this really be mangled the same as nullptr?
3352 // fallthrough
3353
3354 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 Out << "LDnE";
3356 break;
3357 }
3358
3359 case Expr::PackExpansionExprClass:
3360 Out << "sp";
3361 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3362 break;
3363
3364 case Expr::SizeOfPackExprClass: {
3365 Out << "sZ";
3366 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3367 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3368 mangleTemplateParameter(TTP->getIndex());
3369 else if (const NonTypeTemplateParmDecl *NTTP
3370 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3371 mangleTemplateParameter(NTTP->getIndex());
3372 else if (const TemplateTemplateParmDecl *TempTP
3373 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3374 mangleTemplateParameter(TempTP->getIndex());
3375 else
3376 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3377 break;
3378 }
Richard Smith0f0af192014-11-08 05:07:16 +00003379
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 case Expr::MaterializeTemporaryExprClass: {
3381 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3382 break;
3383 }
Richard Smith0f0af192014-11-08 05:07:16 +00003384
3385 case Expr::CXXFoldExprClass: {
3386 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003387 if (FE->isLeftFold())
3388 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003389 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003390 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003391
3392 if (FE->getOperator() == BO_PtrMemD)
3393 Out << "ds";
3394 else
3395 mangleOperatorName(
3396 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3397 /*Arity=*/2);
3398
3399 if (FE->getLHS())
3400 mangleExpression(FE->getLHS());
3401 if (FE->getRHS())
3402 mangleExpression(FE->getRHS());
3403 break;
3404 }
3405
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 case Expr::CXXThisExprClass:
3407 Out << "fpT";
3408 break;
3409 }
3410}
3411
3412/// Mangle an expression which refers to a parameter variable.
3413///
3414/// <expression> ::= <function-param>
3415/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3416/// <function-param> ::= fp <top-level CV-qualifiers>
3417/// <parameter-2 non-negative number> _ # L == 0, I > 0
3418/// <function-param> ::= fL <L-1 non-negative number>
3419/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3420/// <function-param> ::= fL <L-1 non-negative number>
3421/// p <top-level CV-qualifiers>
3422/// <I-1 non-negative number> _ # L > 0, I > 0
3423///
3424/// L is the nesting depth of the parameter, defined as 1 if the
3425/// parameter comes from the innermost function prototype scope
3426/// enclosing the current context, 2 if from the next enclosing
3427/// function prototype scope, and so on, with one special case: if
3428/// we've processed the full parameter clause for the innermost
3429/// function type, then L is one less. This definition conveniently
3430/// makes it irrelevant whether a function's result type was written
3431/// trailing or leading, but is otherwise overly complicated; the
3432/// numbering was first designed without considering references to
3433/// parameter in locations other than return types, and then the
3434/// mangling had to be generalized without changing the existing
3435/// manglings.
3436///
3437/// I is the zero-based index of the parameter within its parameter
3438/// declaration clause. Note that the original ABI document describes
3439/// this using 1-based ordinals.
3440void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3441 unsigned parmDepth = parm->getFunctionScopeDepth();
3442 unsigned parmIndex = parm->getFunctionScopeIndex();
3443
3444 // Compute 'L'.
3445 // parmDepth does not include the declaring function prototype.
3446 // FunctionTypeDepth does account for that.
3447 assert(parmDepth < FunctionTypeDepth.getDepth());
3448 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3449 if (FunctionTypeDepth.isInResultType())
3450 nestingDepth--;
3451
3452 if (nestingDepth == 0) {
3453 Out << "fp";
3454 } else {
3455 Out << "fL" << (nestingDepth - 1) << 'p';
3456 }
3457
3458 // Top-level qualifiers. We don't have to worry about arrays here,
3459 // because parameters declared as arrays should already have been
3460 // transformed to have pointer type. FIXME: apparently these don't
3461 // get mangled if used as an rvalue of a known non-class type?
3462 assert(!parm->getType()->isArrayType()
3463 && "parameter's type is still an array type?");
3464 mangleQualifiers(parm->getType().getQualifiers());
3465
3466 // Parameter index.
3467 if (parmIndex != 0) {
3468 Out << (parmIndex - 1);
3469 }
3470 Out << '_';
3471}
3472
3473void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3474 // <ctor-dtor-name> ::= C1 # complete object constructor
3475 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003477 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 switch (T) {
3479 case Ctor_Complete:
3480 Out << "C1";
3481 break;
3482 case Ctor_Base:
3483 Out << "C2";
3484 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003485 case Ctor_Comdat:
3486 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003488 case Ctor_DefaultClosure:
3489 case Ctor_CopyingClosure:
3490 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 }
3492}
3493
3494void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3495 // <ctor-dtor-name> ::= D0 # deleting destructor
3496 // ::= D1 # complete object destructor
3497 // ::= D2 # base object destructor
3498 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003499 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 switch (T) {
3501 case Dtor_Deleting:
3502 Out << "D0";
3503 break;
3504 case Dtor_Complete:
3505 Out << "D1";
3506 break;
3507 case Dtor_Base:
3508 Out << "D2";
3509 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003510 case Dtor_Comdat:
3511 Out << "D5";
3512 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 }
3514}
3515
3516void CXXNameMangler::mangleTemplateArgs(
3517 const ASTTemplateArgumentListInfo &TemplateArgs) {
3518 // <template-args> ::= I <template-arg>+ E
3519 Out << 'I';
3520 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3521 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3522 Out << 'E';
3523}
3524
3525void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3526 // <template-args> ::= I <template-arg>+ E
3527 Out << 'I';
3528 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3529 mangleTemplateArg(AL[i]);
3530 Out << 'E';
3531}
3532
3533void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3534 unsigned NumTemplateArgs) {
3535 // <template-args> ::= I <template-arg>+ E
3536 Out << 'I';
3537 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3538 mangleTemplateArg(TemplateArgs[i]);
3539 Out << 'E';
3540}
3541
3542void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3543 // <template-arg> ::= <type> # type or template
3544 // ::= X <expression> E # expression
3545 // ::= <expr-primary> # simple expressions
3546 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 if (!A.isInstantiationDependent() || A.isDependent())
3548 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3549
3550 switch (A.getKind()) {
3551 case TemplateArgument::Null:
3552 llvm_unreachable("Cannot mangle NULL template argument");
3553
3554 case TemplateArgument::Type:
3555 mangleType(A.getAsType());
3556 break;
3557 case TemplateArgument::Template:
3558 // This is mangled as <type>.
3559 mangleType(A.getAsTemplate());
3560 break;
3561 case TemplateArgument::TemplateExpansion:
3562 // <type> ::= Dp <type> # pack expansion (C++0x)
3563 Out << "Dp";
3564 mangleType(A.getAsTemplateOrTemplatePattern());
3565 break;
3566 case TemplateArgument::Expression: {
3567 // It's possible to end up with a DeclRefExpr here in certain
3568 // dependent cases, in which case we should mangle as a
3569 // declaration.
3570 const Expr *E = A.getAsExpr()->IgnoreParens();
3571 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3572 const ValueDecl *D = DRE->getDecl();
3573 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003574 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003575 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 Out << 'E';
3577 break;
3578 }
3579 }
3580
3581 Out << 'X';
3582 mangleExpression(E);
3583 Out << 'E';
3584 break;
3585 }
3586 case TemplateArgument::Integral:
3587 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3588 break;
3589 case TemplateArgument::Declaration: {
3590 // <expr-primary> ::= L <mangled-name> E # external name
3591 // Clang produces AST's where pointer-to-member-function expressions
3592 // and pointer-to-function expressions are represented as a declaration not
3593 // an expression. We compensate for it here to produce the correct mangling.
3594 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003595 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 if (compensateMangling) {
3597 Out << 'X';
3598 mangleOperatorName(OO_Amp, 1);
3599 }
3600
3601 Out << 'L';
3602 // References to external entities use the mangled name; if the name would
3603 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003604 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 Out << 'E';
3606
3607 if (compensateMangling)
3608 Out << 'E';
3609
3610 break;
3611 }
3612 case TemplateArgument::NullPtr: {
3613 // <expr-primary> ::= L <type> 0 E
3614 Out << 'L';
3615 mangleType(A.getNullPtrType());
3616 Out << "0E";
3617 break;
3618 }
3619 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003620 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003622 for (const auto &P : A.pack_elements())
3623 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 Out << 'E';
3625 }
3626 }
3627}
3628
3629void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3630 // <template-param> ::= T_ # first template parameter
3631 // ::= T <parameter-2 non-negative number> _
3632 if (Index == 0)
3633 Out << "T_";
3634 else
3635 Out << 'T' << (Index - 1) << '_';
3636}
3637
David Majnemer3b3bdb52014-05-06 22:49:16 +00003638void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3639 if (SeqID == 1)
3640 Out << '0';
3641 else if (SeqID > 1) {
3642 SeqID--;
3643
3644 // <seq-id> is encoded in base-36, using digits and upper case letters.
3645 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003646 MutableArrayRef<char> BufferRef(Buffer);
3647 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003648
3649 for (; SeqID != 0; SeqID /= 36) {
3650 unsigned C = SeqID % 36;
3651 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3652 }
3653
3654 Out.write(I.base(), I - BufferRef.rbegin());
3655 }
3656 Out << '_';
3657}
3658
Guy Benyei11169dd2012-12-18 14:30:41 +00003659void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3660 bool result = mangleSubstitution(type);
3661 assert(result && "no existing substitution for type");
3662 (void) result;
3663}
3664
3665void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3666 bool result = mangleSubstitution(tname);
3667 assert(result && "no existing substitution for template name");
3668 (void) result;
3669}
3670
3671// <substitution> ::= S <seq-id> _
3672// ::= S_
3673bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3674 // Try one of the standard substitutions first.
3675 if (mangleStandardSubstitution(ND))
3676 return true;
3677
3678 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3679 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3680}
3681
Justin Bognere8d762e2015-05-22 06:48:13 +00003682/// Determine whether the given type has any qualifiers that are relevant for
3683/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003684static bool hasMangledSubstitutionQualifiers(QualType T) {
3685 Qualifiers Qs = T.getQualifiers();
3686 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3687}
3688
3689bool CXXNameMangler::mangleSubstitution(QualType T) {
3690 if (!hasMangledSubstitutionQualifiers(T)) {
3691 if (const RecordType *RT = T->getAs<RecordType>())
3692 return mangleSubstitution(RT->getDecl());
3693 }
3694
3695 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3696
3697 return mangleSubstitution(TypePtr);
3698}
3699
3700bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3701 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3702 return mangleSubstitution(TD);
3703
3704 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3705 return mangleSubstitution(
3706 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3707}
3708
3709bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3710 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3711 if (I == Substitutions.end())
3712 return false;
3713
3714 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003715 Out << 'S';
3716 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003717
3718 return true;
3719}
3720
3721static bool isCharType(QualType T) {
3722 if (T.isNull())
3723 return false;
3724
3725 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3726 T->isSpecificBuiltinType(BuiltinType::Char_U);
3727}
3728
Justin Bognere8d762e2015-05-22 06:48:13 +00003729/// Returns whether a given type is a template specialization of a given name
3730/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003731static bool isCharSpecialization(QualType T, const char *Name) {
3732 if (T.isNull())
3733 return false;
3734
3735 const RecordType *RT = T->getAs<RecordType>();
3736 if (!RT)
3737 return false;
3738
3739 const ClassTemplateSpecializationDecl *SD =
3740 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3741 if (!SD)
3742 return false;
3743
3744 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3745 return false;
3746
3747 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3748 if (TemplateArgs.size() != 1)
3749 return false;
3750
3751 if (!isCharType(TemplateArgs[0].getAsType()))
3752 return false;
3753
3754 return SD->getIdentifier()->getName() == Name;
3755}
3756
3757template <std::size_t StrLen>
3758static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3759 const char (&Str)[StrLen]) {
3760 if (!SD->getIdentifier()->isStr(Str))
3761 return false;
3762
3763 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3764 if (TemplateArgs.size() != 2)
3765 return false;
3766
3767 if (!isCharType(TemplateArgs[0].getAsType()))
3768 return false;
3769
3770 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3771 return false;
3772
3773 return true;
3774}
3775
3776bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3777 // <substitution> ::= St # ::std::
3778 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3779 if (isStd(NS)) {
3780 Out << "St";
3781 return true;
3782 }
3783 }
3784
3785 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3786 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3787 return false;
3788
3789 // <substitution> ::= Sa # ::std::allocator
3790 if (TD->getIdentifier()->isStr("allocator")) {
3791 Out << "Sa";
3792 return true;
3793 }
3794
3795 // <<substitution> ::= Sb # ::std::basic_string
3796 if (TD->getIdentifier()->isStr("basic_string")) {
3797 Out << "Sb";
3798 return true;
3799 }
3800 }
3801
3802 if (const ClassTemplateSpecializationDecl *SD =
3803 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3804 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3805 return false;
3806
3807 // <substitution> ::= Ss # ::std::basic_string<char,
3808 // ::std::char_traits<char>,
3809 // ::std::allocator<char> >
3810 if (SD->getIdentifier()->isStr("basic_string")) {
3811 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3812
3813 if (TemplateArgs.size() != 3)
3814 return false;
3815
3816 if (!isCharType(TemplateArgs[0].getAsType()))
3817 return false;
3818
3819 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3820 return false;
3821
3822 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3823 return false;
3824
3825 Out << "Ss";
3826 return true;
3827 }
3828
3829 // <substitution> ::= Si # ::std::basic_istream<char,
3830 // ::std::char_traits<char> >
3831 if (isStreamCharSpecialization(SD, "basic_istream")) {
3832 Out << "Si";
3833 return true;
3834 }
3835
3836 // <substitution> ::= So # ::std::basic_ostream<char,
3837 // ::std::char_traits<char> >
3838 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3839 Out << "So";
3840 return true;
3841 }
3842
3843 // <substitution> ::= Sd # ::std::basic_iostream<char,
3844 // ::std::char_traits<char> >
3845 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3846 Out << "Sd";
3847 return true;
3848 }
3849 }
3850 return false;
3851}
3852
3853void CXXNameMangler::addSubstitution(QualType T) {
3854 if (!hasMangledSubstitutionQualifiers(T)) {
3855 if (const RecordType *RT = T->getAs<RecordType>()) {
3856 addSubstitution(RT->getDecl());
3857 return;
3858 }
3859 }
3860
3861 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3862 addSubstitution(TypePtr);
3863}
3864
3865void CXXNameMangler::addSubstitution(TemplateName Template) {
3866 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3867 return addSubstitution(TD);
3868
3869 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3870 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3871}
3872
3873void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3874 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3875 Substitutions[Ptr] = SeqID++;
3876}
3877
3878//
3879
Justin Bognere8d762e2015-05-22 06:48:13 +00003880/// Mangles the name of the declaration D and emits that name to the given
3881/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00003882///
3883/// If the declaration D requires a mangled name, this routine will emit that
3884/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3885/// and this routine will return false. In this case, the caller should just
3886/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3887/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003888void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3889 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3891 "Invalid mangleName() call, argument is not a variable or function!");
3892 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3893 "Invalid mangleName() call on 'structor decl!");
3894
3895 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3896 getASTContext().getSourceManager(),
3897 "Mangling declaration");
3898
3899 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003900 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003901}
3902
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003903void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3904 CXXCtorType Type,
3905 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 CXXNameMangler Mangler(*this, Out, D, Type);
3907 Mangler.mangle(D);
3908}
3909
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003910void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3911 CXXDtorType Type,
3912 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 CXXNameMangler Mangler(*this, Out, D, Type);
3914 Mangler.mangle(D);
3915}
3916
Rafael Espindola1e4df922014-09-16 15:18:21 +00003917void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3918 raw_ostream &Out) {
3919 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3920 Mangler.mangle(D);
3921}
3922
3923void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3924 raw_ostream &Out) {
3925 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3926 Mangler.mangle(D);
3927}
3928
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003929void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3930 const ThunkInfo &Thunk,
3931 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 // <special-name> ::= T <call-offset> <base encoding>
3933 // # base is the nominal target function of thunk
3934 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3935 // # base is the nominal target function of thunk
3936 // # first call-offset is 'this' adjustment
3937 // # second call-offset is result adjustment
3938
3939 assert(!isa<CXXDestructorDecl>(MD) &&
3940 "Use mangleCXXDtor for destructor decls!");
3941 CXXNameMangler Mangler(*this, Out);
3942 Mangler.getStream() << "_ZT";
3943 if (!Thunk.Return.isEmpty())
3944 Mangler.getStream() << 'c';
3945
3946 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003947 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3948 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3949
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 // Mangle the return pointer adjustment if there is one.
3951 if (!Thunk.Return.isEmpty())
3952 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003953 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3954
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 Mangler.mangleFunctionEncoding(MD);
3956}
3957
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003958void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3959 const CXXDestructorDecl *DD, CXXDtorType Type,
3960 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // <special-name> ::= T <call-offset> <base encoding>
3962 // # base is the nominal target function of thunk
3963 CXXNameMangler Mangler(*this, Out, DD, Type);
3964 Mangler.getStream() << "_ZT";
3965
3966 // Mangle the 'this' pointer adjustment.
3967 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003968 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003969
3970 Mangler.mangleFunctionEncoding(DD);
3971}
3972
Justin Bognere8d762e2015-05-22 06:48:13 +00003973/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003974void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3975 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 // <special-name> ::= GV <object name> # Guard variable for one-time
3977 // # initialization
3978 CXXNameMangler Mangler(*this, Out);
3979 Mangler.getStream() << "_ZGV";
3980 Mangler.mangleName(D);
3981}
3982
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003983void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3984 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003985 // These symbols are internal in the Itanium ABI, so the names don't matter.
3986 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3987 // avoid duplicate symbols.
3988 Out << "__cxx_global_var_init";
3989}
3990
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003991void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3992 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003993 // Prefix the mangling of D with __dtor_.
3994 CXXNameMangler Mangler(*this, Out);
3995 Mangler.getStream() << "__dtor_";
3996 if (shouldMangleDeclName(D))
3997 Mangler.mangle(D);
3998 else
3999 Mangler.getStream() << D->getName();
4000}
4001
Reid Kleckner1d59f992015-01-22 01:36:17 +00004002void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4003 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4004 CXXNameMangler Mangler(*this, Out);
4005 Mangler.getStream() << "__filt_";
4006 if (shouldMangleDeclName(EnclosingDecl))
4007 Mangler.mangle(EnclosingDecl);
4008 else
4009 Mangler.getStream() << EnclosingDecl->getName();
4010}
4011
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004012void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4013 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4014 CXXNameMangler Mangler(*this, Out);
4015 Mangler.getStream() << "__fin_";
4016 if (shouldMangleDeclName(EnclosingDecl))
4017 Mangler.mangle(EnclosingDecl);
4018 else
4019 Mangler.getStream() << EnclosingDecl->getName();
4020}
4021
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004022void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4023 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004024 // <special-name> ::= TH <object name>
4025 CXXNameMangler Mangler(*this, Out);
4026 Mangler.getStream() << "_ZTH";
4027 Mangler.mangleName(D);
4028}
4029
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004030void
4031ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4032 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004033 // <special-name> ::= TW <object name>
4034 CXXNameMangler Mangler(*this, Out);
4035 Mangler.getStream() << "_ZTW";
4036 Mangler.mangleName(D);
4037}
4038
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004039void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004040 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004041 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 // We match the GCC mangling here.
4043 // <special-name> ::= GR <object name>
4044 CXXNameMangler Mangler(*this, Out);
4045 Mangler.getStream() << "_ZGR";
4046 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004047 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004048 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004049}
4050
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004051void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4052 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 // <special-name> ::= TV <type> # virtual table
4054 CXXNameMangler Mangler(*this, Out);
4055 Mangler.getStream() << "_ZTV";
4056 Mangler.mangleNameOrStandardSubstitution(RD);
4057}
4058
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004059void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4060 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 // <special-name> ::= TT <type> # VTT structure
4062 CXXNameMangler Mangler(*this, Out);
4063 Mangler.getStream() << "_ZTT";
4064 Mangler.mangleNameOrStandardSubstitution(RD);
4065}
4066
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004067void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4068 int64_t Offset,
4069 const CXXRecordDecl *Type,
4070 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 // <special-name> ::= TC <type> <offset number> _ <base type>
4072 CXXNameMangler Mangler(*this, Out);
4073 Mangler.getStream() << "_ZTC";
4074 Mangler.mangleNameOrStandardSubstitution(RD);
4075 Mangler.getStream() << Offset;
4076 Mangler.getStream() << '_';
4077 Mangler.mangleNameOrStandardSubstitution(Type);
4078}
4079
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004080void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 // <special-name> ::= TI <type> # typeinfo structure
4082 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4083 CXXNameMangler Mangler(*this, Out);
4084 Mangler.getStream() << "_ZTI";
4085 Mangler.mangleType(Ty);
4086}
4087
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004088void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4089 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4091 CXXNameMangler Mangler(*this, Out);
4092 Mangler.getStream() << "_ZTS";
4093 Mangler.mangleType(Ty);
4094}
4095
Reid Klecknercc99e262013-11-19 23:23:00 +00004096void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4097 mangleCXXRTTIName(Ty, Out);
4098}
4099
Peter Collingbournea4ccff32015-02-20 20:30:56 +00004100void ItaniumMangleContextImpl::mangleCXXVTableBitSet(const CXXRecordDecl *RD,
4101 raw_ostream &Out) {
Peter Collingbourned9546012015-06-19 02:30:43 +00004102 if (!RD->isExternallyVisible()) {
Peter Collingbournea4ccff32015-02-20 20:30:56 +00004103 // This part of the identifier needs to be unique across all translation
4104 // units in the linked program. The scheme fails if multiple translation
4105 // units are compiled using the same relative source file path, or if
4106 // multiple translation units are built from the same source file.
4107 SourceManager &SM = getASTContext().getSourceManager();
4108 Out << "[" << SM.getFileEntryForID(SM.getMainFileID())->getName() << "]";
4109 }
4110
4111 CXXNameMangler Mangler(*this, Out);
4112 Mangler.mangleType(QualType(RD->getTypeForDecl(), 0));
4113}
4114
David Majnemer58e5bee2014-03-24 21:43:36 +00004115void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4116 llvm_unreachable("Can't mangle string literals");
4117}
4118
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004119ItaniumMangleContext *
4120ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4121 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004122}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004123