blob: 16e1e1c775a8f812b5b7fb7828f737a9f9334b3d [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"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/ABI.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33
34#define MANGLE_CHECKER 0
35
36#if MANGLE_CHECKER
37#include <cxxabi.h>
38#endif
39
40using namespace clang;
41
42namespace {
43
44/// \brief Retrieve the declaration context that should be used when mangling
45/// the given declaration.
46static const DeclContext *getEffectiveDeclContext(const Decl *D) {
47 // The ABI assumes that lambda closure types that occur within
48 // default arguments live in the context of the function. However, due to
49 // the way in which Clang parses and creates function declarations, this is
50 // not the case: the lambda closure type ends up living in the context
51 // where the function itself resides, because the function declaration itself
52 // had not yet been created. Fix the context here.
53 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
54 if (RD->isLambda())
55 if (ParmVarDecl *ContextParam
56 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
57 return ContextParam->getDeclContext();
58 }
Eli Friedman0cd23352013-07-10 01:33:19 +000059
60 // Perform the same check for block literals.
61 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
62 if (ParmVarDecl *ContextParam
63 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
64 return ContextParam->getDeclContext();
65 }
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Eli Friedman95f50122013-07-02 17:52:28 +000067 const DeclContext *DC = D->getDeclContext();
68 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
69 return getEffectiveDeclContext(CD);
70
71 return DC;
Guy Benyei11169dd2012-12-18 14:30:41 +000072}
73
74static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
75 return getEffectiveDeclContext(cast<Decl>(DC));
76}
Eli Friedman95f50122013-07-02 17:52:28 +000077
78static bool isLocalContainerContext(const DeclContext *DC) {
79 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
80}
81
Eli Friedmaneecc09a2013-07-05 20:27:40 +000082static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000083 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000084 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000085 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000086 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000087 D = cast<Decl>(DC);
88 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000089 }
90 return 0;
91}
92
93static const FunctionDecl *getStructor(const FunctionDecl *fn) {
94 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
95 return ftd->getTemplatedDecl();
96
97 return fn;
98}
99
100static const NamedDecl *getStructor(const NamedDecl *decl) {
101 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
102 return (fn ? getStructor(fn) : decl);
103}
David Majnemer2206bf52014-03-05 08:57:59 +0000104
105static bool isLambda(const NamedDecl *ND) {
106 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
107 if (!Record)
108 return false;
109
110 return Record->isLambda();
111}
112
Guy Benyei11169dd2012-12-18 14:30:41 +0000113static const unsigned UnknownArity = ~0U;
114
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000115class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000116 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
117 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000118 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
119
120public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000121 explicit ItaniumMangleContextImpl(ASTContext &Context,
122 DiagnosticsEngine &Diags)
123 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000124
Guy Benyei11169dd2012-12-18 14:30:41 +0000125 /// @name Mangler Entry Points
126 /// @{
127
Craig Toppercbce6e92014-03-11 06:22:39 +0000128 bool shouldMangleCXXName(const NamedDecl *D) override;
129 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
130 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
131 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000132 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
133 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000134 raw_ostream &) override;
135 void mangleReferenceTemporary(const VarDecl *D, raw_ostream &) override;
136 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
137 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000138 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 const CXXRecordDecl *Type, raw_ostream &) override;
140 void mangleCXXRTTI(QualType T, raw_ostream &) override;
141 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
142 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000144 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000145 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000146 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000147
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
149 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
150 void mangleDynamicAtExitDestructor(const VarDecl *D,
151 raw_ostream &Out) override;
152 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
153 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
154 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000155
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000157 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000158 if (isLambda(ND))
159 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000160
161 // Anonymous tags are already numbered.
162 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
163 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
164 return false;
165 }
166
167 // Use the canonical number for externally visible decls.
168 if (ND->isExternallyVisible()) {
169 unsigned discriminator = getASTContext().getManglingNumber(ND);
170 if (discriminator == 1)
171 return false;
172 disc = discriminator - 2;
173 return true;
174 }
175
176 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000177 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000178 if (!discriminator) {
179 const DeclContext *DC = getEffectiveDeclContext(ND);
180 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
181 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000182 if (discriminator == 1)
183 return false;
184 disc = discriminator-2;
185 return true;
186 }
187 /// @}
188};
189
190/// CXXNameMangler - Manage the mangling of a single name.
191class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000192 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 raw_ostream &Out;
194
195 /// The "structor" is the top-level declaration being mangled, if
196 /// that's not a template specialization; otherwise it's the pattern
197 /// for that specialization.
198 const NamedDecl *Structor;
199 unsigned StructorType;
200
201 /// SeqID - The next subsitution sequence number.
202 unsigned SeqID;
203
204 class FunctionTypeDepthState {
205 unsigned Bits;
206
207 enum { InResultTypeMask = 1 };
208
209 public:
210 FunctionTypeDepthState() : Bits(0) {}
211
212 /// The number of function types we're inside.
213 unsigned getDepth() const {
214 return Bits >> 1;
215 }
216
217 /// True if we're in the return type of the innermost function type.
218 bool isInResultType() const {
219 return Bits & InResultTypeMask;
220 }
221
222 FunctionTypeDepthState push() {
223 FunctionTypeDepthState tmp = *this;
224 Bits = (Bits & ~InResultTypeMask) + 2;
225 return tmp;
226 }
227
228 void enterResultType() {
229 Bits |= InResultTypeMask;
230 }
231
232 void leaveResultType() {
233 Bits &= ~InResultTypeMask;
234 }
235
236 void pop(FunctionTypeDepthState saved) {
237 assert(getDepth() == saved.getDepth() + 1);
238 Bits = saved.Bits;
239 }
240
241 } FunctionTypeDepth;
242
243 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
244
245 ASTContext &getASTContext() const { return Context.getASTContext(); }
246
247public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000248 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 const NamedDecl *D = 0)
250 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
251 SeqID(0) {
252 // These can't be mangled without a ctor type or dtor type.
253 assert(!D || (!isa<CXXDestructorDecl>(D) &&
254 !isa<CXXConstructorDecl>(D)));
255 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000256 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000257 const CXXConstructorDecl *D, CXXCtorType Type)
258 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
259 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000260 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000261 const CXXDestructorDecl *D, CXXDtorType Type)
262 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
263 SeqID(0) { }
264
265#if MANGLE_CHECKER
266 ~CXXNameMangler() {
267 if (Out.str()[0] == '\01')
268 return;
269
270 int status = 0;
271 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
272 assert(status == 0 && "Could not demangle mangled name!");
273 free(result);
274 }
275#endif
276 raw_ostream &getStream() { return Out; }
277
278 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
279 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
280 void mangleNumber(const llvm::APSInt &I);
281 void mangleNumber(int64_t Number);
282 void mangleFloat(const llvm::APFloat &F);
283 void mangleFunctionEncoding(const FunctionDecl *FD);
284 void mangleName(const NamedDecl *ND);
285 void mangleType(QualType T);
286 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
287
288private:
289 bool mangleSubstitution(const NamedDecl *ND);
290 bool mangleSubstitution(QualType T);
291 bool mangleSubstitution(TemplateName Template);
292 bool mangleSubstitution(uintptr_t Ptr);
293
294 void mangleExistingSubstitution(QualType type);
295 void mangleExistingSubstitution(TemplateName name);
296
297 bool mangleStandardSubstitution(const NamedDecl *ND);
298
299 void addSubstitution(const NamedDecl *ND) {
300 ND = cast<NamedDecl>(ND->getCanonicalDecl());
301
302 addSubstitution(reinterpret_cast<uintptr_t>(ND));
303 }
304 void addSubstitution(QualType T);
305 void addSubstitution(TemplateName Template);
306 void addSubstitution(uintptr_t Ptr);
307
308 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
309 NamedDecl *firstQualifierLookup,
310 bool recursive = false);
311 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
312 NamedDecl *firstQualifierLookup,
313 DeclarationName name,
314 unsigned KnownArity = UnknownArity);
315
316 void mangleName(const TemplateDecl *TD,
317 const TemplateArgument *TemplateArgs,
318 unsigned NumTemplateArgs);
319 void mangleUnqualifiedName(const NamedDecl *ND) {
320 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
321 }
322 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
323 unsigned KnownArity);
324 void mangleUnscopedName(const NamedDecl *ND);
325 void mangleUnscopedTemplateName(const TemplateDecl *ND);
326 void mangleUnscopedTemplateName(TemplateName);
327 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000328 void mangleLocalName(const Decl *D);
329 void mangleBlockForPrefix(const BlockDecl *Block);
330 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000331 void mangleLambda(const CXXRecordDecl *Lambda);
332 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
333 bool NoFunction=false);
334 void mangleNestedName(const TemplateDecl *TD,
335 const TemplateArgument *TemplateArgs,
336 unsigned NumTemplateArgs);
337 void manglePrefix(NestedNameSpecifier *qualifier);
338 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
339 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000340 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000341 void mangleTemplatePrefix(TemplateName Template);
342 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
343 void mangleQualifiers(Qualifiers Quals);
344 void mangleRefQualifier(RefQualifierKind RefQualifier);
345
346 void mangleObjCMethodName(const ObjCMethodDecl *MD);
347
348 // Declare manglers for every type class.
349#define ABSTRACT_TYPE(CLASS, PARENT)
350#define NON_CANONICAL_TYPE(CLASS, PARENT)
351#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
352#include "clang/AST/TypeNodes.def"
353
354 void mangleType(const TagType*);
355 void mangleType(TemplateName);
356 void mangleBareFunctionType(const FunctionType *T,
357 bool MangleReturnType);
358 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000359 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000360
361 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
362 void mangleMemberExpr(const Expr *base, bool isArrow,
363 NestedNameSpecifier *qualifier,
364 NamedDecl *firstQualifierLookup,
365 DeclarationName name,
366 unsigned knownArity);
367 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
368 void mangleCXXCtorType(CXXCtorType T);
369 void mangleCXXDtorType(CXXDtorType T);
370
371 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
372 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
373 unsigned NumTemplateArgs);
374 void mangleTemplateArgs(const TemplateArgumentList &AL);
375 void mangleTemplateArg(TemplateArgument A);
376
377 void mangleTemplateParameter(unsigned Index);
378
379 void mangleFunctionParam(const ParmVarDecl *parm);
380};
381
382}
383
Rafael Espindola002667c2013-10-16 01:40:34 +0000384bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000386 if (FD) {
387 LanguageLinkage L = FD->getLanguageLinkage();
388 // Overloadable functions need mangling.
389 if (FD->hasAttr<OverloadableAttr>())
390 return true;
391
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000392 // "main" is not mangled.
393 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000394 return false;
395
396 // C++ functions and those whose names are not a simple identifier need
397 // mangling.
398 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
399 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000400
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000401 // C functions are not mangled.
402 if (L == CLanguageLinkage)
403 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000404 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000405
406 // Otherwise, no mangling is done outside C++ mode.
407 if (!getASTContext().getLangOpts().CPlusPlus)
408 return false;
409
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000410 const VarDecl *VD = dyn_cast<VarDecl>(D);
411 if (VD) {
412 // C variables are not mangled.
413 if (VD->isExternC())
414 return false;
415
416 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 const DeclContext *DC = getEffectiveDeclContext(D);
418 // Check for extern variable declared locally.
419 if (DC->isFunctionOrMethod() && D->hasLinkage())
420 while (!DC->isNamespace() && !DC->isTranslationUnit())
421 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000422 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
423 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 return false;
425 }
426
Guy Benyei11169dd2012-12-18 14:30:41 +0000427 return true;
428}
429
430void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000431 // <mangled-name> ::= _Z <encoding>
432 // ::= <data name>
433 // ::= <special-name>
434 Out << Prefix;
435 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
436 mangleFunctionEncoding(FD);
437 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
438 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000439 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
440 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 else
442 mangleName(cast<FieldDecl>(D));
443}
444
445void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
446 // <encoding> ::= <function name> <bare-function-type>
447 mangleName(FD);
448
449 // Don't mangle in the type if this isn't a decl we should typically mangle.
450 if (!Context.shouldMangleDeclName(FD))
451 return;
452
453 // Whether the mangling of a function type includes the return type depends on
454 // the context and the nature of the function. The rules for deciding whether
455 // the return type is included are:
456 //
457 // 1. Template functions (names or types) have return types encoded, with
458 // the exceptions listed below.
459 // 2. Function types not appearing as part of a function name mangling,
460 // e.g. parameters, pointer types, etc., have return type encoded, with the
461 // exceptions listed below.
462 // 3. Non-template function names do not have return types encoded.
463 //
464 // The exceptions mentioned in (1) and (2) above, for which the return type is
465 // never included, are
466 // 1. Constructors.
467 // 2. Destructors.
468 // 3. Conversion operator functions, e.g. operator int.
469 bool MangleReturnType = false;
470 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
471 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
472 isa<CXXConversionDecl>(FD)))
473 MangleReturnType = true;
474
475 // Mangle the type of the primary template.
476 FD = PrimaryTemplate->getTemplatedDecl();
477 }
478
479 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
480 MangleReturnType);
481}
482
483static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
484 while (isa<LinkageSpecDecl>(DC)) {
485 DC = getEffectiveParentContext(DC);
486 }
487
488 return DC;
489}
490
491/// isStd - Return whether a given namespace is the 'std' namespace.
492static bool isStd(const NamespaceDecl *NS) {
493 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
494 ->isTranslationUnit())
495 return false;
496
497 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
498 return II && II->isStr("std");
499}
500
501// isStdNamespace - Return whether a given decl context is a toplevel 'std'
502// namespace.
503static bool isStdNamespace(const DeclContext *DC) {
504 if (!DC->isNamespace())
505 return false;
506
507 return isStd(cast<NamespaceDecl>(DC));
508}
509
510static const TemplateDecl *
511isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
512 // Check if we have a function template.
513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
514 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
515 TemplateArgs = FD->getTemplateSpecializationArgs();
516 return TD;
517 }
518 }
519
520 // Check if we have a class template.
521 if (const ClassTemplateSpecializationDecl *Spec =
522 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
523 TemplateArgs = &Spec->getTemplateArgs();
524 return Spec->getSpecializedTemplate();
525 }
526
Larisse Voufo39a1e502013-08-06 01:03:05 +0000527 // Check if we have a variable template.
528 if (const VarTemplateSpecializationDecl *Spec =
529 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
530 TemplateArgs = &Spec->getTemplateArgs();
531 return Spec->getSpecializedTemplate();
532 }
533
Guy Benyei11169dd2012-12-18 14:30:41 +0000534 return 0;
535}
536
Guy Benyei11169dd2012-12-18 14:30:41 +0000537void CXXNameMangler::mangleName(const NamedDecl *ND) {
538 // <name> ::= <nested-name>
539 // ::= <unscoped-name>
540 // ::= <unscoped-template-name> <template-args>
541 // ::= <local-name>
542 //
543 const DeclContext *DC = getEffectiveDeclContext(ND);
544
545 // If this is an extern variable declared locally, the relevant DeclContext
546 // is that of the containing namespace, or the translation unit.
547 // FIXME: This is a hack; extern variables declared locally should have
548 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000549 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000550 while (!DC->isNamespace() && !DC->isTranslationUnit())
551 DC = getEffectiveParentContext(DC);
552 else if (GetLocalClassDecl(ND)) {
553 mangleLocalName(ND);
554 return;
555 }
556
557 DC = IgnoreLinkageSpecDecls(DC);
558
559 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
560 // Check if we have a template.
561 const TemplateArgumentList *TemplateArgs = 0;
562 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
563 mangleUnscopedTemplateName(TD);
564 mangleTemplateArgs(*TemplateArgs);
565 return;
566 }
567
568 mangleUnscopedName(ND);
569 return;
570 }
571
Eli Friedman95f50122013-07-02 17:52:28 +0000572 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000573 mangleLocalName(ND);
574 return;
575 }
576
577 mangleNestedName(ND, DC);
578}
579void CXXNameMangler::mangleName(const TemplateDecl *TD,
580 const TemplateArgument *TemplateArgs,
581 unsigned NumTemplateArgs) {
582 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
583
584 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
585 mangleUnscopedTemplateName(TD);
586 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
587 } else {
588 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
589 }
590}
591
592void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
593 // <unscoped-name> ::= <unqualified-name>
594 // ::= St <unqualified-name> # ::std::
595
596 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
597 Out << "St";
598
599 mangleUnqualifiedName(ND);
600}
601
602void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
603 // <unscoped-template-name> ::= <unscoped-name>
604 // ::= <substitution>
605 if (mangleSubstitution(ND))
606 return;
607
608 // <template-template-param> ::= <template-param>
609 if (const TemplateTemplateParmDecl *TTP
610 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
611 mangleTemplateParameter(TTP->getIndex());
612 return;
613 }
614
615 mangleUnscopedName(ND->getTemplatedDecl());
616 addSubstitution(ND);
617}
618
619void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
620 // <unscoped-template-name> ::= <unscoped-name>
621 // ::= <substitution>
622 if (TemplateDecl *TD = Template.getAsTemplateDecl())
623 return mangleUnscopedTemplateName(TD);
624
625 if (mangleSubstitution(Template))
626 return;
627
628 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
629 assert(Dependent && "Not a dependent template name?");
630 if (const IdentifierInfo *Id = Dependent->getIdentifier())
631 mangleSourceName(Id);
632 else
633 mangleOperatorName(Dependent->getOperator(), UnknownArity);
634
635 addSubstitution(Template);
636}
637
638void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
639 // ABI:
640 // Floating-point literals are encoded using a fixed-length
641 // lowercase hexadecimal string corresponding to the internal
642 // representation (IEEE on Itanium), high-order bytes first,
643 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
644 // on Itanium.
645 // The 'without leading zeroes' thing seems to be an editorial
646 // mistake; see the discussion on cxx-abi-dev beginning on
647 // 2012-01-16.
648
649 // Our requirements here are just barely weird enough to justify
650 // using a custom algorithm instead of post-processing APInt::toString().
651
652 llvm::APInt valueBits = f.bitcastToAPInt();
653 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
654 assert(numCharacters != 0);
655
656 // Allocate a buffer of the right number of characters.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000657 SmallVector<char, 20> buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 buffer.set_size(numCharacters);
659
660 // Fill the buffer left-to-right.
661 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
662 // The bit-index of the next hex digit.
663 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
664
665 // Project out 4 bits starting at 'digitIndex'.
666 llvm::integerPart hexDigit
667 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
668 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
669 hexDigit &= 0xF;
670
671 // Map that over to a lowercase hex digit.
672 static const char charForHex[16] = {
673 '0', '1', '2', '3', '4', '5', '6', '7',
674 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
675 };
676 buffer[stringIndex] = charForHex[hexDigit];
677 }
678
679 Out.write(buffer.data(), numCharacters);
680}
681
682void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
683 if (Value.isSigned() && Value.isNegative()) {
684 Out << 'n';
685 Value.abs().print(Out, /*signed*/ false);
686 } else {
687 Value.print(Out, /*signed*/ false);
688 }
689}
690
691void CXXNameMangler::mangleNumber(int64_t Number) {
692 // <number> ::= [n] <non-negative decimal integer>
693 if (Number < 0) {
694 Out << 'n';
695 Number = -Number;
696 }
697
698 Out << Number;
699}
700
701void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
702 // <call-offset> ::= h <nv-offset> _
703 // ::= v <v-offset> _
704 // <nv-offset> ::= <offset number> # non-virtual base override
705 // <v-offset> ::= <offset number> _ <virtual offset number>
706 // # virtual base override, with vcall offset
707 if (!Virtual) {
708 Out << 'h';
709 mangleNumber(NonVirtual);
710 Out << '_';
711 return;
712 }
713
714 Out << 'v';
715 mangleNumber(NonVirtual);
716 Out << '_';
717 mangleNumber(Virtual);
718 Out << '_';
719}
720
721void CXXNameMangler::manglePrefix(QualType type) {
722 if (const TemplateSpecializationType *TST =
723 type->getAs<TemplateSpecializationType>()) {
724 if (!mangleSubstitution(QualType(TST, 0))) {
725 mangleTemplatePrefix(TST->getTemplateName());
726
727 // FIXME: GCC does not appear to mangle the template arguments when
728 // the template in question is a dependent template name. Should we
729 // emulate that badness?
730 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
731 addSubstitution(QualType(TST, 0));
732 }
733 } else if (const DependentTemplateSpecializationType *DTST
734 = type->getAs<DependentTemplateSpecializationType>()) {
735 TemplateName Template
736 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
737 DTST->getIdentifier());
738 mangleTemplatePrefix(Template);
739
740 // FIXME: GCC does not appear to mangle the template arguments when
741 // the template in question is a dependent template name. Should we
742 // emulate that badness?
743 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
744 } else {
745 // We use the QualType mangle type variant here because it handles
746 // substitutions.
747 mangleType(type);
748 }
749}
750
751/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
752///
753/// \param firstQualifierLookup - the entity found by unqualified lookup
754/// for the first name in the qualifier, if this is for a member expression
755/// \param recursive - true if this is being called recursively,
756/// i.e. if there is more prefix "to the right".
757void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
758 NamedDecl *firstQualifierLookup,
759 bool recursive) {
760
761 // x, ::x
762 // <unresolved-name> ::= [gs] <base-unresolved-name>
763
764 // T::x / decltype(p)::x
765 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
766
767 // T::N::x /decltype(p)::N::x
768 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
769 // <base-unresolved-name>
770
771 // A::x, N::y, A<T>::z; "gs" means leading "::"
772 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
773 // <base-unresolved-name>
774
775 switch (qualifier->getKind()) {
776 case NestedNameSpecifier::Global:
777 Out << "gs";
778
779 // We want an 'sr' unless this is the entire NNS.
780 if (recursive)
781 Out << "sr";
782
783 // We never want an 'E' here.
784 return;
785
786 case NestedNameSpecifier::Namespace:
787 if (qualifier->getPrefix())
788 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
789 /*recursive*/ true);
790 else
791 Out << "sr";
792 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
793 break;
794 case NestedNameSpecifier::NamespaceAlias:
795 if (qualifier->getPrefix())
796 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
797 /*recursive*/ true);
798 else
799 Out << "sr";
800 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
801 break;
802
803 case NestedNameSpecifier::TypeSpec:
804 case NestedNameSpecifier::TypeSpecWithTemplate: {
805 const Type *type = qualifier->getAsType();
806
807 // We only want to use an unresolved-type encoding if this is one of:
808 // - a decltype
809 // - a template type parameter
810 // - a template template parameter with arguments
811 // In all of these cases, we should have no prefix.
812 if (qualifier->getPrefix()) {
813 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
814 /*recursive*/ true);
815 } else {
816 // Otherwise, all the cases want this.
817 Out << "sr";
818 }
819
820 // Only certain other types are valid as prefixes; enumerate them.
821 switch (type->getTypeClass()) {
822 case Type::Builtin:
823 case Type::Complex:
Reid Kleckner0503a872013-12-05 01:23:43 +0000824 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +0000825 case Type::Decayed:
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 case Type::Pointer:
827 case Type::BlockPointer:
828 case Type::LValueReference:
829 case Type::RValueReference:
830 case Type::MemberPointer:
831 case Type::ConstantArray:
832 case Type::IncompleteArray:
833 case Type::VariableArray:
834 case Type::DependentSizedArray:
835 case Type::DependentSizedExtVector:
836 case Type::Vector:
837 case Type::ExtVector:
838 case Type::FunctionProto:
839 case Type::FunctionNoProto:
840 case Type::Enum:
841 case Type::Paren:
842 case Type::Elaborated:
843 case Type::Attributed:
844 case Type::Auto:
845 case Type::PackExpansion:
846 case Type::ObjCObject:
847 case Type::ObjCInterface:
848 case Type::ObjCObjectPointer:
849 case Type::Atomic:
850 llvm_unreachable("type is illegal as a nested name specifier");
851
852 case Type::SubstTemplateTypeParmPack:
853 // FIXME: not clear how to mangle this!
854 // template <class T...> class A {
855 // template <class U...> void foo(decltype(T::foo(U())) x...);
856 // };
857 Out << "_SUBSTPACK_";
858 break;
859
860 // <unresolved-type> ::= <template-param>
861 // ::= <decltype>
862 // ::= <template-template-param> <template-args>
863 // (this last is not official yet)
864 case Type::TypeOfExpr:
865 case Type::TypeOf:
866 case Type::Decltype:
867 case Type::TemplateTypeParm:
868 case Type::UnaryTransform:
869 case Type::SubstTemplateTypeParm:
870 unresolvedType:
871 assert(!qualifier->getPrefix());
872
873 // We only get here recursively if we're followed by identifiers.
874 if (recursive) Out << 'N';
875
876 // This seems to do everything we want. It's not really
877 // sanctioned for a substituted template parameter, though.
878 mangleType(QualType(type, 0));
879
880 // We never want to print 'E' directly after an unresolved-type,
881 // so we return directly.
882 return;
883
884 case Type::Typedef:
885 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
886 break;
887
888 case Type::UnresolvedUsing:
889 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
890 ->getIdentifier());
891 break;
892
893 case Type::Record:
894 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
895 break;
896
897 case Type::TemplateSpecialization: {
898 const TemplateSpecializationType *tst
899 = cast<TemplateSpecializationType>(type);
900 TemplateName name = tst->getTemplateName();
901 switch (name.getKind()) {
902 case TemplateName::Template:
903 case TemplateName::QualifiedTemplate: {
904 TemplateDecl *temp = name.getAsTemplateDecl();
905
906 // If the base is a template template parameter, this is an
907 // unresolved type.
908 assert(temp && "no template for template specialization type");
909 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
910
911 mangleSourceName(temp->getIdentifier());
912 break;
913 }
914
915 case TemplateName::OverloadedTemplate:
916 case TemplateName::DependentTemplate:
917 llvm_unreachable("invalid base for a template specialization type");
918
919 case TemplateName::SubstTemplateTemplateParm: {
920 SubstTemplateTemplateParmStorage *subst
921 = name.getAsSubstTemplateTemplateParm();
922 mangleExistingSubstitution(subst->getReplacement());
923 break;
924 }
925
926 case TemplateName::SubstTemplateTemplateParmPack: {
927 // FIXME: not clear how to mangle this!
928 // template <template <class U> class T...> class A {
929 // template <class U...> void foo(decltype(T<U>::foo) x...);
930 // };
931 Out << "_SUBSTPACK_";
932 break;
933 }
934 }
935
936 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
937 break;
938 }
939
940 case Type::InjectedClassName:
941 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
942 ->getIdentifier());
943 break;
944
945 case Type::DependentName:
946 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
947 break;
948
949 case Type::DependentTemplateSpecialization: {
950 const DependentTemplateSpecializationType *tst
951 = cast<DependentTemplateSpecializationType>(type);
952 mangleSourceName(tst->getIdentifier());
953 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
954 break;
955 }
956 }
957 break;
958 }
959
960 case NestedNameSpecifier::Identifier:
961 // Member expressions can have these without prefixes.
962 if (qualifier->getPrefix()) {
963 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
964 /*recursive*/ true);
965 } else if (firstQualifierLookup) {
966
967 // Try to make a proper qualifier out of the lookup result, and
968 // then just recurse on that.
969 NestedNameSpecifier *newQualifier;
970 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
971 QualType type = getASTContext().getTypeDeclType(typeDecl);
972
973 // Pretend we had a different nested name specifier.
974 newQualifier = NestedNameSpecifier::Create(getASTContext(),
975 /*prefix*/ 0,
976 /*template*/ false,
977 type.getTypePtr());
978 } else if (NamespaceDecl *nspace =
979 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
980 newQualifier = NestedNameSpecifier::Create(getASTContext(),
981 /*prefix*/ 0,
982 nspace);
983 } else if (NamespaceAliasDecl *alias =
984 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
985 newQualifier = NestedNameSpecifier::Create(getASTContext(),
986 /*prefix*/ 0,
987 alias);
988 } else {
989 // No sensible mangling to do here.
990 newQualifier = 0;
991 }
992
993 if (newQualifier)
994 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
995
996 } else {
997 Out << "sr";
998 }
999
1000 mangleSourceName(qualifier->getAsIdentifier());
1001 break;
1002 }
1003
1004 // If this was the innermost part of the NNS, and we fell out to
1005 // here, append an 'E'.
1006 if (!recursive)
1007 Out << 'E';
1008}
1009
1010/// Mangle an unresolved-name, which is generally used for names which
1011/// weren't resolved to specific entities.
1012void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1013 NamedDecl *firstQualifierLookup,
1014 DeclarationName name,
1015 unsigned knownArity) {
1016 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1017 mangleUnqualifiedName(0, name, knownArity);
1018}
1019
1020static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1021 assert(RD->isAnonymousStructOrUnion() &&
1022 "Expected anonymous struct or union!");
1023
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001024 for (const auto *I : RD->fields()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 if (I->getIdentifier())
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001026 return I;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027
1028 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1029 if (const FieldDecl *NamedDataMember =
1030 FindFirstNamedDataMember(RT->getDecl()))
1031 return NamedDataMember;
1032 }
1033
1034 // We didn't find a named data member.
1035 return 0;
1036}
1037
1038void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1039 DeclarationName Name,
1040 unsigned KnownArity) {
1041 // <unqualified-name> ::= <operator-name>
1042 // ::= <ctor-dtor-name>
1043 // ::= <source-name>
1044 switch (Name.getNameKind()) {
1045 case DeclarationName::Identifier: {
1046 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1047 // We must avoid conflicts between internally- and externally-
1048 // linked variable and function declaration names in the same TU:
1049 // void test() { extern void foo(); }
1050 // static void foo();
1051 // This naming convention is the same as that followed by GCC,
1052 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001053 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001054 getEffectiveDeclContext(ND)->isFileContext())
1055 Out << 'L';
1056
1057 mangleSourceName(II);
1058 break;
1059 }
1060
1061 // Otherwise, an anonymous entity. We must have a declaration.
1062 assert(ND && "mangling empty name without declaration");
1063
1064 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1065 if (NS->isAnonymousNamespace()) {
1066 // This is how gcc mangles these names.
1067 Out << "12_GLOBAL__N_1";
1068 break;
1069 }
1070 }
1071
1072 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1073 // We must have an anonymous union or struct declaration.
1074 const RecordDecl *RD =
1075 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1076
1077 // Itanium C++ ABI 5.1.2:
1078 //
1079 // For the purposes of mangling, the name of an anonymous union is
1080 // considered to be the name of the first named data member found by a
1081 // pre-order, depth-first, declaration-order walk of the data members of
1082 // the anonymous union. If there is no such data member (i.e., if all of
1083 // the data members in the union are unnamed), then there is no way for
1084 // a program to refer to the anonymous union, and there is therefore no
1085 // need to mangle its name.
1086 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1087
1088 // It's actually possible for various reasons for us to get here
1089 // with an empty anonymous struct / union. Fortunately, it
1090 // doesn't really matter what name we generate.
1091 if (!FD) break;
1092 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1093
1094 mangleSourceName(FD->getIdentifier());
1095 break;
1096 }
John McCall924046f2013-04-10 06:08:21 +00001097
1098 // Class extensions have no name as a category, and it's possible
1099 // for them to be the semantic parent of certain declarations
1100 // (primarily, tag decls defined within declarations). Such
1101 // declarations will always have internal linkage, so the name
1102 // doesn't really matter, but we shouldn't crash on them. For
1103 // safety, just handle all ObjC containers here.
1104 if (isa<ObjCContainerDecl>(ND))
1105 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001106
1107 // We must have an anonymous struct.
1108 const TagDecl *TD = cast<TagDecl>(ND);
1109 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1110 assert(TD->getDeclContext() == D->getDeclContext() &&
1111 "Typedef should not be in another decl context!");
1112 assert(D->getDeclName().getAsIdentifierInfo() &&
1113 "Typedef was not named!");
1114 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1115 break;
1116 }
1117
1118 // <unnamed-type-name> ::= <closure-type-name>
1119 //
1120 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1121 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1122 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1123 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1124 mangleLambda(Record);
1125 break;
1126 }
1127 }
1128
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001129 if (TD->isExternallyVisible()) {
1130 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001132 if (UnnamedMangle > 1)
1133 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001134 Out << '_';
1135 break;
1136 }
1137
1138 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001139 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001140
1141 // Mangle it as a source name in the form
1142 // [n] $_<id>
1143 // where n is the length of the string.
1144 SmallString<8> Str;
1145 Str += "$_";
1146 Str += llvm::utostr(AnonStructId);
1147
1148 Out << Str.size();
1149 Out << Str.str();
1150 break;
1151 }
1152
1153 case DeclarationName::ObjCZeroArgSelector:
1154 case DeclarationName::ObjCOneArgSelector:
1155 case DeclarationName::ObjCMultiArgSelector:
1156 llvm_unreachable("Can't mangle Objective-C selector names here!");
1157
1158 case DeclarationName::CXXConstructorName:
1159 if (ND == Structor)
1160 // If the named decl is the C++ constructor we're mangling, use the type
1161 // we were given.
1162 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1163 else
1164 // Otherwise, use the complete constructor name. This is relevant if a
1165 // class with a constructor is declared within a constructor.
1166 mangleCXXCtorType(Ctor_Complete);
1167 break;
1168
1169 case DeclarationName::CXXDestructorName:
1170 if (ND == Structor)
1171 // If the named decl is the C++ destructor we're mangling, use the type we
1172 // were given.
1173 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1174 else
1175 // Otherwise, use the complete destructor name. This is relevant if a
1176 // class with a destructor is declared within a destructor.
1177 mangleCXXDtorType(Dtor_Complete);
1178 break;
1179
1180 case DeclarationName::CXXConversionFunctionName:
1181 // <operator-name> ::= cv <type> # (cast)
1182 Out << "cv";
1183 mangleType(Name.getCXXNameType());
1184 break;
1185
1186 case DeclarationName::CXXOperatorName: {
1187 unsigned Arity;
1188 if (ND) {
1189 Arity = cast<FunctionDecl>(ND)->getNumParams();
1190
1191 // If we have a C++ member function, we need to include the 'this' pointer.
1192 // FIXME: This does not make sense for operators that are static, but their
1193 // names stay the same regardless of the arity (operator new for instance).
1194 if (isa<CXXMethodDecl>(ND))
1195 Arity++;
1196 } else
1197 Arity = KnownArity;
1198
1199 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1200 break;
1201 }
1202
1203 case DeclarationName::CXXLiteralOperatorName:
1204 // FIXME: This mangling is not yet official.
1205 Out << "li";
1206 mangleSourceName(Name.getCXXLiteralIdentifier());
1207 break;
1208
1209 case DeclarationName::CXXUsingDirective:
1210 llvm_unreachable("Can't mangle a using directive name!");
1211 }
1212}
1213
1214void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1215 // <source-name> ::= <positive length number> <identifier>
1216 // <number> ::= [n] <non-negative decimal integer>
1217 // <identifier> ::= <unqualified source code identifier>
1218 Out << II->getLength() << II->getName();
1219}
1220
1221void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1222 const DeclContext *DC,
1223 bool NoFunction) {
1224 // <nested-name>
1225 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1226 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1227 // <template-args> E
1228
1229 Out << 'N';
1230 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001231 Qualifiers MethodQuals =
1232 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1233 // We do not consider restrict a distinguishing attribute for overloading
1234 // purposes so we must not mangle it.
1235 MethodQuals.removeRestrict();
1236 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 mangleRefQualifier(Method->getRefQualifier());
1238 }
1239
1240 // Check if we have a template.
1241 const TemplateArgumentList *TemplateArgs = 0;
1242 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001243 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 mangleTemplateArgs(*TemplateArgs);
1245 }
1246 else {
1247 manglePrefix(DC, NoFunction);
1248 mangleUnqualifiedName(ND);
1249 }
1250
1251 Out << 'E';
1252}
1253void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1254 const TemplateArgument *TemplateArgs,
1255 unsigned NumTemplateArgs) {
1256 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1257
1258 Out << 'N';
1259
1260 mangleTemplatePrefix(TD);
1261 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1262
1263 Out << 'E';
1264}
1265
Eli Friedman95f50122013-07-02 17:52:28 +00001266void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1268 // := Z <function encoding> E s [<discriminator>]
1269 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1270 // _ <entity name>
1271 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001272 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001273 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001274 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001275
1276 Out << 'Z';
1277
Eli Friedman92821742013-07-02 02:01:18 +00001278 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1279 mangleObjCMethodName(MD);
1280 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001281 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001282 else
1283 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001284
Eli Friedman92821742013-07-02 02:01:18 +00001285 Out << 'E';
1286
1287 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 // The parameter number is omitted for the last parameter, 0 for the
1289 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1290 // <entity name> will of course contain a <closure-type-name>: Its
1291 // numbering will be local to the particular argument in which it appears
1292 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001293 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1294 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001296 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 if (const FunctionDecl *Func
1298 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1299 Out << 'd';
1300 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1301 if (Num > 1)
1302 mangleNumber(Num - 2);
1303 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 }
1305 }
1306 }
1307
1308 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001309 // equality ok because RD derived from ND above
1310 if (D == RD) {
1311 mangleUnqualifiedName(RD);
1312 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1313 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1314 mangleUnqualifiedBlock(BD);
1315 } else {
1316 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001317 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001318 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001319 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1320 // Mangle a block in a default parameter; see above explanation for
1321 // lambdas.
1322 if (const ParmVarDecl *Parm
1323 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1324 if (const FunctionDecl *Func
1325 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1326 Out << 'd';
1327 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1328 if (Num > 1)
1329 mangleNumber(Num - 2);
1330 Out << '_';
1331 }
1332 }
1333
1334 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001335 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001336 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001338
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001339 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1340 unsigned disc;
1341 if (Context.getNextDiscriminator(ND, disc)) {
1342 if (disc < 10)
1343 Out << '_' << disc;
1344 else
1345 Out << "__" << disc << '_';
1346 }
1347 }
Eli Friedman95f50122013-07-02 17:52:28 +00001348}
1349
1350void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1351 if (GetLocalClassDecl(Block)) {
1352 mangleLocalName(Block);
1353 return;
1354 }
1355 const DeclContext *DC = getEffectiveDeclContext(Block);
1356 if (isLocalContainerContext(DC)) {
1357 mangleLocalName(Block);
1358 return;
1359 }
1360 manglePrefix(getEffectiveDeclContext(Block));
1361 mangleUnqualifiedBlock(Block);
1362}
1363
1364void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1365 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1366 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1367 Context->getDeclContext()->isRecord()) {
1368 if (const IdentifierInfo *Name
1369 = cast<NamedDecl>(Context)->getIdentifier()) {
1370 mangleSourceName(Name);
1371 Out << 'M';
1372 }
1373 }
1374 }
1375
1376 // If we have a block mangling number, use it.
1377 unsigned Number = Block->getBlockManglingNumber();
1378 // Otherwise, just make up a number. It doesn't matter what it is because
1379 // the symbol in question isn't externally visible.
1380 if (!Number)
1381 Number = Context.getBlockId(Block, false);
1382 Out << "Ub";
1383 if (Number > 1)
1384 Out << Number - 2;
1385 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001386}
1387
1388void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1389 // If the context of a closure type is an initializer for a class member
1390 // (static or nonstatic), it is encoded in a qualified name with a final
1391 // <prefix> of the form:
1392 //
1393 // <data-member-prefix> := <member source-name> M
1394 //
1395 // Technically, the data-member-prefix is part of the <prefix>. However,
1396 // since a closure type will always be mangled with a prefix, it's easier
1397 // to emit that last part of the prefix here.
1398 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1399 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1400 Context->getDeclContext()->isRecord()) {
1401 if (const IdentifierInfo *Name
1402 = cast<NamedDecl>(Context)->getIdentifier()) {
1403 mangleSourceName(Name);
1404 Out << 'M';
1405 }
1406 }
1407 }
1408
1409 Out << "Ul";
1410 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1411 getAs<FunctionProtoType>();
1412 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1413 Out << "E";
1414
1415 // The number is omitted for the first closure type with a given
1416 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1417 // (in lexical order) with that same <lambda-sig> and context.
1418 //
1419 // The AST keeps track of the number for us.
1420 unsigned Number = Lambda->getLambdaManglingNumber();
1421 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1422 if (Number > 1)
1423 mangleNumber(Number - 2);
1424 Out << '_';
1425}
1426
1427void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1428 switch (qualifier->getKind()) {
1429 case NestedNameSpecifier::Global:
1430 // nothing
1431 return;
1432
1433 case NestedNameSpecifier::Namespace:
1434 mangleName(qualifier->getAsNamespace());
1435 return;
1436
1437 case NestedNameSpecifier::NamespaceAlias:
1438 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1439 return;
1440
1441 case NestedNameSpecifier::TypeSpec:
1442 case NestedNameSpecifier::TypeSpecWithTemplate:
1443 manglePrefix(QualType(qualifier->getAsType(), 0));
1444 return;
1445
1446 case NestedNameSpecifier::Identifier:
1447 // Member expressions can have these without prefixes, but that
1448 // should end up in mangleUnresolvedPrefix instead.
1449 assert(qualifier->getPrefix());
1450 manglePrefix(qualifier->getPrefix());
1451
1452 mangleSourceName(qualifier->getAsIdentifier());
1453 return;
1454 }
1455
1456 llvm_unreachable("unexpected nested name specifier");
1457}
1458
1459void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1460 // <prefix> ::= <prefix> <unqualified-name>
1461 // ::= <template-prefix> <template-args>
1462 // ::= <template-param>
1463 // ::= # empty
1464 // ::= <substitution>
1465
1466 DC = IgnoreLinkageSpecDecls(DC);
1467
1468 if (DC->isTranslationUnit())
1469 return;
1470
Eli Friedman95f50122013-07-02 17:52:28 +00001471 if (NoFunction && isLocalContainerContext(DC))
1472 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001473
Eli Friedman95f50122013-07-02 17:52:28 +00001474 assert(!isLocalContainerContext(DC));
1475
Guy Benyei11169dd2012-12-18 14:30:41 +00001476 const NamedDecl *ND = cast<NamedDecl>(DC);
1477 if (mangleSubstitution(ND))
1478 return;
1479
1480 // Check if we have a template.
1481 const TemplateArgumentList *TemplateArgs = 0;
1482 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1483 mangleTemplatePrefix(TD);
1484 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001485 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1487 mangleUnqualifiedName(ND);
1488 }
1489
1490 addSubstitution(ND);
1491}
1492
1493void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1494 // <template-prefix> ::= <prefix> <template unqualified-name>
1495 // ::= <template-param>
1496 // ::= <substitution>
1497 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1498 return mangleTemplatePrefix(TD);
1499
1500 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1501 manglePrefix(Qualified->getQualifier());
1502
1503 if (OverloadedTemplateStorage *Overloaded
1504 = Template.getAsOverloadedTemplate()) {
1505 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1506 UnknownArity);
1507 return;
1508 }
1509
1510 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1511 assert(Dependent && "Unknown template name kind?");
1512 manglePrefix(Dependent->getQualifier());
1513 mangleUnscopedTemplateName(Template);
1514}
1515
Eli Friedman86af13f02013-07-05 18:41:30 +00001516void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1517 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 // <template-prefix> ::= <prefix> <template unqualified-name>
1519 // ::= <template-param>
1520 // ::= <substitution>
1521 // <template-template-param> ::= <template-param>
1522 // <substitution>
1523
1524 if (mangleSubstitution(ND))
1525 return;
1526
1527 // <template-template-param> ::= <template-param>
1528 if (const TemplateTemplateParmDecl *TTP
1529 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1530 mangleTemplateParameter(TTP->getIndex());
1531 return;
1532 }
1533
Eli Friedman86af13f02013-07-05 18:41:30 +00001534 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 mangleUnqualifiedName(ND->getTemplatedDecl());
1536 addSubstitution(ND);
1537}
1538
1539/// Mangles a template name under the production <type>. Required for
1540/// template template arguments.
1541/// <type> ::= <class-enum-type>
1542/// ::= <template-param>
1543/// ::= <substitution>
1544void CXXNameMangler::mangleType(TemplateName TN) {
1545 if (mangleSubstitution(TN))
1546 return;
1547
1548 TemplateDecl *TD = 0;
1549
1550 switch (TN.getKind()) {
1551 case TemplateName::QualifiedTemplate:
1552 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1553 goto HaveDecl;
1554
1555 case TemplateName::Template:
1556 TD = TN.getAsTemplateDecl();
1557 goto HaveDecl;
1558
1559 HaveDecl:
1560 if (isa<TemplateTemplateParmDecl>(TD))
1561 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1562 else
1563 mangleName(TD);
1564 break;
1565
1566 case TemplateName::OverloadedTemplate:
1567 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1568
1569 case TemplateName::DependentTemplate: {
1570 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1571 assert(Dependent->isIdentifier());
1572
1573 // <class-enum-type> ::= <name>
1574 // <name> ::= <nested-name>
1575 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1576 mangleSourceName(Dependent->getIdentifier());
1577 break;
1578 }
1579
1580 case TemplateName::SubstTemplateTemplateParm: {
1581 // Substituted template parameters are mangled as the substituted
1582 // template. This will check for the substitution twice, which is
1583 // fine, but we have to return early so that we don't try to *add*
1584 // the substitution twice.
1585 SubstTemplateTemplateParmStorage *subst
1586 = TN.getAsSubstTemplateTemplateParm();
1587 mangleType(subst->getReplacement());
1588 return;
1589 }
1590
1591 case TemplateName::SubstTemplateTemplateParmPack: {
1592 // FIXME: not clear how to mangle this!
1593 // template <template <class> class T...> class A {
1594 // template <template <class> class U...> void foo(B<T,U> x...);
1595 // };
1596 Out << "_SUBSTPACK_";
1597 break;
1598 }
1599 }
1600
1601 addSubstitution(TN);
1602}
1603
1604void
1605CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1606 switch (OO) {
1607 // <operator-name> ::= nw # new
1608 case OO_New: Out << "nw"; break;
1609 // ::= na # new[]
1610 case OO_Array_New: Out << "na"; break;
1611 // ::= dl # delete
1612 case OO_Delete: Out << "dl"; break;
1613 // ::= da # delete[]
1614 case OO_Array_Delete: Out << "da"; break;
1615 // ::= ps # + (unary)
1616 // ::= pl # + (binary or unknown)
1617 case OO_Plus:
1618 Out << (Arity == 1? "ps" : "pl"); break;
1619 // ::= ng # - (unary)
1620 // ::= mi # - (binary or unknown)
1621 case OO_Minus:
1622 Out << (Arity == 1? "ng" : "mi"); break;
1623 // ::= ad # & (unary)
1624 // ::= an # & (binary or unknown)
1625 case OO_Amp:
1626 Out << (Arity == 1? "ad" : "an"); break;
1627 // ::= de # * (unary)
1628 // ::= ml # * (binary or unknown)
1629 case OO_Star:
1630 // Use binary when unknown.
1631 Out << (Arity == 1? "de" : "ml"); break;
1632 // ::= co # ~
1633 case OO_Tilde: Out << "co"; break;
1634 // ::= dv # /
1635 case OO_Slash: Out << "dv"; break;
1636 // ::= rm # %
1637 case OO_Percent: Out << "rm"; break;
1638 // ::= or # |
1639 case OO_Pipe: Out << "or"; break;
1640 // ::= eo # ^
1641 case OO_Caret: Out << "eo"; break;
1642 // ::= aS # =
1643 case OO_Equal: Out << "aS"; break;
1644 // ::= pL # +=
1645 case OO_PlusEqual: Out << "pL"; break;
1646 // ::= mI # -=
1647 case OO_MinusEqual: Out << "mI"; break;
1648 // ::= mL # *=
1649 case OO_StarEqual: Out << "mL"; break;
1650 // ::= dV # /=
1651 case OO_SlashEqual: Out << "dV"; break;
1652 // ::= rM # %=
1653 case OO_PercentEqual: Out << "rM"; break;
1654 // ::= aN # &=
1655 case OO_AmpEqual: Out << "aN"; break;
1656 // ::= oR # |=
1657 case OO_PipeEqual: Out << "oR"; break;
1658 // ::= eO # ^=
1659 case OO_CaretEqual: Out << "eO"; break;
1660 // ::= ls # <<
1661 case OO_LessLess: Out << "ls"; break;
1662 // ::= rs # >>
1663 case OO_GreaterGreater: Out << "rs"; break;
1664 // ::= lS # <<=
1665 case OO_LessLessEqual: Out << "lS"; break;
1666 // ::= rS # >>=
1667 case OO_GreaterGreaterEqual: Out << "rS"; break;
1668 // ::= eq # ==
1669 case OO_EqualEqual: Out << "eq"; break;
1670 // ::= ne # !=
1671 case OO_ExclaimEqual: Out << "ne"; break;
1672 // ::= lt # <
1673 case OO_Less: Out << "lt"; break;
1674 // ::= gt # >
1675 case OO_Greater: Out << "gt"; break;
1676 // ::= le # <=
1677 case OO_LessEqual: Out << "le"; break;
1678 // ::= ge # >=
1679 case OO_GreaterEqual: Out << "ge"; break;
1680 // ::= nt # !
1681 case OO_Exclaim: Out << "nt"; break;
1682 // ::= aa # &&
1683 case OO_AmpAmp: Out << "aa"; break;
1684 // ::= oo # ||
1685 case OO_PipePipe: Out << "oo"; break;
1686 // ::= pp # ++
1687 case OO_PlusPlus: Out << "pp"; break;
1688 // ::= mm # --
1689 case OO_MinusMinus: Out << "mm"; break;
1690 // ::= cm # ,
1691 case OO_Comma: Out << "cm"; break;
1692 // ::= pm # ->*
1693 case OO_ArrowStar: Out << "pm"; break;
1694 // ::= pt # ->
1695 case OO_Arrow: Out << "pt"; break;
1696 // ::= cl # ()
1697 case OO_Call: Out << "cl"; break;
1698 // ::= ix # []
1699 case OO_Subscript: Out << "ix"; break;
1700
1701 // ::= qu # ?
1702 // The conditional operator can't be overloaded, but we still handle it when
1703 // mangling expressions.
1704 case OO_Conditional: Out << "qu"; break;
1705
1706 case OO_None:
1707 case NUM_OVERLOADED_OPERATORS:
1708 llvm_unreachable("Not an overloaded operator");
1709 }
1710}
1711
1712void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1713 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1714 if (Quals.hasRestrict())
1715 Out << 'r';
1716 if (Quals.hasVolatile())
1717 Out << 'V';
1718 if (Quals.hasConst())
1719 Out << 'K';
1720
1721 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001722 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 //
David Tweed31d09b02013-09-13 12:04:22 +00001724 // <type> ::= U <target-addrspace>
1725 // <type> ::= U <OpenCL-addrspace>
1726 // <type> ::= U <CUDA-addrspace>
1727
Guy Benyei11169dd2012-12-18 14:30:41 +00001728 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001729 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001730
1731 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1732 // <target-addrspace> ::= "AS" <address-space-number>
1733 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1734 ASString = "AS" + llvm::utostr_32(TargetAS);
1735 } else {
1736 switch (AS) {
1737 default: llvm_unreachable("Not a language specific address space");
1738 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1739 case LangAS::opencl_global: ASString = "CLglobal"; break;
1740 case LangAS::opencl_local: ASString = "CLlocal"; break;
1741 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1742 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1743 case LangAS::cuda_device: ASString = "CUdevice"; break;
1744 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1745 case LangAS::cuda_shared: ASString = "CUshared"; break;
1746 }
1747 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 Out << 'U' << ASString.size() << ASString;
1749 }
1750
1751 StringRef LifetimeName;
1752 switch (Quals.getObjCLifetime()) {
1753 // Objective-C ARC Extension:
1754 //
1755 // <type> ::= U "__strong"
1756 // <type> ::= U "__weak"
1757 // <type> ::= U "__autoreleasing"
1758 case Qualifiers::OCL_None:
1759 break;
1760
1761 case Qualifiers::OCL_Weak:
1762 LifetimeName = "__weak";
1763 break;
1764
1765 case Qualifiers::OCL_Strong:
1766 LifetimeName = "__strong";
1767 break;
1768
1769 case Qualifiers::OCL_Autoreleasing:
1770 LifetimeName = "__autoreleasing";
1771 break;
1772
1773 case Qualifiers::OCL_ExplicitNone:
1774 // The __unsafe_unretained qualifier is *not* mangled, so that
1775 // __unsafe_unretained types in ARC produce the same manglings as the
1776 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1777 // better ABI compatibility.
1778 //
1779 // It's safe to do this because unqualified 'id' won't show up
1780 // in any type signatures that need to be mangled.
1781 break;
1782 }
1783 if (!LifetimeName.empty())
1784 Out << 'U' << LifetimeName.size() << LifetimeName;
1785}
1786
1787void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1788 // <ref-qualifier> ::= R # lvalue reference
1789 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 switch (RefQualifier) {
1791 case RQ_None:
1792 break;
1793
1794 case RQ_LValue:
1795 Out << 'R';
1796 break;
1797
1798 case RQ_RValue:
1799 Out << 'O';
1800 break;
1801 }
1802}
1803
1804void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1805 Context.mangleObjCMethodName(MD, Out);
1806}
1807
1808void CXXNameMangler::mangleType(QualType T) {
1809 // If our type is instantiation-dependent but not dependent, we mangle
1810 // it as it was written in the source, removing any top-level sugar.
1811 // Otherwise, use the canonical type.
1812 //
1813 // FIXME: This is an approximation of the instantiation-dependent name
1814 // mangling rules, since we should really be using the type as written and
1815 // augmented via semantic analysis (i.e., with implicit conversions and
1816 // default template arguments) for any instantiation-dependent type.
1817 // Unfortunately, that requires several changes to our AST:
1818 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1819 // uniqued, so that we can handle substitutions properly
1820 // - Default template arguments will need to be represented in the
1821 // TemplateSpecializationType, since they need to be mangled even though
1822 // they aren't written.
1823 // - Conversions on non-type template arguments need to be expressed, since
1824 // they can affect the mangling of sizeof/alignof.
1825 if (!T->isInstantiationDependentType() || T->isDependentType())
1826 T = T.getCanonicalType();
1827 else {
1828 // Desugar any types that are purely sugar.
1829 do {
1830 // Don't desugar through template specialization types that aren't
1831 // type aliases. We need to mangle the template arguments as written.
1832 if (const TemplateSpecializationType *TST
1833 = dyn_cast<TemplateSpecializationType>(T))
1834 if (!TST->isTypeAlias())
1835 break;
1836
1837 QualType Desugared
1838 = T.getSingleStepDesugaredType(Context.getASTContext());
1839 if (Desugared == T)
1840 break;
1841
1842 T = Desugared;
1843 } while (true);
1844 }
1845 SplitQualType split = T.split();
1846 Qualifiers quals = split.Quals;
1847 const Type *ty = split.Ty;
1848
1849 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1850 if (isSubstitutable && mangleSubstitution(T))
1851 return;
1852
1853 // If we're mangling a qualified array type, push the qualifiers to
1854 // the element type.
1855 if (quals && isa<ArrayType>(T)) {
1856 ty = Context.getASTContext().getAsArrayType(T);
1857 quals = Qualifiers();
1858
1859 // Note that we don't update T: we want to add the
1860 // substitution at the original type.
1861 }
1862
1863 if (quals) {
1864 mangleQualifiers(quals);
1865 // Recurse: even if the qualified type isn't yet substitutable,
1866 // the unqualified type might be.
1867 mangleType(QualType(ty, 0));
1868 } else {
1869 switch (ty->getTypeClass()) {
1870#define ABSTRACT_TYPE(CLASS, PARENT)
1871#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1872 case Type::CLASS: \
1873 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1874 return;
1875#define TYPE(CLASS, PARENT) \
1876 case Type::CLASS: \
1877 mangleType(static_cast<const CLASS##Type*>(ty)); \
1878 break;
1879#include "clang/AST/TypeNodes.def"
1880 }
1881 }
1882
1883 // Add the substitution.
1884 if (isSubstitutable)
1885 addSubstitution(T);
1886}
1887
1888void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1889 if (!mangleStandardSubstitution(ND))
1890 mangleName(ND);
1891}
1892
1893void CXXNameMangler::mangleType(const BuiltinType *T) {
1894 // <type> ::= <builtin-type>
1895 // <builtin-type> ::= v # void
1896 // ::= w # wchar_t
1897 // ::= b # bool
1898 // ::= c # char
1899 // ::= a # signed char
1900 // ::= h # unsigned char
1901 // ::= s # short
1902 // ::= t # unsigned short
1903 // ::= i # int
1904 // ::= j # unsigned int
1905 // ::= l # long
1906 // ::= m # unsigned long
1907 // ::= x # long long, __int64
1908 // ::= y # unsigned long long, __int64
1909 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001910 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001911 // ::= f # float
1912 // ::= d # double
1913 // ::= e # long double, __float80
1914 // UNSUPPORTED: ::= g # __float128
1915 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1916 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1917 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1918 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1919 // ::= Di # char32_t
1920 // ::= Ds # char16_t
1921 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1922 // ::= u <source-name> # vendor extended type
1923 switch (T->getKind()) {
1924 case BuiltinType::Void: Out << 'v'; break;
1925 case BuiltinType::Bool: Out << 'b'; break;
1926 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1927 case BuiltinType::UChar: Out << 'h'; break;
1928 case BuiltinType::UShort: Out << 't'; break;
1929 case BuiltinType::UInt: Out << 'j'; break;
1930 case BuiltinType::ULong: Out << 'm'; break;
1931 case BuiltinType::ULongLong: Out << 'y'; break;
1932 case BuiltinType::UInt128: Out << 'o'; break;
1933 case BuiltinType::SChar: Out << 'a'; break;
1934 case BuiltinType::WChar_S:
1935 case BuiltinType::WChar_U: Out << 'w'; break;
1936 case BuiltinType::Char16: Out << "Ds"; break;
1937 case BuiltinType::Char32: Out << "Di"; break;
1938 case BuiltinType::Short: Out << 's'; break;
1939 case BuiltinType::Int: Out << 'i'; break;
1940 case BuiltinType::Long: Out << 'l'; break;
1941 case BuiltinType::LongLong: Out << 'x'; break;
1942 case BuiltinType::Int128: Out << 'n'; break;
1943 case BuiltinType::Half: Out << "Dh"; break;
1944 case BuiltinType::Float: Out << 'f'; break;
1945 case BuiltinType::Double: Out << 'd'; break;
1946 case BuiltinType::LongDouble: Out << 'e'; break;
1947 case BuiltinType::NullPtr: Out << "Dn"; break;
1948
1949#define BUILTIN_TYPE(Id, SingletonId)
1950#define PLACEHOLDER_TYPE(Id, SingletonId) \
1951 case BuiltinType::Id:
1952#include "clang/AST/BuiltinTypes.def"
1953 case BuiltinType::Dependent:
1954 llvm_unreachable("mangling a placeholder type");
1955 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1956 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1957 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001958 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1959 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1960 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1961 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1962 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1963 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00001964 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001965 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001966 }
1967}
1968
1969// <type> ::= <function-type>
1970// <function-type> ::= [<CV-qualifiers>] F [Y]
1971// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00001972void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1973 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1974 // e.g. "const" in "int (A::*)() const".
1975 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1976
1977 Out << 'F';
1978
1979 // FIXME: We don't have enough information in the AST to produce the 'Y'
1980 // encoding for extern "C" function types.
1981 mangleBareFunctionType(T, /*MangleReturnType=*/true);
1982
1983 // Mangle the ref-qualifier, if present.
1984 mangleRefQualifier(T->getRefQualifier());
1985
1986 Out << 'E';
1987}
1988void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1989 llvm_unreachable("Can't mangle K&R function prototypes");
1990}
1991void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1992 bool MangleReturnType) {
1993 // We should never be mangling something without a prototype.
1994 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1995
1996 // Record that we're in a function type. See mangleFunctionParam
1997 // for details on what we're trying to achieve here.
1998 FunctionTypeDepthState saved = FunctionTypeDepth.push();
1999
2000 // <bare-function-type> ::= <signature type>+
2001 if (MangleReturnType) {
2002 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002003 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002004 FunctionTypeDepth.leaveResultType();
2005 }
2006
Alp Toker9cacbab2014-01-20 20:26:09 +00002007 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 // <builtin-type> ::= v # void
2009 Out << 'v';
2010
2011 FunctionTypeDepth.pop(saved);
2012 return;
2013 }
2014
Alp Toker9cacbab2014-01-20 20:26:09 +00002015 for (FunctionProtoType::param_type_iterator Arg = Proto->param_type_begin(),
2016 ArgEnd = Proto->param_type_end();
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 Arg != ArgEnd; ++Arg)
2018 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
2019
2020 FunctionTypeDepth.pop(saved);
2021
2022 // <builtin-type> ::= z # ellipsis
2023 if (Proto->isVariadic())
2024 Out << 'z';
2025}
2026
2027// <type> ::= <class-enum-type>
2028// <class-enum-type> ::= <name>
2029void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2030 mangleName(T->getDecl());
2031}
2032
2033// <type> ::= <class-enum-type>
2034// <class-enum-type> ::= <name>
2035void CXXNameMangler::mangleType(const EnumType *T) {
2036 mangleType(static_cast<const TagType*>(T));
2037}
2038void CXXNameMangler::mangleType(const RecordType *T) {
2039 mangleType(static_cast<const TagType*>(T));
2040}
2041void CXXNameMangler::mangleType(const TagType *T) {
2042 mangleName(T->getDecl());
2043}
2044
2045// <type> ::= <array-type>
2046// <array-type> ::= A <positive dimension number> _ <element type>
2047// ::= A [<dimension expression>] _ <element type>
2048void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2049 Out << 'A' << T->getSize() << '_';
2050 mangleType(T->getElementType());
2051}
2052void CXXNameMangler::mangleType(const VariableArrayType *T) {
2053 Out << 'A';
2054 // decayed vla types (size 0) will just be skipped.
2055 if (T->getSizeExpr())
2056 mangleExpression(T->getSizeExpr());
2057 Out << '_';
2058 mangleType(T->getElementType());
2059}
2060void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2061 Out << 'A';
2062 mangleExpression(T->getSizeExpr());
2063 Out << '_';
2064 mangleType(T->getElementType());
2065}
2066void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2067 Out << "A_";
2068 mangleType(T->getElementType());
2069}
2070
2071// <type> ::= <pointer-to-member-type>
2072// <pointer-to-member-type> ::= M <class type> <member type>
2073void CXXNameMangler::mangleType(const MemberPointerType *T) {
2074 Out << 'M';
2075 mangleType(QualType(T->getClass(), 0));
2076 QualType PointeeType = T->getPointeeType();
2077 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2078 mangleType(FPT);
2079
2080 // Itanium C++ ABI 5.1.8:
2081 //
2082 // The type of a non-static member function is considered to be different,
2083 // for the purposes of substitution, from the type of a namespace-scope or
2084 // static member function whose type appears similar. The types of two
2085 // non-static member functions are considered to be different, for the
2086 // purposes of substitution, if the functions are members of different
2087 // classes. In other words, for the purposes of substitution, the class of
2088 // which the function is a member is considered part of the type of
2089 // function.
2090
2091 // Given that we already substitute member function pointers as a
2092 // whole, the net effect of this rule is just to unconditionally
2093 // suppress substitution on the function type in a member pointer.
2094 // We increment the SeqID here to emulate adding an entry to the
2095 // substitution table.
2096 ++SeqID;
2097 } else
2098 mangleType(PointeeType);
2099}
2100
2101// <type> ::= <template-param>
2102void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2103 mangleTemplateParameter(T->getIndex());
2104}
2105
2106// <type> ::= <template-param>
2107void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2108 // FIXME: not clear how to mangle this!
2109 // template <class T...> class A {
2110 // template <class U...> void foo(T(*)(U) x...);
2111 // };
2112 Out << "_SUBSTPACK_";
2113}
2114
2115// <type> ::= P <type> # pointer-to
2116void CXXNameMangler::mangleType(const PointerType *T) {
2117 Out << 'P';
2118 mangleType(T->getPointeeType());
2119}
2120void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2121 Out << 'P';
2122 mangleType(T->getPointeeType());
2123}
2124
2125// <type> ::= R <type> # reference-to
2126void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2127 Out << 'R';
2128 mangleType(T->getPointeeType());
2129}
2130
2131// <type> ::= O <type> # rvalue reference-to (C++0x)
2132void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2133 Out << 'O';
2134 mangleType(T->getPointeeType());
2135}
2136
2137// <type> ::= C <type> # complex pair (C 2000)
2138void CXXNameMangler::mangleType(const ComplexType *T) {
2139 Out << 'C';
2140 mangleType(T->getElementType());
2141}
2142
2143// ARM's ABI for Neon vector types specifies that they should be mangled as
2144// if they are structs (to match ARM's initial implementation). The
2145// vector type must be one of the special types predefined by ARM.
2146void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2147 QualType EltType = T->getElementType();
2148 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2149 const char *EltName = 0;
2150 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2151 switch (cast<BuiltinType>(EltType)->getKind()) {
2152 case BuiltinType::SChar: EltName = "poly8_t"; break;
2153 case BuiltinType::Short: EltName = "poly16_t"; break;
2154 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2155 }
2156 } else {
2157 switch (cast<BuiltinType>(EltType)->getKind()) {
2158 case BuiltinType::SChar: EltName = "int8_t"; break;
2159 case BuiltinType::UChar: EltName = "uint8_t"; break;
2160 case BuiltinType::Short: EltName = "int16_t"; break;
2161 case BuiltinType::UShort: EltName = "uint16_t"; break;
2162 case BuiltinType::Int: EltName = "int32_t"; break;
2163 case BuiltinType::UInt: EltName = "uint32_t"; break;
2164 case BuiltinType::LongLong: EltName = "int64_t"; break;
2165 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2166 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002167 case BuiltinType::Half: EltName = "float16_t";break;
2168 default:
2169 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002170 }
2171 }
2172 const char *BaseName = 0;
2173 unsigned BitSize = (T->getNumElements() *
2174 getASTContext().getTypeSize(EltType));
2175 if (BitSize == 64)
2176 BaseName = "__simd64_";
2177 else {
2178 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2179 BaseName = "__simd128_";
2180 }
2181 Out << strlen(BaseName) + strlen(EltName);
2182 Out << BaseName << EltName;
2183}
2184
Tim Northover2fe823a2013-08-01 09:23:19 +00002185static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2186 switch (EltType->getKind()) {
2187 case BuiltinType::SChar:
2188 return "Int8";
2189 case BuiltinType::Short:
2190 return "Int16";
2191 case BuiltinType::Int:
2192 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002193 case BuiltinType::Long:
Tim Northover2fe823a2013-08-01 09:23:19 +00002194 return "Int64";
2195 case BuiltinType::UChar:
2196 return "Uint8";
2197 case BuiltinType::UShort:
2198 return "Uint16";
2199 case BuiltinType::UInt:
2200 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002201 case BuiltinType::ULong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002202 return "Uint64";
2203 case BuiltinType::Half:
2204 return "Float16";
2205 case BuiltinType::Float:
2206 return "Float32";
2207 case BuiltinType::Double:
2208 return "Float64";
2209 default:
2210 llvm_unreachable("Unexpected vector element base type");
2211 }
2212}
2213
2214// AArch64's ABI for Neon vector types specifies that they should be mangled as
2215// the equivalent internal name. The vector type must be one of the special
2216// types predefined by ARM.
2217void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2218 QualType EltType = T->getElementType();
2219 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2220 unsigned BitSize =
2221 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002222 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002223
2224 assert((BitSize == 64 || BitSize == 128) &&
2225 "Neon vector type not 64 or 128 bits");
2226
Tim Northover2fe823a2013-08-01 09:23:19 +00002227 StringRef EltName;
2228 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2229 switch (cast<BuiltinType>(EltType)->getKind()) {
2230 case BuiltinType::UChar:
2231 EltName = "Poly8";
2232 break;
2233 case BuiltinType::UShort:
2234 EltName = "Poly16";
2235 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002236 case BuiltinType::ULong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002237 EltName = "Poly64";
2238 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002239 default:
2240 llvm_unreachable("unexpected Neon polynomial vector element type");
2241 }
2242 } else
2243 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2244
2245 std::string TypeName =
2246 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2247 Out << TypeName.length() << TypeName;
2248}
2249
Guy Benyei11169dd2012-12-18 14:30:41 +00002250// GNU extension: vector types
2251// <type> ::= <vector-type>
2252// <vector-type> ::= Dv <positive dimension number> _
2253// <extended element type>
2254// ::= Dv [<dimension expression>] _ <element type>
2255// <extended element type> ::= <element type>
2256// ::= p # AltiVec vector pixel
2257// ::= b # Altivec vector bool
2258void CXXNameMangler::mangleType(const VectorType *T) {
2259 if ((T->getVectorKind() == VectorType::NeonVector ||
2260 T->getVectorKind() == VectorType::NeonPolyVector)) {
Christian Pirker9b019ae2014-02-25 13:51:00 +00002261 llvm::Triple::ArchType Arch =
2262 getASTContext().getTargetInfo().getTriple().getArch();
2263 if ((Arch == llvm::Triple::aarch64) ||
2264 (Arch == llvm::Triple::aarch64_be))
Tim Northover2fe823a2013-08-01 09:23:19 +00002265 mangleAArch64NeonVectorType(T);
2266 else
2267 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 return;
2269 }
2270 Out << "Dv" << T->getNumElements() << '_';
2271 if (T->getVectorKind() == VectorType::AltiVecPixel)
2272 Out << 'p';
2273 else if (T->getVectorKind() == VectorType::AltiVecBool)
2274 Out << 'b';
2275 else
2276 mangleType(T->getElementType());
2277}
2278void CXXNameMangler::mangleType(const ExtVectorType *T) {
2279 mangleType(static_cast<const VectorType*>(T));
2280}
2281void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2282 Out << "Dv";
2283 mangleExpression(T->getSizeExpr());
2284 Out << '_';
2285 mangleType(T->getElementType());
2286}
2287
2288void CXXNameMangler::mangleType(const PackExpansionType *T) {
2289 // <type> ::= Dp <type> # pack expansion (C++0x)
2290 Out << "Dp";
2291 mangleType(T->getPattern());
2292}
2293
2294void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2295 mangleSourceName(T->getDecl()->getIdentifier());
2296}
2297
2298void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman5f508952013-06-18 22:41:37 +00002299 if (!T->qual_empty()) {
2300 // Mangle protocol qualifiers.
2301 SmallString<64> QualStr;
2302 llvm::raw_svector_ostream QualOS(QualStr);
2303 QualOS << "objcproto";
2304 ObjCObjectType::qual_iterator i = T->qual_begin(), e = T->qual_end();
2305 for ( ; i != e; ++i) {
2306 StringRef name = (*i)->getName();
2307 QualOS << name.size() << name;
2308 }
2309 QualOS.flush();
2310 Out << 'U' << QualStr.size() << QualStr;
2311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 mangleType(T->getBaseType());
2313}
2314
2315void CXXNameMangler::mangleType(const BlockPointerType *T) {
2316 Out << "U13block_pointer";
2317 mangleType(T->getPointeeType());
2318}
2319
2320void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2321 // Mangle injected class name types as if the user had written the
2322 // specialization out fully. It may not actually be possible to see
2323 // this mangling, though.
2324 mangleType(T->getInjectedSpecializationType());
2325}
2326
2327void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2328 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2329 mangleName(TD, T->getArgs(), T->getNumArgs());
2330 } else {
2331 if (mangleSubstitution(QualType(T, 0)))
2332 return;
2333
2334 mangleTemplatePrefix(T->getTemplateName());
2335
2336 // FIXME: GCC does not appear to mangle the template arguments when
2337 // the template in question is a dependent template name. Should we
2338 // emulate that badness?
2339 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2340 addSubstitution(QualType(T, 0));
2341 }
2342}
2343
2344void CXXNameMangler::mangleType(const DependentNameType *T) {
2345 // Typename types are always nested
2346 Out << 'N';
2347 manglePrefix(T->getQualifier());
2348 mangleSourceName(T->getIdentifier());
2349 Out << 'E';
2350}
2351
2352void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2353 // Dependently-scoped template types are nested if they have a prefix.
2354 Out << 'N';
2355
2356 // TODO: avoid making this TemplateName.
2357 TemplateName Prefix =
2358 getASTContext().getDependentTemplateName(T->getQualifier(),
2359 T->getIdentifier());
2360 mangleTemplatePrefix(Prefix);
2361
2362 // FIXME: GCC does not appear to mangle the template arguments when
2363 // the template in question is a dependent template name. Should we
2364 // emulate that badness?
2365 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2366 Out << 'E';
2367}
2368
2369void CXXNameMangler::mangleType(const TypeOfType *T) {
2370 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2371 // "extension with parameters" mangling.
2372 Out << "u6typeof";
2373}
2374
2375void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2376 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2377 // "extension with parameters" mangling.
2378 Out << "u6typeof";
2379}
2380
2381void CXXNameMangler::mangleType(const DecltypeType *T) {
2382 Expr *E = T->getUnderlyingExpr();
2383
2384 // type ::= Dt <expression> E # decltype of an id-expression
2385 // # or class member access
2386 // ::= DT <expression> E # decltype of an expression
2387
2388 // This purports to be an exhaustive list of id-expressions and
2389 // class member accesses. Note that we do not ignore parentheses;
2390 // parentheses change the semantics of decltype for these
2391 // expressions (and cause the mangler to use the other form).
2392 if (isa<DeclRefExpr>(E) ||
2393 isa<MemberExpr>(E) ||
2394 isa<UnresolvedLookupExpr>(E) ||
2395 isa<DependentScopeDeclRefExpr>(E) ||
2396 isa<CXXDependentScopeMemberExpr>(E) ||
2397 isa<UnresolvedMemberExpr>(E))
2398 Out << "Dt";
2399 else
2400 Out << "DT";
2401 mangleExpression(E);
2402 Out << 'E';
2403}
2404
2405void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2406 // If this is dependent, we need to record that. If not, we simply
2407 // mangle it as the underlying type since they are equivalent.
2408 if (T->isDependentType()) {
2409 Out << 'U';
2410
2411 switch (T->getUTTKind()) {
2412 case UnaryTransformType::EnumUnderlyingType:
2413 Out << "3eut";
2414 break;
2415 }
2416 }
2417
2418 mangleType(T->getUnderlyingType());
2419}
2420
2421void CXXNameMangler::mangleType(const AutoType *T) {
2422 QualType D = T->getDeducedType();
2423 // <builtin-type> ::= Da # dependent auto
2424 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002425 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 else
2427 mangleType(D);
2428}
2429
2430void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002431 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 // (Until there's a standardized mangling...)
2433 Out << "U7_Atomic";
2434 mangleType(T->getValueType());
2435}
2436
2437void CXXNameMangler::mangleIntegerLiteral(QualType T,
2438 const llvm::APSInt &Value) {
2439 // <expr-primary> ::= L <type> <value number> E # integer literal
2440 Out << 'L';
2441
2442 mangleType(T);
2443 if (T->isBooleanType()) {
2444 // Boolean values are encoded as 0/1.
2445 Out << (Value.getBoolValue() ? '1' : '0');
2446 } else {
2447 mangleNumber(Value);
2448 }
2449 Out << 'E';
2450
2451}
2452
2453/// Mangles a member expression.
2454void CXXNameMangler::mangleMemberExpr(const Expr *base,
2455 bool isArrow,
2456 NestedNameSpecifier *qualifier,
2457 NamedDecl *firstQualifierLookup,
2458 DeclarationName member,
2459 unsigned arity) {
2460 // <expression> ::= dt <expression> <unresolved-name>
2461 // ::= pt <expression> <unresolved-name>
2462 if (base) {
2463 if (base->isImplicitCXXThis()) {
2464 // Note: GCC mangles member expressions to the implicit 'this' as
2465 // *this., whereas we represent them as this->. The Itanium C++ ABI
2466 // does not specify anything here, so we follow GCC.
2467 Out << "dtdefpT";
2468 } else {
2469 Out << (isArrow ? "pt" : "dt");
2470 mangleExpression(base);
2471 }
2472 }
2473 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2474}
2475
2476/// Look at the callee of the given call expression and determine if
2477/// it's a parenthesized id-expression which would have triggered ADL
2478/// otherwise.
2479static bool isParenthesizedADLCallee(const CallExpr *call) {
2480 const Expr *callee = call->getCallee();
2481 const Expr *fn = callee->IgnoreParens();
2482
2483 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2484 // too, but for those to appear in the callee, it would have to be
2485 // parenthesized.
2486 if (callee == fn) return false;
2487
2488 // Must be an unresolved lookup.
2489 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2490 if (!lookup) return false;
2491
2492 assert(!lookup->requiresADL());
2493
2494 // Must be an unqualified lookup.
2495 if (lookup->getQualifier()) return false;
2496
2497 // Must not have found a class member. Note that if one is a class
2498 // member, they're all class members.
2499 if (lookup->getNumDecls() > 0 &&
2500 (*lookup->decls_begin())->isCXXClassMember())
2501 return false;
2502
2503 // Otherwise, ADL would have been triggered.
2504 return true;
2505}
2506
2507void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2508 // <expression> ::= <unary operator-name> <expression>
2509 // ::= <binary operator-name> <expression> <expression>
2510 // ::= <trinary operator-name> <expression> <expression> <expression>
2511 // ::= cv <type> expression # conversion with one argument
2512 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2513 // ::= st <type> # sizeof (a type)
2514 // ::= at <type> # alignof (a type)
2515 // ::= <template-param>
2516 // ::= <function-param>
2517 // ::= sr <type> <unqualified-name> # dependent name
2518 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2519 // ::= ds <expression> <expression> # expr.*expr
2520 // ::= sZ <template-param> # size of a parameter pack
2521 // ::= sZ <function-param> # size of a function parameter pack
2522 // ::= <expr-primary>
2523 // <expr-primary> ::= L <type> <value number> E # integer literal
2524 // ::= L <type <value float> E # floating literal
2525 // ::= L <mangled-name> E # external name
2526 // ::= fpT # 'this' expression
2527 QualType ImplicitlyConvertedToType;
2528
2529recurse:
2530 switch (E->getStmtClass()) {
2531 case Expr::NoStmtClass:
2532#define ABSTRACT_STMT(Type)
2533#define EXPR(Type, Base)
2534#define STMT(Type, Base) \
2535 case Expr::Type##Class:
2536#include "clang/AST/StmtNodes.inc"
2537 // fallthrough
2538
2539 // These all can only appear in local or variable-initialization
2540 // contexts and so should never appear in a mangling.
2541 case Expr::AddrLabelExprClass:
2542 case Expr::DesignatedInitExprClass:
2543 case Expr::ImplicitValueInitExprClass:
2544 case Expr::ParenListExprClass:
2545 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002546 case Expr::MSPropertyRefExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 llvm_unreachable("unexpected statement kind");
2548
2549 // FIXME: invent manglings for all these.
2550 case Expr::BlockExprClass:
2551 case Expr::CXXPseudoDestructorExprClass:
2552 case Expr::ChooseExprClass:
2553 case Expr::CompoundLiteralExprClass:
2554 case Expr::ExtVectorElementExprClass:
2555 case Expr::GenericSelectionExprClass:
2556 case Expr::ObjCEncodeExprClass:
2557 case Expr::ObjCIsaExprClass:
2558 case Expr::ObjCIvarRefExprClass:
2559 case Expr::ObjCMessageExprClass:
2560 case Expr::ObjCPropertyRefExprClass:
2561 case Expr::ObjCProtocolExprClass:
2562 case Expr::ObjCSelectorExprClass:
2563 case Expr::ObjCStringLiteralClass:
2564 case Expr::ObjCBoxedExprClass:
2565 case Expr::ObjCArrayLiteralClass:
2566 case Expr::ObjCDictionaryLiteralClass:
2567 case Expr::ObjCSubscriptRefExprClass:
2568 case Expr::ObjCIndirectCopyRestoreExprClass:
2569 case Expr::OffsetOfExprClass:
2570 case Expr::PredefinedExprClass:
2571 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002572 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case Expr::TypeTraitExprClass:
2575 case Expr::ArrayTypeTraitExprClass:
2576 case Expr::ExpressionTraitExprClass:
2577 case Expr::VAArgExprClass:
2578 case Expr::CXXUuidofExprClass:
2579 case Expr::CUDAKernelCallExprClass:
2580 case Expr::AsTypeExprClass:
2581 case Expr::PseudoObjectExprClass:
2582 case Expr::AtomicExprClass:
2583 {
2584 // As bad as this diagnostic is, it's better than crashing.
2585 DiagnosticsEngine &Diags = Context.getDiags();
2586 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2587 "cannot yet mangle expression type %0");
2588 Diags.Report(E->getExprLoc(), DiagID)
2589 << E->getStmtClassName() << E->getSourceRange();
2590 break;
2591 }
2592
2593 // Even gcc-4.5 doesn't mangle this.
2594 case Expr::BinaryConditionalOperatorClass: {
2595 DiagnosticsEngine &Diags = Context.getDiags();
2596 unsigned DiagID =
2597 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2598 "?: operator with omitted middle operand cannot be mangled");
2599 Diags.Report(E->getExprLoc(), DiagID)
2600 << E->getStmtClassName() << E->getSourceRange();
2601 break;
2602 }
2603
2604 // These are used for internal purposes and cannot be meaningfully mangled.
2605 case Expr::OpaqueValueExprClass:
2606 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2607
2608 case Expr::InitListExprClass: {
2609 // Proposal by Jason Merrill, 2012-01-03
2610 Out << "il";
2611 const InitListExpr *InitList = cast<InitListExpr>(E);
2612 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2613 mangleExpression(InitList->getInit(i));
2614 Out << "E";
2615 break;
2616 }
2617
2618 case Expr::CXXDefaultArgExprClass:
2619 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2620 break;
2621
Richard Smith852c9db2013-04-20 22:23:05 +00002622 case Expr::CXXDefaultInitExprClass:
2623 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2624 break;
2625
Richard Smithcc1b96d2013-06-12 22:31:48 +00002626 case Expr::CXXStdInitializerListExprClass:
2627 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2628 break;
2629
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 case Expr::SubstNonTypeTemplateParmExprClass:
2631 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2632 Arity);
2633 break;
2634
2635 case Expr::UserDefinedLiteralClass:
2636 // We follow g++'s approach of mangling a UDL as a call to the literal
2637 // operator.
2638 case Expr::CXXMemberCallExprClass: // fallthrough
2639 case Expr::CallExprClass: {
2640 const CallExpr *CE = cast<CallExpr>(E);
2641
2642 // <expression> ::= cp <simple-id> <expression>* E
2643 // We use this mangling only when the call would use ADL except
2644 // for being parenthesized. Per discussion with David
2645 // Vandervoorde, 2011.04.25.
2646 if (isParenthesizedADLCallee(CE)) {
2647 Out << "cp";
2648 // The callee here is a parenthesized UnresolvedLookupExpr with
2649 // no qualifier and should always get mangled as a <simple-id>
2650 // anyway.
2651
2652 // <expression> ::= cl <expression>* E
2653 } else {
2654 Out << "cl";
2655 }
2656
2657 mangleExpression(CE->getCallee(), CE->getNumArgs());
2658 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2659 mangleExpression(CE->getArg(I));
2660 Out << 'E';
2661 break;
2662 }
2663
2664 case Expr::CXXNewExprClass: {
2665 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2666 if (New->isGlobalNew()) Out << "gs";
2667 Out << (New->isArray() ? "na" : "nw");
2668 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2669 E = New->placement_arg_end(); I != E; ++I)
2670 mangleExpression(*I);
2671 Out << '_';
2672 mangleType(New->getAllocatedType());
2673 if (New->hasInitializer()) {
2674 // Proposal by Jason Merrill, 2012-01-03
2675 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2676 Out << "il";
2677 else
2678 Out << "pi";
2679 const Expr *Init = New->getInitializer();
2680 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2681 // Directly inline the initializers.
2682 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2683 E = CCE->arg_end();
2684 I != E; ++I)
2685 mangleExpression(*I);
2686 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2687 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2688 mangleExpression(PLE->getExpr(i));
2689 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2690 isa<InitListExpr>(Init)) {
2691 // Only take InitListExprs apart for list-initialization.
2692 const InitListExpr *InitList = cast<InitListExpr>(Init);
2693 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2694 mangleExpression(InitList->getInit(i));
2695 } else
2696 mangleExpression(Init);
2697 }
2698 Out << 'E';
2699 break;
2700 }
2701
2702 case Expr::MemberExprClass: {
2703 const MemberExpr *ME = cast<MemberExpr>(E);
2704 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2705 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2706 Arity);
2707 break;
2708 }
2709
2710 case Expr::UnresolvedMemberExprClass: {
2711 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2712 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2713 ME->getQualifier(), 0, ME->getMemberName(),
2714 Arity);
2715 if (ME->hasExplicitTemplateArgs())
2716 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2717 break;
2718 }
2719
2720 case Expr::CXXDependentScopeMemberExprClass: {
2721 const CXXDependentScopeMemberExpr *ME
2722 = cast<CXXDependentScopeMemberExpr>(E);
2723 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2724 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2725 ME->getMember(), Arity);
2726 if (ME->hasExplicitTemplateArgs())
2727 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2728 break;
2729 }
2730
2731 case Expr::UnresolvedLookupExprClass: {
2732 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2733 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2734
2735 // All the <unresolved-name> productions end in a
2736 // base-unresolved-name, where <template-args> are just tacked
2737 // onto the end.
2738 if (ULE->hasExplicitTemplateArgs())
2739 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2740 break;
2741 }
2742
2743 case Expr::CXXUnresolvedConstructExprClass: {
2744 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2745 unsigned N = CE->arg_size();
2746
2747 Out << "cv";
2748 mangleType(CE->getType());
2749 if (N != 1) Out << '_';
2750 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2751 if (N != 1) Out << 'E';
2752 break;
2753 }
2754
2755 case Expr::CXXTemporaryObjectExprClass:
2756 case Expr::CXXConstructExprClass: {
2757 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2758 unsigned N = CE->getNumArgs();
2759
2760 // Proposal by Jason Merrill, 2012-01-03
2761 if (CE->isListInitialization())
2762 Out << "tl";
2763 else
2764 Out << "cv";
2765 mangleType(CE->getType());
2766 if (N != 1) Out << '_';
2767 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2768 if (N != 1) Out << 'E';
2769 break;
2770 }
2771
2772 case Expr::CXXScalarValueInitExprClass:
2773 Out <<"cv";
2774 mangleType(E->getType());
2775 Out <<"_E";
2776 break;
2777
2778 case Expr::CXXNoexceptExprClass:
2779 Out << "nx";
2780 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2781 break;
2782
2783 case Expr::UnaryExprOrTypeTraitExprClass: {
2784 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2785
2786 if (!SAE->isInstantiationDependent()) {
2787 // Itanium C++ ABI:
2788 // If the operand of a sizeof or alignof operator is not
2789 // instantiation-dependent it is encoded as an integer literal
2790 // reflecting the result of the operator.
2791 //
2792 // If the result of the operator is implicitly converted to a known
2793 // integer type, that type is used for the literal; otherwise, the type
2794 // of std::size_t or std::ptrdiff_t is used.
2795 QualType T = (ImplicitlyConvertedToType.isNull() ||
2796 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2797 : ImplicitlyConvertedToType;
2798 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2799 mangleIntegerLiteral(T, V);
2800 break;
2801 }
2802
2803 switch(SAE->getKind()) {
2804 case UETT_SizeOf:
2805 Out << 's';
2806 break;
2807 case UETT_AlignOf:
2808 Out << 'a';
2809 break;
2810 case UETT_VecStep:
2811 DiagnosticsEngine &Diags = Context.getDiags();
2812 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2813 "cannot yet mangle vec_step expression");
2814 Diags.Report(DiagID);
2815 return;
2816 }
2817 if (SAE->isArgumentType()) {
2818 Out << 't';
2819 mangleType(SAE->getArgumentType());
2820 } else {
2821 Out << 'z';
2822 mangleExpression(SAE->getArgumentExpr());
2823 }
2824 break;
2825 }
2826
2827 case Expr::CXXThrowExprClass: {
2828 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00002829 // <expression> ::= tw <expression> # throw expression
2830 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 if (TE->getSubExpr()) {
2832 Out << "tw";
2833 mangleExpression(TE->getSubExpr());
2834 } else {
2835 Out << "tr";
2836 }
2837 break;
2838 }
2839
2840 case Expr::CXXTypeidExprClass: {
2841 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00002842 // <expression> ::= ti <type> # typeid (type)
2843 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 if (TIE->isTypeOperand()) {
2845 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00002846 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 } else {
2848 Out << "te";
2849 mangleExpression(TIE->getExprOperand());
2850 }
2851 break;
2852 }
2853
2854 case Expr::CXXDeleteExprClass: {
2855 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00002856 // <expression> ::= [gs] dl <expression> # [::] delete expr
2857 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 if (DE->isGlobalDelete()) Out << "gs";
2859 Out << (DE->isArrayForm() ? "da" : "dl");
2860 mangleExpression(DE->getArgument());
2861 break;
2862 }
2863
2864 case Expr::UnaryOperatorClass: {
2865 const UnaryOperator *UO = cast<UnaryOperator>(E);
2866 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2867 /*Arity=*/1);
2868 mangleExpression(UO->getSubExpr());
2869 break;
2870 }
2871
2872 case Expr::ArraySubscriptExprClass: {
2873 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2874
2875 // Array subscript is treated as a syntactically weird form of
2876 // binary operator.
2877 Out << "ix";
2878 mangleExpression(AE->getLHS());
2879 mangleExpression(AE->getRHS());
2880 break;
2881 }
2882
2883 case Expr::CompoundAssignOperatorClass: // fallthrough
2884 case Expr::BinaryOperatorClass: {
2885 const BinaryOperator *BO = cast<BinaryOperator>(E);
2886 if (BO->getOpcode() == BO_PtrMemD)
2887 Out << "ds";
2888 else
2889 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2890 /*Arity=*/2);
2891 mangleExpression(BO->getLHS());
2892 mangleExpression(BO->getRHS());
2893 break;
2894 }
2895
2896 case Expr::ConditionalOperatorClass: {
2897 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2898 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2899 mangleExpression(CO->getCond());
2900 mangleExpression(CO->getLHS(), Arity);
2901 mangleExpression(CO->getRHS(), Arity);
2902 break;
2903 }
2904
2905 case Expr::ImplicitCastExprClass: {
2906 ImplicitlyConvertedToType = E->getType();
2907 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2908 goto recurse;
2909 }
2910
2911 case Expr::ObjCBridgedCastExprClass: {
2912 // Mangle ownership casts as a vendor extended operator __bridge,
2913 // __bridge_transfer, or __bridge_retain.
2914 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2915 Out << "v1U" << Kind.size() << Kind;
2916 }
2917 // Fall through to mangle the cast itself.
2918
2919 case Expr::CStyleCastExprClass:
2920 case Expr::CXXStaticCastExprClass:
2921 case Expr::CXXDynamicCastExprClass:
2922 case Expr::CXXReinterpretCastExprClass:
2923 case Expr::CXXConstCastExprClass:
2924 case Expr::CXXFunctionalCastExprClass: {
2925 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2926 Out << "cv";
2927 mangleType(ECE->getType());
2928 mangleExpression(ECE->getSubExpr());
2929 break;
2930 }
2931
2932 case Expr::CXXOperatorCallExprClass: {
2933 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2934 unsigned NumArgs = CE->getNumArgs();
2935 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2936 // Mangle the arguments.
2937 for (unsigned i = 0; i != NumArgs; ++i)
2938 mangleExpression(CE->getArg(i));
2939 break;
2940 }
2941
2942 case Expr::ParenExprClass:
2943 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2944 break;
2945
2946 case Expr::DeclRefExprClass: {
2947 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2948
2949 switch (D->getKind()) {
2950 default:
2951 // <expr-primary> ::= L <mangled-name> E # external name
2952 Out << 'L';
2953 mangle(D, "_Z");
2954 Out << 'E';
2955 break;
2956
2957 case Decl::ParmVar:
2958 mangleFunctionParam(cast<ParmVarDecl>(D));
2959 break;
2960
2961 case Decl::EnumConstant: {
2962 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2963 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2964 break;
2965 }
2966
2967 case Decl::NonTypeTemplateParm: {
2968 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2969 mangleTemplateParameter(PD->getIndex());
2970 break;
2971 }
2972
2973 }
2974
2975 break;
2976 }
2977
2978 case Expr::SubstNonTypeTemplateParmPackExprClass:
2979 // FIXME: not clear how to mangle this!
2980 // template <unsigned N...> class A {
2981 // template <class U...> void foo(U (&x)[N]...);
2982 // };
2983 Out << "_SUBSTPACK_";
2984 break;
2985
2986 case Expr::FunctionParmPackExprClass: {
2987 // FIXME: not clear how to mangle this!
2988 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
2989 Out << "v110_SUBSTPACK";
2990 mangleFunctionParam(FPPE->getParameterPack());
2991 break;
2992 }
2993
2994 case Expr::DependentScopeDeclRefExprClass: {
2995 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2996 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2997
2998 // All the <unresolved-name> productions end in a
2999 // base-unresolved-name, where <template-args> are just tacked
3000 // onto the end.
3001 if (DRE->hasExplicitTemplateArgs())
3002 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3003 break;
3004 }
3005
3006 case Expr::CXXBindTemporaryExprClass:
3007 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3008 break;
3009
3010 case Expr::ExprWithCleanupsClass:
3011 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3012 break;
3013
3014 case Expr::FloatingLiteralClass: {
3015 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3016 Out << 'L';
3017 mangleType(FL->getType());
3018 mangleFloat(FL->getValue());
3019 Out << 'E';
3020 break;
3021 }
3022
3023 case Expr::CharacterLiteralClass:
3024 Out << 'L';
3025 mangleType(E->getType());
3026 Out << cast<CharacterLiteral>(E)->getValue();
3027 Out << 'E';
3028 break;
3029
3030 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3031 case Expr::ObjCBoolLiteralExprClass:
3032 Out << "Lb";
3033 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3034 Out << 'E';
3035 break;
3036
3037 case Expr::CXXBoolLiteralExprClass:
3038 Out << "Lb";
3039 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3040 Out << 'E';
3041 break;
3042
3043 case Expr::IntegerLiteralClass: {
3044 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3045 if (E->getType()->isSignedIntegerType())
3046 Value.setIsSigned(true);
3047 mangleIntegerLiteral(E->getType(), Value);
3048 break;
3049 }
3050
3051 case Expr::ImaginaryLiteralClass: {
3052 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3053 // Mangle as if a complex literal.
3054 // Proposal from David Vandevoorde, 2010.06.30.
3055 Out << 'L';
3056 mangleType(E->getType());
3057 if (const FloatingLiteral *Imag =
3058 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3059 // Mangle a floating-point zero of the appropriate type.
3060 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3061 Out << '_';
3062 mangleFloat(Imag->getValue());
3063 } else {
3064 Out << "0_";
3065 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3066 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3067 Value.setIsSigned(true);
3068 mangleNumber(Value);
3069 }
3070 Out << 'E';
3071 break;
3072 }
3073
3074 case Expr::StringLiteralClass: {
3075 // Revised proposal from David Vandervoorde, 2010.07.15.
3076 Out << 'L';
3077 assert(isa<ConstantArrayType>(E->getType()));
3078 mangleType(E->getType());
3079 Out << 'E';
3080 break;
3081 }
3082
3083 case Expr::GNUNullExprClass:
3084 // FIXME: should this really be mangled the same as nullptr?
3085 // fallthrough
3086
3087 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 Out << "LDnE";
3089 break;
3090 }
3091
3092 case Expr::PackExpansionExprClass:
3093 Out << "sp";
3094 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3095 break;
3096
3097 case Expr::SizeOfPackExprClass: {
3098 Out << "sZ";
3099 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3100 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3101 mangleTemplateParameter(TTP->getIndex());
3102 else if (const NonTypeTemplateParmDecl *NTTP
3103 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3104 mangleTemplateParameter(NTTP->getIndex());
3105 else if (const TemplateTemplateParmDecl *TempTP
3106 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3107 mangleTemplateParameter(TempTP->getIndex());
3108 else
3109 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3110 break;
3111 }
3112
3113 case Expr::MaterializeTemporaryExprClass: {
3114 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3115 break;
3116 }
3117
3118 case Expr::CXXThisExprClass:
3119 Out << "fpT";
3120 break;
3121 }
3122}
3123
3124/// Mangle an expression which refers to a parameter variable.
3125///
3126/// <expression> ::= <function-param>
3127/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3128/// <function-param> ::= fp <top-level CV-qualifiers>
3129/// <parameter-2 non-negative number> _ # L == 0, I > 0
3130/// <function-param> ::= fL <L-1 non-negative number>
3131/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3132/// <function-param> ::= fL <L-1 non-negative number>
3133/// p <top-level CV-qualifiers>
3134/// <I-1 non-negative number> _ # L > 0, I > 0
3135///
3136/// L is the nesting depth of the parameter, defined as 1 if the
3137/// parameter comes from the innermost function prototype scope
3138/// enclosing the current context, 2 if from the next enclosing
3139/// function prototype scope, and so on, with one special case: if
3140/// we've processed the full parameter clause for the innermost
3141/// function type, then L is one less. This definition conveniently
3142/// makes it irrelevant whether a function's result type was written
3143/// trailing or leading, but is otherwise overly complicated; the
3144/// numbering was first designed without considering references to
3145/// parameter in locations other than return types, and then the
3146/// mangling had to be generalized without changing the existing
3147/// manglings.
3148///
3149/// I is the zero-based index of the parameter within its parameter
3150/// declaration clause. Note that the original ABI document describes
3151/// this using 1-based ordinals.
3152void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3153 unsigned parmDepth = parm->getFunctionScopeDepth();
3154 unsigned parmIndex = parm->getFunctionScopeIndex();
3155
3156 // Compute 'L'.
3157 // parmDepth does not include the declaring function prototype.
3158 // FunctionTypeDepth does account for that.
3159 assert(parmDepth < FunctionTypeDepth.getDepth());
3160 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3161 if (FunctionTypeDepth.isInResultType())
3162 nestingDepth--;
3163
3164 if (nestingDepth == 0) {
3165 Out << "fp";
3166 } else {
3167 Out << "fL" << (nestingDepth - 1) << 'p';
3168 }
3169
3170 // Top-level qualifiers. We don't have to worry about arrays here,
3171 // because parameters declared as arrays should already have been
3172 // transformed to have pointer type. FIXME: apparently these don't
3173 // get mangled if used as an rvalue of a known non-class type?
3174 assert(!parm->getType()->isArrayType()
3175 && "parameter's type is still an array type?");
3176 mangleQualifiers(parm->getType().getQualifiers());
3177
3178 // Parameter index.
3179 if (parmIndex != 0) {
3180 Out << (parmIndex - 1);
3181 }
3182 Out << '_';
3183}
3184
3185void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3186 // <ctor-dtor-name> ::= C1 # complete object constructor
3187 // ::= C2 # base object constructor
3188 // ::= C3 # complete object allocating constructor
3189 //
3190 switch (T) {
3191 case Ctor_Complete:
3192 Out << "C1";
3193 break;
3194 case Ctor_Base:
3195 Out << "C2";
3196 break;
3197 case Ctor_CompleteAllocating:
3198 Out << "C3";
3199 break;
3200 }
3201}
3202
3203void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3204 // <ctor-dtor-name> ::= D0 # deleting destructor
3205 // ::= D1 # complete object destructor
3206 // ::= D2 # base object destructor
3207 //
3208 switch (T) {
3209 case Dtor_Deleting:
3210 Out << "D0";
3211 break;
3212 case Dtor_Complete:
3213 Out << "D1";
3214 break;
3215 case Dtor_Base:
3216 Out << "D2";
3217 break;
3218 }
3219}
3220
3221void CXXNameMangler::mangleTemplateArgs(
3222 const ASTTemplateArgumentListInfo &TemplateArgs) {
3223 // <template-args> ::= I <template-arg>+ E
3224 Out << 'I';
3225 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3226 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3227 Out << 'E';
3228}
3229
3230void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3231 // <template-args> ::= I <template-arg>+ E
3232 Out << 'I';
3233 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3234 mangleTemplateArg(AL[i]);
3235 Out << 'E';
3236}
3237
3238void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3239 unsigned NumTemplateArgs) {
3240 // <template-args> ::= I <template-arg>+ E
3241 Out << 'I';
3242 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3243 mangleTemplateArg(TemplateArgs[i]);
3244 Out << 'E';
3245}
3246
3247void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3248 // <template-arg> ::= <type> # type or template
3249 // ::= X <expression> E # expression
3250 // ::= <expr-primary> # simple expressions
3251 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 if (!A.isInstantiationDependent() || A.isDependent())
3253 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3254
3255 switch (A.getKind()) {
3256 case TemplateArgument::Null:
3257 llvm_unreachable("Cannot mangle NULL template argument");
3258
3259 case TemplateArgument::Type:
3260 mangleType(A.getAsType());
3261 break;
3262 case TemplateArgument::Template:
3263 // This is mangled as <type>.
3264 mangleType(A.getAsTemplate());
3265 break;
3266 case TemplateArgument::TemplateExpansion:
3267 // <type> ::= Dp <type> # pack expansion (C++0x)
3268 Out << "Dp";
3269 mangleType(A.getAsTemplateOrTemplatePattern());
3270 break;
3271 case TemplateArgument::Expression: {
3272 // It's possible to end up with a DeclRefExpr here in certain
3273 // dependent cases, in which case we should mangle as a
3274 // declaration.
3275 const Expr *E = A.getAsExpr()->IgnoreParens();
3276 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3277 const ValueDecl *D = DRE->getDecl();
3278 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3279 Out << "L";
3280 mangle(D, "_Z");
3281 Out << 'E';
3282 break;
3283 }
3284 }
3285
3286 Out << 'X';
3287 mangleExpression(E);
3288 Out << 'E';
3289 break;
3290 }
3291 case TemplateArgument::Integral:
3292 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3293 break;
3294 case TemplateArgument::Declaration: {
3295 // <expr-primary> ::= L <mangled-name> E # external name
3296 // Clang produces AST's where pointer-to-member-function expressions
3297 // and pointer-to-function expressions are represented as a declaration not
3298 // an expression. We compensate for it here to produce the correct mangling.
3299 ValueDecl *D = A.getAsDecl();
3300 bool compensateMangling = !A.isDeclForReferenceParam();
3301 if (compensateMangling) {
3302 Out << 'X';
3303 mangleOperatorName(OO_Amp, 1);
3304 }
3305
3306 Out << 'L';
3307 // References to external entities use the mangled name; if the name would
3308 // not normally be manged then mangle it as unqualified.
3309 //
3310 // FIXME: The ABI specifies that external names here should have _Z, but
3311 // gcc leaves this off.
3312 if (compensateMangling)
3313 mangle(D, "_Z");
3314 else
3315 mangle(D, "Z");
3316 Out << 'E';
3317
3318 if (compensateMangling)
3319 Out << 'E';
3320
3321 break;
3322 }
3323 case TemplateArgument::NullPtr: {
3324 // <expr-primary> ::= L <type> 0 E
3325 Out << 'L';
3326 mangleType(A.getNullPtrType());
3327 Out << "0E";
3328 break;
3329 }
3330 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003331 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 Out << 'J';
Richard Smitheb0133c2013-08-27 01:03:46 +00003333 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 PAEnd = A.pack_end();
3335 PA != PAEnd; ++PA)
3336 mangleTemplateArg(*PA);
3337 Out << 'E';
3338 }
3339 }
3340}
3341
3342void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3343 // <template-param> ::= T_ # first template parameter
3344 // ::= T <parameter-2 non-negative number> _
3345 if (Index == 0)
3346 Out << "T_";
3347 else
3348 Out << 'T' << (Index - 1) << '_';
3349}
3350
3351void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3352 bool result = mangleSubstitution(type);
3353 assert(result && "no existing substitution for type");
3354 (void) result;
3355}
3356
3357void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3358 bool result = mangleSubstitution(tname);
3359 assert(result && "no existing substitution for template name");
3360 (void) result;
3361}
3362
3363// <substitution> ::= S <seq-id> _
3364// ::= S_
3365bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3366 // Try one of the standard substitutions first.
3367 if (mangleStandardSubstitution(ND))
3368 return true;
3369
3370 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3371 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3372}
3373
3374/// \brief Determine whether the given type has any qualifiers that are
3375/// relevant for substitutions.
3376static bool hasMangledSubstitutionQualifiers(QualType T) {
3377 Qualifiers Qs = T.getQualifiers();
3378 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3379}
3380
3381bool CXXNameMangler::mangleSubstitution(QualType T) {
3382 if (!hasMangledSubstitutionQualifiers(T)) {
3383 if (const RecordType *RT = T->getAs<RecordType>())
3384 return mangleSubstitution(RT->getDecl());
3385 }
3386
3387 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3388
3389 return mangleSubstitution(TypePtr);
3390}
3391
3392bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3393 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3394 return mangleSubstitution(TD);
3395
3396 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3397 return mangleSubstitution(
3398 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3399}
3400
3401bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3402 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3403 if (I == Substitutions.end())
3404 return false;
3405
3406 unsigned SeqID = I->second;
3407 if (SeqID == 0)
3408 Out << "S_";
3409 else {
3410 SeqID--;
3411
3412 // <seq-id> is encoded in base-36, using digits and upper case letters.
3413 char Buffer[10];
3414 char *BufferPtr = llvm::array_endof(Buffer);
3415
3416 if (SeqID == 0) *--BufferPtr = '0';
3417
3418 while (SeqID) {
3419 assert(BufferPtr > Buffer && "Buffer overflow!");
3420
3421 char c = static_cast<char>(SeqID % 36);
3422
3423 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3424 SeqID /= 36;
3425 }
3426
3427 Out << 'S'
3428 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3429 << '_';
3430 }
3431
3432 return true;
3433}
3434
3435static bool isCharType(QualType T) {
3436 if (T.isNull())
3437 return false;
3438
3439 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3440 T->isSpecificBuiltinType(BuiltinType::Char_U);
3441}
3442
3443/// isCharSpecialization - Returns whether a given type is a template
3444/// specialization of a given name with a single argument of type char.
3445static bool isCharSpecialization(QualType T, const char *Name) {
3446 if (T.isNull())
3447 return false;
3448
3449 const RecordType *RT = T->getAs<RecordType>();
3450 if (!RT)
3451 return false;
3452
3453 const ClassTemplateSpecializationDecl *SD =
3454 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3455 if (!SD)
3456 return false;
3457
3458 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3459 return false;
3460
3461 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3462 if (TemplateArgs.size() != 1)
3463 return false;
3464
3465 if (!isCharType(TemplateArgs[0].getAsType()))
3466 return false;
3467
3468 return SD->getIdentifier()->getName() == Name;
3469}
3470
3471template <std::size_t StrLen>
3472static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3473 const char (&Str)[StrLen]) {
3474 if (!SD->getIdentifier()->isStr(Str))
3475 return false;
3476
3477 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3478 if (TemplateArgs.size() != 2)
3479 return false;
3480
3481 if (!isCharType(TemplateArgs[0].getAsType()))
3482 return false;
3483
3484 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3485 return false;
3486
3487 return true;
3488}
3489
3490bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3491 // <substitution> ::= St # ::std::
3492 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3493 if (isStd(NS)) {
3494 Out << "St";
3495 return true;
3496 }
3497 }
3498
3499 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3500 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3501 return false;
3502
3503 // <substitution> ::= Sa # ::std::allocator
3504 if (TD->getIdentifier()->isStr("allocator")) {
3505 Out << "Sa";
3506 return true;
3507 }
3508
3509 // <<substitution> ::= Sb # ::std::basic_string
3510 if (TD->getIdentifier()->isStr("basic_string")) {
3511 Out << "Sb";
3512 return true;
3513 }
3514 }
3515
3516 if (const ClassTemplateSpecializationDecl *SD =
3517 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3518 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3519 return false;
3520
3521 // <substitution> ::= Ss # ::std::basic_string<char,
3522 // ::std::char_traits<char>,
3523 // ::std::allocator<char> >
3524 if (SD->getIdentifier()->isStr("basic_string")) {
3525 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3526
3527 if (TemplateArgs.size() != 3)
3528 return false;
3529
3530 if (!isCharType(TemplateArgs[0].getAsType()))
3531 return false;
3532
3533 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3534 return false;
3535
3536 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3537 return false;
3538
3539 Out << "Ss";
3540 return true;
3541 }
3542
3543 // <substitution> ::= Si # ::std::basic_istream<char,
3544 // ::std::char_traits<char> >
3545 if (isStreamCharSpecialization(SD, "basic_istream")) {
3546 Out << "Si";
3547 return true;
3548 }
3549
3550 // <substitution> ::= So # ::std::basic_ostream<char,
3551 // ::std::char_traits<char> >
3552 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3553 Out << "So";
3554 return true;
3555 }
3556
3557 // <substitution> ::= Sd # ::std::basic_iostream<char,
3558 // ::std::char_traits<char> >
3559 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3560 Out << "Sd";
3561 return true;
3562 }
3563 }
3564 return false;
3565}
3566
3567void CXXNameMangler::addSubstitution(QualType T) {
3568 if (!hasMangledSubstitutionQualifiers(T)) {
3569 if (const RecordType *RT = T->getAs<RecordType>()) {
3570 addSubstitution(RT->getDecl());
3571 return;
3572 }
3573 }
3574
3575 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3576 addSubstitution(TypePtr);
3577}
3578
3579void CXXNameMangler::addSubstitution(TemplateName Template) {
3580 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3581 return addSubstitution(TD);
3582
3583 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3584 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3585}
3586
3587void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3588 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3589 Substitutions[Ptr] = SeqID++;
3590}
3591
3592//
3593
3594/// \brief Mangles the name of the declaration D and emits that name to the
3595/// given output stream.
3596///
3597/// If the declaration D requires a mangled name, this routine will emit that
3598/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3599/// and this routine will return false. In this case, the caller should just
3600/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3601/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003602void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3603 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3605 "Invalid mangleName() call, argument is not a variable or function!");
3606 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3607 "Invalid mangleName() call on 'structor decl!");
3608
3609 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3610 getASTContext().getSourceManager(),
3611 "Mangling declaration");
3612
3613 CXXNameMangler Mangler(*this, Out, D);
3614 return Mangler.mangle(D);
3615}
3616
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003617void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3618 CXXCtorType Type,
3619 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 CXXNameMangler Mangler(*this, Out, D, Type);
3621 Mangler.mangle(D);
3622}
3623
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003624void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3625 CXXDtorType Type,
3626 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 CXXNameMangler Mangler(*this, Out, D, Type);
3628 Mangler.mangle(D);
3629}
3630
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003631void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3632 const ThunkInfo &Thunk,
3633 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 // <special-name> ::= T <call-offset> <base encoding>
3635 // # base is the nominal target function of thunk
3636 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3637 // # base is the nominal target function of thunk
3638 // # first call-offset is 'this' adjustment
3639 // # second call-offset is result adjustment
3640
3641 assert(!isa<CXXDestructorDecl>(MD) &&
3642 "Use mangleCXXDtor for destructor decls!");
3643 CXXNameMangler Mangler(*this, Out);
3644 Mangler.getStream() << "_ZT";
3645 if (!Thunk.Return.isEmpty())
3646 Mangler.getStream() << 'c';
3647
3648 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003649 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3650 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3651
Guy Benyei11169dd2012-12-18 14:30:41 +00003652 // Mangle the return pointer adjustment if there is one.
3653 if (!Thunk.Return.isEmpty())
3654 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003655 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3656
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 Mangler.mangleFunctionEncoding(MD);
3658}
3659
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003660void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3661 const CXXDestructorDecl *DD, CXXDtorType Type,
3662 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 // <special-name> ::= T <call-offset> <base encoding>
3664 // # base is the nominal target function of thunk
3665 CXXNameMangler Mangler(*this, Out, DD, Type);
3666 Mangler.getStream() << "_ZT";
3667
3668 // Mangle the 'this' pointer adjustment.
3669 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003670 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003671
3672 Mangler.mangleFunctionEncoding(DD);
3673}
3674
3675/// mangleGuardVariable - Returns the mangled name for a guard variable
3676/// for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003677void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3678 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 // <special-name> ::= GV <object name> # Guard variable for one-time
3680 // # initialization
3681 CXXNameMangler Mangler(*this, Out);
3682 Mangler.getStream() << "_ZGV";
3683 Mangler.mangleName(D);
3684}
3685
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003686void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3687 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003688 // These symbols are internal in the Itanium ABI, so the names don't matter.
3689 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3690 // avoid duplicate symbols.
3691 Out << "__cxx_global_var_init";
3692}
3693
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003694void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3695 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003696 // Prefix the mangling of D with __dtor_.
3697 CXXNameMangler Mangler(*this, Out);
3698 Mangler.getStream() << "__dtor_";
3699 if (shouldMangleDeclName(D))
3700 Mangler.mangle(D);
3701 else
3702 Mangler.getStream() << D->getName();
3703}
3704
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003705void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3706 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003707 // <special-name> ::= TH <object name>
3708 CXXNameMangler Mangler(*this, Out);
3709 Mangler.getStream() << "_ZTH";
3710 Mangler.mangleName(D);
3711}
3712
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003713void
3714ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3715 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003716 // <special-name> ::= TW <object name>
3717 CXXNameMangler Mangler(*this, Out);
3718 Mangler.getStream() << "_ZTW";
3719 Mangler.mangleName(D);
3720}
3721
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003722void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
3723 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 // We match the GCC mangling here.
3725 // <special-name> ::= GR <object name>
3726 CXXNameMangler Mangler(*this, Out);
3727 Mangler.getStream() << "_ZGR";
3728 Mangler.mangleName(D);
3729}
3730
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003731void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
3732 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 // <special-name> ::= TV <type> # virtual table
3734 CXXNameMangler Mangler(*this, Out);
3735 Mangler.getStream() << "_ZTV";
3736 Mangler.mangleNameOrStandardSubstitution(RD);
3737}
3738
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003739void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
3740 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 // <special-name> ::= TT <type> # VTT structure
3742 CXXNameMangler Mangler(*this, Out);
3743 Mangler.getStream() << "_ZTT";
3744 Mangler.mangleNameOrStandardSubstitution(RD);
3745}
3746
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003747void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3748 int64_t Offset,
3749 const CXXRecordDecl *Type,
3750 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 // <special-name> ::= TC <type> <offset number> _ <base type>
3752 CXXNameMangler Mangler(*this, Out);
3753 Mangler.getStream() << "_ZTC";
3754 Mangler.mangleNameOrStandardSubstitution(RD);
3755 Mangler.getStream() << Offset;
3756 Mangler.getStream() << '_';
3757 Mangler.mangleNameOrStandardSubstitution(Type);
3758}
3759
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003760void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 // <special-name> ::= TI <type> # typeinfo structure
3762 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3763 CXXNameMangler Mangler(*this, Out);
3764 Mangler.getStream() << "_ZTI";
3765 Mangler.mangleType(Ty);
3766}
3767
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003768void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
3769 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3771 CXXNameMangler Mangler(*this, Out);
3772 Mangler.getStream() << "_ZTS";
3773 Mangler.mangleType(Ty);
3774}
3775
Reid Klecknercc99e262013-11-19 23:23:00 +00003776void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
3777 mangleCXXRTTIName(Ty, Out);
3778}
3779
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003780ItaniumMangleContext *
3781ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3782 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00003783}