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