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