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