blob: d181f356fcd6640553f5dc22e81b1ae239ecda95 [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
45/// \brief Retrieve the declaration context that should be used when mangling
46/// the given declaration.
47static 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;
Craig Toppercbce6e92014-03-11 06:22:39 +0000169 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
170 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
171 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000172
David Majnemer58e5bee2014-03-24 21:43:36 +0000173 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
174
Guy Benyei11169dd2012-12-18 14:30:41 +0000175 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000176 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000177 if (isLambda(ND))
178 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000179
180 // Anonymous tags are already numbered.
181 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
182 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
183 return false;
184 }
185
186 // Use the canonical number for externally visible decls.
187 if (ND->isExternallyVisible()) {
188 unsigned discriminator = getASTContext().getManglingNumber(ND);
189 if (discriminator == 1)
190 return false;
191 disc = discriminator - 2;
192 return true;
193 }
194
195 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000197 if (!discriminator) {
198 const DeclContext *DC = getEffectiveDeclContext(ND);
199 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
200 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000201 if (discriminator == 1)
202 return false;
203 disc = discriminator-2;
204 return true;
205 }
206 /// @}
207};
208
209/// CXXNameMangler - Manage the mangling of a single name.
210class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000211 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000212 raw_ostream &Out;
213
214 /// The "structor" is the top-level declaration being mangled, if
215 /// that's not a template specialization; otherwise it's the pattern
216 /// for that specialization.
217 const NamedDecl *Structor;
218 unsigned StructorType;
219
220 /// SeqID - The next subsitution sequence number.
221 unsigned SeqID;
222
223 class FunctionTypeDepthState {
224 unsigned Bits;
225
226 enum { InResultTypeMask = 1 };
227
228 public:
229 FunctionTypeDepthState() : Bits(0) {}
230
231 /// The number of function types we're inside.
232 unsigned getDepth() const {
233 return Bits >> 1;
234 }
235
236 /// True if we're in the return type of the innermost function type.
237 bool isInResultType() const {
238 return Bits & InResultTypeMask;
239 }
240
241 FunctionTypeDepthState push() {
242 FunctionTypeDepthState tmp = *this;
243 Bits = (Bits & ~InResultTypeMask) + 2;
244 return tmp;
245 }
246
247 void enterResultType() {
248 Bits |= InResultTypeMask;
249 }
250
251 void leaveResultType() {
252 Bits &= ~InResultTypeMask;
253 }
254
255 void pop(FunctionTypeDepthState saved) {
256 assert(getDepth() == saved.getDepth() + 1);
257 Bits = saved.Bits;
258 }
259
260 } FunctionTypeDepth;
261
262 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
263
264 ASTContext &getASTContext() const { return Context.getASTContext(); }
265
266public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000267 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000268 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000269 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
270 SeqID(0) {
271 // These can't be mangled without a ctor type or dtor type.
272 assert(!D || (!isa<CXXDestructorDecl>(D) &&
273 !isa<CXXConstructorDecl>(D)));
274 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000275 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000276 const CXXConstructorDecl *D, CXXCtorType Type)
277 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
278 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 const CXXDestructorDecl *D, CXXDtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282 SeqID(0) { }
283
284#if MANGLE_CHECKER
285 ~CXXNameMangler() {
286 if (Out.str()[0] == '\01')
287 return;
288
289 int status = 0;
290 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
291 assert(status == 0 && "Could not demangle mangled name!");
292 free(result);
293 }
294#endif
295 raw_ostream &getStream() { return Out; }
296
David Majnemer7ff7eb72015-02-18 07:47:09 +0000297 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
299 void mangleNumber(const llvm::APSInt &I);
300 void mangleNumber(int64_t Number);
301 void mangleFloat(const llvm::APFloat &F);
302 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000303 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 void mangleName(const NamedDecl *ND);
305 void mangleType(QualType T);
306 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
307
308private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000309
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 bool mangleSubstitution(const NamedDecl *ND);
311 bool mangleSubstitution(QualType T);
312 bool mangleSubstitution(TemplateName Template);
313 bool mangleSubstitution(uintptr_t Ptr);
314
315 void mangleExistingSubstitution(QualType type);
316 void mangleExistingSubstitution(TemplateName name);
317
318 bool mangleStandardSubstitution(const NamedDecl *ND);
319
320 void addSubstitution(const NamedDecl *ND) {
321 ND = cast<NamedDecl>(ND->getCanonicalDecl());
322
323 addSubstitution(reinterpret_cast<uintptr_t>(ND));
324 }
325 void addSubstitution(QualType T);
326 void addSubstitution(TemplateName Template);
327 void addSubstitution(uintptr_t Ptr);
328
329 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000330 bool recursive = false);
331 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 DeclarationName name,
333 unsigned KnownArity = UnknownArity);
334
335 void mangleName(const TemplateDecl *TD,
336 const TemplateArgument *TemplateArgs,
337 unsigned NumTemplateArgs);
338 void mangleUnqualifiedName(const NamedDecl *ND) {
339 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
340 }
341 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
342 unsigned KnownArity);
343 void mangleUnscopedName(const NamedDecl *ND);
344 void mangleUnscopedTemplateName(const TemplateDecl *ND);
345 void mangleUnscopedTemplateName(TemplateName);
346 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000347 void mangleLocalName(const Decl *D);
348 void mangleBlockForPrefix(const BlockDecl *Block);
349 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000350 void mangleLambda(const CXXRecordDecl *Lambda);
351 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
352 bool NoFunction=false);
353 void mangleNestedName(const TemplateDecl *TD,
354 const TemplateArgument *TemplateArgs,
355 unsigned NumTemplateArgs);
356 void manglePrefix(NestedNameSpecifier *qualifier);
357 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
358 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000359 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000361 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
362 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000363 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
365 void mangleQualifiers(Qualifiers Quals);
366 void mangleRefQualifier(RefQualifierKind RefQualifier);
367
368 void mangleObjCMethodName(const ObjCMethodDecl *MD);
369
370 // Declare manglers for every type class.
371#define ABSTRACT_TYPE(CLASS, PARENT)
372#define NON_CANONICAL_TYPE(CLASS, PARENT)
373#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
374#include "clang/AST/TypeNodes.def"
375
376 void mangleType(const TagType*);
377 void mangleType(TemplateName);
378 void mangleBareFunctionType(const FunctionType *T,
379 bool MangleReturnType);
380 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000381 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000382
383 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000384 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 void mangleMemberExpr(const Expr *base, bool isArrow,
386 NestedNameSpecifier *qualifier,
387 NamedDecl *firstQualifierLookup,
388 DeclarationName name,
389 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000390 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000391 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
393 void mangleCXXCtorType(CXXCtorType T);
394 void mangleCXXDtorType(CXXDtorType T);
395
396 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
397 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
398 unsigned NumTemplateArgs);
399 void mangleTemplateArgs(const TemplateArgumentList &AL);
400 void mangleTemplateArg(TemplateArgument A);
401
402 void mangleTemplateParameter(unsigned Index);
403
404 void mangleFunctionParam(const ParmVarDecl *parm);
405};
406
407}
408
Rafael Espindola002667c2013-10-16 01:40:34 +0000409bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000410 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000411 if (FD) {
412 LanguageLinkage L = FD->getLanguageLinkage();
413 // Overloadable functions need mangling.
414 if (FD->hasAttr<OverloadableAttr>())
415 return true;
416
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000417 // "main" is not mangled.
418 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000419 return false;
420
421 // C++ functions and those whose names are not a simple identifier need
422 // mangling.
423 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
424 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000425
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000426 // C functions are not mangled.
427 if (L == CLanguageLinkage)
428 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000429 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000430
431 // Otherwise, no mangling is done outside C++ mode.
432 if (!getASTContext().getLangOpts().CPlusPlus)
433 return false;
434
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000435 const VarDecl *VD = dyn_cast<VarDecl>(D);
436 if (VD) {
437 // C variables are not mangled.
438 if (VD->isExternC())
439 return false;
440
441 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 const DeclContext *DC = getEffectiveDeclContext(D);
443 // Check for extern variable declared locally.
444 if (DC->isFunctionOrMethod() && D->hasLinkage())
445 while (!DC->isNamespace() && !DC->isTranslationUnit())
446 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000447 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
448 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000449 return false;
450 }
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 return true;
453}
454
David Majnemer7ff7eb72015-02-18 07:47:09 +0000455void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 // <mangled-name> ::= _Z <encoding>
457 // ::= <data name>
458 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000459 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
461 mangleFunctionEncoding(FD);
462 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
463 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000464 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
465 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000466 else
467 mangleName(cast<FieldDecl>(D));
468}
469
470void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
471 // <encoding> ::= <function name> <bare-function-type>
472 mangleName(FD);
473
474 // Don't mangle in the type if this isn't a decl we should typically mangle.
475 if (!Context.shouldMangleDeclName(FD))
476 return;
477
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000478 if (FD->hasAttr<EnableIfAttr>()) {
479 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
480 Out << "Ua9enable_ifI";
481 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
482 // it here.
483 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
484 E = FD->getAttrs().rend();
485 I != E; ++I) {
486 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
487 if (!EIA)
488 continue;
489 Out << 'X';
490 mangleExpression(EIA->getCond());
491 Out << 'E';
492 }
493 Out << 'E';
494 FunctionTypeDepth.pop(Saved);
495 }
496
Guy Benyei11169dd2012-12-18 14:30:41 +0000497 // Whether the mangling of a function type includes the return type depends on
498 // the context and the nature of the function. The rules for deciding whether
499 // the return type is included are:
500 //
501 // 1. Template functions (names or types) have return types encoded, with
502 // the exceptions listed below.
503 // 2. Function types not appearing as part of a function name mangling,
504 // e.g. parameters, pointer types, etc., have return type encoded, with the
505 // exceptions listed below.
506 // 3. Non-template function names do not have return types encoded.
507 //
508 // The exceptions mentioned in (1) and (2) above, for which the return type is
509 // never included, are
510 // 1. Constructors.
511 // 2. Destructors.
512 // 3. Conversion operator functions, e.g. operator int.
513 bool MangleReturnType = false;
514 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
515 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
516 isa<CXXConversionDecl>(FD)))
517 MangleReturnType = true;
518
519 // Mangle the type of the primary template.
520 FD = PrimaryTemplate->getTemplatedDecl();
521 }
522
523 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
524 MangleReturnType);
525}
526
527static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
528 while (isa<LinkageSpecDecl>(DC)) {
529 DC = getEffectiveParentContext(DC);
530 }
531
532 return DC;
533}
534
535/// isStd - Return whether a given namespace is the 'std' namespace.
536static bool isStd(const NamespaceDecl *NS) {
537 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
538 ->isTranslationUnit())
539 return false;
540
541 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
542 return II && II->isStr("std");
543}
544
545// isStdNamespace - Return whether a given decl context is a toplevel 'std'
546// namespace.
547static bool isStdNamespace(const DeclContext *DC) {
548 if (!DC->isNamespace())
549 return false;
550
551 return isStd(cast<NamespaceDecl>(DC));
552}
553
554static const TemplateDecl *
555isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
556 // Check if we have a function template.
557 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
558 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
559 TemplateArgs = FD->getTemplateSpecializationArgs();
560 return TD;
561 }
562 }
563
564 // Check if we have a class template.
565 if (const ClassTemplateSpecializationDecl *Spec =
566 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
567 TemplateArgs = &Spec->getTemplateArgs();
568 return Spec->getSpecializedTemplate();
569 }
570
Larisse Voufo39a1e502013-08-06 01:03:05 +0000571 // Check if we have a variable template.
572 if (const VarTemplateSpecializationDecl *Spec =
573 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
574 TemplateArgs = &Spec->getTemplateArgs();
575 return Spec->getSpecializedTemplate();
576 }
577
Craig Topper36250ad2014-05-12 05:36:57 +0000578 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579}
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581void CXXNameMangler::mangleName(const NamedDecl *ND) {
582 // <name> ::= <nested-name>
583 // ::= <unscoped-name>
584 // ::= <unscoped-template-name> <template-args>
585 // ::= <local-name>
586 //
587 const DeclContext *DC = getEffectiveDeclContext(ND);
588
589 // If this is an extern variable declared locally, the relevant DeclContext
590 // is that of the containing namespace, or the translation unit.
591 // FIXME: This is a hack; extern variables declared locally should have
592 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000593 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 while (!DC->isNamespace() && !DC->isTranslationUnit())
595 DC = getEffectiveParentContext(DC);
596 else if (GetLocalClassDecl(ND)) {
597 mangleLocalName(ND);
598 return;
599 }
600
601 DC = IgnoreLinkageSpecDecls(DC);
602
603 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
604 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000605 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
607 mangleUnscopedTemplateName(TD);
608 mangleTemplateArgs(*TemplateArgs);
609 return;
610 }
611
612 mangleUnscopedName(ND);
613 return;
614 }
615
Eli Friedman95f50122013-07-02 17:52:28 +0000616 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000617 mangleLocalName(ND);
618 return;
619 }
620
621 mangleNestedName(ND, DC);
622}
623void CXXNameMangler::mangleName(const TemplateDecl *TD,
624 const TemplateArgument *TemplateArgs,
625 unsigned NumTemplateArgs) {
626 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
627
628 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
629 mangleUnscopedTemplateName(TD);
630 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
631 } else {
632 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
633 }
634}
635
636void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
637 // <unscoped-name> ::= <unqualified-name>
638 // ::= St <unqualified-name> # ::std::
639
640 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
641 Out << "St";
642
643 mangleUnqualifiedName(ND);
644}
645
646void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
647 // <unscoped-template-name> ::= <unscoped-name>
648 // ::= <substitution>
649 if (mangleSubstitution(ND))
650 return;
651
652 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000653 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000654 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000655 else
656 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000657
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 addSubstitution(ND);
659}
660
661void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
662 // <unscoped-template-name> ::= <unscoped-name>
663 // ::= <substitution>
664 if (TemplateDecl *TD = Template.getAsTemplateDecl())
665 return mangleUnscopedTemplateName(TD);
666
667 if (mangleSubstitution(Template))
668 return;
669
670 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
671 assert(Dependent && "Not a dependent template name?");
672 if (const IdentifierInfo *Id = Dependent->getIdentifier())
673 mangleSourceName(Id);
674 else
675 mangleOperatorName(Dependent->getOperator(), UnknownArity);
676
677 addSubstitution(Template);
678}
679
680void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
681 // ABI:
682 // Floating-point literals are encoded using a fixed-length
683 // lowercase hexadecimal string corresponding to the internal
684 // representation (IEEE on Itanium), high-order bytes first,
685 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
686 // on Itanium.
687 // The 'without leading zeroes' thing seems to be an editorial
688 // mistake; see the discussion on cxx-abi-dev beginning on
689 // 2012-01-16.
690
691 // Our requirements here are just barely weird enough to justify
692 // using a custom algorithm instead of post-processing APInt::toString().
693
694 llvm::APInt valueBits = f.bitcastToAPInt();
695 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
696 assert(numCharacters != 0);
697
698 // Allocate a buffer of the right number of characters.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000699 SmallVector<char, 20> buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +0000700 buffer.set_size(numCharacters);
701
702 // Fill the buffer left-to-right.
703 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
704 // The bit-index of the next hex digit.
705 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
706
707 // Project out 4 bits starting at 'digitIndex'.
708 llvm::integerPart hexDigit
709 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
710 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
711 hexDigit &= 0xF;
712
713 // Map that over to a lowercase hex digit.
714 static const char charForHex[16] = {
715 '0', '1', '2', '3', '4', '5', '6', '7',
716 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
717 };
718 buffer[stringIndex] = charForHex[hexDigit];
719 }
720
721 Out.write(buffer.data(), numCharacters);
722}
723
724void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
725 if (Value.isSigned() && Value.isNegative()) {
726 Out << 'n';
727 Value.abs().print(Out, /*signed*/ false);
728 } else {
729 Value.print(Out, /*signed*/ false);
730 }
731}
732
733void CXXNameMangler::mangleNumber(int64_t Number) {
734 // <number> ::= [n] <non-negative decimal integer>
735 if (Number < 0) {
736 Out << 'n';
737 Number = -Number;
738 }
739
740 Out << Number;
741}
742
743void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
744 // <call-offset> ::= h <nv-offset> _
745 // ::= v <v-offset> _
746 // <nv-offset> ::= <offset number> # non-virtual base override
747 // <v-offset> ::= <offset number> _ <virtual offset number>
748 // # virtual base override, with vcall offset
749 if (!Virtual) {
750 Out << 'h';
751 mangleNumber(NonVirtual);
752 Out << '_';
753 return;
754 }
755
756 Out << 'v';
757 mangleNumber(NonVirtual);
758 Out << '_';
759 mangleNumber(Virtual);
760 Out << '_';
761}
762
763void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000764 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000765 if (!mangleSubstitution(QualType(TST, 0))) {
766 mangleTemplatePrefix(TST->getTemplateName());
767
768 // FIXME: GCC does not appear to mangle the template arguments when
769 // the template in question is a dependent template name. Should we
770 // emulate that badness?
771 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
772 addSubstitution(QualType(TST, 0));
773 }
David Majnemera88b3592015-02-18 02:28:01 +0000774 } else if (const auto *DTST =
775 type->getAs<DependentTemplateSpecializationType>()) {
776 if (!mangleSubstitution(QualType(DTST, 0))) {
777 TemplateName Template = getASTContext().getDependentTemplateName(
778 DTST->getQualifier(), DTST->getIdentifier());
779 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000780
David Majnemera88b3592015-02-18 02:28:01 +0000781 // FIXME: GCC does not appear to mangle the template arguments when
782 // the template in question is a dependent template name. Should we
783 // emulate that badness?
784 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
785 addSubstitution(QualType(DTST, 0));
786 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 } else {
788 // We use the QualType mangle type variant here because it handles
789 // substitutions.
790 mangleType(type);
791 }
792}
793
794/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
795///
796/// \param firstQualifierLookup - the entity found by unqualified lookup
797/// for the first name in the qualifier, if this is for a member expression
798/// \param recursive - true if this is being called recursively,
799/// i.e. if there is more prefix "to the right".
800void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 bool recursive) {
802
803 // x, ::x
804 // <unresolved-name> ::= [gs] <base-unresolved-name>
805
806 // T::x / decltype(p)::x
807 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
808
809 // T::N::x /decltype(p)::N::x
810 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
811 // <base-unresolved-name>
812
813 // A::x, N::y, A<T>::z; "gs" means leading "::"
814 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
815 // <base-unresolved-name>
816
817 switch (qualifier->getKind()) {
818 case NestedNameSpecifier::Global:
819 Out << "gs";
820
821 // We want an 'sr' unless this is the entire NNS.
822 if (recursive)
823 Out << "sr";
824
825 // We never want an 'E' here.
826 return;
827
Nikola Smiljanic67860242014-09-26 00:28:20 +0000828 case NestedNameSpecifier::Super:
829 llvm_unreachable("Can't mangle __super specifier");
830
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 case NestedNameSpecifier::Namespace:
832 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000833 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 /*recursive*/ true);
835 else
836 Out << "sr";
837 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
838 break;
839 case NestedNameSpecifier::NamespaceAlias:
840 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000841 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000842 /*recursive*/ true);
843 else
844 Out << "sr";
845 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
846 break;
847
848 case NestedNameSpecifier::TypeSpec:
849 case NestedNameSpecifier::TypeSpecWithTemplate: {
850 const Type *type = qualifier->getAsType();
851
852 // We only want to use an unresolved-type encoding if this is one of:
853 // - a decltype
854 // - a template type parameter
855 // - a template template parameter with arguments
856 // In all of these cases, we should have no prefix.
857 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000858 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 /*recursive*/ true);
860 } else {
861 // Otherwise, all the cases want this.
862 Out << "sr";
863 }
864
David Majnemerb8014dd2015-02-19 02:16:16 +0000865 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 return;
867
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 break;
869 }
870
871 case NestedNameSpecifier::Identifier:
872 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000873 if (qualifier->getPrefix())
874 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000875 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000876 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000878
879 mangleSourceName(qualifier->getAsIdentifier());
880 break;
881 }
882
883 // If this was the innermost part of the NNS, and we fell out to
884 // here, append an 'E'.
885 if (!recursive)
886 Out << 'E';
887}
888
889/// Mangle an unresolved-name, which is generally used for names which
890/// weren't resolved to specific entities.
891void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 DeclarationName name,
893 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000894 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000895 switch (name.getNameKind()) {
896 // <base-unresolved-name> ::= <simple-id>
897 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000898 mangleSourceName(name.getAsIdentifierInfo());
899 break;
900 // <base-unresolved-name> ::= dn <destructor-name>
901 case DeclarationName::CXXDestructorName:
902 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000903 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000904 break;
905 // <base-unresolved-name> ::= on <operator-name>
906 case DeclarationName::CXXConversionFunctionName:
907 case DeclarationName::CXXLiteralOperatorName:
908 case DeclarationName::CXXOperatorName:
909 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000910 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000911 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000912 case DeclarationName::CXXConstructorName:
913 llvm_unreachable("Can't mangle a constructor name!");
914 case DeclarationName::CXXUsingDirective:
915 llvm_unreachable("Can't mangle a using directive name!");
916 case DeclarationName::ObjCMultiArgSelector:
917 case DeclarationName::ObjCOneArgSelector:
918 case DeclarationName::ObjCZeroArgSelector:
919 llvm_unreachable("Can't mangle Objective-C selector names here!");
920 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000921}
922
Guy Benyei11169dd2012-12-18 14:30:41 +0000923void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
924 DeclarationName Name,
925 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000926 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000927 // <unqualified-name> ::= <operator-name>
928 // ::= <ctor-dtor-name>
929 // ::= <source-name>
930 switch (Name.getNameKind()) {
931 case DeclarationName::Identifier: {
932 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
933 // We must avoid conflicts between internally- and externally-
934 // linked variable and function declaration names in the same TU:
935 // void test() { extern void foo(); }
936 // static void foo();
937 // This naming convention is the same as that followed by GCC,
938 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000939 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 getEffectiveDeclContext(ND)->isFileContext())
941 Out << 'L';
942
943 mangleSourceName(II);
944 break;
945 }
946
947 // Otherwise, an anonymous entity. We must have a declaration.
948 assert(ND && "mangling empty name without declaration");
949
950 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
951 if (NS->isAnonymousNamespace()) {
952 // This is how gcc mangles these names.
953 Out << "12_GLOBAL__N_1";
954 break;
955 }
956 }
957
958 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
959 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000960 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000962
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 // Itanium C++ ABI 5.1.2:
964 //
965 // For the purposes of mangling, the name of an anonymous union is
966 // considered to be the name of the first named data member found by a
967 // pre-order, depth-first, declaration-order walk of the data members of
968 // the anonymous union. If there is no such data member (i.e., if all of
969 // the data members in the union are unnamed), then there is no way for
970 // a program to refer to the anonymous union, and there is therefore no
971 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000972 assert(RD->isAnonymousStructOrUnion()
973 && "Expected anonymous struct or union!");
974 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000975
976 // It's actually possible for various reasons for us to get here
977 // with an empty anonymous struct / union. Fortunately, it
978 // doesn't really matter what name we generate.
979 if (!FD) break;
980 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000981
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 mangleSourceName(FD->getIdentifier());
983 break;
984 }
John McCall924046f2013-04-10 06:08:21 +0000985
986 // Class extensions have no name as a category, and it's possible
987 // for them to be the semantic parent of certain declarations
988 // (primarily, tag decls defined within declarations). Such
989 // declarations will always have internal linkage, so the name
990 // doesn't really matter, but we shouldn't crash on them. For
991 // safety, just handle all ObjC containers here.
992 if (isa<ObjCContainerDecl>(ND))
993 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000994
995 // We must have an anonymous struct.
996 const TagDecl *TD = cast<TagDecl>(ND);
997 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
998 assert(TD->getDeclContext() == D->getDeclContext() &&
999 "Typedef should not be in another decl context!");
1000 assert(D->getDeclName().getAsIdentifierInfo() &&
1001 "Typedef was not named!");
1002 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1003 break;
1004 }
1005
1006 // <unnamed-type-name> ::= <closure-type-name>
1007 //
1008 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1009 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1010 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1011 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1012 mangleLambda(Record);
1013 break;
1014 }
1015 }
1016
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001017 if (TD->isExternallyVisible()) {
1018 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001020 if (UnnamedMangle > 1)
1021 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 Out << '_';
1023 break;
1024 }
1025
1026 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001027 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001028
1029 // Mangle it as a source name in the form
1030 // [n] $_<id>
1031 // where n is the length of the string.
1032 SmallString<8> Str;
1033 Str += "$_";
1034 Str += llvm::utostr(AnonStructId);
1035
1036 Out << Str.size();
1037 Out << Str.str();
1038 break;
1039 }
1040
1041 case DeclarationName::ObjCZeroArgSelector:
1042 case DeclarationName::ObjCOneArgSelector:
1043 case DeclarationName::ObjCMultiArgSelector:
1044 llvm_unreachable("Can't mangle Objective-C selector names here!");
1045
1046 case DeclarationName::CXXConstructorName:
1047 if (ND == Structor)
1048 // If the named decl is the C++ constructor we're mangling, use the type
1049 // we were given.
1050 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1051 else
1052 // Otherwise, use the complete constructor name. This is relevant if a
1053 // class with a constructor is declared within a constructor.
1054 mangleCXXCtorType(Ctor_Complete);
1055 break;
1056
1057 case DeclarationName::CXXDestructorName:
1058 if (ND == Structor)
1059 // If the named decl is the C++ destructor we're mangling, use the type we
1060 // were given.
1061 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1062 else
1063 // Otherwise, use the complete destructor name. This is relevant if a
1064 // class with a destructor is declared within a destructor.
1065 mangleCXXDtorType(Dtor_Complete);
1066 break;
1067
David Majnemera88b3592015-02-18 02:28:01 +00001068 case DeclarationName::CXXOperatorName:
1069 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001070 Arity = cast<FunctionDecl>(ND)->getNumParams();
1071
David Majnemera88b3592015-02-18 02:28:01 +00001072 // If we have a member function, we need to include the 'this' pointer.
1073 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1074 if (!MD->isStatic())
1075 Arity++;
1076 }
1077 // FALLTHROUGH
1078 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001079 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001080 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 break;
1082
1083 case DeclarationName::CXXUsingDirective:
1084 llvm_unreachable("Can't mangle a using directive name!");
1085 }
1086}
1087
1088void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1089 // <source-name> ::= <positive length number> <identifier>
1090 // <number> ::= [n] <non-negative decimal integer>
1091 // <identifier> ::= <unqualified source code identifier>
1092 Out << II->getLength() << II->getName();
1093}
1094
1095void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1096 const DeclContext *DC,
1097 bool NoFunction) {
1098 // <nested-name>
1099 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1100 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1101 // <template-args> E
1102
1103 Out << 'N';
1104 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001105 Qualifiers MethodQuals =
1106 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1107 // We do not consider restrict a distinguishing attribute for overloading
1108 // purposes so we must not mangle it.
1109 MethodQuals.removeRestrict();
1110 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 mangleRefQualifier(Method->getRefQualifier());
1112 }
1113
1114 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001115 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001117 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 mangleTemplateArgs(*TemplateArgs);
1119 }
1120 else {
1121 manglePrefix(DC, NoFunction);
1122 mangleUnqualifiedName(ND);
1123 }
1124
1125 Out << 'E';
1126}
1127void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1128 const TemplateArgument *TemplateArgs,
1129 unsigned NumTemplateArgs) {
1130 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1131
1132 Out << 'N';
1133
1134 mangleTemplatePrefix(TD);
1135 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1136
1137 Out << 'E';
1138}
1139
Eli Friedman95f50122013-07-02 17:52:28 +00001140void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1142 // := Z <function encoding> E s [<discriminator>]
1143 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1144 // _ <entity name>
1145 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001146 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001147 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001148 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001149
1150 Out << 'Z';
1151
Eli Friedman92821742013-07-02 02:01:18 +00001152 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1153 mangleObjCMethodName(MD);
1154 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001155 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001156 else
1157 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001158
Eli Friedman92821742013-07-02 02:01:18 +00001159 Out << 'E';
1160
1161 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 // The parameter number is omitted for the last parameter, 0 for the
1163 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1164 // <entity name> will of course contain a <closure-type-name>: Its
1165 // numbering will be local to the particular argument in which it appears
1166 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001167 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1168 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001170 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 if (const FunctionDecl *Func
1172 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1173 Out << 'd';
1174 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1175 if (Num > 1)
1176 mangleNumber(Num - 2);
1177 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001178 }
1179 }
1180 }
1181
1182 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001183 // equality ok because RD derived from ND above
1184 if (D == RD) {
1185 mangleUnqualifiedName(RD);
1186 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1187 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1188 mangleUnqualifiedBlock(BD);
1189 } else {
1190 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001191 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001192 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001193 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1194 // Mangle a block in a default parameter; see above explanation for
1195 // lambdas.
1196 if (const ParmVarDecl *Parm
1197 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1198 if (const FunctionDecl *Func
1199 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1200 Out << 'd';
1201 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1202 if (Num > 1)
1203 mangleNumber(Num - 2);
1204 Out << '_';
1205 }
1206 }
1207
1208 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001209 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001210 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001212
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001213 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1214 unsigned disc;
1215 if (Context.getNextDiscriminator(ND, disc)) {
1216 if (disc < 10)
1217 Out << '_' << disc;
1218 else
1219 Out << "__" << disc << '_';
1220 }
1221 }
Eli Friedman95f50122013-07-02 17:52:28 +00001222}
1223
1224void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1225 if (GetLocalClassDecl(Block)) {
1226 mangleLocalName(Block);
1227 return;
1228 }
1229 const DeclContext *DC = getEffectiveDeclContext(Block);
1230 if (isLocalContainerContext(DC)) {
1231 mangleLocalName(Block);
1232 return;
1233 }
1234 manglePrefix(getEffectiveDeclContext(Block));
1235 mangleUnqualifiedBlock(Block);
1236}
1237
1238void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1239 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1240 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1241 Context->getDeclContext()->isRecord()) {
1242 if (const IdentifierInfo *Name
1243 = cast<NamedDecl>(Context)->getIdentifier()) {
1244 mangleSourceName(Name);
1245 Out << 'M';
1246 }
1247 }
1248 }
1249
1250 // If we have a block mangling number, use it.
1251 unsigned Number = Block->getBlockManglingNumber();
1252 // Otherwise, just make up a number. It doesn't matter what it is because
1253 // the symbol in question isn't externally visible.
1254 if (!Number)
1255 Number = Context.getBlockId(Block, false);
1256 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001257 if (Number > 0)
1258 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001259 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001260}
1261
1262void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1263 // If the context of a closure type is an initializer for a class member
1264 // (static or nonstatic), it is encoded in a qualified name with a final
1265 // <prefix> of the form:
1266 //
1267 // <data-member-prefix> := <member source-name> M
1268 //
1269 // Technically, the data-member-prefix is part of the <prefix>. However,
1270 // since a closure type will always be mangled with a prefix, it's easier
1271 // to emit that last part of the prefix here.
1272 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1273 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1274 Context->getDeclContext()->isRecord()) {
1275 if (const IdentifierInfo *Name
1276 = cast<NamedDecl>(Context)->getIdentifier()) {
1277 mangleSourceName(Name);
1278 Out << 'M';
1279 }
1280 }
1281 }
1282
1283 Out << "Ul";
1284 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1285 getAs<FunctionProtoType>();
1286 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1287 Out << "E";
1288
1289 // The number is omitted for the first closure type with a given
1290 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1291 // (in lexical order) with that same <lambda-sig> and context.
1292 //
1293 // The AST keeps track of the number for us.
1294 unsigned Number = Lambda->getLambdaManglingNumber();
1295 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1296 if (Number > 1)
1297 mangleNumber(Number - 2);
1298 Out << '_';
1299}
1300
1301void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1302 switch (qualifier->getKind()) {
1303 case NestedNameSpecifier::Global:
1304 // nothing
1305 return;
1306
Nikola Smiljanic67860242014-09-26 00:28:20 +00001307 case NestedNameSpecifier::Super:
1308 llvm_unreachable("Can't mangle __super specifier");
1309
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 case NestedNameSpecifier::Namespace:
1311 mangleName(qualifier->getAsNamespace());
1312 return;
1313
1314 case NestedNameSpecifier::NamespaceAlias:
1315 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1316 return;
1317
1318 case NestedNameSpecifier::TypeSpec:
1319 case NestedNameSpecifier::TypeSpecWithTemplate:
1320 manglePrefix(QualType(qualifier->getAsType(), 0));
1321 return;
1322
1323 case NestedNameSpecifier::Identifier:
1324 // Member expressions can have these without prefixes, but that
1325 // should end up in mangleUnresolvedPrefix instead.
1326 assert(qualifier->getPrefix());
1327 manglePrefix(qualifier->getPrefix());
1328
1329 mangleSourceName(qualifier->getAsIdentifier());
1330 return;
1331 }
1332
1333 llvm_unreachable("unexpected nested name specifier");
1334}
1335
1336void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1337 // <prefix> ::= <prefix> <unqualified-name>
1338 // ::= <template-prefix> <template-args>
1339 // ::= <template-param>
1340 // ::= # empty
1341 // ::= <substitution>
1342
1343 DC = IgnoreLinkageSpecDecls(DC);
1344
1345 if (DC->isTranslationUnit())
1346 return;
1347
Eli Friedman95f50122013-07-02 17:52:28 +00001348 if (NoFunction && isLocalContainerContext(DC))
1349 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001350
Eli Friedman95f50122013-07-02 17:52:28 +00001351 assert(!isLocalContainerContext(DC));
1352
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 const NamedDecl *ND = cast<NamedDecl>(DC);
1354 if (mangleSubstitution(ND))
1355 return;
1356
1357 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001358 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1360 mangleTemplatePrefix(TD);
1361 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001362 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1364 mangleUnqualifiedName(ND);
1365 }
1366
1367 addSubstitution(ND);
1368}
1369
1370void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1371 // <template-prefix> ::= <prefix> <template unqualified-name>
1372 // ::= <template-param>
1373 // ::= <substitution>
1374 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1375 return mangleTemplatePrefix(TD);
1376
1377 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1378 manglePrefix(Qualified->getQualifier());
1379
1380 if (OverloadedTemplateStorage *Overloaded
1381 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001382 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 UnknownArity);
1384 return;
1385 }
1386
1387 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1388 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001389 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1390 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 mangleUnscopedTemplateName(Template);
1392}
1393
Eli Friedman86af13f02013-07-05 18:41:30 +00001394void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1395 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 // <template-prefix> ::= <prefix> <template unqualified-name>
1397 // ::= <template-param>
1398 // ::= <substitution>
1399 // <template-template-param> ::= <template-param>
1400 // <substitution>
1401
1402 if (mangleSubstitution(ND))
1403 return;
1404
1405 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001406 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001408 } else {
1409 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1410 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 }
1412
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 addSubstitution(ND);
1414}
1415
1416/// Mangles a template name under the production <type>. Required for
1417/// template template arguments.
1418/// <type> ::= <class-enum-type>
1419/// ::= <template-param>
1420/// ::= <substitution>
1421void CXXNameMangler::mangleType(TemplateName TN) {
1422 if (mangleSubstitution(TN))
1423 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001424
1425 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001426
1427 switch (TN.getKind()) {
1428 case TemplateName::QualifiedTemplate:
1429 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1430 goto HaveDecl;
1431
1432 case TemplateName::Template:
1433 TD = TN.getAsTemplateDecl();
1434 goto HaveDecl;
1435
1436 HaveDecl:
1437 if (isa<TemplateTemplateParmDecl>(TD))
1438 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1439 else
1440 mangleName(TD);
1441 break;
1442
1443 case TemplateName::OverloadedTemplate:
1444 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1445
1446 case TemplateName::DependentTemplate: {
1447 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1448 assert(Dependent->isIdentifier());
1449
1450 // <class-enum-type> ::= <name>
1451 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001452 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 mangleSourceName(Dependent->getIdentifier());
1454 break;
1455 }
1456
1457 case TemplateName::SubstTemplateTemplateParm: {
1458 // Substituted template parameters are mangled as the substituted
1459 // template. This will check for the substitution twice, which is
1460 // fine, but we have to return early so that we don't try to *add*
1461 // the substitution twice.
1462 SubstTemplateTemplateParmStorage *subst
1463 = TN.getAsSubstTemplateTemplateParm();
1464 mangleType(subst->getReplacement());
1465 return;
1466 }
1467
1468 case TemplateName::SubstTemplateTemplateParmPack: {
1469 // FIXME: not clear how to mangle this!
1470 // template <template <class> class T...> class A {
1471 // template <template <class> class U...> void foo(B<T,U> x...);
1472 // };
1473 Out << "_SUBSTPACK_";
1474 break;
1475 }
1476 }
1477
1478 addSubstitution(TN);
1479}
1480
David Majnemerb8014dd2015-02-19 02:16:16 +00001481bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1482 StringRef Prefix) {
1483 // Only certain other types are valid as prefixes; enumerate them.
1484 switch (Ty->getTypeClass()) {
1485 case Type::Builtin:
1486 case Type::Complex:
1487 case Type::Adjusted:
1488 case Type::Decayed:
1489 case Type::Pointer:
1490 case Type::BlockPointer:
1491 case Type::LValueReference:
1492 case Type::RValueReference:
1493 case Type::MemberPointer:
1494 case Type::ConstantArray:
1495 case Type::IncompleteArray:
1496 case Type::VariableArray:
1497 case Type::DependentSizedArray:
1498 case Type::DependentSizedExtVector:
1499 case Type::Vector:
1500 case Type::ExtVector:
1501 case Type::FunctionProto:
1502 case Type::FunctionNoProto:
1503 case Type::Paren:
1504 case Type::Attributed:
1505 case Type::Auto:
1506 case Type::PackExpansion:
1507 case Type::ObjCObject:
1508 case Type::ObjCInterface:
1509 case Type::ObjCObjectPointer:
1510 case Type::Atomic:
1511 llvm_unreachable("type is illegal as a nested name specifier");
1512
1513 case Type::SubstTemplateTypeParmPack:
1514 // FIXME: not clear how to mangle this!
1515 // template <class T...> class A {
1516 // template <class U...> void foo(decltype(T::foo(U())) x...);
1517 // };
1518 Out << "_SUBSTPACK_";
1519 break;
1520
1521 // <unresolved-type> ::= <template-param>
1522 // ::= <decltype>
1523 // ::= <template-template-param> <template-args>
1524 // (this last is not official yet)
1525 case Type::TypeOfExpr:
1526 case Type::TypeOf:
1527 case Type::Decltype:
1528 case Type::TemplateTypeParm:
1529 case Type::UnaryTransform:
1530 case Type::SubstTemplateTypeParm:
1531 unresolvedType:
1532 // Some callers want a prefix before the mangled type.
1533 Out << Prefix;
1534
1535 // This seems to do everything we want. It's not really
1536 // sanctioned for a substituted template parameter, though.
1537 mangleType(Ty);
1538
1539 // We never want to print 'E' directly after an unresolved-type,
1540 // so we return directly.
1541 return true;
1542
1543 case Type::Typedef:
1544 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1545 break;
1546
1547 case Type::UnresolvedUsing:
1548 mangleSourceName(
1549 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1550 break;
1551
1552 case Type::Enum:
1553 case Type::Record:
1554 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1555 break;
1556
1557 case Type::TemplateSpecialization: {
1558 const TemplateSpecializationType *TST =
1559 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001560 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001561 switch (TN.getKind()) {
1562 case TemplateName::Template:
1563 case TemplateName::QualifiedTemplate: {
1564 TemplateDecl *TD = TN.getAsTemplateDecl();
1565
1566 // If the base is a template template parameter, this is an
1567 // unresolved type.
1568 assert(TD && "no template for template specialization type");
1569 if (isa<TemplateTemplateParmDecl>(TD))
1570 goto unresolvedType;
1571
1572 mangleSourceName(TD->getIdentifier());
1573 break;
David Majnemera88b3592015-02-18 02:28:01 +00001574 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001575
1576 case TemplateName::OverloadedTemplate:
1577 case TemplateName::DependentTemplate:
1578 llvm_unreachable("invalid base for a template specialization type");
1579
1580 case TemplateName::SubstTemplateTemplateParm: {
1581 SubstTemplateTemplateParmStorage *subst =
1582 TN.getAsSubstTemplateTemplateParm();
1583 mangleExistingSubstitution(subst->getReplacement());
1584 break;
1585 }
1586
1587 case TemplateName::SubstTemplateTemplateParmPack: {
1588 // FIXME: not clear how to mangle this!
1589 // template <template <class U> class T...> class A {
1590 // template <class U...> void foo(decltype(T<U>::foo) x...);
1591 // };
1592 Out << "_SUBSTPACK_";
1593 break;
1594 }
1595 }
1596
David Majnemera88b3592015-02-18 02:28:01 +00001597 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001598 break;
David Majnemera88b3592015-02-18 02:28:01 +00001599 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001600
1601 case Type::InjectedClassName:
1602 mangleSourceName(
1603 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1604 break;
1605
1606 case Type::DependentName:
1607 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1608 break;
1609
1610 case Type::DependentTemplateSpecialization: {
1611 const DependentTemplateSpecializationType *DTST =
1612 cast<DependentTemplateSpecializationType>(Ty);
1613 mangleSourceName(DTST->getIdentifier());
1614 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1615 break;
1616 }
1617
1618 case Type::Elaborated:
1619 return mangleUnresolvedTypeOrSimpleId(
1620 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1621 }
1622
1623 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001624}
1625
1626void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1627 switch (Name.getNameKind()) {
1628 case DeclarationName::CXXConstructorName:
1629 case DeclarationName::CXXDestructorName:
1630 case DeclarationName::CXXUsingDirective:
1631 case DeclarationName::Identifier:
1632 case DeclarationName::ObjCMultiArgSelector:
1633 case DeclarationName::ObjCOneArgSelector:
1634 case DeclarationName::ObjCZeroArgSelector:
1635 llvm_unreachable("Not an operator name");
1636
1637 case DeclarationName::CXXConversionFunctionName:
1638 // <operator-name> ::= cv <type> # (cast)
1639 Out << "cv";
1640 mangleType(Name.getCXXNameType());
1641 break;
1642
1643 case DeclarationName::CXXLiteralOperatorName:
1644 Out << "li";
1645 mangleSourceName(Name.getCXXLiteralIdentifier());
1646 return;
1647
1648 case DeclarationName::CXXOperatorName:
1649 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1650 break;
1651 }
1652}
1653
1654
1655
Guy Benyei11169dd2012-12-18 14:30:41 +00001656void
1657CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1658 switch (OO) {
1659 // <operator-name> ::= nw # new
1660 case OO_New: Out << "nw"; break;
1661 // ::= na # new[]
1662 case OO_Array_New: Out << "na"; break;
1663 // ::= dl # delete
1664 case OO_Delete: Out << "dl"; break;
1665 // ::= da # delete[]
1666 case OO_Array_Delete: Out << "da"; break;
1667 // ::= ps # + (unary)
1668 // ::= pl # + (binary or unknown)
1669 case OO_Plus:
1670 Out << (Arity == 1? "ps" : "pl"); break;
1671 // ::= ng # - (unary)
1672 // ::= mi # - (binary or unknown)
1673 case OO_Minus:
1674 Out << (Arity == 1? "ng" : "mi"); break;
1675 // ::= ad # & (unary)
1676 // ::= an # & (binary or unknown)
1677 case OO_Amp:
1678 Out << (Arity == 1? "ad" : "an"); break;
1679 // ::= de # * (unary)
1680 // ::= ml # * (binary or unknown)
1681 case OO_Star:
1682 // Use binary when unknown.
1683 Out << (Arity == 1? "de" : "ml"); break;
1684 // ::= co # ~
1685 case OO_Tilde: Out << "co"; break;
1686 // ::= dv # /
1687 case OO_Slash: Out << "dv"; break;
1688 // ::= rm # %
1689 case OO_Percent: Out << "rm"; break;
1690 // ::= or # |
1691 case OO_Pipe: Out << "or"; break;
1692 // ::= eo # ^
1693 case OO_Caret: Out << "eo"; break;
1694 // ::= aS # =
1695 case OO_Equal: Out << "aS"; break;
1696 // ::= pL # +=
1697 case OO_PlusEqual: Out << "pL"; break;
1698 // ::= mI # -=
1699 case OO_MinusEqual: Out << "mI"; break;
1700 // ::= mL # *=
1701 case OO_StarEqual: Out << "mL"; break;
1702 // ::= dV # /=
1703 case OO_SlashEqual: Out << "dV"; break;
1704 // ::= rM # %=
1705 case OO_PercentEqual: Out << "rM"; break;
1706 // ::= aN # &=
1707 case OO_AmpEqual: Out << "aN"; break;
1708 // ::= oR # |=
1709 case OO_PipeEqual: Out << "oR"; break;
1710 // ::= eO # ^=
1711 case OO_CaretEqual: Out << "eO"; break;
1712 // ::= ls # <<
1713 case OO_LessLess: Out << "ls"; break;
1714 // ::= rs # >>
1715 case OO_GreaterGreater: Out << "rs"; break;
1716 // ::= lS # <<=
1717 case OO_LessLessEqual: Out << "lS"; break;
1718 // ::= rS # >>=
1719 case OO_GreaterGreaterEqual: Out << "rS"; break;
1720 // ::= eq # ==
1721 case OO_EqualEqual: Out << "eq"; break;
1722 // ::= ne # !=
1723 case OO_ExclaimEqual: Out << "ne"; break;
1724 // ::= lt # <
1725 case OO_Less: Out << "lt"; break;
1726 // ::= gt # >
1727 case OO_Greater: Out << "gt"; break;
1728 // ::= le # <=
1729 case OO_LessEqual: Out << "le"; break;
1730 // ::= ge # >=
1731 case OO_GreaterEqual: Out << "ge"; break;
1732 // ::= nt # !
1733 case OO_Exclaim: Out << "nt"; break;
1734 // ::= aa # &&
1735 case OO_AmpAmp: Out << "aa"; break;
1736 // ::= oo # ||
1737 case OO_PipePipe: Out << "oo"; break;
1738 // ::= pp # ++
1739 case OO_PlusPlus: Out << "pp"; break;
1740 // ::= mm # --
1741 case OO_MinusMinus: Out << "mm"; break;
1742 // ::= cm # ,
1743 case OO_Comma: Out << "cm"; break;
1744 // ::= pm # ->*
1745 case OO_ArrowStar: Out << "pm"; break;
1746 // ::= pt # ->
1747 case OO_Arrow: Out << "pt"; break;
1748 // ::= cl # ()
1749 case OO_Call: Out << "cl"; break;
1750 // ::= ix # []
1751 case OO_Subscript: Out << "ix"; break;
1752
1753 // ::= qu # ?
1754 // The conditional operator can't be overloaded, but we still handle it when
1755 // mangling expressions.
1756 case OO_Conditional: Out << "qu"; break;
1757
1758 case OO_None:
1759 case NUM_OVERLOADED_OPERATORS:
1760 llvm_unreachable("Not an overloaded operator");
1761 }
1762}
1763
1764void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1765 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1766 if (Quals.hasRestrict())
1767 Out << 'r';
1768 if (Quals.hasVolatile())
1769 Out << 'V';
1770 if (Quals.hasConst())
1771 Out << 'K';
1772
1773 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001774 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 //
David Tweed31d09b02013-09-13 12:04:22 +00001776 // <type> ::= U <target-addrspace>
1777 // <type> ::= U <OpenCL-addrspace>
1778 // <type> ::= U <CUDA-addrspace>
1779
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001781 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001782
1783 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1784 // <target-addrspace> ::= "AS" <address-space-number>
1785 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1786 ASString = "AS" + llvm::utostr_32(TargetAS);
1787 } else {
1788 switch (AS) {
1789 default: llvm_unreachable("Not a language specific address space");
1790 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1791 case LangAS::opencl_global: ASString = "CLglobal"; break;
1792 case LangAS::opencl_local: ASString = "CLlocal"; break;
1793 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1794 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1795 case LangAS::cuda_device: ASString = "CUdevice"; break;
1796 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1797 case LangAS::cuda_shared: ASString = "CUshared"; break;
1798 }
1799 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 Out << 'U' << ASString.size() << ASString;
1801 }
1802
1803 StringRef LifetimeName;
1804 switch (Quals.getObjCLifetime()) {
1805 // Objective-C ARC Extension:
1806 //
1807 // <type> ::= U "__strong"
1808 // <type> ::= U "__weak"
1809 // <type> ::= U "__autoreleasing"
1810 case Qualifiers::OCL_None:
1811 break;
1812
1813 case Qualifiers::OCL_Weak:
1814 LifetimeName = "__weak";
1815 break;
1816
1817 case Qualifiers::OCL_Strong:
1818 LifetimeName = "__strong";
1819 break;
1820
1821 case Qualifiers::OCL_Autoreleasing:
1822 LifetimeName = "__autoreleasing";
1823 break;
1824
1825 case Qualifiers::OCL_ExplicitNone:
1826 // The __unsafe_unretained qualifier is *not* mangled, so that
1827 // __unsafe_unretained types in ARC produce the same manglings as the
1828 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1829 // better ABI compatibility.
1830 //
1831 // It's safe to do this because unqualified 'id' won't show up
1832 // in any type signatures that need to be mangled.
1833 break;
1834 }
1835 if (!LifetimeName.empty())
1836 Out << 'U' << LifetimeName.size() << LifetimeName;
1837}
1838
1839void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1840 // <ref-qualifier> ::= R # lvalue reference
1841 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 switch (RefQualifier) {
1843 case RQ_None:
1844 break;
1845
1846 case RQ_LValue:
1847 Out << 'R';
1848 break;
1849
1850 case RQ_RValue:
1851 Out << 'O';
1852 break;
1853 }
1854}
1855
1856void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1857 Context.mangleObjCMethodName(MD, Out);
1858}
1859
David Majnemereea02ee2014-11-28 22:22:46 +00001860static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1861 if (Quals)
1862 return true;
1863 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1864 return true;
1865 if (Ty->isOpenCLSpecificType())
1866 return true;
1867 if (Ty->isBuiltinType())
1868 return false;
1869
1870 return true;
1871}
1872
Guy Benyei11169dd2012-12-18 14:30:41 +00001873void CXXNameMangler::mangleType(QualType T) {
1874 // If our type is instantiation-dependent but not dependent, we mangle
1875 // it as it was written in the source, removing any top-level sugar.
1876 // Otherwise, use the canonical type.
1877 //
1878 // FIXME: This is an approximation of the instantiation-dependent name
1879 // mangling rules, since we should really be using the type as written and
1880 // augmented via semantic analysis (i.e., with implicit conversions and
1881 // default template arguments) for any instantiation-dependent type.
1882 // Unfortunately, that requires several changes to our AST:
1883 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1884 // uniqued, so that we can handle substitutions properly
1885 // - Default template arguments will need to be represented in the
1886 // TemplateSpecializationType, since they need to be mangled even though
1887 // they aren't written.
1888 // - Conversions on non-type template arguments need to be expressed, since
1889 // they can affect the mangling of sizeof/alignof.
1890 if (!T->isInstantiationDependentType() || T->isDependentType())
1891 T = T.getCanonicalType();
1892 else {
1893 // Desugar any types that are purely sugar.
1894 do {
1895 // Don't desugar through template specialization types that aren't
1896 // type aliases. We need to mangle the template arguments as written.
1897 if (const TemplateSpecializationType *TST
1898 = dyn_cast<TemplateSpecializationType>(T))
1899 if (!TST->isTypeAlias())
1900 break;
1901
1902 QualType Desugared
1903 = T.getSingleStepDesugaredType(Context.getASTContext());
1904 if (Desugared == T)
1905 break;
1906
1907 T = Desugared;
1908 } while (true);
1909 }
1910 SplitQualType split = T.split();
1911 Qualifiers quals = split.Quals;
1912 const Type *ty = split.Ty;
1913
David Majnemereea02ee2014-11-28 22:22:46 +00001914 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 if (isSubstitutable && mangleSubstitution(T))
1916 return;
1917
1918 // If we're mangling a qualified array type, push the qualifiers to
1919 // the element type.
1920 if (quals && isa<ArrayType>(T)) {
1921 ty = Context.getASTContext().getAsArrayType(T);
1922 quals = Qualifiers();
1923
1924 // Note that we don't update T: we want to add the
1925 // substitution at the original type.
1926 }
1927
1928 if (quals) {
1929 mangleQualifiers(quals);
1930 // Recurse: even if the qualified type isn't yet substitutable,
1931 // the unqualified type might be.
1932 mangleType(QualType(ty, 0));
1933 } else {
1934 switch (ty->getTypeClass()) {
1935#define ABSTRACT_TYPE(CLASS, PARENT)
1936#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1937 case Type::CLASS: \
1938 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1939 return;
1940#define TYPE(CLASS, PARENT) \
1941 case Type::CLASS: \
1942 mangleType(static_cast<const CLASS##Type*>(ty)); \
1943 break;
1944#include "clang/AST/TypeNodes.def"
1945 }
1946 }
1947
1948 // Add the substitution.
1949 if (isSubstitutable)
1950 addSubstitution(T);
1951}
1952
1953void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1954 if (!mangleStandardSubstitution(ND))
1955 mangleName(ND);
1956}
1957
1958void CXXNameMangler::mangleType(const BuiltinType *T) {
1959 // <type> ::= <builtin-type>
1960 // <builtin-type> ::= v # void
1961 // ::= w # wchar_t
1962 // ::= b # bool
1963 // ::= c # char
1964 // ::= a # signed char
1965 // ::= h # unsigned char
1966 // ::= s # short
1967 // ::= t # unsigned short
1968 // ::= i # int
1969 // ::= j # unsigned int
1970 // ::= l # long
1971 // ::= m # unsigned long
1972 // ::= x # long long, __int64
1973 // ::= y # unsigned long long, __int64
1974 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001975 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001976 // ::= f # float
1977 // ::= d # double
1978 // ::= e # long double, __float80
1979 // UNSUPPORTED: ::= g # __float128
1980 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1981 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1982 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1983 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1984 // ::= Di # char32_t
1985 // ::= Ds # char16_t
1986 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1987 // ::= u <source-name> # vendor extended type
1988 switch (T->getKind()) {
1989 case BuiltinType::Void: Out << 'v'; break;
1990 case BuiltinType::Bool: Out << 'b'; break;
1991 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1992 case BuiltinType::UChar: Out << 'h'; break;
1993 case BuiltinType::UShort: Out << 't'; break;
1994 case BuiltinType::UInt: Out << 'j'; break;
1995 case BuiltinType::ULong: Out << 'm'; break;
1996 case BuiltinType::ULongLong: Out << 'y'; break;
1997 case BuiltinType::UInt128: Out << 'o'; break;
1998 case BuiltinType::SChar: Out << 'a'; break;
1999 case BuiltinType::WChar_S:
2000 case BuiltinType::WChar_U: Out << 'w'; break;
2001 case BuiltinType::Char16: Out << "Ds"; break;
2002 case BuiltinType::Char32: Out << "Di"; break;
2003 case BuiltinType::Short: Out << 's'; break;
2004 case BuiltinType::Int: Out << 'i'; break;
2005 case BuiltinType::Long: Out << 'l'; break;
2006 case BuiltinType::LongLong: Out << 'x'; break;
2007 case BuiltinType::Int128: Out << 'n'; break;
2008 case BuiltinType::Half: Out << "Dh"; break;
2009 case BuiltinType::Float: Out << 'f'; break;
2010 case BuiltinType::Double: Out << 'd'; break;
2011 case BuiltinType::LongDouble: Out << 'e'; break;
2012 case BuiltinType::NullPtr: Out << "Dn"; break;
2013
2014#define BUILTIN_TYPE(Id, SingletonId)
2015#define PLACEHOLDER_TYPE(Id, SingletonId) \
2016 case BuiltinType::Id:
2017#include "clang/AST/BuiltinTypes.def"
2018 case BuiltinType::Dependent:
2019 llvm_unreachable("mangling a placeholder type");
2020 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2021 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2022 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00002023 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2024 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2025 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2026 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2027 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2028 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00002029 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002030 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 }
2032}
2033
2034// <type> ::= <function-type>
2035// <function-type> ::= [<CV-qualifiers>] F [Y]
2036// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002037void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2038 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2039 // e.g. "const" in "int (A::*)() const".
2040 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2041
2042 Out << 'F';
2043
2044 // FIXME: We don't have enough information in the AST to produce the 'Y'
2045 // encoding for extern "C" function types.
2046 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2047
2048 // Mangle the ref-qualifier, if present.
2049 mangleRefQualifier(T->getRefQualifier());
2050
2051 Out << 'E';
2052}
2053void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2054 llvm_unreachable("Can't mangle K&R function prototypes");
2055}
2056void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2057 bool MangleReturnType) {
2058 // We should never be mangling something without a prototype.
2059 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2060
2061 // Record that we're in a function type. See mangleFunctionParam
2062 // for details on what we're trying to achieve here.
2063 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2064
2065 // <bare-function-type> ::= <signature type>+
2066 if (MangleReturnType) {
2067 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002068 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 FunctionTypeDepth.leaveResultType();
2070 }
2071
Alp Toker9cacbab2014-01-20 20:26:09 +00002072 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 // <builtin-type> ::= v # void
2074 Out << 'v';
2075
2076 FunctionTypeDepth.pop(saved);
2077 return;
2078 }
2079
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002080 for (const auto &Arg : Proto->param_types())
2081 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002082
2083 FunctionTypeDepth.pop(saved);
2084
2085 // <builtin-type> ::= z # ellipsis
2086 if (Proto->isVariadic())
2087 Out << 'z';
2088}
2089
2090// <type> ::= <class-enum-type>
2091// <class-enum-type> ::= <name>
2092void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2093 mangleName(T->getDecl());
2094}
2095
2096// <type> ::= <class-enum-type>
2097// <class-enum-type> ::= <name>
2098void CXXNameMangler::mangleType(const EnumType *T) {
2099 mangleType(static_cast<const TagType*>(T));
2100}
2101void CXXNameMangler::mangleType(const RecordType *T) {
2102 mangleType(static_cast<const TagType*>(T));
2103}
2104void CXXNameMangler::mangleType(const TagType *T) {
2105 mangleName(T->getDecl());
2106}
2107
2108// <type> ::= <array-type>
2109// <array-type> ::= A <positive dimension number> _ <element type>
2110// ::= A [<dimension expression>] _ <element type>
2111void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2112 Out << 'A' << T->getSize() << '_';
2113 mangleType(T->getElementType());
2114}
2115void CXXNameMangler::mangleType(const VariableArrayType *T) {
2116 Out << 'A';
2117 // decayed vla types (size 0) will just be skipped.
2118 if (T->getSizeExpr())
2119 mangleExpression(T->getSizeExpr());
2120 Out << '_';
2121 mangleType(T->getElementType());
2122}
2123void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2124 Out << 'A';
2125 mangleExpression(T->getSizeExpr());
2126 Out << '_';
2127 mangleType(T->getElementType());
2128}
2129void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2130 Out << "A_";
2131 mangleType(T->getElementType());
2132}
2133
2134// <type> ::= <pointer-to-member-type>
2135// <pointer-to-member-type> ::= M <class type> <member type>
2136void CXXNameMangler::mangleType(const MemberPointerType *T) {
2137 Out << 'M';
2138 mangleType(QualType(T->getClass(), 0));
2139 QualType PointeeType = T->getPointeeType();
2140 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2141 mangleType(FPT);
2142
2143 // Itanium C++ ABI 5.1.8:
2144 //
2145 // The type of a non-static member function is considered to be different,
2146 // for the purposes of substitution, from the type of a namespace-scope or
2147 // static member function whose type appears similar. The types of two
2148 // non-static member functions are considered to be different, for the
2149 // purposes of substitution, if the functions are members of different
2150 // classes. In other words, for the purposes of substitution, the class of
2151 // which the function is a member is considered part of the type of
2152 // function.
2153
2154 // Given that we already substitute member function pointers as a
2155 // whole, the net effect of this rule is just to unconditionally
2156 // suppress substitution on the function type in a member pointer.
2157 // We increment the SeqID here to emulate adding an entry to the
2158 // substitution table.
2159 ++SeqID;
2160 } else
2161 mangleType(PointeeType);
2162}
2163
2164// <type> ::= <template-param>
2165void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2166 mangleTemplateParameter(T->getIndex());
2167}
2168
2169// <type> ::= <template-param>
2170void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2171 // FIXME: not clear how to mangle this!
2172 // template <class T...> class A {
2173 // template <class U...> void foo(T(*)(U) x...);
2174 // };
2175 Out << "_SUBSTPACK_";
2176}
2177
2178// <type> ::= P <type> # pointer-to
2179void CXXNameMangler::mangleType(const PointerType *T) {
2180 Out << 'P';
2181 mangleType(T->getPointeeType());
2182}
2183void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2184 Out << 'P';
2185 mangleType(T->getPointeeType());
2186}
2187
2188// <type> ::= R <type> # reference-to
2189void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2190 Out << 'R';
2191 mangleType(T->getPointeeType());
2192}
2193
2194// <type> ::= O <type> # rvalue reference-to (C++0x)
2195void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2196 Out << 'O';
2197 mangleType(T->getPointeeType());
2198}
2199
2200// <type> ::= C <type> # complex pair (C 2000)
2201void CXXNameMangler::mangleType(const ComplexType *T) {
2202 Out << 'C';
2203 mangleType(T->getElementType());
2204}
2205
2206// ARM's ABI for Neon vector types specifies that they should be mangled as
2207// if they are structs (to match ARM's initial implementation). The
2208// vector type must be one of the special types predefined by ARM.
2209void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2210 QualType EltType = T->getElementType();
2211 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002212 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002213 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2214 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002215 case BuiltinType::SChar:
2216 case BuiltinType::UChar:
2217 EltName = "poly8_t";
2218 break;
2219 case BuiltinType::Short:
2220 case BuiltinType::UShort:
2221 EltName = "poly16_t";
2222 break;
2223 case BuiltinType::ULongLong:
2224 EltName = "poly64_t";
2225 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2227 }
2228 } else {
2229 switch (cast<BuiltinType>(EltType)->getKind()) {
2230 case BuiltinType::SChar: EltName = "int8_t"; break;
2231 case BuiltinType::UChar: EltName = "uint8_t"; break;
2232 case BuiltinType::Short: EltName = "int16_t"; break;
2233 case BuiltinType::UShort: EltName = "uint16_t"; break;
2234 case BuiltinType::Int: EltName = "int32_t"; break;
2235 case BuiltinType::UInt: EltName = "uint32_t"; break;
2236 case BuiltinType::LongLong: EltName = "int64_t"; break;
2237 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002238 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002240 case BuiltinType::Half: EltName = "float16_t";break;
2241 default:
2242 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 }
2244 }
Craig Topper36250ad2014-05-12 05:36:57 +00002245 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 unsigned BitSize = (T->getNumElements() *
2247 getASTContext().getTypeSize(EltType));
2248 if (BitSize == 64)
2249 BaseName = "__simd64_";
2250 else {
2251 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2252 BaseName = "__simd128_";
2253 }
2254 Out << strlen(BaseName) + strlen(EltName);
2255 Out << BaseName << EltName;
2256}
2257
Tim Northover2fe823a2013-08-01 09:23:19 +00002258static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2259 switch (EltType->getKind()) {
2260 case BuiltinType::SChar:
2261 return "Int8";
2262 case BuiltinType::Short:
2263 return "Int16";
2264 case BuiltinType::Int:
2265 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002266 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002267 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002268 return "Int64";
2269 case BuiltinType::UChar:
2270 return "Uint8";
2271 case BuiltinType::UShort:
2272 return "Uint16";
2273 case BuiltinType::UInt:
2274 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002275 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002276 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002277 return "Uint64";
2278 case BuiltinType::Half:
2279 return "Float16";
2280 case BuiltinType::Float:
2281 return "Float32";
2282 case BuiltinType::Double:
2283 return "Float64";
2284 default:
2285 llvm_unreachable("Unexpected vector element base type");
2286 }
2287}
2288
2289// AArch64's ABI for Neon vector types specifies that they should be mangled as
2290// the equivalent internal name. The vector type must be one of the special
2291// types predefined by ARM.
2292void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2293 QualType EltType = T->getElementType();
2294 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2295 unsigned BitSize =
2296 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002297 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002298
2299 assert((BitSize == 64 || BitSize == 128) &&
2300 "Neon vector type not 64 or 128 bits");
2301
Tim Northover2fe823a2013-08-01 09:23:19 +00002302 StringRef EltName;
2303 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2304 switch (cast<BuiltinType>(EltType)->getKind()) {
2305 case BuiltinType::UChar:
2306 EltName = "Poly8";
2307 break;
2308 case BuiltinType::UShort:
2309 EltName = "Poly16";
2310 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002311 case BuiltinType::ULong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002312 EltName = "Poly64";
2313 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002314 default:
2315 llvm_unreachable("unexpected Neon polynomial vector element type");
2316 }
2317 } else
2318 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2319
2320 std::string TypeName =
2321 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2322 Out << TypeName.length() << TypeName;
2323}
2324
Guy Benyei11169dd2012-12-18 14:30:41 +00002325// GNU extension: vector types
2326// <type> ::= <vector-type>
2327// <vector-type> ::= Dv <positive dimension number> _
2328// <extended element type>
2329// ::= Dv [<dimension expression>] _ <element type>
2330// <extended element type> ::= <element type>
2331// ::= p # AltiVec vector pixel
2332// ::= b # Altivec vector bool
2333void CXXNameMangler::mangleType(const VectorType *T) {
2334 if ((T->getVectorKind() == VectorType::NeonVector ||
2335 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002336 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002337 llvm::Triple::ArchType Arch =
2338 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002339 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002340 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002341 mangleAArch64NeonVectorType(T);
2342 else
2343 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 return;
2345 }
2346 Out << "Dv" << T->getNumElements() << '_';
2347 if (T->getVectorKind() == VectorType::AltiVecPixel)
2348 Out << 'p';
2349 else if (T->getVectorKind() == VectorType::AltiVecBool)
2350 Out << 'b';
2351 else
2352 mangleType(T->getElementType());
2353}
2354void CXXNameMangler::mangleType(const ExtVectorType *T) {
2355 mangleType(static_cast<const VectorType*>(T));
2356}
2357void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2358 Out << "Dv";
2359 mangleExpression(T->getSizeExpr());
2360 Out << '_';
2361 mangleType(T->getElementType());
2362}
2363
2364void CXXNameMangler::mangleType(const PackExpansionType *T) {
2365 // <type> ::= Dp <type> # pack expansion (C++0x)
2366 Out << "Dp";
2367 mangleType(T->getPattern());
2368}
2369
2370void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2371 mangleSourceName(T->getDecl()->getIdentifier());
2372}
2373
2374void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman5f508952013-06-18 22:41:37 +00002375 if (!T->qual_empty()) {
2376 // Mangle protocol qualifiers.
2377 SmallString<64> QualStr;
2378 llvm::raw_svector_ostream QualOS(QualStr);
2379 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002380 for (const auto *I : T->quals()) {
2381 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002382 QualOS << name.size() << name;
2383 }
2384 QualOS.flush();
2385 Out << 'U' << QualStr.size() << QualStr;
2386 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 mangleType(T->getBaseType());
2388}
2389
2390void CXXNameMangler::mangleType(const BlockPointerType *T) {
2391 Out << "U13block_pointer";
2392 mangleType(T->getPointeeType());
2393}
2394
2395void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2396 // Mangle injected class name types as if the user had written the
2397 // specialization out fully. It may not actually be possible to see
2398 // this mangling, though.
2399 mangleType(T->getInjectedSpecializationType());
2400}
2401
2402void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2403 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2404 mangleName(TD, T->getArgs(), T->getNumArgs());
2405 } else {
2406 if (mangleSubstitution(QualType(T, 0)))
2407 return;
2408
2409 mangleTemplatePrefix(T->getTemplateName());
2410
2411 // FIXME: GCC does not appear to mangle the template arguments when
2412 // the template in question is a dependent template name. Should we
2413 // emulate that badness?
2414 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2415 addSubstitution(QualType(T, 0));
2416 }
2417}
2418
2419void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002420 // Proposal by cxx-abi-dev, 2014-03-26
2421 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2422 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002423 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002424 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002425 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002426 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002427 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002428 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002429 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002430 switch (T->getKeyword()) {
2431 case ETK_Typename:
2432 break;
2433 case ETK_Struct:
2434 case ETK_Class:
2435 case ETK_Interface:
2436 Out << "Ts";
2437 break;
2438 case ETK_Union:
2439 Out << "Tu";
2440 break;
2441 case ETK_Enum:
2442 Out << "Te";
2443 break;
2444 default:
2445 llvm_unreachable("unexpected keyword for dependent type name");
2446 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002447 // Typename types are always nested
2448 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002450 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 Out << 'E';
2452}
2453
2454void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2455 // Dependently-scoped template types are nested if they have a prefix.
2456 Out << 'N';
2457
2458 // TODO: avoid making this TemplateName.
2459 TemplateName Prefix =
2460 getASTContext().getDependentTemplateName(T->getQualifier(),
2461 T->getIdentifier());
2462 mangleTemplatePrefix(Prefix);
2463
2464 // FIXME: GCC does not appear to mangle the template arguments when
2465 // the template in question is a dependent template name. Should we
2466 // emulate that badness?
2467 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2468 Out << 'E';
2469}
2470
2471void CXXNameMangler::mangleType(const TypeOfType *T) {
2472 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2473 // "extension with parameters" mangling.
2474 Out << "u6typeof";
2475}
2476
2477void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2478 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2479 // "extension with parameters" mangling.
2480 Out << "u6typeof";
2481}
2482
2483void CXXNameMangler::mangleType(const DecltypeType *T) {
2484 Expr *E = T->getUnderlyingExpr();
2485
2486 // type ::= Dt <expression> E # decltype of an id-expression
2487 // # or class member access
2488 // ::= DT <expression> E # decltype of an expression
2489
2490 // This purports to be an exhaustive list of id-expressions and
2491 // class member accesses. Note that we do not ignore parentheses;
2492 // parentheses change the semantics of decltype for these
2493 // expressions (and cause the mangler to use the other form).
2494 if (isa<DeclRefExpr>(E) ||
2495 isa<MemberExpr>(E) ||
2496 isa<UnresolvedLookupExpr>(E) ||
2497 isa<DependentScopeDeclRefExpr>(E) ||
2498 isa<CXXDependentScopeMemberExpr>(E) ||
2499 isa<UnresolvedMemberExpr>(E))
2500 Out << "Dt";
2501 else
2502 Out << "DT";
2503 mangleExpression(E);
2504 Out << 'E';
2505}
2506
2507void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2508 // If this is dependent, we need to record that. If not, we simply
2509 // mangle it as the underlying type since they are equivalent.
2510 if (T->isDependentType()) {
2511 Out << 'U';
2512
2513 switch (T->getUTTKind()) {
2514 case UnaryTransformType::EnumUnderlyingType:
2515 Out << "3eut";
2516 break;
2517 }
2518 }
2519
2520 mangleType(T->getUnderlyingType());
2521}
2522
2523void CXXNameMangler::mangleType(const AutoType *T) {
2524 QualType D = T->getDeducedType();
2525 // <builtin-type> ::= Da # dependent auto
2526 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002527 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 else
2529 mangleType(D);
2530}
2531
2532void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002533 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 // (Until there's a standardized mangling...)
2535 Out << "U7_Atomic";
2536 mangleType(T->getValueType());
2537}
2538
2539void CXXNameMangler::mangleIntegerLiteral(QualType T,
2540 const llvm::APSInt &Value) {
2541 // <expr-primary> ::= L <type> <value number> E # integer literal
2542 Out << 'L';
2543
2544 mangleType(T);
2545 if (T->isBooleanType()) {
2546 // Boolean values are encoded as 0/1.
2547 Out << (Value.getBoolValue() ? '1' : '0');
2548 } else {
2549 mangleNumber(Value);
2550 }
2551 Out << 'E';
2552
2553}
2554
David Majnemer1dabfdc2015-02-14 13:23:54 +00002555void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2556 // Ignore member expressions involving anonymous unions.
2557 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2558 if (!RT->getDecl()->isAnonymousStructOrUnion())
2559 break;
2560 const auto *ME = dyn_cast<MemberExpr>(Base);
2561 if (!ME)
2562 break;
2563 Base = ME->getBase();
2564 IsArrow = ME->isArrow();
2565 }
2566
2567 if (Base->isImplicitCXXThis()) {
2568 // Note: GCC mangles member expressions to the implicit 'this' as
2569 // *this., whereas we represent them as this->. The Itanium C++ ABI
2570 // does not specify anything here, so we follow GCC.
2571 Out << "dtdefpT";
2572 } else {
2573 Out << (IsArrow ? "pt" : "dt");
2574 mangleExpression(Base);
2575 }
2576}
2577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578/// Mangles a member expression.
2579void CXXNameMangler::mangleMemberExpr(const Expr *base,
2580 bool isArrow,
2581 NestedNameSpecifier *qualifier,
2582 NamedDecl *firstQualifierLookup,
2583 DeclarationName member,
2584 unsigned arity) {
2585 // <expression> ::= dt <expression> <unresolved-name>
2586 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002587 if (base)
2588 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002589 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002590}
2591
2592/// Look at the callee of the given call expression and determine if
2593/// it's a parenthesized id-expression which would have triggered ADL
2594/// otherwise.
2595static bool isParenthesizedADLCallee(const CallExpr *call) {
2596 const Expr *callee = call->getCallee();
2597 const Expr *fn = callee->IgnoreParens();
2598
2599 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2600 // too, but for those to appear in the callee, it would have to be
2601 // parenthesized.
2602 if (callee == fn) return false;
2603
2604 // Must be an unresolved lookup.
2605 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2606 if (!lookup) return false;
2607
2608 assert(!lookup->requiresADL());
2609
2610 // Must be an unqualified lookup.
2611 if (lookup->getQualifier()) return false;
2612
2613 // Must not have found a class member. Note that if one is a class
2614 // member, they're all class members.
2615 if (lookup->getNumDecls() > 0 &&
2616 (*lookup->decls_begin())->isCXXClassMember())
2617 return false;
2618
2619 // Otherwise, ADL would have been triggered.
2620 return true;
2621}
2622
David Majnemer9c775c72014-09-23 04:27:55 +00002623void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2624 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2625 Out << CastEncoding;
2626 mangleType(ECE->getType());
2627 mangleExpression(ECE->getSubExpr());
2628}
2629
Richard Smith520449d2015-02-05 06:15:50 +00002630void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2631 if (auto *Syntactic = InitList->getSyntacticForm())
2632 InitList = Syntactic;
2633 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2634 mangleExpression(InitList->getInit(i));
2635}
2636
Guy Benyei11169dd2012-12-18 14:30:41 +00002637void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2638 // <expression> ::= <unary operator-name> <expression>
2639 // ::= <binary operator-name> <expression> <expression>
2640 // ::= <trinary operator-name> <expression> <expression> <expression>
2641 // ::= cv <type> expression # conversion with one argument
2642 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002643 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2644 // ::= sc <type> <expression> # static_cast<type> (expression)
2645 // ::= cc <type> <expression> # const_cast<type> (expression)
2646 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 // ::= st <type> # sizeof (a type)
2648 // ::= at <type> # alignof (a type)
2649 // ::= <template-param>
2650 // ::= <function-param>
2651 // ::= sr <type> <unqualified-name> # dependent name
2652 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2653 // ::= ds <expression> <expression> # expr.*expr
2654 // ::= sZ <template-param> # size of a parameter pack
2655 // ::= sZ <function-param> # size of a function parameter pack
2656 // ::= <expr-primary>
2657 // <expr-primary> ::= L <type> <value number> E # integer literal
2658 // ::= L <type <value float> E # floating literal
2659 // ::= L <mangled-name> E # external name
2660 // ::= fpT # 'this' expression
2661 QualType ImplicitlyConvertedToType;
2662
2663recurse:
2664 switch (E->getStmtClass()) {
2665 case Expr::NoStmtClass:
2666#define ABSTRACT_STMT(Type)
2667#define EXPR(Type, Base)
2668#define STMT(Type, Base) \
2669 case Expr::Type##Class:
2670#include "clang/AST/StmtNodes.inc"
2671 // fallthrough
2672
2673 // These all can only appear in local or variable-initialization
2674 // contexts and so should never appear in a mangling.
2675 case Expr::AddrLabelExprClass:
2676 case Expr::DesignatedInitExprClass:
2677 case Expr::ImplicitValueInitExprClass:
2678 case Expr::ParenListExprClass:
2679 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002680 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002681 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 llvm_unreachable("unexpected statement kind");
2683
2684 // FIXME: invent manglings for all these.
2685 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 case Expr::ChooseExprClass:
2687 case Expr::CompoundLiteralExprClass:
2688 case Expr::ExtVectorElementExprClass:
2689 case Expr::GenericSelectionExprClass:
2690 case Expr::ObjCEncodeExprClass:
2691 case Expr::ObjCIsaExprClass:
2692 case Expr::ObjCIvarRefExprClass:
2693 case Expr::ObjCMessageExprClass:
2694 case Expr::ObjCPropertyRefExprClass:
2695 case Expr::ObjCProtocolExprClass:
2696 case Expr::ObjCSelectorExprClass:
2697 case Expr::ObjCStringLiteralClass:
2698 case Expr::ObjCBoxedExprClass:
2699 case Expr::ObjCArrayLiteralClass:
2700 case Expr::ObjCDictionaryLiteralClass:
2701 case Expr::ObjCSubscriptRefExprClass:
2702 case Expr::ObjCIndirectCopyRestoreExprClass:
2703 case Expr::OffsetOfExprClass:
2704 case Expr::PredefinedExprClass:
2705 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002706 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 case Expr::TypeTraitExprClass:
2709 case Expr::ArrayTypeTraitExprClass:
2710 case Expr::ExpressionTraitExprClass:
2711 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 case Expr::CUDAKernelCallExprClass:
2713 case Expr::AsTypeExprClass:
2714 case Expr::PseudoObjectExprClass:
2715 case Expr::AtomicExprClass:
2716 {
2717 // As bad as this diagnostic is, it's better than crashing.
2718 DiagnosticsEngine &Diags = Context.getDiags();
2719 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2720 "cannot yet mangle expression type %0");
2721 Diags.Report(E->getExprLoc(), DiagID)
2722 << E->getStmtClassName() << E->getSourceRange();
2723 break;
2724 }
2725
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002726 case Expr::CXXUuidofExprClass: {
2727 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2728 if (UE->isTypeOperand()) {
2729 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2730 Out << "u8__uuidoft";
2731 mangleType(UuidT);
2732 } else {
2733 Expr *UuidExp = UE->getExprOperand();
2734 Out << "u8__uuidofz";
2735 mangleExpression(UuidExp, Arity);
2736 }
2737 break;
2738 }
2739
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // Even gcc-4.5 doesn't mangle this.
2741 case Expr::BinaryConditionalOperatorClass: {
2742 DiagnosticsEngine &Diags = Context.getDiags();
2743 unsigned DiagID =
2744 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2745 "?: operator with omitted middle operand cannot be mangled");
2746 Diags.Report(E->getExprLoc(), DiagID)
2747 << E->getStmtClassName() << E->getSourceRange();
2748 break;
2749 }
2750
2751 // These are used for internal purposes and cannot be meaningfully mangled.
2752 case Expr::OpaqueValueExprClass:
2753 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2754
2755 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002757 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 Out << "E";
2759 break;
2760 }
2761
2762 case Expr::CXXDefaultArgExprClass:
2763 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2764 break;
2765
Richard Smith852c9db2013-04-20 22:23:05 +00002766 case Expr::CXXDefaultInitExprClass:
2767 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2768 break;
2769
Richard Smithcc1b96d2013-06-12 22:31:48 +00002770 case Expr::CXXStdInitializerListExprClass:
2771 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2772 break;
2773
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 case Expr::SubstNonTypeTemplateParmExprClass:
2775 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2776 Arity);
2777 break;
2778
2779 case Expr::UserDefinedLiteralClass:
2780 // We follow g++'s approach of mangling a UDL as a call to the literal
2781 // operator.
2782 case Expr::CXXMemberCallExprClass: // fallthrough
2783 case Expr::CallExprClass: {
2784 const CallExpr *CE = cast<CallExpr>(E);
2785
2786 // <expression> ::= cp <simple-id> <expression>* E
2787 // We use this mangling only when the call would use ADL except
2788 // for being parenthesized. Per discussion with David
2789 // Vandervoorde, 2011.04.25.
2790 if (isParenthesizedADLCallee(CE)) {
2791 Out << "cp";
2792 // The callee here is a parenthesized UnresolvedLookupExpr with
2793 // no qualifier and should always get mangled as a <simple-id>
2794 // anyway.
2795
2796 // <expression> ::= cl <expression>* E
2797 } else {
2798 Out << "cl";
2799 }
2800
2801 mangleExpression(CE->getCallee(), CE->getNumArgs());
2802 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2803 mangleExpression(CE->getArg(I));
2804 Out << 'E';
2805 break;
2806 }
2807
2808 case Expr::CXXNewExprClass: {
2809 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2810 if (New->isGlobalNew()) Out << "gs";
2811 Out << (New->isArray() ? "na" : "nw");
2812 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2813 E = New->placement_arg_end(); I != E; ++I)
2814 mangleExpression(*I);
2815 Out << '_';
2816 mangleType(New->getAllocatedType());
2817 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2819 Out << "il";
2820 else
2821 Out << "pi";
2822 const Expr *Init = New->getInitializer();
2823 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2824 // Directly inline the initializers.
2825 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2826 E = CCE->arg_end();
2827 I != E; ++I)
2828 mangleExpression(*I);
2829 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2830 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2831 mangleExpression(PLE->getExpr(i));
2832 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2833 isa<InitListExpr>(Init)) {
2834 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002835 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 } else
2837 mangleExpression(Init);
2838 }
2839 Out << 'E';
2840 break;
2841 }
2842
David Majnemer1dabfdc2015-02-14 13:23:54 +00002843 case Expr::CXXPseudoDestructorExprClass: {
2844 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2845 if (const Expr *Base = PDE->getBase())
2846 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00002847 NestedNameSpecifier *Qualifier = PDE->getQualifier();
2848 QualType ScopeType;
2849 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
2850 if (Qualifier) {
2851 mangleUnresolvedPrefix(Qualifier,
2852 /*Recursive=*/true);
2853 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
2854 Out << 'E';
2855 } else {
2856 Out << "sr";
2857 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
2858 Out << 'E';
2859 }
2860 } else if (Qualifier) {
2861 mangleUnresolvedPrefix(Qualifier);
2862 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00002863 // <base-unresolved-name> ::= dn <destructor-name>
2864 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00002865 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00002866 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00002867 break;
2868 }
2869
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 case Expr::MemberExprClass: {
2871 const MemberExpr *ME = cast<MemberExpr>(E);
2872 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002873 ME->getQualifier(), nullptr,
2874 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 break;
2876 }
2877
2878 case Expr::UnresolvedMemberExprClass: {
2879 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2880 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002881 ME->getQualifier(), nullptr, ME->getMemberName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 Arity);
2883 if (ME->hasExplicitTemplateArgs())
2884 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2885 break;
2886 }
2887
2888 case Expr::CXXDependentScopeMemberExprClass: {
2889 const CXXDependentScopeMemberExpr *ME
2890 = cast<CXXDependentScopeMemberExpr>(E);
2891 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2892 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2893 ME->getMember(), Arity);
2894 if (ME->hasExplicitTemplateArgs())
2895 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2896 break;
2897 }
2898
2899 case Expr::UnresolvedLookupExprClass: {
2900 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00002901 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002902
2903 // All the <unresolved-name> productions end in a
2904 // base-unresolved-name, where <template-args> are just tacked
2905 // onto the end.
2906 if (ULE->hasExplicitTemplateArgs())
2907 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2908 break;
2909 }
2910
2911 case Expr::CXXUnresolvedConstructExprClass: {
2912 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2913 unsigned N = CE->arg_size();
2914
2915 Out << "cv";
2916 mangleType(CE->getType());
2917 if (N != 1) Out << '_';
2918 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2919 if (N != 1) Out << 'E';
2920 break;
2921 }
2922
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00002924 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00002925 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00002926 assert(
2927 CE->getNumArgs() >= 1 &&
2928 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2929 "implicit CXXConstructExpr must have one argument");
2930 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2931 }
2932 Out << "il";
2933 for (auto *E : CE->arguments())
2934 mangleExpression(E);
2935 Out << "E";
2936 break;
2937 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002938
Richard Smith520449d2015-02-05 06:15:50 +00002939 case Expr::CXXTemporaryObjectExprClass: {
2940 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2941 unsigned N = CE->getNumArgs();
2942 bool List = CE->isListInitialization();
2943
2944 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 Out << "tl";
2946 else
2947 Out << "cv";
2948 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002949 if (!List && N != 1)
2950 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00002951 if (CE->isStdInitListInitialization()) {
2952 // We implicitly created a std::initializer_list<T> for the first argument
2953 // of a constructor of type U in an expression of the form U{a, b, c}.
2954 // Strip all the semantic gunk off the initializer list.
2955 auto *SILE =
2956 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2957 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2958 mangleInitListElements(ILE);
2959 } else {
2960 for (auto *E : CE->arguments())
2961 mangleExpression(E);
2962 }
Richard Smith520449d2015-02-05 06:15:50 +00002963 if (List || N != 1)
2964 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 break;
2966 }
2967
2968 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00002969 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002971 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 break;
2973
2974 case Expr::CXXNoexceptExprClass:
2975 Out << "nx";
2976 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2977 break;
2978
2979 case Expr::UnaryExprOrTypeTraitExprClass: {
2980 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2981
2982 if (!SAE->isInstantiationDependent()) {
2983 // Itanium C++ ABI:
2984 // If the operand of a sizeof or alignof operator is not
2985 // instantiation-dependent it is encoded as an integer literal
2986 // reflecting the result of the operator.
2987 //
2988 // If the result of the operator is implicitly converted to a known
2989 // integer type, that type is used for the literal; otherwise, the type
2990 // of std::size_t or std::ptrdiff_t is used.
2991 QualType T = (ImplicitlyConvertedToType.isNull() ||
2992 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2993 : ImplicitlyConvertedToType;
2994 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2995 mangleIntegerLiteral(T, V);
2996 break;
2997 }
2998
2999 switch(SAE->getKind()) {
3000 case UETT_SizeOf:
3001 Out << 's';
3002 break;
3003 case UETT_AlignOf:
3004 Out << 'a';
3005 break;
3006 case UETT_VecStep:
3007 DiagnosticsEngine &Diags = Context.getDiags();
3008 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3009 "cannot yet mangle vec_step expression");
3010 Diags.Report(DiagID);
3011 return;
3012 }
3013 if (SAE->isArgumentType()) {
3014 Out << 't';
3015 mangleType(SAE->getArgumentType());
3016 } else {
3017 Out << 'z';
3018 mangleExpression(SAE->getArgumentExpr());
3019 }
3020 break;
3021 }
3022
3023 case Expr::CXXThrowExprClass: {
3024 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003025 // <expression> ::= tw <expression> # throw expression
3026 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 if (TE->getSubExpr()) {
3028 Out << "tw";
3029 mangleExpression(TE->getSubExpr());
3030 } else {
3031 Out << "tr";
3032 }
3033 break;
3034 }
3035
3036 case Expr::CXXTypeidExprClass: {
3037 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003038 // <expression> ::= ti <type> # typeid (type)
3039 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 if (TIE->isTypeOperand()) {
3041 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003042 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 } else {
3044 Out << "te";
3045 mangleExpression(TIE->getExprOperand());
3046 }
3047 break;
3048 }
3049
3050 case Expr::CXXDeleteExprClass: {
3051 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003052 // <expression> ::= [gs] dl <expression> # [::] delete expr
3053 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 if (DE->isGlobalDelete()) Out << "gs";
3055 Out << (DE->isArrayForm() ? "da" : "dl");
3056 mangleExpression(DE->getArgument());
3057 break;
3058 }
3059
3060 case Expr::UnaryOperatorClass: {
3061 const UnaryOperator *UO = cast<UnaryOperator>(E);
3062 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3063 /*Arity=*/1);
3064 mangleExpression(UO->getSubExpr());
3065 break;
3066 }
3067
3068 case Expr::ArraySubscriptExprClass: {
3069 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3070
3071 // Array subscript is treated as a syntactically weird form of
3072 // binary operator.
3073 Out << "ix";
3074 mangleExpression(AE->getLHS());
3075 mangleExpression(AE->getRHS());
3076 break;
3077 }
3078
3079 case Expr::CompoundAssignOperatorClass: // fallthrough
3080 case Expr::BinaryOperatorClass: {
3081 const BinaryOperator *BO = cast<BinaryOperator>(E);
3082 if (BO->getOpcode() == BO_PtrMemD)
3083 Out << "ds";
3084 else
3085 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3086 /*Arity=*/2);
3087 mangleExpression(BO->getLHS());
3088 mangleExpression(BO->getRHS());
3089 break;
3090 }
3091
3092 case Expr::ConditionalOperatorClass: {
3093 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3094 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3095 mangleExpression(CO->getCond());
3096 mangleExpression(CO->getLHS(), Arity);
3097 mangleExpression(CO->getRHS(), Arity);
3098 break;
3099 }
3100
3101 case Expr::ImplicitCastExprClass: {
3102 ImplicitlyConvertedToType = E->getType();
3103 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3104 goto recurse;
3105 }
3106
3107 case Expr::ObjCBridgedCastExprClass: {
3108 // Mangle ownership casts as a vendor extended operator __bridge,
3109 // __bridge_transfer, or __bridge_retain.
3110 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3111 Out << "v1U" << Kind.size() << Kind;
3112 }
3113 // Fall through to mangle the cast itself.
3114
3115 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003116 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003118
Richard Smith520449d2015-02-05 06:15:50 +00003119 case Expr::CXXFunctionalCastExprClass: {
3120 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3121 // FIXME: Add isImplicit to CXXConstructExpr.
3122 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3123 if (CCE->getParenOrBraceRange().isInvalid())
3124 Sub = CCE->getArg(0)->IgnoreImplicit();
3125 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3126 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3127 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3128 Out << "tl";
3129 mangleType(E->getType());
3130 mangleInitListElements(IL);
3131 Out << "E";
3132 } else {
3133 mangleCastExpression(E, "cv");
3134 }
3135 break;
3136 }
3137
David Majnemer9c775c72014-09-23 04:27:55 +00003138 case Expr::CXXStaticCastExprClass:
3139 mangleCastExpression(E, "sc");
3140 break;
3141 case Expr::CXXDynamicCastExprClass:
3142 mangleCastExpression(E, "dc");
3143 break;
3144 case Expr::CXXReinterpretCastExprClass:
3145 mangleCastExpression(E, "rc");
3146 break;
3147 case Expr::CXXConstCastExprClass:
3148 mangleCastExpression(E, "cc");
3149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003150
3151 case Expr::CXXOperatorCallExprClass: {
3152 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3153 unsigned NumArgs = CE->getNumArgs();
3154 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3155 // Mangle the arguments.
3156 for (unsigned i = 0; i != NumArgs; ++i)
3157 mangleExpression(CE->getArg(i));
3158 break;
3159 }
3160
3161 case Expr::ParenExprClass:
3162 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3163 break;
3164
3165 case Expr::DeclRefExprClass: {
3166 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3167
3168 switch (D->getKind()) {
3169 default:
3170 // <expr-primary> ::= L <mangled-name> E # external name
3171 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003172 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 Out << 'E';
3174 break;
3175
3176 case Decl::ParmVar:
3177 mangleFunctionParam(cast<ParmVarDecl>(D));
3178 break;
3179
3180 case Decl::EnumConstant: {
3181 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3182 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3183 break;
3184 }
3185
3186 case Decl::NonTypeTemplateParm: {
3187 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3188 mangleTemplateParameter(PD->getIndex());
3189 break;
3190 }
3191
3192 }
3193
3194 break;
3195 }
3196
3197 case Expr::SubstNonTypeTemplateParmPackExprClass:
3198 // FIXME: not clear how to mangle this!
3199 // template <unsigned N...> class A {
3200 // template <class U...> void foo(U (&x)[N]...);
3201 // };
3202 Out << "_SUBSTPACK_";
3203 break;
3204
3205 case Expr::FunctionParmPackExprClass: {
3206 // FIXME: not clear how to mangle this!
3207 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3208 Out << "v110_SUBSTPACK";
3209 mangleFunctionParam(FPPE->getParameterPack());
3210 break;
3211 }
3212
3213 case Expr::DependentScopeDeclRefExprClass: {
3214 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003215 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003216
3217 // All the <unresolved-name> productions end in a
3218 // base-unresolved-name, where <template-args> are just tacked
3219 // onto the end.
3220 if (DRE->hasExplicitTemplateArgs())
3221 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3222 break;
3223 }
3224
3225 case Expr::CXXBindTemporaryExprClass:
3226 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3227 break;
3228
3229 case Expr::ExprWithCleanupsClass:
3230 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3231 break;
3232
3233 case Expr::FloatingLiteralClass: {
3234 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3235 Out << 'L';
3236 mangleType(FL->getType());
3237 mangleFloat(FL->getValue());
3238 Out << 'E';
3239 break;
3240 }
3241
3242 case Expr::CharacterLiteralClass:
3243 Out << 'L';
3244 mangleType(E->getType());
3245 Out << cast<CharacterLiteral>(E)->getValue();
3246 Out << 'E';
3247 break;
3248
3249 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3250 case Expr::ObjCBoolLiteralExprClass:
3251 Out << "Lb";
3252 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3253 Out << 'E';
3254 break;
3255
3256 case Expr::CXXBoolLiteralExprClass:
3257 Out << "Lb";
3258 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3259 Out << 'E';
3260 break;
3261
3262 case Expr::IntegerLiteralClass: {
3263 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3264 if (E->getType()->isSignedIntegerType())
3265 Value.setIsSigned(true);
3266 mangleIntegerLiteral(E->getType(), Value);
3267 break;
3268 }
3269
3270 case Expr::ImaginaryLiteralClass: {
3271 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3272 // Mangle as if a complex literal.
3273 // Proposal from David Vandevoorde, 2010.06.30.
3274 Out << 'L';
3275 mangleType(E->getType());
3276 if (const FloatingLiteral *Imag =
3277 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3278 // Mangle a floating-point zero of the appropriate type.
3279 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3280 Out << '_';
3281 mangleFloat(Imag->getValue());
3282 } else {
3283 Out << "0_";
3284 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3285 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3286 Value.setIsSigned(true);
3287 mangleNumber(Value);
3288 }
3289 Out << 'E';
3290 break;
3291 }
3292
3293 case Expr::StringLiteralClass: {
3294 // Revised proposal from David Vandervoorde, 2010.07.15.
3295 Out << 'L';
3296 assert(isa<ConstantArrayType>(E->getType()));
3297 mangleType(E->getType());
3298 Out << 'E';
3299 break;
3300 }
3301
3302 case Expr::GNUNullExprClass:
3303 // FIXME: should this really be mangled the same as nullptr?
3304 // fallthrough
3305
3306 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 Out << "LDnE";
3308 break;
3309 }
3310
3311 case Expr::PackExpansionExprClass:
3312 Out << "sp";
3313 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3314 break;
3315
3316 case Expr::SizeOfPackExprClass: {
3317 Out << "sZ";
3318 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3319 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3320 mangleTemplateParameter(TTP->getIndex());
3321 else if (const NonTypeTemplateParmDecl *NTTP
3322 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3323 mangleTemplateParameter(NTTP->getIndex());
3324 else if (const TemplateTemplateParmDecl *TempTP
3325 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3326 mangleTemplateParameter(TempTP->getIndex());
3327 else
3328 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3329 break;
3330 }
Richard Smith0f0af192014-11-08 05:07:16 +00003331
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 case Expr::MaterializeTemporaryExprClass: {
3333 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3334 break;
3335 }
Richard Smith0f0af192014-11-08 05:07:16 +00003336
3337 case Expr::CXXFoldExprClass: {
3338 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003339 if (FE->isLeftFold())
3340 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003341 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003342 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003343
3344 if (FE->getOperator() == BO_PtrMemD)
3345 Out << "ds";
3346 else
3347 mangleOperatorName(
3348 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3349 /*Arity=*/2);
3350
3351 if (FE->getLHS())
3352 mangleExpression(FE->getLHS());
3353 if (FE->getRHS())
3354 mangleExpression(FE->getRHS());
3355 break;
3356 }
3357
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 case Expr::CXXThisExprClass:
3359 Out << "fpT";
3360 break;
3361 }
3362}
3363
3364/// Mangle an expression which refers to a parameter variable.
3365///
3366/// <expression> ::= <function-param>
3367/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3368/// <function-param> ::= fp <top-level CV-qualifiers>
3369/// <parameter-2 non-negative number> _ # L == 0, I > 0
3370/// <function-param> ::= fL <L-1 non-negative number>
3371/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3372/// <function-param> ::= fL <L-1 non-negative number>
3373/// p <top-level CV-qualifiers>
3374/// <I-1 non-negative number> _ # L > 0, I > 0
3375///
3376/// L is the nesting depth of the parameter, defined as 1 if the
3377/// parameter comes from the innermost function prototype scope
3378/// enclosing the current context, 2 if from the next enclosing
3379/// function prototype scope, and so on, with one special case: if
3380/// we've processed the full parameter clause for the innermost
3381/// function type, then L is one less. This definition conveniently
3382/// makes it irrelevant whether a function's result type was written
3383/// trailing or leading, but is otherwise overly complicated; the
3384/// numbering was first designed without considering references to
3385/// parameter in locations other than return types, and then the
3386/// mangling had to be generalized without changing the existing
3387/// manglings.
3388///
3389/// I is the zero-based index of the parameter within its parameter
3390/// declaration clause. Note that the original ABI document describes
3391/// this using 1-based ordinals.
3392void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3393 unsigned parmDepth = parm->getFunctionScopeDepth();
3394 unsigned parmIndex = parm->getFunctionScopeIndex();
3395
3396 // Compute 'L'.
3397 // parmDepth does not include the declaring function prototype.
3398 // FunctionTypeDepth does account for that.
3399 assert(parmDepth < FunctionTypeDepth.getDepth());
3400 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3401 if (FunctionTypeDepth.isInResultType())
3402 nestingDepth--;
3403
3404 if (nestingDepth == 0) {
3405 Out << "fp";
3406 } else {
3407 Out << "fL" << (nestingDepth - 1) << 'p';
3408 }
3409
3410 // Top-level qualifiers. We don't have to worry about arrays here,
3411 // because parameters declared as arrays should already have been
3412 // transformed to have pointer type. FIXME: apparently these don't
3413 // get mangled if used as an rvalue of a known non-class type?
3414 assert(!parm->getType()->isArrayType()
3415 && "parameter's type is still an array type?");
3416 mangleQualifiers(parm->getType().getQualifiers());
3417
3418 // Parameter index.
3419 if (parmIndex != 0) {
3420 Out << (parmIndex - 1);
3421 }
3422 Out << '_';
3423}
3424
3425void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3426 // <ctor-dtor-name> ::= C1 # complete object constructor
3427 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003429 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 switch (T) {
3431 case Ctor_Complete:
3432 Out << "C1";
3433 break;
3434 case Ctor_Base:
3435 Out << "C2";
3436 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003437 case Ctor_Comdat:
3438 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 break;
3440 }
3441}
3442
3443void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3444 // <ctor-dtor-name> ::= D0 # deleting destructor
3445 // ::= D1 # complete object destructor
3446 // ::= D2 # base object destructor
3447 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003448 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 switch (T) {
3450 case Dtor_Deleting:
3451 Out << "D0";
3452 break;
3453 case Dtor_Complete:
3454 Out << "D1";
3455 break;
3456 case Dtor_Base:
3457 Out << "D2";
3458 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003459 case Dtor_Comdat:
3460 Out << "D5";
3461 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 }
3463}
3464
3465void CXXNameMangler::mangleTemplateArgs(
3466 const ASTTemplateArgumentListInfo &TemplateArgs) {
3467 // <template-args> ::= I <template-arg>+ E
3468 Out << 'I';
3469 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3470 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3471 Out << 'E';
3472}
3473
3474void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3475 // <template-args> ::= I <template-arg>+ E
3476 Out << 'I';
3477 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3478 mangleTemplateArg(AL[i]);
3479 Out << 'E';
3480}
3481
3482void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3483 unsigned NumTemplateArgs) {
3484 // <template-args> ::= I <template-arg>+ E
3485 Out << 'I';
3486 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3487 mangleTemplateArg(TemplateArgs[i]);
3488 Out << 'E';
3489}
3490
3491void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3492 // <template-arg> ::= <type> # type or template
3493 // ::= X <expression> E # expression
3494 // ::= <expr-primary> # simple expressions
3495 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003496 if (!A.isInstantiationDependent() || A.isDependent())
3497 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3498
3499 switch (A.getKind()) {
3500 case TemplateArgument::Null:
3501 llvm_unreachable("Cannot mangle NULL template argument");
3502
3503 case TemplateArgument::Type:
3504 mangleType(A.getAsType());
3505 break;
3506 case TemplateArgument::Template:
3507 // This is mangled as <type>.
3508 mangleType(A.getAsTemplate());
3509 break;
3510 case TemplateArgument::TemplateExpansion:
3511 // <type> ::= Dp <type> # pack expansion (C++0x)
3512 Out << "Dp";
3513 mangleType(A.getAsTemplateOrTemplatePattern());
3514 break;
3515 case TemplateArgument::Expression: {
3516 // It's possible to end up with a DeclRefExpr here in certain
3517 // dependent cases, in which case we should mangle as a
3518 // declaration.
3519 const Expr *E = A.getAsExpr()->IgnoreParens();
3520 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3521 const ValueDecl *D = DRE->getDecl();
3522 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003523 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003524 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 Out << 'E';
3526 break;
3527 }
3528 }
3529
3530 Out << 'X';
3531 mangleExpression(E);
3532 Out << 'E';
3533 break;
3534 }
3535 case TemplateArgument::Integral:
3536 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3537 break;
3538 case TemplateArgument::Declaration: {
3539 // <expr-primary> ::= L <mangled-name> E # external name
3540 // Clang produces AST's where pointer-to-member-function expressions
3541 // and pointer-to-function expressions are represented as a declaration not
3542 // an expression. We compensate for it here to produce the correct mangling.
3543 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003544 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 if (compensateMangling) {
3546 Out << 'X';
3547 mangleOperatorName(OO_Amp, 1);
3548 }
3549
3550 Out << 'L';
3551 // References to external entities use the mangled name; if the name would
3552 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003553 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 Out << 'E';
3555
3556 if (compensateMangling)
3557 Out << 'E';
3558
3559 break;
3560 }
3561 case TemplateArgument::NullPtr: {
3562 // <expr-primary> ::= L <type> 0 E
3563 Out << 'L';
3564 mangleType(A.getNullPtrType());
3565 Out << "0E";
3566 break;
3567 }
3568 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003569 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003570 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003571 for (const auto &P : A.pack_elements())
3572 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 Out << 'E';
3574 }
3575 }
3576}
3577
3578void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3579 // <template-param> ::= T_ # first template parameter
3580 // ::= T <parameter-2 non-negative number> _
3581 if (Index == 0)
3582 Out << "T_";
3583 else
3584 Out << 'T' << (Index - 1) << '_';
3585}
3586
David Majnemer3b3bdb52014-05-06 22:49:16 +00003587void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3588 if (SeqID == 1)
3589 Out << '0';
3590 else if (SeqID > 1) {
3591 SeqID--;
3592
3593 // <seq-id> is encoded in base-36, using digits and upper case letters.
3594 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003595 MutableArrayRef<char> BufferRef(Buffer);
3596 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003597
3598 for (; SeqID != 0; SeqID /= 36) {
3599 unsigned C = SeqID % 36;
3600 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3601 }
3602
3603 Out.write(I.base(), I - BufferRef.rbegin());
3604 }
3605 Out << '_';
3606}
3607
Guy Benyei11169dd2012-12-18 14:30:41 +00003608void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3609 bool result = mangleSubstitution(type);
3610 assert(result && "no existing substitution for type");
3611 (void) result;
3612}
3613
3614void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3615 bool result = mangleSubstitution(tname);
3616 assert(result && "no existing substitution for template name");
3617 (void) result;
3618}
3619
3620// <substitution> ::= S <seq-id> _
3621// ::= S_
3622bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3623 // Try one of the standard substitutions first.
3624 if (mangleStandardSubstitution(ND))
3625 return true;
3626
3627 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3628 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3629}
3630
3631/// \brief Determine whether the given type has any qualifiers that are
3632/// relevant for substitutions.
3633static bool hasMangledSubstitutionQualifiers(QualType T) {
3634 Qualifiers Qs = T.getQualifiers();
3635 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3636}
3637
3638bool CXXNameMangler::mangleSubstitution(QualType T) {
3639 if (!hasMangledSubstitutionQualifiers(T)) {
3640 if (const RecordType *RT = T->getAs<RecordType>())
3641 return mangleSubstitution(RT->getDecl());
3642 }
3643
3644 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3645
3646 return mangleSubstitution(TypePtr);
3647}
3648
3649bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3650 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3651 return mangleSubstitution(TD);
3652
3653 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3654 return mangleSubstitution(
3655 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3656}
3657
3658bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3659 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3660 if (I == Substitutions.end())
3661 return false;
3662
3663 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003664 Out << 'S';
3665 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003666
3667 return true;
3668}
3669
3670static bool isCharType(QualType T) {
3671 if (T.isNull())
3672 return false;
3673
3674 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3675 T->isSpecificBuiltinType(BuiltinType::Char_U);
3676}
3677
3678/// isCharSpecialization - Returns whether a given type is a template
3679/// specialization of a given name with a single argument of type char.
3680static bool isCharSpecialization(QualType T, const char *Name) {
3681 if (T.isNull())
3682 return false;
3683
3684 const RecordType *RT = T->getAs<RecordType>();
3685 if (!RT)
3686 return false;
3687
3688 const ClassTemplateSpecializationDecl *SD =
3689 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3690 if (!SD)
3691 return false;
3692
3693 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3694 return false;
3695
3696 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3697 if (TemplateArgs.size() != 1)
3698 return false;
3699
3700 if (!isCharType(TemplateArgs[0].getAsType()))
3701 return false;
3702
3703 return SD->getIdentifier()->getName() == Name;
3704}
3705
3706template <std::size_t StrLen>
3707static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3708 const char (&Str)[StrLen]) {
3709 if (!SD->getIdentifier()->isStr(Str))
3710 return false;
3711
3712 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3713 if (TemplateArgs.size() != 2)
3714 return false;
3715
3716 if (!isCharType(TemplateArgs[0].getAsType()))
3717 return false;
3718
3719 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3720 return false;
3721
3722 return true;
3723}
3724
3725bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3726 // <substitution> ::= St # ::std::
3727 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3728 if (isStd(NS)) {
3729 Out << "St";
3730 return true;
3731 }
3732 }
3733
3734 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3735 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3736 return false;
3737
3738 // <substitution> ::= Sa # ::std::allocator
3739 if (TD->getIdentifier()->isStr("allocator")) {
3740 Out << "Sa";
3741 return true;
3742 }
3743
3744 // <<substitution> ::= Sb # ::std::basic_string
3745 if (TD->getIdentifier()->isStr("basic_string")) {
3746 Out << "Sb";
3747 return true;
3748 }
3749 }
3750
3751 if (const ClassTemplateSpecializationDecl *SD =
3752 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3753 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3754 return false;
3755
3756 // <substitution> ::= Ss # ::std::basic_string<char,
3757 // ::std::char_traits<char>,
3758 // ::std::allocator<char> >
3759 if (SD->getIdentifier()->isStr("basic_string")) {
3760 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3761
3762 if (TemplateArgs.size() != 3)
3763 return false;
3764
3765 if (!isCharType(TemplateArgs[0].getAsType()))
3766 return false;
3767
3768 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3769 return false;
3770
3771 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3772 return false;
3773
3774 Out << "Ss";
3775 return true;
3776 }
3777
3778 // <substitution> ::= Si # ::std::basic_istream<char,
3779 // ::std::char_traits<char> >
3780 if (isStreamCharSpecialization(SD, "basic_istream")) {
3781 Out << "Si";
3782 return true;
3783 }
3784
3785 // <substitution> ::= So # ::std::basic_ostream<char,
3786 // ::std::char_traits<char> >
3787 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3788 Out << "So";
3789 return true;
3790 }
3791
3792 // <substitution> ::= Sd # ::std::basic_iostream<char,
3793 // ::std::char_traits<char> >
3794 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3795 Out << "Sd";
3796 return true;
3797 }
3798 }
3799 return false;
3800}
3801
3802void CXXNameMangler::addSubstitution(QualType T) {
3803 if (!hasMangledSubstitutionQualifiers(T)) {
3804 if (const RecordType *RT = T->getAs<RecordType>()) {
3805 addSubstitution(RT->getDecl());
3806 return;
3807 }
3808 }
3809
3810 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3811 addSubstitution(TypePtr);
3812}
3813
3814void CXXNameMangler::addSubstitution(TemplateName Template) {
3815 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3816 return addSubstitution(TD);
3817
3818 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3819 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3820}
3821
3822void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3823 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3824 Substitutions[Ptr] = SeqID++;
3825}
3826
3827//
3828
3829/// \brief Mangles the name of the declaration D and emits that name to the
3830/// given output stream.
3831///
3832/// If the declaration D requires a mangled name, this routine will emit that
3833/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3834/// and this routine will return false. In this case, the caller should just
3835/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3836/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003837void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3838 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3840 "Invalid mangleName() call, argument is not a variable or function!");
3841 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3842 "Invalid mangleName() call on 'structor decl!");
3843
3844 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3845 getASTContext().getSourceManager(),
3846 "Mangling declaration");
3847
3848 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003849 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003850}
3851
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003852void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3853 CXXCtorType Type,
3854 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 CXXNameMangler Mangler(*this, Out, D, Type);
3856 Mangler.mangle(D);
3857}
3858
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003859void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3860 CXXDtorType Type,
3861 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003862 CXXNameMangler Mangler(*this, Out, D, Type);
3863 Mangler.mangle(D);
3864}
3865
Rafael Espindola1e4df922014-09-16 15:18:21 +00003866void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3867 raw_ostream &Out) {
3868 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3869 Mangler.mangle(D);
3870}
3871
3872void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3873 raw_ostream &Out) {
3874 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3875 Mangler.mangle(D);
3876}
3877
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003878void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3879 const ThunkInfo &Thunk,
3880 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 // <special-name> ::= T <call-offset> <base encoding>
3882 // # base is the nominal target function of thunk
3883 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3884 // # base is the nominal target function of thunk
3885 // # first call-offset is 'this' adjustment
3886 // # second call-offset is result adjustment
3887
3888 assert(!isa<CXXDestructorDecl>(MD) &&
3889 "Use mangleCXXDtor for destructor decls!");
3890 CXXNameMangler Mangler(*this, Out);
3891 Mangler.getStream() << "_ZT";
3892 if (!Thunk.Return.isEmpty())
3893 Mangler.getStream() << 'c';
3894
3895 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003896 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3897 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3898
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 // Mangle the return pointer adjustment if there is one.
3900 if (!Thunk.Return.isEmpty())
3901 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003902 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3903
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 Mangler.mangleFunctionEncoding(MD);
3905}
3906
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003907void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3908 const CXXDestructorDecl *DD, CXXDtorType Type,
3909 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 // <special-name> ::= T <call-offset> <base encoding>
3911 // # base is the nominal target function of thunk
3912 CXXNameMangler Mangler(*this, Out, DD, Type);
3913 Mangler.getStream() << "_ZT";
3914
3915 // Mangle the 'this' pointer adjustment.
3916 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003917 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003918
3919 Mangler.mangleFunctionEncoding(DD);
3920}
3921
3922/// mangleGuardVariable - Returns the mangled name for a guard variable
3923/// for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003924void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3925 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 // <special-name> ::= GV <object name> # Guard variable for one-time
3927 // # initialization
3928 CXXNameMangler Mangler(*this, Out);
3929 Mangler.getStream() << "_ZGV";
3930 Mangler.mangleName(D);
3931}
3932
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003933void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3934 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003935 // These symbols are internal in the Itanium ABI, so the names don't matter.
3936 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3937 // avoid duplicate symbols.
3938 Out << "__cxx_global_var_init";
3939}
3940
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003941void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3942 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003943 // Prefix the mangling of D with __dtor_.
3944 CXXNameMangler Mangler(*this, Out);
3945 Mangler.getStream() << "__dtor_";
3946 if (shouldMangleDeclName(D))
3947 Mangler.mangle(D);
3948 else
3949 Mangler.getStream() << D->getName();
3950}
3951
Reid Kleckner1d59f992015-01-22 01:36:17 +00003952void ItaniumMangleContextImpl::mangleSEHFilterExpression(
3953 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3954 CXXNameMangler Mangler(*this, Out);
3955 Mangler.getStream() << "__filt_";
3956 if (shouldMangleDeclName(EnclosingDecl))
3957 Mangler.mangle(EnclosingDecl);
3958 else
3959 Mangler.getStream() << EnclosingDecl->getName();
3960}
3961
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003962void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3963 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003964 // <special-name> ::= TH <object name>
3965 CXXNameMangler Mangler(*this, Out);
3966 Mangler.getStream() << "_ZTH";
3967 Mangler.mangleName(D);
3968}
3969
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003970void
3971ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3972 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003973 // <special-name> ::= TW <object name>
3974 CXXNameMangler Mangler(*this, Out);
3975 Mangler.getStream() << "_ZTW";
3976 Mangler.mangleName(D);
3977}
3978
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003979void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00003980 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003981 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 // We match the GCC mangling here.
3983 // <special-name> ::= GR <object name>
3984 CXXNameMangler Mangler(*this, Out);
3985 Mangler.getStream() << "_ZGR";
3986 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00003987 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00003988 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00003989}
3990
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003991void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
3992 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 // <special-name> ::= TV <type> # virtual table
3994 CXXNameMangler Mangler(*this, Out);
3995 Mangler.getStream() << "_ZTV";
3996 Mangler.mangleNameOrStandardSubstitution(RD);
3997}
3998
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003999void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4000 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 // <special-name> ::= TT <type> # VTT structure
4002 CXXNameMangler Mangler(*this, Out);
4003 Mangler.getStream() << "_ZTT";
4004 Mangler.mangleNameOrStandardSubstitution(RD);
4005}
4006
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004007void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4008 int64_t Offset,
4009 const CXXRecordDecl *Type,
4010 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 // <special-name> ::= TC <type> <offset number> _ <base type>
4012 CXXNameMangler Mangler(*this, Out);
4013 Mangler.getStream() << "_ZTC";
4014 Mangler.mangleNameOrStandardSubstitution(RD);
4015 Mangler.getStream() << Offset;
4016 Mangler.getStream() << '_';
4017 Mangler.mangleNameOrStandardSubstitution(Type);
4018}
4019
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004020void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 // <special-name> ::= TI <type> # typeinfo structure
4022 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4023 CXXNameMangler Mangler(*this, Out);
4024 Mangler.getStream() << "_ZTI";
4025 Mangler.mangleType(Ty);
4026}
4027
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004028void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4029 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4031 CXXNameMangler Mangler(*this, Out);
4032 Mangler.getStream() << "_ZTS";
4033 Mangler.mangleType(Ty);
4034}
4035
Reid Klecknercc99e262013-11-19 23:23:00 +00004036void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4037 mangleCXXRTTIName(Ty, Out);
4038}
4039
David Majnemer58e5bee2014-03-24 21:43:36 +00004040void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4041 llvm_unreachable("Can't mangle string literals");
4042}
4043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004044ItaniumMangleContext *
4045ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4046 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004047}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004048