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