blob: fdb256434f6820a3a7a07e406403af52d3265372 [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;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000120
Guy Benyei11169dd2012-12-18 14:30:41 +0000121public:
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;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000159 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
160 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
162 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
163 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000164
David Majnemer58e5bee2014-03-24 21:43:36 +0000165 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
166
Guy Benyei11169dd2012-12-18 14:30:41 +0000167 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000168 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000169 if (isLambda(ND))
170 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000171
172 // Anonymous tags are already numbered.
173 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
174 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
175 return false;
176 }
177
178 // Use the canonical number for externally visible decls.
179 if (ND->isExternallyVisible()) {
180 unsigned discriminator = getASTContext().getManglingNumber(ND);
181 if (discriminator == 1)
182 return false;
183 disc = discriminator - 2;
184 return true;
185 }
186
187 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000189 if (!discriminator) {
190 const DeclContext *DC = getEffectiveDeclContext(ND);
191 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
192 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 if (discriminator == 1)
194 return false;
195 disc = discriminator-2;
196 return true;
197 }
198 /// @}
199};
200
201/// CXXNameMangler - Manage the mangling of a single name.
202class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000203 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000204 raw_ostream &Out;
205
206 /// The "structor" is the top-level declaration being mangled, if
207 /// that's not a template specialization; otherwise it's the pattern
208 /// for that specialization.
209 const NamedDecl *Structor;
210 unsigned StructorType;
211
212 /// SeqID - The next subsitution sequence number.
213 unsigned SeqID;
214
215 class FunctionTypeDepthState {
216 unsigned Bits;
217
218 enum { InResultTypeMask = 1 };
219
220 public:
221 FunctionTypeDepthState() : Bits(0) {}
222
223 /// The number of function types we're inside.
224 unsigned getDepth() const {
225 return Bits >> 1;
226 }
227
228 /// True if we're in the return type of the innermost function type.
229 bool isInResultType() const {
230 return Bits & InResultTypeMask;
231 }
232
233 FunctionTypeDepthState push() {
234 FunctionTypeDepthState tmp = *this;
235 Bits = (Bits & ~InResultTypeMask) + 2;
236 return tmp;
237 }
238
239 void enterResultType() {
240 Bits |= InResultTypeMask;
241 }
242
243 void leaveResultType() {
244 Bits &= ~InResultTypeMask;
245 }
246
247 void pop(FunctionTypeDepthState saved) {
248 assert(getDepth() == saved.getDepth() + 1);
249 Bits = saved.Bits;
250 }
251
252 } FunctionTypeDepth;
253
254 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
255
256 ASTContext &getASTContext() const { return Context.getASTContext(); }
257
258public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000259 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000260 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000261 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
262 SeqID(0) {
263 // These can't be mangled without a ctor type or dtor type.
264 assert(!D || (!isa<CXXDestructorDecl>(D) &&
265 !isa<CXXConstructorDecl>(D)));
266 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000267 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000268 const CXXConstructorDecl *D, CXXCtorType Type)
269 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
270 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000271 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000272 const CXXDestructorDecl *D, CXXDtorType Type)
273 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
274 SeqID(0) { }
275
276#if MANGLE_CHECKER
277 ~CXXNameMangler() {
278 if (Out.str()[0] == '\01')
279 return;
280
281 int status = 0;
282 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
283 assert(status == 0 && "Could not demangle mangled name!");
284 free(result);
285 }
286#endif
287 raw_ostream &getStream() { return Out; }
288
289 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
290 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
291 void mangleNumber(const llvm::APSInt &I);
292 void mangleNumber(int64_t Number);
293 void mangleFloat(const llvm::APFloat &F);
294 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000295 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 void mangleName(const NamedDecl *ND);
297 void mangleType(QualType T);
298 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
299
300private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000301
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 bool mangleSubstitution(const NamedDecl *ND);
303 bool mangleSubstitution(QualType T);
304 bool mangleSubstitution(TemplateName Template);
305 bool mangleSubstitution(uintptr_t Ptr);
306
307 void mangleExistingSubstitution(QualType type);
308 void mangleExistingSubstitution(TemplateName name);
309
310 bool mangleStandardSubstitution(const NamedDecl *ND);
311
312 void addSubstitution(const NamedDecl *ND) {
313 ND = cast<NamedDecl>(ND->getCanonicalDecl());
314
315 addSubstitution(reinterpret_cast<uintptr_t>(ND));
316 }
317 void addSubstitution(QualType T);
318 void addSubstitution(TemplateName Template);
319 void addSubstitution(uintptr_t Ptr);
320
321 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
322 NamedDecl *firstQualifierLookup,
323 bool recursive = false);
324 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
325 NamedDecl *firstQualifierLookup,
326 DeclarationName name,
327 unsigned KnownArity = UnknownArity);
328
329 void mangleName(const TemplateDecl *TD,
330 const TemplateArgument *TemplateArgs,
331 unsigned NumTemplateArgs);
332 void mangleUnqualifiedName(const NamedDecl *ND) {
333 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
334 }
335 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
336 unsigned KnownArity);
337 void mangleUnscopedName(const NamedDecl *ND);
338 void mangleUnscopedTemplateName(const TemplateDecl *ND);
339 void mangleUnscopedTemplateName(TemplateName);
340 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000341 void mangleLocalName(const Decl *D);
342 void mangleBlockForPrefix(const BlockDecl *Block);
343 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000344 void mangleLambda(const CXXRecordDecl *Lambda);
345 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
346 bool NoFunction=false);
347 void mangleNestedName(const TemplateDecl *TD,
348 const TemplateArgument *TemplateArgs,
349 unsigned NumTemplateArgs);
350 void manglePrefix(NestedNameSpecifier *qualifier);
351 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
352 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000353 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 void mangleTemplatePrefix(TemplateName Template);
355 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
356 void mangleQualifiers(Qualifiers Quals);
357 void mangleRefQualifier(RefQualifierKind RefQualifier);
358
359 void mangleObjCMethodName(const ObjCMethodDecl *MD);
360
361 // Declare manglers for every type class.
362#define ABSTRACT_TYPE(CLASS, PARENT)
363#define NON_CANONICAL_TYPE(CLASS, PARENT)
364#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
365#include "clang/AST/TypeNodes.def"
366
367 void mangleType(const TagType*);
368 void mangleType(TemplateName);
369 void mangleBareFunctionType(const FunctionType *T,
370 bool MangleReturnType);
371 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000372 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000373
374 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000375 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000376 void mangleMemberExpr(const Expr *base, bool isArrow,
377 NestedNameSpecifier *qualifier,
378 NamedDecl *firstQualifierLookup,
379 DeclarationName name,
380 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000381 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000382 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
384 void mangleCXXCtorType(CXXCtorType T);
385 void mangleCXXDtorType(CXXDtorType T);
386
387 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
388 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
389 unsigned NumTemplateArgs);
390 void mangleTemplateArgs(const TemplateArgumentList &AL);
391 void mangleTemplateArg(TemplateArgument A);
392
393 void mangleTemplateParameter(unsigned Index);
394
395 void mangleFunctionParam(const ParmVarDecl *parm);
396};
397
398}
399
Rafael Espindola002667c2013-10-16 01:40:34 +0000400bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000401 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000402 if (FD) {
403 LanguageLinkage L = FD->getLanguageLinkage();
404 // Overloadable functions need mangling.
405 if (FD->hasAttr<OverloadableAttr>())
406 return true;
407
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000408 // "main" is not mangled.
409 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000410 return false;
411
412 // C++ functions and those whose names are not a simple identifier need
413 // mangling.
414 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
415 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000416
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000417 // C functions are not mangled.
418 if (L == CLanguageLinkage)
419 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000420 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000421
422 // Otherwise, no mangling is done outside C++ mode.
423 if (!getASTContext().getLangOpts().CPlusPlus)
424 return false;
425
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000426 const VarDecl *VD = dyn_cast<VarDecl>(D);
427 if (VD) {
428 // C variables are not mangled.
429 if (VD->isExternC())
430 return false;
431
432 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 const DeclContext *DC = getEffectiveDeclContext(D);
434 // Check for extern variable declared locally.
435 if (DC->isFunctionOrMethod() && D->hasLinkage())
436 while (!DC->isNamespace() && !DC->isTranslationUnit())
437 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000438 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
439 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 return false;
441 }
442
Guy Benyei11169dd2012-12-18 14:30:41 +0000443 return true;
444}
445
446void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 // <mangled-name> ::= _Z <encoding>
448 // ::= <data name>
449 // ::= <special-name>
450 Out << Prefix;
451 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
452 mangleFunctionEncoding(FD);
453 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
454 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000455 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
456 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 else
458 mangleName(cast<FieldDecl>(D));
459}
460
461void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
462 // <encoding> ::= <function name> <bare-function-type>
463 mangleName(FD);
464
465 // Don't mangle in the type if this isn't a decl we should typically mangle.
466 if (!Context.shouldMangleDeclName(FD))
467 return;
468
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000469 if (FD->hasAttr<EnableIfAttr>()) {
470 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
471 Out << "Ua9enable_ifI";
472 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
473 // it here.
474 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
475 E = FD->getAttrs().rend();
476 I != E; ++I) {
477 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
478 if (!EIA)
479 continue;
480 Out << 'X';
481 mangleExpression(EIA->getCond());
482 Out << 'E';
483 }
484 Out << 'E';
485 FunctionTypeDepth.pop(Saved);
486 }
487
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Whether the mangling of a function type includes the return type depends on
489 // the context and the nature of the function. The rules for deciding whether
490 // the return type is included are:
491 //
492 // 1. Template functions (names or types) have return types encoded, with
493 // the exceptions listed below.
494 // 2. Function types not appearing as part of a function name mangling,
495 // e.g. parameters, pointer types, etc., have return type encoded, with the
496 // exceptions listed below.
497 // 3. Non-template function names do not have return types encoded.
498 //
499 // The exceptions mentioned in (1) and (2) above, for which the return type is
500 // never included, are
501 // 1. Constructors.
502 // 2. Destructors.
503 // 3. Conversion operator functions, e.g. operator int.
504 bool MangleReturnType = false;
505 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
506 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
507 isa<CXXConversionDecl>(FD)))
508 MangleReturnType = true;
509
510 // Mangle the type of the primary template.
511 FD = PrimaryTemplate->getTemplatedDecl();
512 }
513
514 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
515 MangleReturnType);
516}
517
518static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
519 while (isa<LinkageSpecDecl>(DC)) {
520 DC = getEffectiveParentContext(DC);
521 }
522
523 return DC;
524}
525
526/// isStd - Return whether a given namespace is the 'std' namespace.
527static bool isStd(const NamespaceDecl *NS) {
528 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
529 ->isTranslationUnit())
530 return false;
531
532 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
533 return II && II->isStr("std");
534}
535
536// isStdNamespace - Return whether a given decl context is a toplevel 'std'
537// namespace.
538static bool isStdNamespace(const DeclContext *DC) {
539 if (!DC->isNamespace())
540 return false;
541
542 return isStd(cast<NamespaceDecl>(DC));
543}
544
545static const TemplateDecl *
546isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
547 // Check if we have a function template.
548 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
549 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
550 TemplateArgs = FD->getTemplateSpecializationArgs();
551 return TD;
552 }
553 }
554
555 // Check if we have a class template.
556 if (const ClassTemplateSpecializationDecl *Spec =
557 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
558 TemplateArgs = &Spec->getTemplateArgs();
559 return Spec->getSpecializedTemplate();
560 }
561
Larisse Voufo39a1e502013-08-06 01:03:05 +0000562 // Check if we have a variable template.
563 if (const VarTemplateSpecializationDecl *Spec =
564 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
565 TemplateArgs = &Spec->getTemplateArgs();
566 return Spec->getSpecializedTemplate();
567 }
568
Craig Topper36250ad2014-05-12 05:36:57 +0000569 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000570}
571
Guy Benyei11169dd2012-12-18 14:30:41 +0000572void CXXNameMangler::mangleName(const NamedDecl *ND) {
573 // <name> ::= <nested-name>
574 // ::= <unscoped-name>
575 // ::= <unscoped-template-name> <template-args>
576 // ::= <local-name>
577 //
578 const DeclContext *DC = getEffectiveDeclContext(ND);
579
580 // If this is an extern variable declared locally, the relevant DeclContext
581 // is that of the containing namespace, or the translation unit.
582 // FIXME: This is a hack; extern variables declared locally should have
583 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000584 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000585 while (!DC->isNamespace() && !DC->isTranslationUnit())
586 DC = getEffectiveParentContext(DC);
587 else if (GetLocalClassDecl(ND)) {
588 mangleLocalName(ND);
589 return;
590 }
591
592 DC = IgnoreLinkageSpecDecls(DC);
593
594 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
595 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000596 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000597 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
598 mangleUnscopedTemplateName(TD);
599 mangleTemplateArgs(*TemplateArgs);
600 return;
601 }
602
603 mangleUnscopedName(ND);
604 return;
605 }
606
Eli Friedman95f50122013-07-02 17:52:28 +0000607 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 mangleLocalName(ND);
609 return;
610 }
611
612 mangleNestedName(ND, DC);
613}
614void CXXNameMangler::mangleName(const TemplateDecl *TD,
615 const TemplateArgument *TemplateArgs,
616 unsigned NumTemplateArgs) {
617 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
618
619 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
620 mangleUnscopedTemplateName(TD);
621 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
622 } else {
623 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
624 }
625}
626
627void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
628 // <unscoped-name> ::= <unqualified-name>
629 // ::= St <unqualified-name> # ::std::
630
631 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
632 Out << "St";
633
634 mangleUnqualifiedName(ND);
635}
636
637void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
638 // <unscoped-template-name> ::= <unscoped-name>
639 // ::= <substitution>
640 if (mangleSubstitution(ND))
641 return;
642
643 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000644 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000646 else
647 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000648
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 addSubstitution(ND);
650}
651
652void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
653 // <unscoped-template-name> ::= <unscoped-name>
654 // ::= <substitution>
655 if (TemplateDecl *TD = Template.getAsTemplateDecl())
656 return mangleUnscopedTemplateName(TD);
657
658 if (mangleSubstitution(Template))
659 return;
660
661 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
662 assert(Dependent && "Not a dependent template name?");
663 if (const IdentifierInfo *Id = Dependent->getIdentifier())
664 mangleSourceName(Id);
665 else
666 mangleOperatorName(Dependent->getOperator(), UnknownArity);
667
668 addSubstitution(Template);
669}
670
671void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
672 // ABI:
673 // Floating-point literals are encoded using a fixed-length
674 // lowercase hexadecimal string corresponding to the internal
675 // representation (IEEE on Itanium), high-order bytes first,
676 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
677 // on Itanium.
678 // The 'without leading zeroes' thing seems to be an editorial
679 // mistake; see the discussion on cxx-abi-dev beginning on
680 // 2012-01-16.
681
682 // Our requirements here are just barely weird enough to justify
683 // using a custom algorithm instead of post-processing APInt::toString().
684
685 llvm::APInt valueBits = f.bitcastToAPInt();
686 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
687 assert(numCharacters != 0);
688
689 // Allocate a buffer of the right number of characters.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000690 SmallVector<char, 20> buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 buffer.set_size(numCharacters);
692
693 // Fill the buffer left-to-right.
694 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
695 // The bit-index of the next hex digit.
696 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
697
698 // Project out 4 bits starting at 'digitIndex'.
699 llvm::integerPart hexDigit
700 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
701 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
702 hexDigit &= 0xF;
703
704 // Map that over to a lowercase hex digit.
705 static const char charForHex[16] = {
706 '0', '1', '2', '3', '4', '5', '6', '7',
707 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
708 };
709 buffer[stringIndex] = charForHex[hexDigit];
710 }
711
712 Out.write(buffer.data(), numCharacters);
713}
714
715void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
716 if (Value.isSigned() && Value.isNegative()) {
717 Out << 'n';
718 Value.abs().print(Out, /*signed*/ false);
719 } else {
720 Value.print(Out, /*signed*/ false);
721 }
722}
723
724void CXXNameMangler::mangleNumber(int64_t Number) {
725 // <number> ::= [n] <non-negative decimal integer>
726 if (Number < 0) {
727 Out << 'n';
728 Number = -Number;
729 }
730
731 Out << Number;
732}
733
734void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
735 // <call-offset> ::= h <nv-offset> _
736 // ::= v <v-offset> _
737 // <nv-offset> ::= <offset number> # non-virtual base override
738 // <v-offset> ::= <offset number> _ <virtual offset number>
739 // # virtual base override, with vcall offset
740 if (!Virtual) {
741 Out << 'h';
742 mangleNumber(NonVirtual);
743 Out << '_';
744 return;
745 }
746
747 Out << 'v';
748 mangleNumber(NonVirtual);
749 Out << '_';
750 mangleNumber(Virtual);
751 Out << '_';
752}
753
754void CXXNameMangler::manglePrefix(QualType type) {
755 if (const TemplateSpecializationType *TST =
756 type->getAs<TemplateSpecializationType>()) {
757 if (!mangleSubstitution(QualType(TST, 0))) {
758 mangleTemplatePrefix(TST->getTemplateName());
759
760 // FIXME: GCC does not appear to mangle the template arguments when
761 // the template in question is a dependent template name. Should we
762 // emulate that badness?
763 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
764 addSubstitution(QualType(TST, 0));
765 }
766 } else if (const DependentTemplateSpecializationType *DTST
767 = type->getAs<DependentTemplateSpecializationType>()) {
768 TemplateName Template
769 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
770 DTST->getIdentifier());
771 mangleTemplatePrefix(Template);
772
773 // FIXME: GCC does not appear to mangle the template arguments when
774 // the template in question is a dependent template name. Should we
775 // emulate that badness?
776 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
777 } else {
778 // We use the QualType mangle type variant here because it handles
779 // substitutions.
780 mangleType(type);
781 }
782}
783
784/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
785///
786/// \param firstQualifierLookup - the entity found by unqualified lookup
787/// for the first name in the qualifier, if this is for a member expression
788/// \param recursive - true if this is being called recursively,
789/// i.e. if there is more prefix "to the right".
790void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
791 NamedDecl *firstQualifierLookup,
792 bool recursive) {
793
794 // x, ::x
795 // <unresolved-name> ::= [gs] <base-unresolved-name>
796
797 // T::x / decltype(p)::x
798 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
799
800 // T::N::x /decltype(p)::N::x
801 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
802 // <base-unresolved-name>
803
804 // A::x, N::y, A<T>::z; "gs" means leading "::"
805 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
806 // <base-unresolved-name>
807
808 switch (qualifier->getKind()) {
809 case NestedNameSpecifier::Global:
810 Out << "gs";
811
812 // We want an 'sr' unless this is the entire NNS.
813 if (recursive)
814 Out << "sr";
815
816 // We never want an 'E' here.
817 return;
818
Nikola Smiljanic67860242014-09-26 00:28:20 +0000819 case NestedNameSpecifier::Super:
820 llvm_unreachable("Can't mangle __super specifier");
821
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 case NestedNameSpecifier::Namespace:
823 if (qualifier->getPrefix())
824 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
825 /*recursive*/ true);
826 else
827 Out << "sr";
828 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
829 break;
830 case NestedNameSpecifier::NamespaceAlias:
831 if (qualifier->getPrefix())
832 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
833 /*recursive*/ true);
834 else
835 Out << "sr";
836 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
837 break;
838
839 case NestedNameSpecifier::TypeSpec:
840 case NestedNameSpecifier::TypeSpecWithTemplate: {
841 const Type *type = qualifier->getAsType();
842
843 // We only want to use an unresolved-type encoding if this is one of:
844 // - a decltype
845 // - a template type parameter
846 // - a template template parameter with arguments
847 // In all of these cases, we should have no prefix.
848 if (qualifier->getPrefix()) {
849 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
850 /*recursive*/ true);
851 } else {
852 // Otherwise, all the cases want this.
853 Out << "sr";
854 }
855
856 // Only certain other types are valid as prefixes; enumerate them.
857 switch (type->getTypeClass()) {
858 case Type::Builtin:
859 case Type::Complex:
Reid Kleckner0503a872013-12-05 01:23:43 +0000860 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +0000861 case Type::Decayed:
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 case Type::Pointer:
863 case Type::BlockPointer:
864 case Type::LValueReference:
865 case Type::RValueReference:
866 case Type::MemberPointer:
867 case Type::ConstantArray:
868 case Type::IncompleteArray:
869 case Type::VariableArray:
870 case Type::DependentSizedArray:
871 case Type::DependentSizedExtVector:
872 case Type::Vector:
873 case Type::ExtVector:
874 case Type::FunctionProto:
875 case Type::FunctionNoProto:
876 case Type::Enum:
877 case Type::Paren:
878 case Type::Elaborated:
879 case Type::Attributed:
880 case Type::Auto:
881 case Type::PackExpansion:
882 case Type::ObjCObject:
883 case Type::ObjCInterface:
884 case Type::ObjCObjectPointer:
885 case Type::Atomic:
886 llvm_unreachable("type is illegal as a nested name specifier");
887
888 case Type::SubstTemplateTypeParmPack:
889 // FIXME: not clear how to mangle this!
890 // template <class T...> class A {
891 // template <class U...> void foo(decltype(T::foo(U())) x...);
892 // };
893 Out << "_SUBSTPACK_";
894 break;
895
896 // <unresolved-type> ::= <template-param>
897 // ::= <decltype>
898 // ::= <template-template-param> <template-args>
899 // (this last is not official yet)
900 case Type::TypeOfExpr:
901 case Type::TypeOf:
902 case Type::Decltype:
903 case Type::TemplateTypeParm:
904 case Type::UnaryTransform:
905 case Type::SubstTemplateTypeParm:
906 unresolvedType:
907 assert(!qualifier->getPrefix());
908
909 // We only get here recursively if we're followed by identifiers.
910 if (recursive) Out << 'N';
911
912 // This seems to do everything we want. It's not really
913 // sanctioned for a substituted template parameter, though.
914 mangleType(QualType(type, 0));
915
916 // We never want to print 'E' directly after an unresolved-type,
917 // so we return directly.
918 return;
919
920 case Type::Typedef:
921 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
922 break;
923
924 case Type::UnresolvedUsing:
925 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
926 ->getIdentifier());
927 break;
928
929 case Type::Record:
930 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
931 break;
932
933 case Type::TemplateSpecialization: {
934 const TemplateSpecializationType *tst
935 = cast<TemplateSpecializationType>(type);
936 TemplateName name = tst->getTemplateName();
937 switch (name.getKind()) {
938 case TemplateName::Template:
939 case TemplateName::QualifiedTemplate: {
940 TemplateDecl *temp = name.getAsTemplateDecl();
941
942 // If the base is a template template parameter, this is an
943 // unresolved type.
944 assert(temp && "no template for template specialization type");
945 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
946
947 mangleSourceName(temp->getIdentifier());
948 break;
949 }
950
951 case TemplateName::OverloadedTemplate:
952 case TemplateName::DependentTemplate:
953 llvm_unreachable("invalid base for a template specialization type");
954
955 case TemplateName::SubstTemplateTemplateParm: {
956 SubstTemplateTemplateParmStorage *subst
957 = name.getAsSubstTemplateTemplateParm();
958 mangleExistingSubstitution(subst->getReplacement());
959 break;
960 }
961
962 case TemplateName::SubstTemplateTemplateParmPack: {
963 // FIXME: not clear how to mangle this!
964 // template <template <class U> class T...> class A {
965 // template <class U...> void foo(decltype(T<U>::foo) x...);
966 // };
967 Out << "_SUBSTPACK_";
968 break;
969 }
970 }
971
972 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
973 break;
974 }
975
976 case Type::InjectedClassName:
977 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
978 ->getIdentifier());
979 break;
980
981 case Type::DependentName:
982 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
983 break;
984
985 case Type::DependentTemplateSpecialization: {
986 const DependentTemplateSpecializationType *tst
987 = cast<DependentTemplateSpecializationType>(type);
988 mangleSourceName(tst->getIdentifier());
989 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
990 break;
991 }
992 }
993 break;
994 }
995
996 case NestedNameSpecifier::Identifier:
997 // Member expressions can have these without prefixes.
998 if (qualifier->getPrefix()) {
999 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
1000 /*recursive*/ true);
1001 } else if (firstQualifierLookup) {
1002
1003 // Try to make a proper qualifier out of the lookup result, and
1004 // then just recurse on that.
1005 NestedNameSpecifier *newQualifier;
1006 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
1007 QualType type = getASTContext().getTypeDeclType(typeDecl);
1008
1009 // Pretend we had a different nested name specifier.
1010 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001011 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001012 /*template*/ false,
1013 type.getTypePtr());
1014 } else if (NamespaceDecl *nspace =
1015 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
1016 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001017 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 nspace);
1019 } else if (NamespaceAliasDecl *alias =
1020 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
1021 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001022 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 alias);
1024 } else {
1025 // No sensible mangling to do here.
Craig Topper36250ad2014-05-12 05:36:57 +00001026 newQualifier = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 }
1028
1029 if (newQualifier)
Craig Topper36250ad2014-05-12 05:36:57 +00001030 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
1031 recursive);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032
1033 } else {
1034 Out << "sr";
1035 }
1036
1037 mangleSourceName(qualifier->getAsIdentifier());
1038 break;
1039 }
1040
1041 // If this was the innermost part of the NNS, and we fell out to
1042 // here, append an 'E'.
1043 if (!recursive)
1044 Out << 'E';
1045}
1046
1047/// Mangle an unresolved-name, which is generally used for names which
1048/// weren't resolved to specific entities.
1049void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1050 NamedDecl *firstQualifierLookup,
1051 DeclarationName name,
1052 unsigned knownArity) {
1053 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001054 switch (name.getNameKind()) {
1055 // <base-unresolved-name> ::= <simple-id>
1056 case DeclarationName::Identifier:
1057 break;
1058 // <base-unresolved-name> ::= on <operator-name>
1059 case DeclarationName::CXXConversionFunctionName:
1060 case DeclarationName::CXXLiteralOperatorName:
1061 case DeclarationName::CXXOperatorName:
1062 Out << "on";
1063 break;
1064 case DeclarationName::CXXDestructorName:
1065 llvm_unreachable("Can't mangle a constructor name!");
1066 case DeclarationName::CXXConstructorName:
1067 llvm_unreachable("Can't mangle a constructor name!");
1068 case DeclarationName::CXXUsingDirective:
1069 llvm_unreachable("Can't mangle a using directive name!");
1070 case DeclarationName::ObjCMultiArgSelector:
1071 case DeclarationName::ObjCOneArgSelector:
1072 case DeclarationName::ObjCZeroArgSelector:
1073 llvm_unreachable("Can't mangle Objective-C selector names here!");
1074 }
Craig Topper36250ad2014-05-12 05:36:57 +00001075 mangleUnqualifiedName(nullptr, name, knownArity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001076}
1077
Guy Benyei11169dd2012-12-18 14:30:41 +00001078void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1079 DeclarationName Name,
1080 unsigned KnownArity) {
1081 // <unqualified-name> ::= <operator-name>
1082 // ::= <ctor-dtor-name>
1083 // ::= <source-name>
1084 switch (Name.getNameKind()) {
1085 case DeclarationName::Identifier: {
1086 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1087 // We must avoid conflicts between internally- and externally-
1088 // linked variable and function declaration names in the same TU:
1089 // void test() { extern void foo(); }
1090 // static void foo();
1091 // This naming convention is the same as that followed by GCC,
1092 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001093 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 getEffectiveDeclContext(ND)->isFileContext())
1095 Out << 'L';
1096
1097 mangleSourceName(II);
1098 break;
1099 }
1100
1101 // Otherwise, an anonymous entity. We must have a declaration.
1102 assert(ND && "mangling empty name without declaration");
1103
1104 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1105 if (NS->isAnonymousNamespace()) {
1106 // This is how gcc mangles these names.
1107 Out << "12_GLOBAL__N_1";
1108 break;
1109 }
1110 }
1111
1112 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1113 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001114 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001116
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 // Itanium C++ ABI 5.1.2:
1118 //
1119 // For the purposes of mangling, the name of an anonymous union is
1120 // considered to be the name of the first named data member found by a
1121 // pre-order, depth-first, declaration-order walk of the data members of
1122 // the anonymous union. If there is no such data member (i.e., if all of
1123 // the data members in the union are unnamed), then there is no way for
1124 // a program to refer to the anonymous union, and there is therefore no
1125 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001126 assert(RD->isAnonymousStructOrUnion()
1127 && "Expected anonymous struct or union!");
1128 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001129
1130 // It's actually possible for various reasons for us to get here
1131 // with an empty anonymous struct / union. Fortunately, it
1132 // doesn't really matter what name we generate.
1133 if (!FD) break;
1134 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001135
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 mangleSourceName(FD->getIdentifier());
1137 break;
1138 }
John McCall924046f2013-04-10 06:08:21 +00001139
1140 // Class extensions have no name as a category, and it's possible
1141 // for them to be the semantic parent of certain declarations
1142 // (primarily, tag decls defined within declarations). Such
1143 // declarations will always have internal linkage, so the name
1144 // doesn't really matter, but we shouldn't crash on them. For
1145 // safety, just handle all ObjC containers here.
1146 if (isa<ObjCContainerDecl>(ND))
1147 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001148
1149 // We must have an anonymous struct.
1150 const TagDecl *TD = cast<TagDecl>(ND);
1151 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1152 assert(TD->getDeclContext() == D->getDeclContext() &&
1153 "Typedef should not be in another decl context!");
1154 assert(D->getDeclName().getAsIdentifierInfo() &&
1155 "Typedef was not named!");
1156 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1157 break;
1158 }
1159
1160 // <unnamed-type-name> ::= <closure-type-name>
1161 //
1162 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1163 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1164 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1165 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1166 mangleLambda(Record);
1167 break;
1168 }
1169 }
1170
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001171 if (TD->isExternallyVisible()) {
1172 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001174 if (UnnamedMangle > 1)
1175 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 Out << '_';
1177 break;
1178 }
1179
1180 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001181 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001182
1183 // Mangle it as a source name in the form
1184 // [n] $_<id>
1185 // where n is the length of the string.
1186 SmallString<8> Str;
1187 Str += "$_";
1188 Str += llvm::utostr(AnonStructId);
1189
1190 Out << Str.size();
1191 Out << Str.str();
1192 break;
1193 }
1194
1195 case DeclarationName::ObjCZeroArgSelector:
1196 case DeclarationName::ObjCOneArgSelector:
1197 case DeclarationName::ObjCMultiArgSelector:
1198 llvm_unreachable("Can't mangle Objective-C selector names here!");
1199
1200 case DeclarationName::CXXConstructorName:
1201 if (ND == Structor)
1202 // If the named decl is the C++ constructor we're mangling, use the type
1203 // we were given.
1204 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1205 else
1206 // Otherwise, use the complete constructor name. This is relevant if a
1207 // class with a constructor is declared within a constructor.
1208 mangleCXXCtorType(Ctor_Complete);
1209 break;
1210
1211 case DeclarationName::CXXDestructorName:
1212 if (ND == Structor)
1213 // If the named decl is the C++ destructor we're mangling, use the type we
1214 // were given.
1215 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1216 else
1217 // Otherwise, use the complete destructor name. This is relevant if a
1218 // class with a destructor is declared within a destructor.
1219 mangleCXXDtorType(Dtor_Complete);
1220 break;
1221
1222 case DeclarationName::CXXConversionFunctionName:
1223 // <operator-name> ::= cv <type> # (cast)
1224 Out << "cv";
1225 mangleType(Name.getCXXNameType());
1226 break;
1227
1228 case DeclarationName::CXXOperatorName: {
1229 unsigned Arity;
1230 if (ND) {
1231 Arity = cast<FunctionDecl>(ND)->getNumParams();
1232
1233 // If we have a C++ member function, we need to include the 'this' pointer.
1234 // FIXME: This does not make sense for operators that are static, but their
1235 // names stay the same regardless of the arity (operator new for instance).
1236 if (isa<CXXMethodDecl>(ND))
1237 Arity++;
1238 } else
1239 Arity = KnownArity;
1240
1241 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1242 break;
1243 }
1244
1245 case DeclarationName::CXXLiteralOperatorName:
1246 // FIXME: This mangling is not yet official.
1247 Out << "li";
1248 mangleSourceName(Name.getCXXLiteralIdentifier());
1249 break;
1250
1251 case DeclarationName::CXXUsingDirective:
1252 llvm_unreachable("Can't mangle a using directive name!");
1253 }
1254}
1255
1256void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1257 // <source-name> ::= <positive length number> <identifier>
1258 // <number> ::= [n] <non-negative decimal integer>
1259 // <identifier> ::= <unqualified source code identifier>
1260 Out << II->getLength() << II->getName();
1261}
1262
1263void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1264 const DeclContext *DC,
1265 bool NoFunction) {
1266 // <nested-name>
1267 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1268 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1269 // <template-args> E
1270
1271 Out << 'N';
1272 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001273 Qualifiers MethodQuals =
1274 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1275 // We do not consider restrict a distinguishing attribute for overloading
1276 // purposes so we must not mangle it.
1277 MethodQuals.removeRestrict();
1278 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001279 mangleRefQualifier(Method->getRefQualifier());
1280 }
1281
1282 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001283 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001285 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 mangleTemplateArgs(*TemplateArgs);
1287 }
1288 else {
1289 manglePrefix(DC, NoFunction);
1290 mangleUnqualifiedName(ND);
1291 }
1292
1293 Out << 'E';
1294}
1295void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1296 const TemplateArgument *TemplateArgs,
1297 unsigned NumTemplateArgs) {
1298 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1299
1300 Out << 'N';
1301
1302 mangleTemplatePrefix(TD);
1303 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1304
1305 Out << 'E';
1306}
1307
Eli Friedman95f50122013-07-02 17:52:28 +00001308void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1310 // := Z <function encoding> E s [<discriminator>]
1311 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1312 // _ <entity name>
1313 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001314 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001315 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001316 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001317
1318 Out << 'Z';
1319
Eli Friedman92821742013-07-02 02:01:18 +00001320 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1321 mangleObjCMethodName(MD);
1322 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001323 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001324 else
1325 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001326
Eli Friedman92821742013-07-02 02:01:18 +00001327 Out << 'E';
1328
1329 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 // The parameter number is omitted for the last parameter, 0 for the
1331 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1332 // <entity name> will of course contain a <closure-type-name>: Its
1333 // numbering will be local to the particular argument in which it appears
1334 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001335 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1336 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001338 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001339 if (const FunctionDecl *Func
1340 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1341 Out << 'd';
1342 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1343 if (Num > 1)
1344 mangleNumber(Num - 2);
1345 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 }
1347 }
1348 }
1349
1350 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001351 // equality ok because RD derived from ND above
1352 if (D == RD) {
1353 mangleUnqualifiedName(RD);
1354 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1355 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1356 mangleUnqualifiedBlock(BD);
1357 } else {
1358 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001359 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001360 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001361 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1362 // Mangle a block in a default parameter; see above explanation for
1363 // lambdas.
1364 if (const ParmVarDecl *Parm
1365 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1366 if (const FunctionDecl *Func
1367 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1368 Out << 'd';
1369 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1370 if (Num > 1)
1371 mangleNumber(Num - 2);
1372 Out << '_';
1373 }
1374 }
1375
1376 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001377 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001378 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001380
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001381 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1382 unsigned disc;
1383 if (Context.getNextDiscriminator(ND, disc)) {
1384 if (disc < 10)
1385 Out << '_' << disc;
1386 else
1387 Out << "__" << disc << '_';
1388 }
1389 }
Eli Friedman95f50122013-07-02 17:52:28 +00001390}
1391
1392void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1393 if (GetLocalClassDecl(Block)) {
1394 mangleLocalName(Block);
1395 return;
1396 }
1397 const DeclContext *DC = getEffectiveDeclContext(Block);
1398 if (isLocalContainerContext(DC)) {
1399 mangleLocalName(Block);
1400 return;
1401 }
1402 manglePrefix(getEffectiveDeclContext(Block));
1403 mangleUnqualifiedBlock(Block);
1404}
1405
1406void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1407 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1408 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1409 Context->getDeclContext()->isRecord()) {
1410 if (const IdentifierInfo *Name
1411 = cast<NamedDecl>(Context)->getIdentifier()) {
1412 mangleSourceName(Name);
1413 Out << 'M';
1414 }
1415 }
1416 }
1417
1418 // If we have a block mangling number, use it.
1419 unsigned Number = Block->getBlockManglingNumber();
1420 // Otherwise, just make up a number. It doesn't matter what it is because
1421 // the symbol in question isn't externally visible.
1422 if (!Number)
1423 Number = Context.getBlockId(Block, false);
1424 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001425 if (Number > 0)
1426 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001427 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001428}
1429
1430void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1431 // If the context of a closure type is an initializer for a class member
1432 // (static or nonstatic), it is encoded in a qualified name with a final
1433 // <prefix> of the form:
1434 //
1435 // <data-member-prefix> := <member source-name> M
1436 //
1437 // Technically, the data-member-prefix is part of the <prefix>. However,
1438 // since a closure type will always be mangled with a prefix, it's easier
1439 // to emit that last part of the prefix here.
1440 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1441 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1442 Context->getDeclContext()->isRecord()) {
1443 if (const IdentifierInfo *Name
1444 = cast<NamedDecl>(Context)->getIdentifier()) {
1445 mangleSourceName(Name);
1446 Out << 'M';
1447 }
1448 }
1449 }
1450
1451 Out << "Ul";
1452 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1453 getAs<FunctionProtoType>();
1454 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1455 Out << "E";
1456
1457 // The number is omitted for the first closure type with a given
1458 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1459 // (in lexical order) with that same <lambda-sig> and context.
1460 //
1461 // The AST keeps track of the number for us.
1462 unsigned Number = Lambda->getLambdaManglingNumber();
1463 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1464 if (Number > 1)
1465 mangleNumber(Number - 2);
1466 Out << '_';
1467}
1468
1469void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1470 switch (qualifier->getKind()) {
1471 case NestedNameSpecifier::Global:
1472 // nothing
1473 return;
1474
Nikola Smiljanic67860242014-09-26 00:28:20 +00001475 case NestedNameSpecifier::Super:
1476 llvm_unreachable("Can't mangle __super specifier");
1477
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 case NestedNameSpecifier::Namespace:
1479 mangleName(qualifier->getAsNamespace());
1480 return;
1481
1482 case NestedNameSpecifier::NamespaceAlias:
1483 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1484 return;
1485
1486 case NestedNameSpecifier::TypeSpec:
1487 case NestedNameSpecifier::TypeSpecWithTemplate:
1488 manglePrefix(QualType(qualifier->getAsType(), 0));
1489 return;
1490
1491 case NestedNameSpecifier::Identifier:
1492 // Member expressions can have these without prefixes, but that
1493 // should end up in mangleUnresolvedPrefix instead.
1494 assert(qualifier->getPrefix());
1495 manglePrefix(qualifier->getPrefix());
1496
1497 mangleSourceName(qualifier->getAsIdentifier());
1498 return;
1499 }
1500
1501 llvm_unreachable("unexpected nested name specifier");
1502}
1503
1504void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1505 // <prefix> ::= <prefix> <unqualified-name>
1506 // ::= <template-prefix> <template-args>
1507 // ::= <template-param>
1508 // ::= # empty
1509 // ::= <substitution>
1510
1511 DC = IgnoreLinkageSpecDecls(DC);
1512
1513 if (DC->isTranslationUnit())
1514 return;
1515
Eli Friedman95f50122013-07-02 17:52:28 +00001516 if (NoFunction && isLocalContainerContext(DC))
1517 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001518
Eli Friedman95f50122013-07-02 17:52:28 +00001519 assert(!isLocalContainerContext(DC));
1520
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 const NamedDecl *ND = cast<NamedDecl>(DC);
1522 if (mangleSubstitution(ND))
1523 return;
1524
1525 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001526 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1528 mangleTemplatePrefix(TD);
1529 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001530 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1532 mangleUnqualifiedName(ND);
1533 }
1534
1535 addSubstitution(ND);
1536}
1537
1538void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1539 // <template-prefix> ::= <prefix> <template unqualified-name>
1540 // ::= <template-param>
1541 // ::= <substitution>
1542 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1543 return mangleTemplatePrefix(TD);
1544
1545 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1546 manglePrefix(Qualified->getQualifier());
1547
1548 if (OverloadedTemplateStorage *Overloaded
1549 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001550 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 UnknownArity);
1552 return;
1553 }
1554
1555 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1556 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001557 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1558 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001559 mangleUnscopedTemplateName(Template);
1560}
1561
Eli Friedman86af13f02013-07-05 18:41:30 +00001562void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1563 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 // <template-prefix> ::= <prefix> <template unqualified-name>
1565 // ::= <template-param>
1566 // ::= <substitution>
1567 // <template-template-param> ::= <template-param>
1568 // <substitution>
1569
1570 if (mangleSubstitution(ND))
1571 return;
1572
1573 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001574 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001576 } else {
1577 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1578 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 }
1580
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 addSubstitution(ND);
1582}
1583
1584/// Mangles a template name under the production <type>. Required for
1585/// template template arguments.
1586/// <type> ::= <class-enum-type>
1587/// ::= <template-param>
1588/// ::= <substitution>
1589void CXXNameMangler::mangleType(TemplateName TN) {
1590 if (mangleSubstitution(TN))
1591 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001592
1593 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594
1595 switch (TN.getKind()) {
1596 case TemplateName::QualifiedTemplate:
1597 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1598 goto HaveDecl;
1599
1600 case TemplateName::Template:
1601 TD = TN.getAsTemplateDecl();
1602 goto HaveDecl;
1603
1604 HaveDecl:
1605 if (isa<TemplateTemplateParmDecl>(TD))
1606 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1607 else
1608 mangleName(TD);
1609 break;
1610
1611 case TemplateName::OverloadedTemplate:
1612 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1613
1614 case TemplateName::DependentTemplate: {
1615 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1616 assert(Dependent->isIdentifier());
1617
1618 // <class-enum-type> ::= <name>
1619 // <name> ::= <nested-name>
Craig Topper36250ad2014-05-12 05:36:57 +00001620 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 mangleSourceName(Dependent->getIdentifier());
1622 break;
1623 }
1624
1625 case TemplateName::SubstTemplateTemplateParm: {
1626 // Substituted template parameters are mangled as the substituted
1627 // template. This will check for the substitution twice, which is
1628 // fine, but we have to return early so that we don't try to *add*
1629 // the substitution twice.
1630 SubstTemplateTemplateParmStorage *subst
1631 = TN.getAsSubstTemplateTemplateParm();
1632 mangleType(subst->getReplacement());
1633 return;
1634 }
1635
1636 case TemplateName::SubstTemplateTemplateParmPack: {
1637 // FIXME: not clear how to mangle this!
1638 // template <template <class> class T...> class A {
1639 // template <template <class> class U...> void foo(B<T,U> x...);
1640 // };
1641 Out << "_SUBSTPACK_";
1642 break;
1643 }
1644 }
1645
1646 addSubstitution(TN);
1647}
1648
1649void
1650CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1651 switch (OO) {
1652 // <operator-name> ::= nw # new
1653 case OO_New: Out << "nw"; break;
1654 // ::= na # new[]
1655 case OO_Array_New: Out << "na"; break;
1656 // ::= dl # delete
1657 case OO_Delete: Out << "dl"; break;
1658 // ::= da # delete[]
1659 case OO_Array_Delete: Out << "da"; break;
1660 // ::= ps # + (unary)
1661 // ::= pl # + (binary or unknown)
1662 case OO_Plus:
1663 Out << (Arity == 1? "ps" : "pl"); break;
1664 // ::= ng # - (unary)
1665 // ::= mi # - (binary or unknown)
1666 case OO_Minus:
1667 Out << (Arity == 1? "ng" : "mi"); break;
1668 // ::= ad # & (unary)
1669 // ::= an # & (binary or unknown)
1670 case OO_Amp:
1671 Out << (Arity == 1? "ad" : "an"); break;
1672 // ::= de # * (unary)
1673 // ::= ml # * (binary or unknown)
1674 case OO_Star:
1675 // Use binary when unknown.
1676 Out << (Arity == 1? "de" : "ml"); break;
1677 // ::= co # ~
1678 case OO_Tilde: Out << "co"; break;
1679 // ::= dv # /
1680 case OO_Slash: Out << "dv"; break;
1681 // ::= rm # %
1682 case OO_Percent: Out << "rm"; break;
1683 // ::= or # |
1684 case OO_Pipe: Out << "or"; break;
1685 // ::= eo # ^
1686 case OO_Caret: Out << "eo"; break;
1687 // ::= aS # =
1688 case OO_Equal: Out << "aS"; break;
1689 // ::= pL # +=
1690 case OO_PlusEqual: Out << "pL"; break;
1691 // ::= mI # -=
1692 case OO_MinusEqual: Out << "mI"; break;
1693 // ::= mL # *=
1694 case OO_StarEqual: Out << "mL"; break;
1695 // ::= dV # /=
1696 case OO_SlashEqual: Out << "dV"; break;
1697 // ::= rM # %=
1698 case OO_PercentEqual: Out << "rM"; break;
1699 // ::= aN # &=
1700 case OO_AmpEqual: Out << "aN"; break;
1701 // ::= oR # |=
1702 case OO_PipeEqual: Out << "oR"; break;
1703 // ::= eO # ^=
1704 case OO_CaretEqual: Out << "eO"; break;
1705 // ::= ls # <<
1706 case OO_LessLess: Out << "ls"; break;
1707 // ::= rs # >>
1708 case OO_GreaterGreater: Out << "rs"; break;
1709 // ::= lS # <<=
1710 case OO_LessLessEqual: Out << "lS"; break;
1711 // ::= rS # >>=
1712 case OO_GreaterGreaterEqual: Out << "rS"; break;
1713 // ::= eq # ==
1714 case OO_EqualEqual: Out << "eq"; break;
1715 // ::= ne # !=
1716 case OO_ExclaimEqual: Out << "ne"; break;
1717 // ::= lt # <
1718 case OO_Less: Out << "lt"; break;
1719 // ::= gt # >
1720 case OO_Greater: Out << "gt"; break;
1721 // ::= le # <=
1722 case OO_LessEqual: Out << "le"; break;
1723 // ::= ge # >=
1724 case OO_GreaterEqual: Out << "ge"; break;
1725 // ::= nt # !
1726 case OO_Exclaim: Out << "nt"; break;
1727 // ::= aa # &&
1728 case OO_AmpAmp: Out << "aa"; break;
1729 // ::= oo # ||
1730 case OO_PipePipe: Out << "oo"; break;
1731 // ::= pp # ++
1732 case OO_PlusPlus: Out << "pp"; break;
1733 // ::= mm # --
1734 case OO_MinusMinus: Out << "mm"; break;
1735 // ::= cm # ,
1736 case OO_Comma: Out << "cm"; break;
1737 // ::= pm # ->*
1738 case OO_ArrowStar: Out << "pm"; break;
1739 // ::= pt # ->
1740 case OO_Arrow: Out << "pt"; break;
1741 // ::= cl # ()
1742 case OO_Call: Out << "cl"; break;
1743 // ::= ix # []
1744 case OO_Subscript: Out << "ix"; break;
1745
1746 // ::= qu # ?
1747 // The conditional operator can't be overloaded, but we still handle it when
1748 // mangling expressions.
1749 case OO_Conditional: Out << "qu"; break;
1750
1751 case OO_None:
1752 case NUM_OVERLOADED_OPERATORS:
1753 llvm_unreachable("Not an overloaded operator");
1754 }
1755}
1756
1757void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1758 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1759 if (Quals.hasRestrict())
1760 Out << 'r';
1761 if (Quals.hasVolatile())
1762 Out << 'V';
1763 if (Quals.hasConst())
1764 Out << 'K';
1765
1766 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001767 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 //
David Tweed31d09b02013-09-13 12:04:22 +00001769 // <type> ::= U <target-addrspace>
1770 // <type> ::= U <OpenCL-addrspace>
1771 // <type> ::= U <CUDA-addrspace>
1772
Guy Benyei11169dd2012-12-18 14:30:41 +00001773 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001774 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001775
1776 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1777 // <target-addrspace> ::= "AS" <address-space-number>
1778 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1779 ASString = "AS" + llvm::utostr_32(TargetAS);
1780 } else {
1781 switch (AS) {
1782 default: llvm_unreachable("Not a language specific address space");
1783 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1784 case LangAS::opencl_global: ASString = "CLglobal"; break;
1785 case LangAS::opencl_local: ASString = "CLlocal"; break;
1786 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1787 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1788 case LangAS::cuda_device: ASString = "CUdevice"; break;
1789 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1790 case LangAS::cuda_shared: ASString = "CUshared"; break;
1791 }
1792 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 Out << 'U' << ASString.size() << ASString;
1794 }
1795
1796 StringRef LifetimeName;
1797 switch (Quals.getObjCLifetime()) {
1798 // Objective-C ARC Extension:
1799 //
1800 // <type> ::= U "__strong"
1801 // <type> ::= U "__weak"
1802 // <type> ::= U "__autoreleasing"
1803 case Qualifiers::OCL_None:
1804 break;
1805
1806 case Qualifiers::OCL_Weak:
1807 LifetimeName = "__weak";
1808 break;
1809
1810 case Qualifiers::OCL_Strong:
1811 LifetimeName = "__strong";
1812 break;
1813
1814 case Qualifiers::OCL_Autoreleasing:
1815 LifetimeName = "__autoreleasing";
1816 break;
1817
1818 case Qualifiers::OCL_ExplicitNone:
1819 // The __unsafe_unretained qualifier is *not* mangled, so that
1820 // __unsafe_unretained types in ARC produce the same manglings as the
1821 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1822 // better ABI compatibility.
1823 //
1824 // It's safe to do this because unqualified 'id' won't show up
1825 // in any type signatures that need to be mangled.
1826 break;
1827 }
1828 if (!LifetimeName.empty())
1829 Out << 'U' << LifetimeName.size() << LifetimeName;
1830}
1831
1832void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1833 // <ref-qualifier> ::= R # lvalue reference
1834 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 switch (RefQualifier) {
1836 case RQ_None:
1837 break;
1838
1839 case RQ_LValue:
1840 Out << 'R';
1841 break;
1842
1843 case RQ_RValue:
1844 Out << 'O';
1845 break;
1846 }
1847}
1848
1849void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1850 Context.mangleObjCMethodName(MD, Out);
1851}
1852
David Majnemereea02ee2014-11-28 22:22:46 +00001853static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1854 if (Quals)
1855 return true;
1856 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1857 return true;
1858 if (Ty->isOpenCLSpecificType())
1859 return true;
1860 if (Ty->isBuiltinType())
1861 return false;
1862
1863 return true;
1864}
1865
Guy Benyei11169dd2012-12-18 14:30:41 +00001866void CXXNameMangler::mangleType(QualType T) {
1867 // If our type is instantiation-dependent but not dependent, we mangle
1868 // it as it was written in the source, removing any top-level sugar.
1869 // Otherwise, use the canonical type.
1870 //
1871 // FIXME: This is an approximation of the instantiation-dependent name
1872 // mangling rules, since we should really be using the type as written and
1873 // augmented via semantic analysis (i.e., with implicit conversions and
1874 // default template arguments) for any instantiation-dependent type.
1875 // Unfortunately, that requires several changes to our AST:
1876 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1877 // uniqued, so that we can handle substitutions properly
1878 // - Default template arguments will need to be represented in the
1879 // TemplateSpecializationType, since they need to be mangled even though
1880 // they aren't written.
1881 // - Conversions on non-type template arguments need to be expressed, since
1882 // they can affect the mangling of sizeof/alignof.
1883 if (!T->isInstantiationDependentType() || T->isDependentType())
1884 T = T.getCanonicalType();
1885 else {
1886 // Desugar any types that are purely sugar.
1887 do {
1888 // Don't desugar through template specialization types that aren't
1889 // type aliases. We need to mangle the template arguments as written.
1890 if (const TemplateSpecializationType *TST
1891 = dyn_cast<TemplateSpecializationType>(T))
1892 if (!TST->isTypeAlias())
1893 break;
1894
1895 QualType Desugared
1896 = T.getSingleStepDesugaredType(Context.getASTContext());
1897 if (Desugared == T)
1898 break;
1899
1900 T = Desugared;
1901 } while (true);
1902 }
1903 SplitQualType split = T.split();
1904 Qualifiers quals = split.Quals;
1905 const Type *ty = split.Ty;
1906
David Majnemereea02ee2014-11-28 22:22:46 +00001907 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 if (isSubstitutable && mangleSubstitution(T))
1909 return;
1910
1911 // If we're mangling a qualified array type, push the qualifiers to
1912 // the element type.
1913 if (quals && isa<ArrayType>(T)) {
1914 ty = Context.getASTContext().getAsArrayType(T);
1915 quals = Qualifiers();
1916
1917 // Note that we don't update T: we want to add the
1918 // substitution at the original type.
1919 }
1920
1921 if (quals) {
1922 mangleQualifiers(quals);
1923 // Recurse: even if the qualified type isn't yet substitutable,
1924 // the unqualified type might be.
1925 mangleType(QualType(ty, 0));
1926 } else {
1927 switch (ty->getTypeClass()) {
1928#define ABSTRACT_TYPE(CLASS, PARENT)
1929#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1930 case Type::CLASS: \
1931 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1932 return;
1933#define TYPE(CLASS, PARENT) \
1934 case Type::CLASS: \
1935 mangleType(static_cast<const CLASS##Type*>(ty)); \
1936 break;
1937#include "clang/AST/TypeNodes.def"
1938 }
1939 }
1940
1941 // Add the substitution.
1942 if (isSubstitutable)
1943 addSubstitution(T);
1944}
1945
1946void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1947 if (!mangleStandardSubstitution(ND))
1948 mangleName(ND);
1949}
1950
1951void CXXNameMangler::mangleType(const BuiltinType *T) {
1952 // <type> ::= <builtin-type>
1953 // <builtin-type> ::= v # void
1954 // ::= w # wchar_t
1955 // ::= b # bool
1956 // ::= c # char
1957 // ::= a # signed char
1958 // ::= h # unsigned char
1959 // ::= s # short
1960 // ::= t # unsigned short
1961 // ::= i # int
1962 // ::= j # unsigned int
1963 // ::= l # long
1964 // ::= m # unsigned long
1965 // ::= x # long long, __int64
1966 // ::= y # unsigned long long, __int64
1967 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001968 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001969 // ::= f # float
1970 // ::= d # double
1971 // ::= e # long double, __float80
1972 // UNSUPPORTED: ::= g # __float128
1973 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1974 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1975 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1976 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1977 // ::= Di # char32_t
1978 // ::= Ds # char16_t
1979 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1980 // ::= u <source-name> # vendor extended type
1981 switch (T->getKind()) {
1982 case BuiltinType::Void: Out << 'v'; break;
1983 case BuiltinType::Bool: Out << 'b'; break;
1984 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1985 case BuiltinType::UChar: Out << 'h'; break;
1986 case BuiltinType::UShort: Out << 't'; break;
1987 case BuiltinType::UInt: Out << 'j'; break;
1988 case BuiltinType::ULong: Out << 'm'; break;
1989 case BuiltinType::ULongLong: Out << 'y'; break;
1990 case BuiltinType::UInt128: Out << 'o'; break;
1991 case BuiltinType::SChar: Out << 'a'; break;
1992 case BuiltinType::WChar_S:
1993 case BuiltinType::WChar_U: Out << 'w'; break;
1994 case BuiltinType::Char16: Out << "Ds"; break;
1995 case BuiltinType::Char32: Out << "Di"; break;
1996 case BuiltinType::Short: Out << 's'; break;
1997 case BuiltinType::Int: Out << 'i'; break;
1998 case BuiltinType::Long: Out << 'l'; break;
1999 case BuiltinType::LongLong: Out << 'x'; break;
2000 case BuiltinType::Int128: Out << 'n'; break;
2001 case BuiltinType::Half: Out << "Dh"; break;
2002 case BuiltinType::Float: Out << 'f'; break;
2003 case BuiltinType::Double: Out << 'd'; break;
2004 case BuiltinType::LongDouble: Out << 'e'; break;
2005 case BuiltinType::NullPtr: Out << "Dn"; break;
2006
2007#define BUILTIN_TYPE(Id, SingletonId)
2008#define PLACEHOLDER_TYPE(Id, SingletonId) \
2009 case BuiltinType::Id:
2010#include "clang/AST/BuiltinTypes.def"
2011 case BuiltinType::Dependent:
2012 llvm_unreachable("mangling a placeholder type");
2013 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2014 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2015 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00002016 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2017 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2018 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2019 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2020 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2021 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00002022 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002023 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 }
2025}
2026
2027// <type> ::= <function-type>
2028// <function-type> ::= [<CV-qualifiers>] F [Y]
2029// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002030void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2031 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2032 // e.g. "const" in "int (A::*)() const".
2033 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2034
2035 Out << 'F';
2036
2037 // FIXME: We don't have enough information in the AST to produce the 'Y'
2038 // encoding for extern "C" function types.
2039 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2040
2041 // Mangle the ref-qualifier, if present.
2042 mangleRefQualifier(T->getRefQualifier());
2043
2044 Out << 'E';
2045}
2046void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2047 llvm_unreachable("Can't mangle K&R function prototypes");
2048}
2049void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2050 bool MangleReturnType) {
2051 // We should never be mangling something without a prototype.
2052 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2053
2054 // Record that we're in a function type. See mangleFunctionParam
2055 // for details on what we're trying to achieve here.
2056 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2057
2058 // <bare-function-type> ::= <signature type>+
2059 if (MangleReturnType) {
2060 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002061 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002062 FunctionTypeDepth.leaveResultType();
2063 }
2064
Alp Toker9cacbab2014-01-20 20:26:09 +00002065 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 // <builtin-type> ::= v # void
2067 Out << 'v';
2068
2069 FunctionTypeDepth.pop(saved);
2070 return;
2071 }
2072
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002073 for (const auto &Arg : Proto->param_types())
2074 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002075
2076 FunctionTypeDepth.pop(saved);
2077
2078 // <builtin-type> ::= z # ellipsis
2079 if (Proto->isVariadic())
2080 Out << 'z';
2081}
2082
2083// <type> ::= <class-enum-type>
2084// <class-enum-type> ::= <name>
2085void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2086 mangleName(T->getDecl());
2087}
2088
2089// <type> ::= <class-enum-type>
2090// <class-enum-type> ::= <name>
2091void CXXNameMangler::mangleType(const EnumType *T) {
2092 mangleType(static_cast<const TagType*>(T));
2093}
2094void CXXNameMangler::mangleType(const RecordType *T) {
2095 mangleType(static_cast<const TagType*>(T));
2096}
2097void CXXNameMangler::mangleType(const TagType *T) {
2098 mangleName(T->getDecl());
2099}
2100
2101// <type> ::= <array-type>
2102// <array-type> ::= A <positive dimension number> _ <element type>
2103// ::= A [<dimension expression>] _ <element type>
2104void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2105 Out << 'A' << T->getSize() << '_';
2106 mangleType(T->getElementType());
2107}
2108void CXXNameMangler::mangleType(const VariableArrayType *T) {
2109 Out << 'A';
2110 // decayed vla types (size 0) will just be skipped.
2111 if (T->getSizeExpr())
2112 mangleExpression(T->getSizeExpr());
2113 Out << '_';
2114 mangleType(T->getElementType());
2115}
2116void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2117 Out << 'A';
2118 mangleExpression(T->getSizeExpr());
2119 Out << '_';
2120 mangleType(T->getElementType());
2121}
2122void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2123 Out << "A_";
2124 mangleType(T->getElementType());
2125}
2126
2127// <type> ::= <pointer-to-member-type>
2128// <pointer-to-member-type> ::= M <class type> <member type>
2129void CXXNameMangler::mangleType(const MemberPointerType *T) {
2130 Out << 'M';
2131 mangleType(QualType(T->getClass(), 0));
2132 QualType PointeeType = T->getPointeeType();
2133 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2134 mangleType(FPT);
2135
2136 // Itanium C++ ABI 5.1.8:
2137 //
2138 // The type of a non-static member function is considered to be different,
2139 // for the purposes of substitution, from the type of a namespace-scope or
2140 // static member function whose type appears similar. The types of two
2141 // non-static member functions are considered to be different, for the
2142 // purposes of substitution, if the functions are members of different
2143 // classes. In other words, for the purposes of substitution, the class of
2144 // which the function is a member is considered part of the type of
2145 // function.
2146
2147 // Given that we already substitute member function pointers as a
2148 // whole, the net effect of this rule is just to unconditionally
2149 // suppress substitution on the function type in a member pointer.
2150 // We increment the SeqID here to emulate adding an entry to the
2151 // substitution table.
2152 ++SeqID;
2153 } else
2154 mangleType(PointeeType);
2155}
2156
2157// <type> ::= <template-param>
2158void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2159 mangleTemplateParameter(T->getIndex());
2160}
2161
2162// <type> ::= <template-param>
2163void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2164 // FIXME: not clear how to mangle this!
2165 // template <class T...> class A {
2166 // template <class U...> void foo(T(*)(U) x...);
2167 // };
2168 Out << "_SUBSTPACK_";
2169}
2170
2171// <type> ::= P <type> # pointer-to
2172void CXXNameMangler::mangleType(const PointerType *T) {
2173 Out << 'P';
2174 mangleType(T->getPointeeType());
2175}
2176void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2177 Out << 'P';
2178 mangleType(T->getPointeeType());
2179}
2180
2181// <type> ::= R <type> # reference-to
2182void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2183 Out << 'R';
2184 mangleType(T->getPointeeType());
2185}
2186
2187// <type> ::= O <type> # rvalue reference-to (C++0x)
2188void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2189 Out << 'O';
2190 mangleType(T->getPointeeType());
2191}
2192
2193// <type> ::= C <type> # complex pair (C 2000)
2194void CXXNameMangler::mangleType(const ComplexType *T) {
2195 Out << 'C';
2196 mangleType(T->getElementType());
2197}
2198
2199// ARM's ABI for Neon vector types specifies that they should be mangled as
2200// if they are structs (to match ARM's initial implementation). The
2201// vector type must be one of the special types predefined by ARM.
2202void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2203 QualType EltType = T->getElementType();
2204 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002205 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002206 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2207 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002208 case BuiltinType::SChar:
2209 case BuiltinType::UChar:
2210 EltName = "poly8_t";
2211 break;
2212 case BuiltinType::Short:
2213 case BuiltinType::UShort:
2214 EltName = "poly16_t";
2215 break;
2216 case BuiltinType::ULongLong:
2217 EltName = "poly64_t";
2218 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2220 }
2221 } else {
2222 switch (cast<BuiltinType>(EltType)->getKind()) {
2223 case BuiltinType::SChar: EltName = "int8_t"; break;
2224 case BuiltinType::UChar: EltName = "uint8_t"; break;
2225 case BuiltinType::Short: EltName = "int16_t"; break;
2226 case BuiltinType::UShort: EltName = "uint16_t"; break;
2227 case BuiltinType::Int: EltName = "int32_t"; break;
2228 case BuiltinType::UInt: EltName = "uint32_t"; break;
2229 case BuiltinType::LongLong: EltName = "int64_t"; break;
2230 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002231 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002233 case BuiltinType::Half: EltName = "float16_t";break;
2234 default:
2235 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 }
2237 }
Craig Topper36250ad2014-05-12 05:36:57 +00002238 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 unsigned BitSize = (T->getNumElements() *
2240 getASTContext().getTypeSize(EltType));
2241 if (BitSize == 64)
2242 BaseName = "__simd64_";
2243 else {
2244 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2245 BaseName = "__simd128_";
2246 }
2247 Out << strlen(BaseName) + strlen(EltName);
2248 Out << BaseName << EltName;
2249}
2250
Tim Northover2fe823a2013-08-01 09:23:19 +00002251static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2252 switch (EltType->getKind()) {
2253 case BuiltinType::SChar:
2254 return "Int8";
2255 case BuiltinType::Short:
2256 return "Int16";
2257 case BuiltinType::Int:
2258 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002259 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002260 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002261 return "Int64";
2262 case BuiltinType::UChar:
2263 return "Uint8";
2264 case BuiltinType::UShort:
2265 return "Uint16";
2266 case BuiltinType::UInt:
2267 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002268 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002269 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002270 return "Uint64";
2271 case BuiltinType::Half:
2272 return "Float16";
2273 case BuiltinType::Float:
2274 return "Float32";
2275 case BuiltinType::Double:
2276 return "Float64";
2277 default:
2278 llvm_unreachable("Unexpected vector element base type");
2279 }
2280}
2281
2282// AArch64's ABI for Neon vector types specifies that they should be mangled as
2283// the equivalent internal name. The vector type must be one of the special
2284// types predefined by ARM.
2285void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2286 QualType EltType = T->getElementType();
2287 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2288 unsigned BitSize =
2289 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002290 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002291
2292 assert((BitSize == 64 || BitSize == 128) &&
2293 "Neon vector type not 64 or 128 bits");
2294
Tim Northover2fe823a2013-08-01 09:23:19 +00002295 StringRef EltName;
2296 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2297 switch (cast<BuiltinType>(EltType)->getKind()) {
2298 case BuiltinType::UChar:
2299 EltName = "Poly8";
2300 break;
2301 case BuiltinType::UShort:
2302 EltName = "Poly16";
2303 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002304 case BuiltinType::ULong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002305 EltName = "Poly64";
2306 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002307 default:
2308 llvm_unreachable("unexpected Neon polynomial vector element type");
2309 }
2310 } else
2311 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2312
2313 std::string TypeName =
2314 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2315 Out << TypeName.length() << TypeName;
2316}
2317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318// GNU extension: vector types
2319// <type> ::= <vector-type>
2320// <vector-type> ::= Dv <positive dimension number> _
2321// <extended element type>
2322// ::= Dv [<dimension expression>] _ <element type>
2323// <extended element type> ::= <element type>
2324// ::= p # AltiVec vector pixel
2325// ::= b # Altivec vector bool
2326void CXXNameMangler::mangleType(const VectorType *T) {
2327 if ((T->getVectorKind() == VectorType::NeonVector ||
2328 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002329 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002330 llvm::Triple::ArchType Arch =
2331 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002332 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002333 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002334 mangleAArch64NeonVectorType(T);
2335 else
2336 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 return;
2338 }
2339 Out << "Dv" << T->getNumElements() << '_';
2340 if (T->getVectorKind() == VectorType::AltiVecPixel)
2341 Out << 'p';
2342 else if (T->getVectorKind() == VectorType::AltiVecBool)
2343 Out << 'b';
2344 else
2345 mangleType(T->getElementType());
2346}
2347void CXXNameMangler::mangleType(const ExtVectorType *T) {
2348 mangleType(static_cast<const VectorType*>(T));
2349}
2350void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2351 Out << "Dv";
2352 mangleExpression(T->getSizeExpr());
2353 Out << '_';
2354 mangleType(T->getElementType());
2355}
2356
2357void CXXNameMangler::mangleType(const PackExpansionType *T) {
2358 // <type> ::= Dp <type> # pack expansion (C++0x)
2359 Out << "Dp";
2360 mangleType(T->getPattern());
2361}
2362
2363void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2364 mangleSourceName(T->getDecl()->getIdentifier());
2365}
2366
2367void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman5f508952013-06-18 22:41:37 +00002368 if (!T->qual_empty()) {
2369 // Mangle protocol qualifiers.
2370 SmallString<64> QualStr;
2371 llvm::raw_svector_ostream QualOS(QualStr);
2372 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002373 for (const auto *I : T->quals()) {
2374 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002375 QualOS << name.size() << name;
2376 }
2377 QualOS.flush();
2378 Out << 'U' << QualStr.size() << QualStr;
2379 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 mangleType(T->getBaseType());
2381}
2382
2383void CXXNameMangler::mangleType(const BlockPointerType *T) {
2384 Out << "U13block_pointer";
2385 mangleType(T->getPointeeType());
2386}
2387
2388void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2389 // Mangle injected class name types as if the user had written the
2390 // specialization out fully. It may not actually be possible to see
2391 // this mangling, though.
2392 mangleType(T->getInjectedSpecializationType());
2393}
2394
2395void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2396 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2397 mangleName(TD, T->getArgs(), T->getNumArgs());
2398 } else {
2399 if (mangleSubstitution(QualType(T, 0)))
2400 return;
2401
2402 mangleTemplatePrefix(T->getTemplateName());
2403
2404 // FIXME: GCC does not appear to mangle the template arguments when
2405 // the template in question is a dependent template name. Should we
2406 // emulate that badness?
2407 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2408 addSubstitution(QualType(T, 0));
2409 }
2410}
2411
2412void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002413 // Proposal by cxx-abi-dev, 2014-03-26
2414 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2415 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002416 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002417 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002418 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002419 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002420 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002421 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002422 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002423 switch (T->getKeyword()) {
2424 case ETK_Typename:
2425 break;
2426 case ETK_Struct:
2427 case ETK_Class:
2428 case ETK_Interface:
2429 Out << "Ts";
2430 break;
2431 case ETK_Union:
2432 Out << "Tu";
2433 break;
2434 case ETK_Enum:
2435 Out << "Te";
2436 break;
2437 default:
2438 llvm_unreachable("unexpected keyword for dependent type name");
2439 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002440 // Typename types are always nested
2441 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002443 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 Out << 'E';
2445}
2446
2447void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2448 // Dependently-scoped template types are nested if they have a prefix.
2449 Out << 'N';
2450
2451 // TODO: avoid making this TemplateName.
2452 TemplateName Prefix =
2453 getASTContext().getDependentTemplateName(T->getQualifier(),
2454 T->getIdentifier());
2455 mangleTemplatePrefix(Prefix);
2456
2457 // FIXME: GCC does not appear to mangle the template arguments when
2458 // the template in question is a dependent template name. Should we
2459 // emulate that badness?
2460 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2461 Out << 'E';
2462}
2463
2464void CXXNameMangler::mangleType(const TypeOfType *T) {
2465 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2466 // "extension with parameters" mangling.
2467 Out << "u6typeof";
2468}
2469
2470void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2471 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2472 // "extension with parameters" mangling.
2473 Out << "u6typeof";
2474}
2475
2476void CXXNameMangler::mangleType(const DecltypeType *T) {
2477 Expr *E = T->getUnderlyingExpr();
2478
2479 // type ::= Dt <expression> E # decltype of an id-expression
2480 // # or class member access
2481 // ::= DT <expression> E # decltype of an expression
2482
2483 // This purports to be an exhaustive list of id-expressions and
2484 // class member accesses. Note that we do not ignore parentheses;
2485 // parentheses change the semantics of decltype for these
2486 // expressions (and cause the mangler to use the other form).
2487 if (isa<DeclRefExpr>(E) ||
2488 isa<MemberExpr>(E) ||
2489 isa<UnresolvedLookupExpr>(E) ||
2490 isa<DependentScopeDeclRefExpr>(E) ||
2491 isa<CXXDependentScopeMemberExpr>(E) ||
2492 isa<UnresolvedMemberExpr>(E))
2493 Out << "Dt";
2494 else
2495 Out << "DT";
2496 mangleExpression(E);
2497 Out << 'E';
2498}
2499
2500void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2501 // If this is dependent, we need to record that. If not, we simply
2502 // mangle it as the underlying type since they are equivalent.
2503 if (T->isDependentType()) {
2504 Out << 'U';
2505
2506 switch (T->getUTTKind()) {
2507 case UnaryTransformType::EnumUnderlyingType:
2508 Out << "3eut";
2509 break;
2510 }
2511 }
2512
2513 mangleType(T->getUnderlyingType());
2514}
2515
2516void CXXNameMangler::mangleType(const AutoType *T) {
2517 QualType D = T->getDeducedType();
2518 // <builtin-type> ::= Da # dependent auto
2519 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002520 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 else
2522 mangleType(D);
2523}
2524
2525void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002526 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 // (Until there's a standardized mangling...)
2528 Out << "U7_Atomic";
2529 mangleType(T->getValueType());
2530}
2531
2532void CXXNameMangler::mangleIntegerLiteral(QualType T,
2533 const llvm::APSInt &Value) {
2534 // <expr-primary> ::= L <type> <value number> E # integer literal
2535 Out << 'L';
2536
2537 mangleType(T);
2538 if (T->isBooleanType()) {
2539 // Boolean values are encoded as 0/1.
2540 Out << (Value.getBoolValue() ? '1' : '0');
2541 } else {
2542 mangleNumber(Value);
2543 }
2544 Out << 'E';
2545
2546}
2547
David Majnemer1dabfdc2015-02-14 13:23:54 +00002548void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2549 // Ignore member expressions involving anonymous unions.
2550 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2551 if (!RT->getDecl()->isAnonymousStructOrUnion())
2552 break;
2553 const auto *ME = dyn_cast<MemberExpr>(Base);
2554 if (!ME)
2555 break;
2556 Base = ME->getBase();
2557 IsArrow = ME->isArrow();
2558 }
2559
2560 if (Base->isImplicitCXXThis()) {
2561 // Note: GCC mangles member expressions to the implicit 'this' as
2562 // *this., whereas we represent them as this->. The Itanium C++ ABI
2563 // does not specify anything here, so we follow GCC.
2564 Out << "dtdefpT";
2565 } else {
2566 Out << (IsArrow ? "pt" : "dt");
2567 mangleExpression(Base);
2568 }
2569}
2570
Guy Benyei11169dd2012-12-18 14:30:41 +00002571/// Mangles a member expression.
2572void CXXNameMangler::mangleMemberExpr(const Expr *base,
2573 bool isArrow,
2574 NestedNameSpecifier *qualifier,
2575 NamedDecl *firstQualifierLookup,
2576 DeclarationName member,
2577 unsigned arity) {
2578 // <expression> ::= dt <expression> <unresolved-name>
2579 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002580 if (base)
2581 mangleMemberExprBase(base, isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2583}
2584
2585/// Look at the callee of the given call expression and determine if
2586/// it's a parenthesized id-expression which would have triggered ADL
2587/// otherwise.
2588static bool isParenthesizedADLCallee(const CallExpr *call) {
2589 const Expr *callee = call->getCallee();
2590 const Expr *fn = callee->IgnoreParens();
2591
2592 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2593 // too, but for those to appear in the callee, it would have to be
2594 // parenthesized.
2595 if (callee == fn) return false;
2596
2597 // Must be an unresolved lookup.
2598 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2599 if (!lookup) return false;
2600
2601 assert(!lookup->requiresADL());
2602
2603 // Must be an unqualified lookup.
2604 if (lookup->getQualifier()) return false;
2605
2606 // Must not have found a class member. Note that if one is a class
2607 // member, they're all class members.
2608 if (lookup->getNumDecls() > 0 &&
2609 (*lookup->decls_begin())->isCXXClassMember())
2610 return false;
2611
2612 // Otherwise, ADL would have been triggered.
2613 return true;
2614}
2615
David Majnemer9c775c72014-09-23 04:27:55 +00002616void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2617 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2618 Out << CastEncoding;
2619 mangleType(ECE->getType());
2620 mangleExpression(ECE->getSubExpr());
2621}
2622
Richard Smith520449d2015-02-05 06:15:50 +00002623void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2624 if (auto *Syntactic = InitList->getSyntacticForm())
2625 InitList = Syntactic;
2626 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2627 mangleExpression(InitList->getInit(i));
2628}
2629
Guy Benyei11169dd2012-12-18 14:30:41 +00002630void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2631 // <expression> ::= <unary operator-name> <expression>
2632 // ::= <binary operator-name> <expression> <expression>
2633 // ::= <trinary operator-name> <expression> <expression> <expression>
2634 // ::= cv <type> expression # conversion with one argument
2635 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002636 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2637 // ::= sc <type> <expression> # static_cast<type> (expression)
2638 // ::= cc <type> <expression> # const_cast<type> (expression)
2639 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 // ::= st <type> # sizeof (a type)
2641 // ::= at <type> # alignof (a type)
2642 // ::= <template-param>
2643 // ::= <function-param>
2644 // ::= sr <type> <unqualified-name> # dependent name
2645 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2646 // ::= ds <expression> <expression> # expr.*expr
2647 // ::= sZ <template-param> # size of a parameter pack
2648 // ::= sZ <function-param> # size of a function parameter pack
2649 // ::= <expr-primary>
2650 // <expr-primary> ::= L <type> <value number> E # integer literal
2651 // ::= L <type <value float> E # floating literal
2652 // ::= L <mangled-name> E # external name
2653 // ::= fpT # 'this' expression
2654 QualType ImplicitlyConvertedToType;
2655
2656recurse:
2657 switch (E->getStmtClass()) {
2658 case Expr::NoStmtClass:
2659#define ABSTRACT_STMT(Type)
2660#define EXPR(Type, Base)
2661#define STMT(Type, Base) \
2662 case Expr::Type##Class:
2663#include "clang/AST/StmtNodes.inc"
2664 // fallthrough
2665
2666 // These all can only appear in local or variable-initialization
2667 // contexts and so should never appear in a mangling.
2668 case Expr::AddrLabelExprClass:
2669 case Expr::DesignatedInitExprClass:
2670 case Expr::ImplicitValueInitExprClass:
2671 case Expr::ParenListExprClass:
2672 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002673 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002674 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 llvm_unreachable("unexpected statement kind");
2676
2677 // FIXME: invent manglings for all these.
2678 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 case Expr::ChooseExprClass:
2680 case Expr::CompoundLiteralExprClass:
2681 case Expr::ExtVectorElementExprClass:
2682 case Expr::GenericSelectionExprClass:
2683 case Expr::ObjCEncodeExprClass:
2684 case Expr::ObjCIsaExprClass:
2685 case Expr::ObjCIvarRefExprClass:
2686 case Expr::ObjCMessageExprClass:
2687 case Expr::ObjCPropertyRefExprClass:
2688 case Expr::ObjCProtocolExprClass:
2689 case Expr::ObjCSelectorExprClass:
2690 case Expr::ObjCStringLiteralClass:
2691 case Expr::ObjCBoxedExprClass:
2692 case Expr::ObjCArrayLiteralClass:
2693 case Expr::ObjCDictionaryLiteralClass:
2694 case Expr::ObjCSubscriptRefExprClass:
2695 case Expr::ObjCIndirectCopyRestoreExprClass:
2696 case Expr::OffsetOfExprClass:
2697 case Expr::PredefinedExprClass:
2698 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002699 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 case Expr::TypeTraitExprClass:
2702 case Expr::ArrayTypeTraitExprClass:
2703 case Expr::ExpressionTraitExprClass:
2704 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 case Expr::CUDAKernelCallExprClass:
2706 case Expr::AsTypeExprClass:
2707 case Expr::PseudoObjectExprClass:
2708 case Expr::AtomicExprClass:
2709 {
2710 // As bad as this diagnostic is, it's better than crashing.
2711 DiagnosticsEngine &Diags = Context.getDiags();
2712 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2713 "cannot yet mangle expression type %0");
2714 Diags.Report(E->getExprLoc(), DiagID)
2715 << E->getStmtClassName() << E->getSourceRange();
2716 break;
2717 }
2718
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002719 case Expr::CXXUuidofExprClass: {
2720 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2721 if (UE->isTypeOperand()) {
2722 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2723 Out << "u8__uuidoft";
2724 mangleType(UuidT);
2725 } else {
2726 Expr *UuidExp = UE->getExprOperand();
2727 Out << "u8__uuidofz";
2728 mangleExpression(UuidExp, Arity);
2729 }
2730 break;
2731 }
2732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // Even gcc-4.5 doesn't mangle this.
2734 case Expr::BinaryConditionalOperatorClass: {
2735 DiagnosticsEngine &Diags = Context.getDiags();
2736 unsigned DiagID =
2737 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2738 "?: operator with omitted middle operand cannot be mangled");
2739 Diags.Report(E->getExprLoc(), DiagID)
2740 << E->getStmtClassName() << E->getSourceRange();
2741 break;
2742 }
2743
2744 // These are used for internal purposes and cannot be meaningfully mangled.
2745 case Expr::OpaqueValueExprClass:
2746 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2747
2748 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002750 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 Out << "E";
2752 break;
2753 }
2754
2755 case Expr::CXXDefaultArgExprClass:
2756 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2757 break;
2758
Richard Smith852c9db2013-04-20 22:23:05 +00002759 case Expr::CXXDefaultInitExprClass:
2760 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2761 break;
2762
Richard Smithcc1b96d2013-06-12 22:31:48 +00002763 case Expr::CXXStdInitializerListExprClass:
2764 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2765 break;
2766
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 case Expr::SubstNonTypeTemplateParmExprClass:
2768 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2769 Arity);
2770 break;
2771
2772 case Expr::UserDefinedLiteralClass:
2773 // We follow g++'s approach of mangling a UDL as a call to the literal
2774 // operator.
2775 case Expr::CXXMemberCallExprClass: // fallthrough
2776 case Expr::CallExprClass: {
2777 const CallExpr *CE = cast<CallExpr>(E);
2778
2779 // <expression> ::= cp <simple-id> <expression>* E
2780 // We use this mangling only when the call would use ADL except
2781 // for being parenthesized. Per discussion with David
2782 // Vandervoorde, 2011.04.25.
2783 if (isParenthesizedADLCallee(CE)) {
2784 Out << "cp";
2785 // The callee here is a parenthesized UnresolvedLookupExpr with
2786 // no qualifier and should always get mangled as a <simple-id>
2787 // anyway.
2788
2789 // <expression> ::= cl <expression>* E
2790 } else {
2791 Out << "cl";
2792 }
2793
2794 mangleExpression(CE->getCallee(), CE->getNumArgs());
2795 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2796 mangleExpression(CE->getArg(I));
2797 Out << 'E';
2798 break;
2799 }
2800
2801 case Expr::CXXNewExprClass: {
2802 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2803 if (New->isGlobalNew()) Out << "gs";
2804 Out << (New->isArray() ? "na" : "nw");
2805 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2806 E = New->placement_arg_end(); I != E; ++I)
2807 mangleExpression(*I);
2808 Out << '_';
2809 mangleType(New->getAllocatedType());
2810 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2812 Out << "il";
2813 else
2814 Out << "pi";
2815 const Expr *Init = New->getInitializer();
2816 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2817 // Directly inline the initializers.
2818 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2819 E = CCE->arg_end();
2820 I != E; ++I)
2821 mangleExpression(*I);
2822 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2823 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2824 mangleExpression(PLE->getExpr(i));
2825 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2826 isa<InitListExpr>(Init)) {
2827 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002828 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 } else
2830 mangleExpression(Init);
2831 }
2832 Out << 'E';
2833 break;
2834 }
2835
David Majnemer1dabfdc2015-02-14 13:23:54 +00002836 case Expr::CXXPseudoDestructorExprClass: {
2837 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2838 if (const Expr *Base = PDE->getBase())
2839 mangleMemberExprBase(Base, PDE->isArrow());
2840 if (NestedNameSpecifier *Qualifier = PDE->getQualifier())
2841 mangleUnresolvedPrefix(Qualifier, /*FirstQualifierLookup=*/nullptr);
2842 // <base-unresolved-name> ::= dn <destructor-name>
2843 Out << "dn";
2844 // <destructor-name> ::= <unresolved-type>
2845 // ::= <simple-id>
2846 manglePrefix(PDE->getDestroyedType());
2847 break;
2848 }
2849
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 case Expr::MemberExprClass: {
2851 const MemberExpr *ME = cast<MemberExpr>(E);
2852 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002853 ME->getQualifier(), nullptr,
2854 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 break;
2856 }
2857
2858 case Expr::UnresolvedMemberExprClass: {
2859 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2860 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002861 ME->getQualifier(), nullptr, ME->getMemberName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 Arity);
2863 if (ME->hasExplicitTemplateArgs())
2864 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2865 break;
2866 }
2867
2868 case Expr::CXXDependentScopeMemberExprClass: {
2869 const CXXDependentScopeMemberExpr *ME
2870 = cast<CXXDependentScopeMemberExpr>(E);
2871 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2872 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2873 ME->getMember(), Arity);
2874 if (ME->hasExplicitTemplateArgs())
2875 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2876 break;
2877 }
2878
2879 case Expr::UnresolvedLookupExprClass: {
2880 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00002881 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002882
2883 // All the <unresolved-name> productions end in a
2884 // base-unresolved-name, where <template-args> are just tacked
2885 // onto the end.
2886 if (ULE->hasExplicitTemplateArgs())
2887 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2888 break;
2889 }
2890
2891 case Expr::CXXUnresolvedConstructExprClass: {
2892 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2893 unsigned N = CE->arg_size();
2894
2895 Out << "cv";
2896 mangleType(CE->getType());
2897 if (N != 1) Out << '_';
2898 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2899 if (N != 1) Out << 'E';
2900 break;
2901 }
2902
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00002904 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00002905 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00002906 assert(
2907 CE->getNumArgs() >= 1 &&
2908 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2909 "implicit CXXConstructExpr must have one argument");
2910 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2911 }
2912 Out << "il";
2913 for (auto *E : CE->arguments())
2914 mangleExpression(E);
2915 Out << "E";
2916 break;
2917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002918
Richard Smith520449d2015-02-05 06:15:50 +00002919 case Expr::CXXTemporaryObjectExprClass: {
2920 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2921 unsigned N = CE->getNumArgs();
2922 bool List = CE->isListInitialization();
2923
2924 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 Out << "tl";
2926 else
2927 Out << "cv";
2928 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002929 if (!List && N != 1)
2930 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00002931 if (CE->isStdInitListInitialization()) {
2932 // We implicitly created a std::initializer_list<T> for the first argument
2933 // of a constructor of type U in an expression of the form U{a, b, c}.
2934 // Strip all the semantic gunk off the initializer list.
2935 auto *SILE =
2936 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2937 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2938 mangleInitListElements(ILE);
2939 } else {
2940 for (auto *E : CE->arguments())
2941 mangleExpression(E);
2942 }
Richard Smith520449d2015-02-05 06:15:50 +00002943 if (List || N != 1)
2944 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 break;
2946 }
2947
2948 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00002949 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002951 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 break;
2953
2954 case Expr::CXXNoexceptExprClass:
2955 Out << "nx";
2956 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2957 break;
2958
2959 case Expr::UnaryExprOrTypeTraitExprClass: {
2960 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2961
2962 if (!SAE->isInstantiationDependent()) {
2963 // Itanium C++ ABI:
2964 // If the operand of a sizeof or alignof operator is not
2965 // instantiation-dependent it is encoded as an integer literal
2966 // reflecting the result of the operator.
2967 //
2968 // If the result of the operator is implicitly converted to a known
2969 // integer type, that type is used for the literal; otherwise, the type
2970 // of std::size_t or std::ptrdiff_t is used.
2971 QualType T = (ImplicitlyConvertedToType.isNull() ||
2972 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2973 : ImplicitlyConvertedToType;
2974 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2975 mangleIntegerLiteral(T, V);
2976 break;
2977 }
2978
2979 switch(SAE->getKind()) {
2980 case UETT_SizeOf:
2981 Out << 's';
2982 break;
2983 case UETT_AlignOf:
2984 Out << 'a';
2985 break;
2986 case UETT_VecStep:
2987 DiagnosticsEngine &Diags = Context.getDiags();
2988 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2989 "cannot yet mangle vec_step expression");
2990 Diags.Report(DiagID);
2991 return;
2992 }
2993 if (SAE->isArgumentType()) {
2994 Out << 't';
2995 mangleType(SAE->getArgumentType());
2996 } else {
2997 Out << 'z';
2998 mangleExpression(SAE->getArgumentExpr());
2999 }
3000 break;
3001 }
3002
3003 case Expr::CXXThrowExprClass: {
3004 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003005 // <expression> ::= tw <expression> # throw expression
3006 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 if (TE->getSubExpr()) {
3008 Out << "tw";
3009 mangleExpression(TE->getSubExpr());
3010 } else {
3011 Out << "tr";
3012 }
3013 break;
3014 }
3015
3016 case Expr::CXXTypeidExprClass: {
3017 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003018 // <expression> ::= ti <type> # typeid (type)
3019 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 if (TIE->isTypeOperand()) {
3021 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003022 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 } else {
3024 Out << "te";
3025 mangleExpression(TIE->getExprOperand());
3026 }
3027 break;
3028 }
3029
3030 case Expr::CXXDeleteExprClass: {
3031 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003032 // <expression> ::= [gs] dl <expression> # [::] delete expr
3033 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 if (DE->isGlobalDelete()) Out << "gs";
3035 Out << (DE->isArrayForm() ? "da" : "dl");
3036 mangleExpression(DE->getArgument());
3037 break;
3038 }
3039
3040 case Expr::UnaryOperatorClass: {
3041 const UnaryOperator *UO = cast<UnaryOperator>(E);
3042 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3043 /*Arity=*/1);
3044 mangleExpression(UO->getSubExpr());
3045 break;
3046 }
3047
3048 case Expr::ArraySubscriptExprClass: {
3049 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3050
3051 // Array subscript is treated as a syntactically weird form of
3052 // binary operator.
3053 Out << "ix";
3054 mangleExpression(AE->getLHS());
3055 mangleExpression(AE->getRHS());
3056 break;
3057 }
3058
3059 case Expr::CompoundAssignOperatorClass: // fallthrough
3060 case Expr::BinaryOperatorClass: {
3061 const BinaryOperator *BO = cast<BinaryOperator>(E);
3062 if (BO->getOpcode() == BO_PtrMemD)
3063 Out << "ds";
3064 else
3065 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3066 /*Arity=*/2);
3067 mangleExpression(BO->getLHS());
3068 mangleExpression(BO->getRHS());
3069 break;
3070 }
3071
3072 case Expr::ConditionalOperatorClass: {
3073 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3074 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3075 mangleExpression(CO->getCond());
3076 mangleExpression(CO->getLHS(), Arity);
3077 mangleExpression(CO->getRHS(), Arity);
3078 break;
3079 }
3080
3081 case Expr::ImplicitCastExprClass: {
3082 ImplicitlyConvertedToType = E->getType();
3083 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3084 goto recurse;
3085 }
3086
3087 case Expr::ObjCBridgedCastExprClass: {
3088 // Mangle ownership casts as a vendor extended operator __bridge,
3089 // __bridge_transfer, or __bridge_retain.
3090 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3091 Out << "v1U" << Kind.size() << Kind;
3092 }
3093 // Fall through to mangle the cast itself.
3094
3095 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003096 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003098
Richard Smith520449d2015-02-05 06:15:50 +00003099 case Expr::CXXFunctionalCastExprClass: {
3100 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3101 // FIXME: Add isImplicit to CXXConstructExpr.
3102 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3103 if (CCE->getParenOrBraceRange().isInvalid())
3104 Sub = CCE->getArg(0)->IgnoreImplicit();
3105 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3106 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3107 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3108 Out << "tl";
3109 mangleType(E->getType());
3110 mangleInitListElements(IL);
3111 Out << "E";
3112 } else {
3113 mangleCastExpression(E, "cv");
3114 }
3115 break;
3116 }
3117
David Majnemer9c775c72014-09-23 04:27:55 +00003118 case Expr::CXXStaticCastExprClass:
3119 mangleCastExpression(E, "sc");
3120 break;
3121 case Expr::CXXDynamicCastExprClass:
3122 mangleCastExpression(E, "dc");
3123 break;
3124 case Expr::CXXReinterpretCastExprClass:
3125 mangleCastExpression(E, "rc");
3126 break;
3127 case Expr::CXXConstCastExprClass:
3128 mangleCastExpression(E, "cc");
3129 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003130
3131 case Expr::CXXOperatorCallExprClass: {
3132 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3133 unsigned NumArgs = CE->getNumArgs();
3134 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3135 // Mangle the arguments.
3136 for (unsigned i = 0; i != NumArgs; ++i)
3137 mangleExpression(CE->getArg(i));
3138 break;
3139 }
3140
3141 case Expr::ParenExprClass:
3142 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3143 break;
3144
3145 case Expr::DeclRefExprClass: {
3146 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3147
3148 switch (D->getKind()) {
3149 default:
3150 // <expr-primary> ::= L <mangled-name> E # external name
3151 Out << 'L';
3152 mangle(D, "_Z");
3153 Out << 'E';
3154 break;
3155
3156 case Decl::ParmVar:
3157 mangleFunctionParam(cast<ParmVarDecl>(D));
3158 break;
3159
3160 case Decl::EnumConstant: {
3161 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3162 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3163 break;
3164 }
3165
3166 case Decl::NonTypeTemplateParm: {
3167 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3168 mangleTemplateParameter(PD->getIndex());
3169 break;
3170 }
3171
3172 }
3173
3174 break;
3175 }
3176
3177 case Expr::SubstNonTypeTemplateParmPackExprClass:
3178 // FIXME: not clear how to mangle this!
3179 // template <unsigned N...> class A {
3180 // template <class U...> void foo(U (&x)[N]...);
3181 // };
3182 Out << "_SUBSTPACK_";
3183 break;
3184
3185 case Expr::FunctionParmPackExprClass: {
3186 // FIXME: not clear how to mangle this!
3187 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3188 Out << "v110_SUBSTPACK";
3189 mangleFunctionParam(FPPE->getParameterPack());
3190 break;
3191 }
3192
3193 case Expr::DependentScopeDeclRefExprClass: {
3194 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00003195 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
3196 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003197
3198 // All the <unresolved-name> productions end in a
3199 // base-unresolved-name, where <template-args> are just tacked
3200 // onto the end.
3201 if (DRE->hasExplicitTemplateArgs())
3202 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3203 break;
3204 }
3205
3206 case Expr::CXXBindTemporaryExprClass:
3207 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3208 break;
3209
3210 case Expr::ExprWithCleanupsClass:
3211 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3212 break;
3213
3214 case Expr::FloatingLiteralClass: {
3215 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3216 Out << 'L';
3217 mangleType(FL->getType());
3218 mangleFloat(FL->getValue());
3219 Out << 'E';
3220 break;
3221 }
3222
3223 case Expr::CharacterLiteralClass:
3224 Out << 'L';
3225 mangleType(E->getType());
3226 Out << cast<CharacterLiteral>(E)->getValue();
3227 Out << 'E';
3228 break;
3229
3230 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3231 case Expr::ObjCBoolLiteralExprClass:
3232 Out << "Lb";
3233 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3234 Out << 'E';
3235 break;
3236
3237 case Expr::CXXBoolLiteralExprClass:
3238 Out << "Lb";
3239 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3240 Out << 'E';
3241 break;
3242
3243 case Expr::IntegerLiteralClass: {
3244 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3245 if (E->getType()->isSignedIntegerType())
3246 Value.setIsSigned(true);
3247 mangleIntegerLiteral(E->getType(), Value);
3248 break;
3249 }
3250
3251 case Expr::ImaginaryLiteralClass: {
3252 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3253 // Mangle as if a complex literal.
3254 // Proposal from David Vandevoorde, 2010.06.30.
3255 Out << 'L';
3256 mangleType(E->getType());
3257 if (const FloatingLiteral *Imag =
3258 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3259 // Mangle a floating-point zero of the appropriate type.
3260 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3261 Out << '_';
3262 mangleFloat(Imag->getValue());
3263 } else {
3264 Out << "0_";
3265 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3266 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3267 Value.setIsSigned(true);
3268 mangleNumber(Value);
3269 }
3270 Out << 'E';
3271 break;
3272 }
3273
3274 case Expr::StringLiteralClass: {
3275 // Revised proposal from David Vandervoorde, 2010.07.15.
3276 Out << 'L';
3277 assert(isa<ConstantArrayType>(E->getType()));
3278 mangleType(E->getType());
3279 Out << 'E';
3280 break;
3281 }
3282
3283 case Expr::GNUNullExprClass:
3284 // FIXME: should this really be mangled the same as nullptr?
3285 // fallthrough
3286
3287 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 Out << "LDnE";
3289 break;
3290 }
3291
3292 case Expr::PackExpansionExprClass:
3293 Out << "sp";
3294 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3295 break;
3296
3297 case Expr::SizeOfPackExprClass: {
3298 Out << "sZ";
3299 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3300 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3301 mangleTemplateParameter(TTP->getIndex());
3302 else if (const NonTypeTemplateParmDecl *NTTP
3303 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3304 mangleTemplateParameter(NTTP->getIndex());
3305 else if (const TemplateTemplateParmDecl *TempTP
3306 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3307 mangleTemplateParameter(TempTP->getIndex());
3308 else
3309 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3310 break;
3311 }
Richard Smith0f0af192014-11-08 05:07:16 +00003312
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 case Expr::MaterializeTemporaryExprClass: {
3314 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3315 break;
3316 }
Richard Smith0f0af192014-11-08 05:07:16 +00003317
3318 case Expr::CXXFoldExprClass: {
3319 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003320 if (FE->isLeftFold())
3321 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003322 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003323 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003324
3325 if (FE->getOperator() == BO_PtrMemD)
3326 Out << "ds";
3327 else
3328 mangleOperatorName(
3329 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3330 /*Arity=*/2);
3331
3332 if (FE->getLHS())
3333 mangleExpression(FE->getLHS());
3334 if (FE->getRHS())
3335 mangleExpression(FE->getRHS());
3336 break;
3337 }
3338
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 case Expr::CXXThisExprClass:
3340 Out << "fpT";
3341 break;
3342 }
3343}
3344
3345/// Mangle an expression which refers to a parameter variable.
3346///
3347/// <expression> ::= <function-param>
3348/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3349/// <function-param> ::= fp <top-level CV-qualifiers>
3350/// <parameter-2 non-negative number> _ # L == 0, I > 0
3351/// <function-param> ::= fL <L-1 non-negative number>
3352/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3353/// <function-param> ::= fL <L-1 non-negative number>
3354/// p <top-level CV-qualifiers>
3355/// <I-1 non-negative number> _ # L > 0, I > 0
3356///
3357/// L is the nesting depth of the parameter, defined as 1 if the
3358/// parameter comes from the innermost function prototype scope
3359/// enclosing the current context, 2 if from the next enclosing
3360/// function prototype scope, and so on, with one special case: if
3361/// we've processed the full parameter clause for the innermost
3362/// function type, then L is one less. This definition conveniently
3363/// makes it irrelevant whether a function's result type was written
3364/// trailing or leading, but is otherwise overly complicated; the
3365/// numbering was first designed without considering references to
3366/// parameter in locations other than return types, and then the
3367/// mangling had to be generalized without changing the existing
3368/// manglings.
3369///
3370/// I is the zero-based index of the parameter within its parameter
3371/// declaration clause. Note that the original ABI document describes
3372/// this using 1-based ordinals.
3373void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3374 unsigned parmDepth = parm->getFunctionScopeDepth();
3375 unsigned parmIndex = parm->getFunctionScopeIndex();
3376
3377 // Compute 'L'.
3378 // parmDepth does not include the declaring function prototype.
3379 // FunctionTypeDepth does account for that.
3380 assert(parmDepth < FunctionTypeDepth.getDepth());
3381 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3382 if (FunctionTypeDepth.isInResultType())
3383 nestingDepth--;
3384
3385 if (nestingDepth == 0) {
3386 Out << "fp";
3387 } else {
3388 Out << "fL" << (nestingDepth - 1) << 'p';
3389 }
3390
3391 // Top-level qualifiers. We don't have to worry about arrays here,
3392 // because parameters declared as arrays should already have been
3393 // transformed to have pointer type. FIXME: apparently these don't
3394 // get mangled if used as an rvalue of a known non-class type?
3395 assert(!parm->getType()->isArrayType()
3396 && "parameter's type is still an array type?");
3397 mangleQualifiers(parm->getType().getQualifiers());
3398
3399 // Parameter index.
3400 if (parmIndex != 0) {
3401 Out << (parmIndex - 1);
3402 }
3403 Out << '_';
3404}
3405
3406void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3407 // <ctor-dtor-name> ::= C1 # complete object constructor
3408 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003410 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 switch (T) {
3412 case Ctor_Complete:
3413 Out << "C1";
3414 break;
3415 case Ctor_Base:
3416 Out << "C2";
3417 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003418 case Ctor_Comdat:
3419 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 break;
3421 }
3422}
3423
3424void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3425 // <ctor-dtor-name> ::= D0 # deleting destructor
3426 // ::= D1 # complete object destructor
3427 // ::= D2 # base object destructor
3428 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003429 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 switch (T) {
3431 case Dtor_Deleting:
3432 Out << "D0";
3433 break;
3434 case Dtor_Complete:
3435 Out << "D1";
3436 break;
3437 case Dtor_Base:
3438 Out << "D2";
3439 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003440 case Dtor_Comdat:
3441 Out << "D5";
3442 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 }
3444}
3445
3446void CXXNameMangler::mangleTemplateArgs(
3447 const ASTTemplateArgumentListInfo &TemplateArgs) {
3448 // <template-args> ::= I <template-arg>+ E
3449 Out << 'I';
3450 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3451 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3452 Out << 'E';
3453}
3454
3455void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3456 // <template-args> ::= I <template-arg>+ E
3457 Out << 'I';
3458 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3459 mangleTemplateArg(AL[i]);
3460 Out << 'E';
3461}
3462
3463void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3464 unsigned NumTemplateArgs) {
3465 // <template-args> ::= I <template-arg>+ E
3466 Out << 'I';
3467 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3468 mangleTemplateArg(TemplateArgs[i]);
3469 Out << 'E';
3470}
3471
3472void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3473 // <template-arg> ::= <type> # type or template
3474 // ::= X <expression> E # expression
3475 // ::= <expr-primary> # simple expressions
3476 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 if (!A.isInstantiationDependent() || A.isDependent())
3478 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3479
3480 switch (A.getKind()) {
3481 case TemplateArgument::Null:
3482 llvm_unreachable("Cannot mangle NULL template argument");
3483
3484 case TemplateArgument::Type:
3485 mangleType(A.getAsType());
3486 break;
3487 case TemplateArgument::Template:
3488 // This is mangled as <type>.
3489 mangleType(A.getAsTemplate());
3490 break;
3491 case TemplateArgument::TemplateExpansion:
3492 // <type> ::= Dp <type> # pack expansion (C++0x)
3493 Out << "Dp";
3494 mangleType(A.getAsTemplateOrTemplatePattern());
3495 break;
3496 case TemplateArgument::Expression: {
3497 // It's possible to end up with a DeclRefExpr here in certain
3498 // dependent cases, in which case we should mangle as a
3499 // declaration.
3500 const Expr *E = A.getAsExpr()->IgnoreParens();
3501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3502 const ValueDecl *D = DRE->getDecl();
3503 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3504 Out << "L";
3505 mangle(D, "_Z");
3506 Out << 'E';
3507 break;
3508 }
3509 }
3510
3511 Out << 'X';
3512 mangleExpression(E);
3513 Out << 'E';
3514 break;
3515 }
3516 case TemplateArgument::Integral:
3517 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3518 break;
3519 case TemplateArgument::Declaration: {
3520 // <expr-primary> ::= L <mangled-name> E # external name
3521 // Clang produces AST's where pointer-to-member-function expressions
3522 // and pointer-to-function expressions are represented as a declaration not
3523 // an expression. We compensate for it here to produce the correct mangling.
3524 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003525 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 if (compensateMangling) {
3527 Out << 'X';
3528 mangleOperatorName(OO_Amp, 1);
3529 }
3530
3531 Out << 'L';
3532 // References to external entities use the mangled name; if the name would
3533 // not normally be manged then mangle it as unqualified.
3534 //
3535 // FIXME: The ABI specifies that external names here should have _Z, but
3536 // gcc leaves this off.
3537 if (compensateMangling)
3538 mangle(D, "_Z");
3539 else
3540 mangle(D, "Z");
3541 Out << 'E';
3542
3543 if (compensateMangling)
3544 Out << 'E';
3545
3546 break;
3547 }
3548 case TemplateArgument::NullPtr: {
3549 // <expr-primary> ::= L <type> 0 E
3550 Out << 'L';
3551 mangleType(A.getNullPtrType());
3552 Out << "0E";
3553 break;
3554 }
3555 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003556 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003558 for (const auto &P : A.pack_elements())
3559 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 Out << 'E';
3561 }
3562 }
3563}
3564
3565void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3566 // <template-param> ::= T_ # first template parameter
3567 // ::= T <parameter-2 non-negative number> _
3568 if (Index == 0)
3569 Out << "T_";
3570 else
3571 Out << 'T' << (Index - 1) << '_';
3572}
3573
David Majnemer3b3bdb52014-05-06 22:49:16 +00003574void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3575 if (SeqID == 1)
3576 Out << '0';
3577 else if (SeqID > 1) {
3578 SeqID--;
3579
3580 // <seq-id> is encoded in base-36, using digits and upper case letters.
3581 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003582 MutableArrayRef<char> BufferRef(Buffer);
3583 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003584
3585 for (; SeqID != 0; SeqID /= 36) {
3586 unsigned C = SeqID % 36;
3587 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3588 }
3589
3590 Out.write(I.base(), I - BufferRef.rbegin());
3591 }
3592 Out << '_';
3593}
3594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3596 bool result = mangleSubstitution(type);
3597 assert(result && "no existing substitution for type");
3598 (void) result;
3599}
3600
3601void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3602 bool result = mangleSubstitution(tname);
3603 assert(result && "no existing substitution for template name");
3604 (void) result;
3605}
3606
3607// <substitution> ::= S <seq-id> _
3608// ::= S_
3609bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3610 // Try one of the standard substitutions first.
3611 if (mangleStandardSubstitution(ND))
3612 return true;
3613
3614 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3615 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3616}
3617
3618/// \brief Determine whether the given type has any qualifiers that are
3619/// relevant for substitutions.
3620static bool hasMangledSubstitutionQualifiers(QualType T) {
3621 Qualifiers Qs = T.getQualifiers();
3622 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3623}
3624
3625bool CXXNameMangler::mangleSubstitution(QualType T) {
3626 if (!hasMangledSubstitutionQualifiers(T)) {
3627 if (const RecordType *RT = T->getAs<RecordType>())
3628 return mangleSubstitution(RT->getDecl());
3629 }
3630
3631 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3632
3633 return mangleSubstitution(TypePtr);
3634}
3635
3636bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3637 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3638 return mangleSubstitution(TD);
3639
3640 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3641 return mangleSubstitution(
3642 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3643}
3644
3645bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3646 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3647 if (I == Substitutions.end())
3648 return false;
3649
3650 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003651 Out << 'S';
3652 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003653
3654 return true;
3655}
3656
3657static bool isCharType(QualType T) {
3658 if (T.isNull())
3659 return false;
3660
3661 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3662 T->isSpecificBuiltinType(BuiltinType::Char_U);
3663}
3664
3665/// isCharSpecialization - Returns whether a given type is a template
3666/// specialization of a given name with a single argument of type char.
3667static bool isCharSpecialization(QualType T, const char *Name) {
3668 if (T.isNull())
3669 return false;
3670
3671 const RecordType *RT = T->getAs<RecordType>();
3672 if (!RT)
3673 return false;
3674
3675 const ClassTemplateSpecializationDecl *SD =
3676 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3677 if (!SD)
3678 return false;
3679
3680 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3681 return false;
3682
3683 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3684 if (TemplateArgs.size() != 1)
3685 return false;
3686
3687 if (!isCharType(TemplateArgs[0].getAsType()))
3688 return false;
3689
3690 return SD->getIdentifier()->getName() == Name;
3691}
3692
3693template <std::size_t StrLen>
3694static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3695 const char (&Str)[StrLen]) {
3696 if (!SD->getIdentifier()->isStr(Str))
3697 return false;
3698
3699 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3700 if (TemplateArgs.size() != 2)
3701 return false;
3702
3703 if (!isCharType(TemplateArgs[0].getAsType()))
3704 return false;
3705
3706 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3707 return false;
3708
3709 return true;
3710}
3711
3712bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3713 // <substitution> ::= St # ::std::
3714 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3715 if (isStd(NS)) {
3716 Out << "St";
3717 return true;
3718 }
3719 }
3720
3721 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3722 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3723 return false;
3724
3725 // <substitution> ::= Sa # ::std::allocator
3726 if (TD->getIdentifier()->isStr("allocator")) {
3727 Out << "Sa";
3728 return true;
3729 }
3730
3731 // <<substitution> ::= Sb # ::std::basic_string
3732 if (TD->getIdentifier()->isStr("basic_string")) {
3733 Out << "Sb";
3734 return true;
3735 }
3736 }
3737
3738 if (const ClassTemplateSpecializationDecl *SD =
3739 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3740 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3741 return false;
3742
3743 // <substitution> ::= Ss # ::std::basic_string<char,
3744 // ::std::char_traits<char>,
3745 // ::std::allocator<char> >
3746 if (SD->getIdentifier()->isStr("basic_string")) {
3747 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3748
3749 if (TemplateArgs.size() != 3)
3750 return false;
3751
3752 if (!isCharType(TemplateArgs[0].getAsType()))
3753 return false;
3754
3755 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3756 return false;
3757
3758 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3759 return false;
3760
3761 Out << "Ss";
3762 return true;
3763 }
3764
3765 // <substitution> ::= Si # ::std::basic_istream<char,
3766 // ::std::char_traits<char> >
3767 if (isStreamCharSpecialization(SD, "basic_istream")) {
3768 Out << "Si";
3769 return true;
3770 }
3771
3772 // <substitution> ::= So # ::std::basic_ostream<char,
3773 // ::std::char_traits<char> >
3774 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3775 Out << "So";
3776 return true;
3777 }
3778
3779 // <substitution> ::= Sd # ::std::basic_iostream<char,
3780 // ::std::char_traits<char> >
3781 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3782 Out << "Sd";
3783 return true;
3784 }
3785 }
3786 return false;
3787}
3788
3789void CXXNameMangler::addSubstitution(QualType T) {
3790 if (!hasMangledSubstitutionQualifiers(T)) {
3791 if (const RecordType *RT = T->getAs<RecordType>()) {
3792 addSubstitution(RT->getDecl());
3793 return;
3794 }
3795 }
3796
3797 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3798 addSubstitution(TypePtr);
3799}
3800
3801void CXXNameMangler::addSubstitution(TemplateName Template) {
3802 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3803 return addSubstitution(TD);
3804
3805 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3806 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3807}
3808
3809void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3810 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3811 Substitutions[Ptr] = SeqID++;
3812}
3813
3814//
3815
3816/// \brief Mangles the name of the declaration D and emits that name to the
3817/// given output stream.
3818///
3819/// If the declaration D requires a mangled name, this routine will emit that
3820/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3821/// and this routine will return false. In this case, the caller should just
3822/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3823/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003824void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3825 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3827 "Invalid mangleName() call, argument is not a variable or function!");
3828 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3829 "Invalid mangleName() call on 'structor decl!");
3830
3831 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3832 getASTContext().getSourceManager(),
3833 "Mangling declaration");
3834
3835 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003836 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003837}
3838
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003839void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3840 CXXCtorType Type,
3841 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 CXXNameMangler Mangler(*this, Out, D, Type);
3843 Mangler.mangle(D);
3844}
3845
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003846void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3847 CXXDtorType Type,
3848 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 CXXNameMangler Mangler(*this, Out, D, Type);
3850 Mangler.mangle(D);
3851}
3852
Rafael Espindola1e4df922014-09-16 15:18:21 +00003853void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3854 raw_ostream &Out) {
3855 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3856 Mangler.mangle(D);
3857}
3858
3859void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3860 raw_ostream &Out) {
3861 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3862 Mangler.mangle(D);
3863}
3864
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003865void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3866 const ThunkInfo &Thunk,
3867 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 // <special-name> ::= T <call-offset> <base encoding>
3869 // # base is the nominal target function of thunk
3870 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3871 // # base is the nominal target function of thunk
3872 // # first call-offset is 'this' adjustment
3873 // # second call-offset is result adjustment
3874
3875 assert(!isa<CXXDestructorDecl>(MD) &&
3876 "Use mangleCXXDtor for destructor decls!");
3877 CXXNameMangler Mangler(*this, Out);
3878 Mangler.getStream() << "_ZT";
3879 if (!Thunk.Return.isEmpty())
3880 Mangler.getStream() << 'c';
3881
3882 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003883 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3884 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3885
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 // Mangle the return pointer adjustment if there is one.
3887 if (!Thunk.Return.isEmpty())
3888 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003889 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3890
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 Mangler.mangleFunctionEncoding(MD);
3892}
3893
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003894void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3895 const CXXDestructorDecl *DD, CXXDtorType Type,
3896 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 // <special-name> ::= T <call-offset> <base encoding>
3898 // # base is the nominal target function of thunk
3899 CXXNameMangler Mangler(*this, Out, DD, Type);
3900 Mangler.getStream() << "_ZT";
3901
3902 // Mangle the 'this' pointer adjustment.
3903 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003904 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003905
3906 Mangler.mangleFunctionEncoding(DD);
3907}
3908
3909/// mangleGuardVariable - Returns the mangled name for a guard variable
3910/// for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003911void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3912 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 // <special-name> ::= GV <object name> # Guard variable for one-time
3914 // # initialization
3915 CXXNameMangler Mangler(*this, Out);
3916 Mangler.getStream() << "_ZGV";
3917 Mangler.mangleName(D);
3918}
3919
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003920void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3921 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003922 // These symbols are internal in the Itanium ABI, so the names don't matter.
3923 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3924 // avoid duplicate symbols.
3925 Out << "__cxx_global_var_init";
3926}
3927
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003928void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3929 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003930 // Prefix the mangling of D with __dtor_.
3931 CXXNameMangler Mangler(*this, Out);
3932 Mangler.getStream() << "__dtor_";
3933 if (shouldMangleDeclName(D))
3934 Mangler.mangle(D);
3935 else
3936 Mangler.getStream() << D->getName();
3937}
3938
Reid Kleckner1d59f992015-01-22 01:36:17 +00003939void ItaniumMangleContextImpl::mangleSEHFilterExpression(
3940 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3941 CXXNameMangler Mangler(*this, Out);
3942 Mangler.getStream() << "__filt_";
3943 if (shouldMangleDeclName(EnclosingDecl))
3944 Mangler.mangle(EnclosingDecl);
3945 else
3946 Mangler.getStream() << EnclosingDecl->getName();
3947}
3948
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003949void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3950 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003951 // <special-name> ::= TH <object name>
3952 CXXNameMangler Mangler(*this, Out);
3953 Mangler.getStream() << "_ZTH";
3954 Mangler.mangleName(D);
3955}
3956
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003957void
3958ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3959 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003960 // <special-name> ::= TW <object name>
3961 CXXNameMangler Mangler(*this, Out);
3962 Mangler.getStream() << "_ZTW";
3963 Mangler.mangleName(D);
3964}
3965
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003966void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00003967 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003968 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 // We match the GCC mangling here.
3970 // <special-name> ::= GR <object name>
3971 CXXNameMangler Mangler(*this, Out);
3972 Mangler.getStream() << "_ZGR";
3973 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00003974 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00003975 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00003976}
3977
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003978void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
3979 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 // <special-name> ::= TV <type> # virtual table
3981 CXXNameMangler Mangler(*this, Out);
3982 Mangler.getStream() << "_ZTV";
3983 Mangler.mangleNameOrStandardSubstitution(RD);
3984}
3985
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003986void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
3987 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 // <special-name> ::= TT <type> # VTT structure
3989 CXXNameMangler Mangler(*this, Out);
3990 Mangler.getStream() << "_ZTT";
3991 Mangler.mangleNameOrStandardSubstitution(RD);
3992}
3993
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003994void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3995 int64_t Offset,
3996 const CXXRecordDecl *Type,
3997 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 // <special-name> ::= TC <type> <offset number> _ <base type>
3999 CXXNameMangler Mangler(*this, Out);
4000 Mangler.getStream() << "_ZTC";
4001 Mangler.mangleNameOrStandardSubstitution(RD);
4002 Mangler.getStream() << Offset;
4003 Mangler.getStream() << '_';
4004 Mangler.mangleNameOrStandardSubstitution(Type);
4005}
4006
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004007void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 // <special-name> ::= TI <type> # typeinfo structure
4009 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4010 CXXNameMangler Mangler(*this, Out);
4011 Mangler.getStream() << "_ZTI";
4012 Mangler.mangleType(Ty);
4013}
4014
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004015void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4016 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4018 CXXNameMangler Mangler(*this, Out);
4019 Mangler.getStream() << "_ZTS";
4020 Mangler.mangleType(Ty);
4021}
4022
Reid Klecknercc99e262013-11-19 23:23:00 +00004023void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4024 mangleCXXRTTIName(Ty, Out);
4025}
4026
David Majnemer58e5bee2014-03-24 21:43:36 +00004027void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4028 llvm_unreachable("Can't mangle string literals");
4029}
4030
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004031ItaniumMangleContext *
4032ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4033 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004034}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004035