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