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