blob: 0d10bb1d990744da4b40599016400b39550e1f97 [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);
David Majnemera88b3592015-02-18 02:28:01 +0000355 void mangleDestructorName(QualType DestroyedType);
356 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000357 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
358 void mangleQualifiers(Qualifiers Quals);
359 void mangleRefQualifier(RefQualifierKind RefQualifier);
360
361 void mangleObjCMethodName(const ObjCMethodDecl *MD);
362
363 // Declare manglers for every type class.
364#define ABSTRACT_TYPE(CLASS, PARENT)
365#define NON_CANONICAL_TYPE(CLASS, PARENT)
366#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
367#include "clang/AST/TypeNodes.def"
368
369 void mangleType(const TagType*);
370 void mangleType(TemplateName);
371 void mangleBareFunctionType(const FunctionType *T,
372 bool MangleReturnType);
373 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000374 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000375
376 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000377 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000378 void mangleMemberExpr(const Expr *base, bool isArrow,
379 NestedNameSpecifier *qualifier,
380 NamedDecl *firstQualifierLookup,
381 DeclarationName name,
382 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000383 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000384 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
386 void mangleCXXCtorType(CXXCtorType T);
387 void mangleCXXDtorType(CXXDtorType T);
388
389 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
390 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
391 unsigned NumTemplateArgs);
392 void mangleTemplateArgs(const TemplateArgumentList &AL);
393 void mangleTemplateArg(TemplateArgument A);
394
395 void mangleTemplateParameter(unsigned Index);
396
397 void mangleFunctionParam(const ParmVarDecl *parm);
398};
399
400}
401
Rafael Espindola002667c2013-10-16 01:40:34 +0000402bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000403 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000404 if (FD) {
405 LanguageLinkage L = FD->getLanguageLinkage();
406 // Overloadable functions need mangling.
407 if (FD->hasAttr<OverloadableAttr>())
408 return true;
409
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000410 // "main" is not mangled.
411 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000412 return false;
413
414 // C++ functions and those whose names are not a simple identifier need
415 // mangling.
416 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
417 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000418
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000419 // C functions are not mangled.
420 if (L == CLanguageLinkage)
421 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000422 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000423
424 // Otherwise, no mangling is done outside C++ mode.
425 if (!getASTContext().getLangOpts().CPlusPlus)
426 return false;
427
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000428 const VarDecl *VD = dyn_cast<VarDecl>(D);
429 if (VD) {
430 // C variables are not mangled.
431 if (VD->isExternC())
432 return false;
433
434 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 const DeclContext *DC = getEffectiveDeclContext(D);
436 // Check for extern variable declared locally.
437 if (DC->isFunctionOrMethod() && D->hasLinkage())
438 while (!DC->isNamespace() && !DC->isTranslationUnit())
439 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000440 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
441 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 return false;
443 }
444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445 return true;
446}
447
448void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000449 // <mangled-name> ::= _Z <encoding>
450 // ::= <data name>
451 // ::= <special-name>
452 Out << Prefix;
453 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
454 mangleFunctionEncoding(FD);
455 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
456 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000457 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
458 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000459 else
460 mangleName(cast<FieldDecl>(D));
461}
462
463void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
464 // <encoding> ::= <function name> <bare-function-type>
465 mangleName(FD);
466
467 // Don't mangle in the type if this isn't a decl we should typically mangle.
468 if (!Context.shouldMangleDeclName(FD))
469 return;
470
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000471 if (FD->hasAttr<EnableIfAttr>()) {
472 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
473 Out << "Ua9enable_ifI";
474 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
475 // it here.
476 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
477 E = FD->getAttrs().rend();
478 I != E; ++I) {
479 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
480 if (!EIA)
481 continue;
482 Out << 'X';
483 mangleExpression(EIA->getCond());
484 Out << 'E';
485 }
486 Out << 'E';
487 FunctionTypeDepth.pop(Saved);
488 }
489
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 // Whether the mangling of a function type includes the return type depends on
491 // the context and the nature of the function. The rules for deciding whether
492 // the return type is included are:
493 //
494 // 1. Template functions (names or types) have return types encoded, with
495 // the exceptions listed below.
496 // 2. Function types not appearing as part of a function name mangling,
497 // e.g. parameters, pointer types, etc., have return type encoded, with the
498 // exceptions listed below.
499 // 3. Non-template function names do not have return types encoded.
500 //
501 // The exceptions mentioned in (1) and (2) above, for which the return type is
502 // never included, are
503 // 1. Constructors.
504 // 2. Destructors.
505 // 3. Conversion operator functions, e.g. operator int.
506 bool MangleReturnType = false;
507 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
508 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
509 isa<CXXConversionDecl>(FD)))
510 MangleReturnType = true;
511
512 // Mangle the type of the primary template.
513 FD = PrimaryTemplate->getTemplatedDecl();
514 }
515
516 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
517 MangleReturnType);
518}
519
520static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
521 while (isa<LinkageSpecDecl>(DC)) {
522 DC = getEffectiveParentContext(DC);
523 }
524
525 return DC;
526}
527
528/// isStd - Return whether a given namespace is the 'std' namespace.
529static bool isStd(const NamespaceDecl *NS) {
530 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
531 ->isTranslationUnit())
532 return false;
533
534 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
535 return II && II->isStr("std");
536}
537
538// isStdNamespace - Return whether a given decl context is a toplevel 'std'
539// namespace.
540static bool isStdNamespace(const DeclContext *DC) {
541 if (!DC->isNamespace())
542 return false;
543
544 return isStd(cast<NamespaceDecl>(DC));
545}
546
547static const TemplateDecl *
548isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
549 // Check if we have a function template.
550 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
551 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
552 TemplateArgs = FD->getTemplateSpecializationArgs();
553 return TD;
554 }
555 }
556
557 // Check if we have a class template.
558 if (const ClassTemplateSpecializationDecl *Spec =
559 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
560 TemplateArgs = &Spec->getTemplateArgs();
561 return Spec->getSpecializedTemplate();
562 }
563
Larisse Voufo39a1e502013-08-06 01:03:05 +0000564 // Check if we have a variable template.
565 if (const VarTemplateSpecializationDecl *Spec =
566 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
567 TemplateArgs = &Spec->getTemplateArgs();
568 return Spec->getSpecializedTemplate();
569 }
570
Craig Topper36250ad2014-05-12 05:36:57 +0000571 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000572}
573
Guy Benyei11169dd2012-12-18 14:30:41 +0000574void CXXNameMangler::mangleName(const NamedDecl *ND) {
575 // <name> ::= <nested-name>
576 // ::= <unscoped-name>
577 // ::= <unscoped-template-name> <template-args>
578 // ::= <local-name>
579 //
580 const DeclContext *DC = getEffectiveDeclContext(ND);
581
582 // If this is an extern variable declared locally, the relevant DeclContext
583 // is that of the containing namespace, or the translation unit.
584 // FIXME: This is a hack; extern variables declared locally should have
585 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000586 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000587 while (!DC->isNamespace() && !DC->isTranslationUnit())
588 DC = getEffectiveParentContext(DC);
589 else if (GetLocalClassDecl(ND)) {
590 mangleLocalName(ND);
591 return;
592 }
593
594 DC = IgnoreLinkageSpecDecls(DC);
595
596 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
597 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000598 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
600 mangleUnscopedTemplateName(TD);
601 mangleTemplateArgs(*TemplateArgs);
602 return;
603 }
604
605 mangleUnscopedName(ND);
606 return;
607 }
608
Eli Friedman95f50122013-07-02 17:52:28 +0000609 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 mangleLocalName(ND);
611 return;
612 }
613
614 mangleNestedName(ND, DC);
615}
616void CXXNameMangler::mangleName(const TemplateDecl *TD,
617 const TemplateArgument *TemplateArgs,
618 unsigned NumTemplateArgs) {
619 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
620
621 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
622 mangleUnscopedTemplateName(TD);
623 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
624 } else {
625 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
626 }
627}
628
629void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
630 // <unscoped-name> ::= <unqualified-name>
631 // ::= St <unqualified-name> # ::std::
632
633 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
634 Out << "St";
635
636 mangleUnqualifiedName(ND);
637}
638
639void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
640 // <unscoped-template-name> ::= <unscoped-name>
641 // ::= <substitution>
642 if (mangleSubstitution(ND))
643 return;
644
645 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000646 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000648 else
649 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000650
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 addSubstitution(ND);
652}
653
654void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
655 // <unscoped-template-name> ::= <unscoped-name>
656 // ::= <substitution>
657 if (TemplateDecl *TD = Template.getAsTemplateDecl())
658 return mangleUnscopedTemplateName(TD);
659
660 if (mangleSubstitution(Template))
661 return;
662
663 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
664 assert(Dependent && "Not a dependent template name?");
665 if (const IdentifierInfo *Id = Dependent->getIdentifier())
666 mangleSourceName(Id);
667 else
668 mangleOperatorName(Dependent->getOperator(), UnknownArity);
669
670 addSubstitution(Template);
671}
672
673void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
674 // ABI:
675 // Floating-point literals are encoded using a fixed-length
676 // lowercase hexadecimal string corresponding to the internal
677 // representation (IEEE on Itanium), high-order bytes first,
678 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
679 // on Itanium.
680 // The 'without leading zeroes' thing seems to be an editorial
681 // mistake; see the discussion on cxx-abi-dev beginning on
682 // 2012-01-16.
683
684 // Our requirements here are just barely weird enough to justify
685 // using a custom algorithm instead of post-processing APInt::toString().
686
687 llvm::APInt valueBits = f.bitcastToAPInt();
688 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
689 assert(numCharacters != 0);
690
691 // Allocate a buffer of the right number of characters.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000692 SmallVector<char, 20> buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 buffer.set_size(numCharacters);
694
695 // Fill the buffer left-to-right.
696 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
697 // The bit-index of the next hex digit.
698 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
699
700 // Project out 4 bits starting at 'digitIndex'.
701 llvm::integerPart hexDigit
702 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
703 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
704 hexDigit &= 0xF;
705
706 // Map that over to a lowercase hex digit.
707 static const char charForHex[16] = {
708 '0', '1', '2', '3', '4', '5', '6', '7',
709 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
710 };
711 buffer[stringIndex] = charForHex[hexDigit];
712 }
713
714 Out.write(buffer.data(), numCharacters);
715}
716
717void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
718 if (Value.isSigned() && Value.isNegative()) {
719 Out << 'n';
720 Value.abs().print(Out, /*signed*/ false);
721 } else {
722 Value.print(Out, /*signed*/ false);
723 }
724}
725
726void CXXNameMangler::mangleNumber(int64_t Number) {
727 // <number> ::= [n] <non-negative decimal integer>
728 if (Number < 0) {
729 Out << 'n';
730 Number = -Number;
731 }
732
733 Out << Number;
734}
735
736void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
737 // <call-offset> ::= h <nv-offset> _
738 // ::= v <v-offset> _
739 // <nv-offset> ::= <offset number> # non-virtual base override
740 // <v-offset> ::= <offset number> _ <virtual offset number>
741 // # virtual base override, with vcall offset
742 if (!Virtual) {
743 Out << 'h';
744 mangleNumber(NonVirtual);
745 Out << '_';
746 return;
747 }
748
749 Out << 'v';
750 mangleNumber(NonVirtual);
751 Out << '_';
752 mangleNumber(Virtual);
753 Out << '_';
754}
755
756void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000757 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 if (!mangleSubstitution(QualType(TST, 0))) {
759 mangleTemplatePrefix(TST->getTemplateName());
760
761 // FIXME: GCC does not appear to mangle the template arguments when
762 // the template in question is a dependent template name. Should we
763 // emulate that badness?
764 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
765 addSubstitution(QualType(TST, 0));
766 }
David Majnemera88b3592015-02-18 02:28:01 +0000767 } else if (const auto *DTST =
768 type->getAs<DependentTemplateSpecializationType>()) {
769 if (!mangleSubstitution(QualType(DTST, 0))) {
770 TemplateName Template = getASTContext().getDependentTemplateName(
771 DTST->getQualifier(), DTST->getIdentifier());
772 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000773
David Majnemera88b3592015-02-18 02:28:01 +0000774 // FIXME: GCC does not appear to mangle the template arguments when
775 // the template in question is a dependent template name. Should we
776 // emulate that badness?
777 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
778 addSubstitution(QualType(DTST, 0));
779 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 } else {
781 // We use the QualType mangle type variant here because it handles
782 // substitutions.
783 mangleType(type);
784 }
785}
786
787/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
788///
789/// \param firstQualifierLookup - the entity found by unqualified lookup
790/// for the first name in the qualifier, if this is for a member expression
791/// \param recursive - true if this is being called recursively,
792/// i.e. if there is more prefix "to the right".
793void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
794 NamedDecl *firstQualifierLookup,
795 bool recursive) {
796
797 // x, ::x
798 // <unresolved-name> ::= [gs] <base-unresolved-name>
799
800 // T::x / decltype(p)::x
801 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
802
803 // T::N::x /decltype(p)::N::x
804 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
805 // <base-unresolved-name>
806
807 // A::x, N::y, A<T>::z; "gs" means leading "::"
808 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
809 // <base-unresolved-name>
810
811 switch (qualifier->getKind()) {
812 case NestedNameSpecifier::Global:
813 Out << "gs";
814
815 // We want an 'sr' unless this is the entire NNS.
816 if (recursive)
817 Out << "sr";
818
819 // We never want an 'E' here.
820 return;
821
Nikola Smiljanic67860242014-09-26 00:28:20 +0000822 case NestedNameSpecifier::Super:
823 llvm_unreachable("Can't mangle __super specifier");
824
Guy Benyei11169dd2012-12-18 14:30:41 +0000825 case NestedNameSpecifier::Namespace:
826 if (qualifier->getPrefix())
827 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
828 /*recursive*/ true);
829 else
830 Out << "sr";
831 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
832 break;
833 case NestedNameSpecifier::NamespaceAlias:
834 if (qualifier->getPrefix())
835 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
836 /*recursive*/ true);
837 else
838 Out << "sr";
839 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
840 break;
841
842 case NestedNameSpecifier::TypeSpec:
843 case NestedNameSpecifier::TypeSpecWithTemplate: {
844 const Type *type = qualifier->getAsType();
845
846 // We only want to use an unresolved-type encoding if this is one of:
847 // - a decltype
848 // - a template type parameter
849 // - a template template parameter with arguments
850 // In all of these cases, we should have no prefix.
851 if (qualifier->getPrefix()) {
852 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
853 /*recursive*/ true);
854 } else {
855 // Otherwise, all the cases want this.
856 Out << "sr";
857 }
858
859 // Only certain other types are valid as prefixes; enumerate them.
860 switch (type->getTypeClass()) {
861 case Type::Builtin:
862 case Type::Complex:
Reid Kleckner0503a872013-12-05 01:23:43 +0000863 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +0000864 case Type::Decayed:
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 case Type::Pointer:
866 case Type::BlockPointer:
867 case Type::LValueReference:
868 case Type::RValueReference:
869 case Type::MemberPointer:
870 case Type::ConstantArray:
871 case Type::IncompleteArray:
872 case Type::VariableArray:
873 case Type::DependentSizedArray:
874 case Type::DependentSizedExtVector:
875 case Type::Vector:
876 case Type::ExtVector:
877 case Type::FunctionProto:
878 case Type::FunctionNoProto:
879 case Type::Enum:
880 case Type::Paren:
881 case Type::Elaborated:
882 case Type::Attributed:
883 case Type::Auto:
884 case Type::PackExpansion:
885 case Type::ObjCObject:
886 case Type::ObjCInterface:
887 case Type::ObjCObjectPointer:
888 case Type::Atomic:
889 llvm_unreachable("type is illegal as a nested name specifier");
890
891 case Type::SubstTemplateTypeParmPack:
892 // FIXME: not clear how to mangle this!
893 // template <class T...> class A {
894 // template <class U...> void foo(decltype(T::foo(U())) x...);
895 // };
896 Out << "_SUBSTPACK_";
897 break;
898
899 // <unresolved-type> ::= <template-param>
900 // ::= <decltype>
901 // ::= <template-template-param> <template-args>
902 // (this last is not official yet)
903 case Type::TypeOfExpr:
904 case Type::TypeOf:
905 case Type::Decltype:
906 case Type::TemplateTypeParm:
907 case Type::UnaryTransform:
908 case Type::SubstTemplateTypeParm:
909 unresolvedType:
910 assert(!qualifier->getPrefix());
911
912 // We only get here recursively if we're followed by identifiers.
913 if (recursive) Out << 'N';
914
915 // This seems to do everything we want. It's not really
916 // sanctioned for a substituted template parameter, though.
917 mangleType(QualType(type, 0));
918
919 // We never want to print 'E' directly after an unresolved-type,
920 // so we return directly.
921 return;
922
923 case Type::Typedef:
924 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
925 break;
926
927 case Type::UnresolvedUsing:
928 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
929 ->getIdentifier());
930 break;
931
932 case Type::Record:
933 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
934 break;
935
936 case Type::TemplateSpecialization: {
937 const TemplateSpecializationType *tst
938 = cast<TemplateSpecializationType>(type);
939 TemplateName name = tst->getTemplateName();
940 switch (name.getKind()) {
941 case TemplateName::Template:
942 case TemplateName::QualifiedTemplate: {
943 TemplateDecl *temp = name.getAsTemplateDecl();
944
945 // If the base is a template template parameter, this is an
946 // unresolved type.
947 assert(temp && "no template for template specialization type");
948 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
949
950 mangleSourceName(temp->getIdentifier());
951 break;
952 }
953
954 case TemplateName::OverloadedTemplate:
955 case TemplateName::DependentTemplate:
956 llvm_unreachable("invalid base for a template specialization type");
957
958 case TemplateName::SubstTemplateTemplateParm: {
959 SubstTemplateTemplateParmStorage *subst
960 = name.getAsSubstTemplateTemplateParm();
961 mangleExistingSubstitution(subst->getReplacement());
962 break;
963 }
964
965 case TemplateName::SubstTemplateTemplateParmPack: {
966 // FIXME: not clear how to mangle this!
967 // template <template <class U> class T...> class A {
968 // template <class U...> void foo(decltype(T<U>::foo) x...);
969 // };
970 Out << "_SUBSTPACK_";
971 break;
972 }
973 }
974
975 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
976 break;
977 }
978
979 case Type::InjectedClassName:
980 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
981 ->getIdentifier());
982 break;
983
984 case Type::DependentName:
985 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
986 break;
987
988 case Type::DependentTemplateSpecialization: {
989 const DependentTemplateSpecializationType *tst
990 = cast<DependentTemplateSpecializationType>(type);
991 mangleSourceName(tst->getIdentifier());
992 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
993 break;
994 }
995 }
996 break;
997 }
998
999 case NestedNameSpecifier::Identifier:
1000 // Member expressions can have these without prefixes.
1001 if (qualifier->getPrefix()) {
1002 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
1003 /*recursive*/ true);
1004 } else if (firstQualifierLookup) {
1005
1006 // Try to make a proper qualifier out of the lookup result, and
1007 // then just recurse on that.
1008 NestedNameSpecifier *newQualifier;
1009 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
1010 QualType type = getASTContext().getTypeDeclType(typeDecl);
1011
1012 // Pretend we had a different nested name specifier.
1013 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001014 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 /*template*/ false,
1016 type.getTypePtr());
1017 } else if (NamespaceDecl *nspace =
1018 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
1019 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001020 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 nspace);
1022 } else if (NamespaceAliasDecl *alias =
1023 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
1024 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001025 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 alias);
1027 } else {
1028 // No sensible mangling to do here.
Craig Topper36250ad2014-05-12 05:36:57 +00001029 newQualifier = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 }
1031
1032 if (newQualifier)
Craig Topper36250ad2014-05-12 05:36:57 +00001033 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
1034 recursive);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035
1036 } else {
1037 Out << "sr";
1038 }
1039
1040 mangleSourceName(qualifier->getAsIdentifier());
1041 break;
1042 }
1043
1044 // If this was the innermost part of the NNS, and we fell out to
1045 // here, append an 'E'.
1046 if (!recursive)
1047 Out << 'E';
1048}
1049
1050/// Mangle an unresolved-name, which is generally used for names which
1051/// weren't resolved to specific entities.
1052void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1053 NamedDecl *firstQualifierLookup,
1054 DeclarationName name,
1055 unsigned knownArity) {
1056 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001057 switch (name.getNameKind()) {
1058 // <base-unresolved-name> ::= <simple-id>
1059 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001060 mangleSourceName(name.getAsIdentifierInfo());
1061 break;
1062 // <base-unresolved-name> ::= dn <destructor-name>
1063 case DeclarationName::CXXDestructorName:
1064 Out << "dn";
1065 mangleDestructorName(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001066 break;
1067 // <base-unresolved-name> ::= on <operator-name>
1068 case DeclarationName::CXXConversionFunctionName:
1069 case DeclarationName::CXXLiteralOperatorName:
1070 case DeclarationName::CXXOperatorName:
1071 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001072 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001073 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001074 case DeclarationName::CXXConstructorName:
1075 llvm_unreachable("Can't mangle a constructor name!");
1076 case DeclarationName::CXXUsingDirective:
1077 llvm_unreachable("Can't mangle a using directive name!");
1078 case DeclarationName::ObjCMultiArgSelector:
1079 case DeclarationName::ObjCOneArgSelector:
1080 case DeclarationName::ObjCZeroArgSelector:
1081 llvm_unreachable("Can't mangle Objective-C selector names here!");
1082 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001083}
1084
Guy Benyei11169dd2012-12-18 14:30:41 +00001085void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1086 DeclarationName Name,
1087 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +00001088 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 // <unqualified-name> ::= <operator-name>
1090 // ::= <ctor-dtor-name>
1091 // ::= <source-name>
1092 switch (Name.getNameKind()) {
1093 case DeclarationName::Identifier: {
1094 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1095 // We must avoid conflicts between internally- and externally-
1096 // linked variable and function declaration names in the same TU:
1097 // void test() { extern void foo(); }
1098 // static void foo();
1099 // This naming convention is the same as that followed by GCC,
1100 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001101 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 getEffectiveDeclContext(ND)->isFileContext())
1103 Out << 'L';
1104
1105 mangleSourceName(II);
1106 break;
1107 }
1108
1109 // Otherwise, an anonymous entity. We must have a declaration.
1110 assert(ND && "mangling empty name without declaration");
1111
1112 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1113 if (NS->isAnonymousNamespace()) {
1114 // This is how gcc mangles these names.
1115 Out << "12_GLOBAL__N_1";
1116 break;
1117 }
1118 }
1119
1120 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1121 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001122 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001124
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 // Itanium C++ ABI 5.1.2:
1126 //
1127 // For the purposes of mangling, the name of an anonymous union is
1128 // considered to be the name of the first named data member found by a
1129 // pre-order, depth-first, declaration-order walk of the data members of
1130 // the anonymous union. If there is no such data member (i.e., if all of
1131 // the data members in the union are unnamed), then there is no way for
1132 // a program to refer to the anonymous union, and there is therefore no
1133 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001134 assert(RD->isAnonymousStructOrUnion()
1135 && "Expected anonymous struct or union!");
1136 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001137
1138 // It's actually possible for various reasons for us to get here
1139 // with an empty anonymous struct / union. Fortunately, it
1140 // doesn't really matter what name we generate.
1141 if (!FD) break;
1142 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001143
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 mangleSourceName(FD->getIdentifier());
1145 break;
1146 }
John McCall924046f2013-04-10 06:08:21 +00001147
1148 // Class extensions have no name as a category, and it's possible
1149 // for them to be the semantic parent of certain declarations
1150 // (primarily, tag decls defined within declarations). Such
1151 // declarations will always have internal linkage, so the name
1152 // doesn't really matter, but we shouldn't crash on them. For
1153 // safety, just handle all ObjC containers here.
1154 if (isa<ObjCContainerDecl>(ND))
1155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001156
1157 // We must have an anonymous struct.
1158 const TagDecl *TD = cast<TagDecl>(ND);
1159 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1160 assert(TD->getDeclContext() == D->getDeclContext() &&
1161 "Typedef should not be in another decl context!");
1162 assert(D->getDeclName().getAsIdentifierInfo() &&
1163 "Typedef was not named!");
1164 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1165 break;
1166 }
1167
1168 // <unnamed-type-name> ::= <closure-type-name>
1169 //
1170 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1171 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1172 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1173 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1174 mangleLambda(Record);
1175 break;
1176 }
1177 }
1178
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001179 if (TD->isExternallyVisible()) {
1180 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001182 if (UnnamedMangle > 1)
1183 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 Out << '_';
1185 break;
1186 }
1187
1188 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001189 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001190
1191 // Mangle it as a source name in the form
1192 // [n] $_<id>
1193 // where n is the length of the string.
1194 SmallString<8> Str;
1195 Str += "$_";
1196 Str += llvm::utostr(AnonStructId);
1197
1198 Out << Str.size();
1199 Out << Str.str();
1200 break;
1201 }
1202
1203 case DeclarationName::ObjCZeroArgSelector:
1204 case DeclarationName::ObjCOneArgSelector:
1205 case DeclarationName::ObjCMultiArgSelector:
1206 llvm_unreachable("Can't mangle Objective-C selector names here!");
1207
1208 case DeclarationName::CXXConstructorName:
1209 if (ND == Structor)
1210 // If the named decl is the C++ constructor we're mangling, use the type
1211 // we were given.
1212 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1213 else
1214 // Otherwise, use the complete constructor name. This is relevant if a
1215 // class with a constructor is declared within a constructor.
1216 mangleCXXCtorType(Ctor_Complete);
1217 break;
1218
1219 case DeclarationName::CXXDestructorName:
1220 if (ND == Structor)
1221 // If the named decl is the C++ destructor we're mangling, use the type we
1222 // were given.
1223 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1224 else
1225 // Otherwise, use the complete destructor name. This is relevant if a
1226 // class with a destructor is declared within a destructor.
1227 mangleCXXDtorType(Dtor_Complete);
1228 break;
1229
David Majnemera88b3592015-02-18 02:28:01 +00001230 case DeclarationName::CXXOperatorName:
1231 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 Arity = cast<FunctionDecl>(ND)->getNumParams();
1233
David Majnemera88b3592015-02-18 02:28:01 +00001234 // If we have a member function, we need to include the 'this' pointer.
1235 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1236 if (!MD->isStatic())
1237 Arity++;
1238 }
1239 // FALLTHROUGH
1240 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001242 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 break;
1244
1245 case DeclarationName::CXXUsingDirective:
1246 llvm_unreachable("Can't mangle a using directive name!");
1247 }
1248}
1249
1250void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1251 // <source-name> ::= <positive length number> <identifier>
1252 // <number> ::= [n] <non-negative decimal integer>
1253 // <identifier> ::= <unqualified source code identifier>
1254 Out << II->getLength() << II->getName();
1255}
1256
1257void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1258 const DeclContext *DC,
1259 bool NoFunction) {
1260 // <nested-name>
1261 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1262 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1263 // <template-args> E
1264
1265 Out << 'N';
1266 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001267 Qualifiers MethodQuals =
1268 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1269 // We do not consider restrict a distinguishing attribute for overloading
1270 // purposes so we must not mangle it.
1271 MethodQuals.removeRestrict();
1272 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 mangleRefQualifier(Method->getRefQualifier());
1274 }
1275
1276 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001277 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001278 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001279 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 mangleTemplateArgs(*TemplateArgs);
1281 }
1282 else {
1283 manglePrefix(DC, NoFunction);
1284 mangleUnqualifiedName(ND);
1285 }
1286
1287 Out << 'E';
1288}
1289void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1290 const TemplateArgument *TemplateArgs,
1291 unsigned NumTemplateArgs) {
1292 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1293
1294 Out << 'N';
1295
1296 mangleTemplatePrefix(TD);
1297 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1298
1299 Out << 'E';
1300}
1301
Eli Friedman95f50122013-07-02 17:52:28 +00001302void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1304 // := Z <function encoding> E s [<discriminator>]
1305 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1306 // _ <entity name>
1307 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001308 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001309 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001310 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001311
1312 Out << 'Z';
1313
Eli Friedman92821742013-07-02 02:01:18 +00001314 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1315 mangleObjCMethodName(MD);
1316 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001317 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001318 else
1319 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001320
Eli Friedman92821742013-07-02 02:01:18 +00001321 Out << 'E';
1322
1323 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 // The parameter number is omitted for the last parameter, 0 for the
1325 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1326 // <entity name> will of course contain a <closure-type-name>: Its
1327 // numbering will be local to the particular argument in which it appears
1328 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001329 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1330 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001331 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001332 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 if (const FunctionDecl *Func
1334 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1335 Out << 'd';
1336 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1337 if (Num > 1)
1338 mangleNumber(Num - 2);
1339 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 }
1341 }
1342 }
1343
1344 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001345 // equality ok because RD derived from ND above
1346 if (D == RD) {
1347 mangleUnqualifiedName(RD);
1348 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1349 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1350 mangleUnqualifiedBlock(BD);
1351 } else {
1352 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001353 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001354 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001355 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1356 // Mangle a block in a default parameter; see above explanation for
1357 // lambdas.
1358 if (const ParmVarDecl *Parm
1359 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1360 if (const FunctionDecl *Func
1361 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1362 Out << 'd';
1363 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1364 if (Num > 1)
1365 mangleNumber(Num - 2);
1366 Out << '_';
1367 }
1368 }
1369
1370 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001371 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001372 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001374
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001375 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1376 unsigned disc;
1377 if (Context.getNextDiscriminator(ND, disc)) {
1378 if (disc < 10)
1379 Out << '_' << disc;
1380 else
1381 Out << "__" << disc << '_';
1382 }
1383 }
Eli Friedman95f50122013-07-02 17:52:28 +00001384}
1385
1386void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1387 if (GetLocalClassDecl(Block)) {
1388 mangleLocalName(Block);
1389 return;
1390 }
1391 const DeclContext *DC = getEffectiveDeclContext(Block);
1392 if (isLocalContainerContext(DC)) {
1393 mangleLocalName(Block);
1394 return;
1395 }
1396 manglePrefix(getEffectiveDeclContext(Block));
1397 mangleUnqualifiedBlock(Block);
1398}
1399
1400void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1401 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1402 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1403 Context->getDeclContext()->isRecord()) {
1404 if (const IdentifierInfo *Name
1405 = cast<NamedDecl>(Context)->getIdentifier()) {
1406 mangleSourceName(Name);
1407 Out << 'M';
1408 }
1409 }
1410 }
1411
1412 // If we have a block mangling number, use it.
1413 unsigned Number = Block->getBlockManglingNumber();
1414 // Otherwise, just make up a number. It doesn't matter what it is because
1415 // the symbol in question isn't externally visible.
1416 if (!Number)
1417 Number = Context.getBlockId(Block, false);
1418 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001419 if (Number > 0)
1420 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001421 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001422}
1423
1424void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1425 // If the context of a closure type is an initializer for a class member
1426 // (static or nonstatic), it is encoded in a qualified name with a final
1427 // <prefix> of the form:
1428 //
1429 // <data-member-prefix> := <member source-name> M
1430 //
1431 // Technically, the data-member-prefix is part of the <prefix>. However,
1432 // since a closure type will always be mangled with a prefix, it's easier
1433 // to emit that last part of the prefix here.
1434 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1435 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1436 Context->getDeclContext()->isRecord()) {
1437 if (const IdentifierInfo *Name
1438 = cast<NamedDecl>(Context)->getIdentifier()) {
1439 mangleSourceName(Name);
1440 Out << 'M';
1441 }
1442 }
1443 }
1444
1445 Out << "Ul";
1446 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1447 getAs<FunctionProtoType>();
1448 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1449 Out << "E";
1450
1451 // The number is omitted for the first closure type with a given
1452 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1453 // (in lexical order) with that same <lambda-sig> and context.
1454 //
1455 // The AST keeps track of the number for us.
1456 unsigned Number = Lambda->getLambdaManglingNumber();
1457 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1458 if (Number > 1)
1459 mangleNumber(Number - 2);
1460 Out << '_';
1461}
1462
1463void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1464 switch (qualifier->getKind()) {
1465 case NestedNameSpecifier::Global:
1466 // nothing
1467 return;
1468
Nikola Smiljanic67860242014-09-26 00:28:20 +00001469 case NestedNameSpecifier::Super:
1470 llvm_unreachable("Can't mangle __super specifier");
1471
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 case NestedNameSpecifier::Namespace:
1473 mangleName(qualifier->getAsNamespace());
1474 return;
1475
1476 case NestedNameSpecifier::NamespaceAlias:
1477 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1478 return;
1479
1480 case NestedNameSpecifier::TypeSpec:
1481 case NestedNameSpecifier::TypeSpecWithTemplate:
1482 manglePrefix(QualType(qualifier->getAsType(), 0));
1483 return;
1484
1485 case NestedNameSpecifier::Identifier:
1486 // Member expressions can have these without prefixes, but that
1487 // should end up in mangleUnresolvedPrefix instead.
1488 assert(qualifier->getPrefix());
1489 manglePrefix(qualifier->getPrefix());
1490
1491 mangleSourceName(qualifier->getAsIdentifier());
1492 return;
1493 }
1494
1495 llvm_unreachable("unexpected nested name specifier");
1496}
1497
1498void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1499 // <prefix> ::= <prefix> <unqualified-name>
1500 // ::= <template-prefix> <template-args>
1501 // ::= <template-param>
1502 // ::= # empty
1503 // ::= <substitution>
1504
1505 DC = IgnoreLinkageSpecDecls(DC);
1506
1507 if (DC->isTranslationUnit())
1508 return;
1509
Eli Friedman95f50122013-07-02 17:52:28 +00001510 if (NoFunction && isLocalContainerContext(DC))
1511 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001512
Eli Friedman95f50122013-07-02 17:52:28 +00001513 assert(!isLocalContainerContext(DC));
1514
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 const NamedDecl *ND = cast<NamedDecl>(DC);
1516 if (mangleSubstitution(ND))
1517 return;
1518
1519 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001520 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1522 mangleTemplatePrefix(TD);
1523 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001524 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1526 mangleUnqualifiedName(ND);
1527 }
1528
1529 addSubstitution(ND);
1530}
1531
1532void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1533 // <template-prefix> ::= <prefix> <template unqualified-name>
1534 // ::= <template-param>
1535 // ::= <substitution>
1536 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1537 return mangleTemplatePrefix(TD);
1538
1539 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1540 manglePrefix(Qualified->getQualifier());
1541
1542 if (OverloadedTemplateStorage *Overloaded
1543 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001544 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 UnknownArity);
1546 return;
1547 }
1548
1549 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1550 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001551 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1552 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 mangleUnscopedTemplateName(Template);
1554}
1555
Eli Friedman86af13f02013-07-05 18:41:30 +00001556void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1557 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001558 // <template-prefix> ::= <prefix> <template unqualified-name>
1559 // ::= <template-param>
1560 // ::= <substitution>
1561 // <template-template-param> ::= <template-param>
1562 // <substitution>
1563
1564 if (mangleSubstitution(ND))
1565 return;
1566
1567 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001568 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001570 } else {
1571 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1572 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001573 }
1574
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 addSubstitution(ND);
1576}
1577
1578/// Mangles a template name under the production <type>. Required for
1579/// template template arguments.
1580/// <type> ::= <class-enum-type>
1581/// ::= <template-param>
1582/// ::= <substitution>
1583void CXXNameMangler::mangleType(TemplateName TN) {
1584 if (mangleSubstitution(TN))
1585 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001586
1587 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001588
1589 switch (TN.getKind()) {
1590 case TemplateName::QualifiedTemplate:
1591 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1592 goto HaveDecl;
1593
1594 case TemplateName::Template:
1595 TD = TN.getAsTemplateDecl();
1596 goto HaveDecl;
1597
1598 HaveDecl:
1599 if (isa<TemplateTemplateParmDecl>(TD))
1600 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1601 else
1602 mangleName(TD);
1603 break;
1604
1605 case TemplateName::OverloadedTemplate:
1606 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1607
1608 case TemplateName::DependentTemplate: {
1609 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1610 assert(Dependent->isIdentifier());
1611
1612 // <class-enum-type> ::= <name>
1613 // <name> ::= <nested-name>
Craig Topper36250ad2014-05-12 05:36:57 +00001614 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 mangleSourceName(Dependent->getIdentifier());
1616 break;
1617 }
1618
1619 case TemplateName::SubstTemplateTemplateParm: {
1620 // Substituted template parameters are mangled as the substituted
1621 // template. This will check for the substitution twice, which is
1622 // fine, but we have to return early so that we don't try to *add*
1623 // the substitution twice.
1624 SubstTemplateTemplateParmStorage *subst
1625 = TN.getAsSubstTemplateTemplateParm();
1626 mangleType(subst->getReplacement());
1627 return;
1628 }
1629
1630 case TemplateName::SubstTemplateTemplateParmPack: {
1631 // FIXME: not clear how to mangle this!
1632 // template <template <class> class T...> class A {
1633 // template <template <class> class U...> void foo(B<T,U> x...);
1634 // };
1635 Out << "_SUBSTPACK_";
1636 break;
1637 }
1638 }
1639
1640 addSubstitution(TN);
1641}
1642
David Majnemera88b3592015-02-18 02:28:01 +00001643void CXXNameMangler::mangleDestructorName(QualType DestroyedType) {
1644 // <destructor-name> ::= <unresolved-type>
1645 // ::= <simple-id>
1646 if (const auto *TST = DestroyedType->getAs<TemplateSpecializationType>()) {
1647 TemplateName TN = TST->getTemplateName();
1648 const auto *TD = TN.getAsTemplateDecl();
1649 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD)) {
1650 // Proposed to cxx-abi-dev on 2015-02-17.
1651 mangleTemplateParameter(TTP->getIndex());
1652 } else {
1653 mangleUnscopedName(TD->getTemplatedDecl());
1654 }
1655 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1656 } else if (const auto *DTST =
1657 DestroyedType->getAs<DependentTemplateSpecializationType>()) {
1658 const IdentifierInfo *II = DTST->getIdentifier();
1659 mangleSourceName(II);
1660 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1661 } else {
1662 // We use the QualType mangle type variant here because it handles
1663 // substitutions.
1664 mangleType(DestroyedType);
1665 }
1666}
1667
1668void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1669 switch (Name.getNameKind()) {
1670 case DeclarationName::CXXConstructorName:
1671 case DeclarationName::CXXDestructorName:
1672 case DeclarationName::CXXUsingDirective:
1673 case DeclarationName::Identifier:
1674 case DeclarationName::ObjCMultiArgSelector:
1675 case DeclarationName::ObjCOneArgSelector:
1676 case DeclarationName::ObjCZeroArgSelector:
1677 llvm_unreachable("Not an operator name");
1678
1679 case DeclarationName::CXXConversionFunctionName:
1680 // <operator-name> ::= cv <type> # (cast)
1681 Out << "cv";
1682 mangleType(Name.getCXXNameType());
1683 break;
1684
1685 case DeclarationName::CXXLiteralOperatorName:
1686 Out << "li";
1687 mangleSourceName(Name.getCXXLiteralIdentifier());
1688 return;
1689
1690 case DeclarationName::CXXOperatorName:
1691 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1692 break;
1693 }
1694}
1695
1696
1697
Guy Benyei11169dd2012-12-18 14:30:41 +00001698void
1699CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1700 switch (OO) {
1701 // <operator-name> ::= nw # new
1702 case OO_New: Out << "nw"; break;
1703 // ::= na # new[]
1704 case OO_Array_New: Out << "na"; break;
1705 // ::= dl # delete
1706 case OO_Delete: Out << "dl"; break;
1707 // ::= da # delete[]
1708 case OO_Array_Delete: Out << "da"; break;
1709 // ::= ps # + (unary)
1710 // ::= pl # + (binary or unknown)
1711 case OO_Plus:
1712 Out << (Arity == 1? "ps" : "pl"); break;
1713 // ::= ng # - (unary)
1714 // ::= mi # - (binary or unknown)
1715 case OO_Minus:
1716 Out << (Arity == 1? "ng" : "mi"); break;
1717 // ::= ad # & (unary)
1718 // ::= an # & (binary or unknown)
1719 case OO_Amp:
1720 Out << (Arity == 1? "ad" : "an"); break;
1721 // ::= de # * (unary)
1722 // ::= ml # * (binary or unknown)
1723 case OO_Star:
1724 // Use binary when unknown.
1725 Out << (Arity == 1? "de" : "ml"); break;
1726 // ::= co # ~
1727 case OO_Tilde: Out << "co"; break;
1728 // ::= dv # /
1729 case OO_Slash: Out << "dv"; break;
1730 // ::= rm # %
1731 case OO_Percent: Out << "rm"; break;
1732 // ::= or # |
1733 case OO_Pipe: Out << "or"; break;
1734 // ::= eo # ^
1735 case OO_Caret: Out << "eo"; break;
1736 // ::= aS # =
1737 case OO_Equal: Out << "aS"; break;
1738 // ::= pL # +=
1739 case OO_PlusEqual: Out << "pL"; break;
1740 // ::= mI # -=
1741 case OO_MinusEqual: Out << "mI"; break;
1742 // ::= mL # *=
1743 case OO_StarEqual: Out << "mL"; break;
1744 // ::= dV # /=
1745 case OO_SlashEqual: Out << "dV"; break;
1746 // ::= rM # %=
1747 case OO_PercentEqual: Out << "rM"; break;
1748 // ::= aN # &=
1749 case OO_AmpEqual: Out << "aN"; break;
1750 // ::= oR # |=
1751 case OO_PipeEqual: Out << "oR"; break;
1752 // ::= eO # ^=
1753 case OO_CaretEqual: Out << "eO"; break;
1754 // ::= ls # <<
1755 case OO_LessLess: Out << "ls"; break;
1756 // ::= rs # >>
1757 case OO_GreaterGreater: Out << "rs"; break;
1758 // ::= lS # <<=
1759 case OO_LessLessEqual: Out << "lS"; break;
1760 // ::= rS # >>=
1761 case OO_GreaterGreaterEqual: Out << "rS"; break;
1762 // ::= eq # ==
1763 case OO_EqualEqual: Out << "eq"; break;
1764 // ::= ne # !=
1765 case OO_ExclaimEqual: Out << "ne"; break;
1766 // ::= lt # <
1767 case OO_Less: Out << "lt"; break;
1768 // ::= gt # >
1769 case OO_Greater: Out << "gt"; break;
1770 // ::= le # <=
1771 case OO_LessEqual: Out << "le"; break;
1772 // ::= ge # >=
1773 case OO_GreaterEqual: Out << "ge"; break;
1774 // ::= nt # !
1775 case OO_Exclaim: Out << "nt"; break;
1776 // ::= aa # &&
1777 case OO_AmpAmp: Out << "aa"; break;
1778 // ::= oo # ||
1779 case OO_PipePipe: Out << "oo"; break;
1780 // ::= pp # ++
1781 case OO_PlusPlus: Out << "pp"; break;
1782 // ::= mm # --
1783 case OO_MinusMinus: Out << "mm"; break;
1784 // ::= cm # ,
1785 case OO_Comma: Out << "cm"; break;
1786 // ::= pm # ->*
1787 case OO_ArrowStar: Out << "pm"; break;
1788 // ::= pt # ->
1789 case OO_Arrow: Out << "pt"; break;
1790 // ::= cl # ()
1791 case OO_Call: Out << "cl"; break;
1792 // ::= ix # []
1793 case OO_Subscript: Out << "ix"; break;
1794
1795 // ::= qu # ?
1796 // The conditional operator can't be overloaded, but we still handle it when
1797 // mangling expressions.
1798 case OO_Conditional: Out << "qu"; break;
1799
1800 case OO_None:
1801 case NUM_OVERLOADED_OPERATORS:
1802 llvm_unreachable("Not an overloaded operator");
1803 }
1804}
1805
1806void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1807 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1808 if (Quals.hasRestrict())
1809 Out << 'r';
1810 if (Quals.hasVolatile())
1811 Out << 'V';
1812 if (Quals.hasConst())
1813 Out << 'K';
1814
1815 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001816 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 //
David Tweed31d09b02013-09-13 12:04:22 +00001818 // <type> ::= U <target-addrspace>
1819 // <type> ::= U <OpenCL-addrspace>
1820 // <type> ::= U <CUDA-addrspace>
1821
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001823 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001824
1825 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1826 // <target-addrspace> ::= "AS" <address-space-number>
1827 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1828 ASString = "AS" + llvm::utostr_32(TargetAS);
1829 } else {
1830 switch (AS) {
1831 default: llvm_unreachable("Not a language specific address space");
1832 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1833 case LangAS::opencl_global: ASString = "CLglobal"; break;
1834 case LangAS::opencl_local: ASString = "CLlocal"; break;
1835 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1836 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1837 case LangAS::cuda_device: ASString = "CUdevice"; break;
1838 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1839 case LangAS::cuda_shared: ASString = "CUshared"; break;
1840 }
1841 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 Out << 'U' << ASString.size() << ASString;
1843 }
1844
1845 StringRef LifetimeName;
1846 switch (Quals.getObjCLifetime()) {
1847 // Objective-C ARC Extension:
1848 //
1849 // <type> ::= U "__strong"
1850 // <type> ::= U "__weak"
1851 // <type> ::= U "__autoreleasing"
1852 case Qualifiers::OCL_None:
1853 break;
1854
1855 case Qualifiers::OCL_Weak:
1856 LifetimeName = "__weak";
1857 break;
1858
1859 case Qualifiers::OCL_Strong:
1860 LifetimeName = "__strong";
1861 break;
1862
1863 case Qualifiers::OCL_Autoreleasing:
1864 LifetimeName = "__autoreleasing";
1865 break;
1866
1867 case Qualifiers::OCL_ExplicitNone:
1868 // The __unsafe_unretained qualifier is *not* mangled, so that
1869 // __unsafe_unretained types in ARC produce the same manglings as the
1870 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1871 // better ABI compatibility.
1872 //
1873 // It's safe to do this because unqualified 'id' won't show up
1874 // in any type signatures that need to be mangled.
1875 break;
1876 }
1877 if (!LifetimeName.empty())
1878 Out << 'U' << LifetimeName.size() << LifetimeName;
1879}
1880
1881void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1882 // <ref-qualifier> ::= R # lvalue reference
1883 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001884 switch (RefQualifier) {
1885 case RQ_None:
1886 break;
1887
1888 case RQ_LValue:
1889 Out << 'R';
1890 break;
1891
1892 case RQ_RValue:
1893 Out << 'O';
1894 break;
1895 }
1896}
1897
1898void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1899 Context.mangleObjCMethodName(MD, Out);
1900}
1901
David Majnemereea02ee2014-11-28 22:22:46 +00001902static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1903 if (Quals)
1904 return true;
1905 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1906 return true;
1907 if (Ty->isOpenCLSpecificType())
1908 return true;
1909 if (Ty->isBuiltinType())
1910 return false;
1911
1912 return true;
1913}
1914
Guy Benyei11169dd2012-12-18 14:30:41 +00001915void CXXNameMangler::mangleType(QualType T) {
1916 // If our type is instantiation-dependent but not dependent, we mangle
1917 // it as it was written in the source, removing any top-level sugar.
1918 // Otherwise, use the canonical type.
1919 //
1920 // FIXME: This is an approximation of the instantiation-dependent name
1921 // mangling rules, since we should really be using the type as written and
1922 // augmented via semantic analysis (i.e., with implicit conversions and
1923 // default template arguments) for any instantiation-dependent type.
1924 // Unfortunately, that requires several changes to our AST:
1925 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1926 // uniqued, so that we can handle substitutions properly
1927 // - Default template arguments will need to be represented in the
1928 // TemplateSpecializationType, since they need to be mangled even though
1929 // they aren't written.
1930 // - Conversions on non-type template arguments need to be expressed, since
1931 // they can affect the mangling of sizeof/alignof.
1932 if (!T->isInstantiationDependentType() || T->isDependentType())
1933 T = T.getCanonicalType();
1934 else {
1935 // Desugar any types that are purely sugar.
1936 do {
1937 // Don't desugar through template specialization types that aren't
1938 // type aliases. We need to mangle the template arguments as written.
1939 if (const TemplateSpecializationType *TST
1940 = dyn_cast<TemplateSpecializationType>(T))
1941 if (!TST->isTypeAlias())
1942 break;
1943
1944 QualType Desugared
1945 = T.getSingleStepDesugaredType(Context.getASTContext());
1946 if (Desugared == T)
1947 break;
1948
1949 T = Desugared;
1950 } while (true);
1951 }
1952 SplitQualType split = T.split();
1953 Qualifiers quals = split.Quals;
1954 const Type *ty = split.Ty;
1955
David Majnemereea02ee2014-11-28 22:22:46 +00001956 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 if (isSubstitutable && mangleSubstitution(T))
1958 return;
1959
1960 // If we're mangling a qualified array type, push the qualifiers to
1961 // the element type.
1962 if (quals && isa<ArrayType>(T)) {
1963 ty = Context.getASTContext().getAsArrayType(T);
1964 quals = Qualifiers();
1965
1966 // Note that we don't update T: we want to add the
1967 // substitution at the original type.
1968 }
1969
1970 if (quals) {
1971 mangleQualifiers(quals);
1972 // Recurse: even if the qualified type isn't yet substitutable,
1973 // the unqualified type might be.
1974 mangleType(QualType(ty, 0));
1975 } else {
1976 switch (ty->getTypeClass()) {
1977#define ABSTRACT_TYPE(CLASS, PARENT)
1978#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1979 case Type::CLASS: \
1980 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1981 return;
1982#define TYPE(CLASS, PARENT) \
1983 case Type::CLASS: \
1984 mangleType(static_cast<const CLASS##Type*>(ty)); \
1985 break;
1986#include "clang/AST/TypeNodes.def"
1987 }
1988 }
1989
1990 // Add the substitution.
1991 if (isSubstitutable)
1992 addSubstitution(T);
1993}
1994
1995void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1996 if (!mangleStandardSubstitution(ND))
1997 mangleName(ND);
1998}
1999
2000void CXXNameMangler::mangleType(const BuiltinType *T) {
2001 // <type> ::= <builtin-type>
2002 // <builtin-type> ::= v # void
2003 // ::= w # wchar_t
2004 // ::= b # bool
2005 // ::= c # char
2006 // ::= a # signed char
2007 // ::= h # unsigned char
2008 // ::= s # short
2009 // ::= t # unsigned short
2010 // ::= i # int
2011 // ::= j # unsigned int
2012 // ::= l # long
2013 // ::= m # unsigned long
2014 // ::= x # long long, __int64
2015 // ::= y # unsigned long long, __int64
2016 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002017 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 // ::= f # float
2019 // ::= d # double
2020 // ::= e # long double, __float80
2021 // UNSUPPORTED: ::= g # __float128
2022 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2023 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2024 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2025 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2026 // ::= Di # char32_t
2027 // ::= Ds # char16_t
2028 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2029 // ::= u <source-name> # vendor extended type
2030 switch (T->getKind()) {
2031 case BuiltinType::Void: Out << 'v'; break;
2032 case BuiltinType::Bool: Out << 'b'; break;
2033 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
2034 case BuiltinType::UChar: Out << 'h'; break;
2035 case BuiltinType::UShort: Out << 't'; break;
2036 case BuiltinType::UInt: Out << 'j'; break;
2037 case BuiltinType::ULong: Out << 'm'; break;
2038 case BuiltinType::ULongLong: Out << 'y'; break;
2039 case BuiltinType::UInt128: Out << 'o'; break;
2040 case BuiltinType::SChar: Out << 'a'; break;
2041 case BuiltinType::WChar_S:
2042 case BuiltinType::WChar_U: Out << 'w'; break;
2043 case BuiltinType::Char16: Out << "Ds"; break;
2044 case BuiltinType::Char32: Out << "Di"; break;
2045 case BuiltinType::Short: Out << 's'; break;
2046 case BuiltinType::Int: Out << 'i'; break;
2047 case BuiltinType::Long: Out << 'l'; break;
2048 case BuiltinType::LongLong: Out << 'x'; break;
2049 case BuiltinType::Int128: Out << 'n'; break;
2050 case BuiltinType::Half: Out << "Dh"; break;
2051 case BuiltinType::Float: Out << 'f'; break;
2052 case BuiltinType::Double: Out << 'd'; break;
2053 case BuiltinType::LongDouble: Out << 'e'; break;
2054 case BuiltinType::NullPtr: Out << "Dn"; break;
2055
2056#define BUILTIN_TYPE(Id, SingletonId)
2057#define PLACEHOLDER_TYPE(Id, SingletonId) \
2058 case BuiltinType::Id:
2059#include "clang/AST/BuiltinTypes.def"
2060 case BuiltinType::Dependent:
2061 llvm_unreachable("mangling a placeholder type");
2062 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2063 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2064 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00002065 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2066 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2067 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2068 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2069 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2070 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00002071 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002072 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 }
2074}
2075
2076// <type> ::= <function-type>
2077// <function-type> ::= [<CV-qualifiers>] F [Y]
2078// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002079void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2080 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2081 // e.g. "const" in "int (A::*)() const".
2082 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2083
2084 Out << 'F';
2085
2086 // FIXME: We don't have enough information in the AST to produce the 'Y'
2087 // encoding for extern "C" function types.
2088 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2089
2090 // Mangle the ref-qualifier, if present.
2091 mangleRefQualifier(T->getRefQualifier());
2092
2093 Out << 'E';
2094}
2095void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2096 llvm_unreachable("Can't mangle K&R function prototypes");
2097}
2098void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2099 bool MangleReturnType) {
2100 // We should never be mangling something without a prototype.
2101 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2102
2103 // Record that we're in a function type. See mangleFunctionParam
2104 // for details on what we're trying to achieve here.
2105 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2106
2107 // <bare-function-type> ::= <signature type>+
2108 if (MangleReturnType) {
2109 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002110 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 FunctionTypeDepth.leaveResultType();
2112 }
2113
Alp Toker9cacbab2014-01-20 20:26:09 +00002114 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 // <builtin-type> ::= v # void
2116 Out << 'v';
2117
2118 FunctionTypeDepth.pop(saved);
2119 return;
2120 }
2121
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002122 for (const auto &Arg : Proto->param_types())
2123 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002124
2125 FunctionTypeDepth.pop(saved);
2126
2127 // <builtin-type> ::= z # ellipsis
2128 if (Proto->isVariadic())
2129 Out << 'z';
2130}
2131
2132// <type> ::= <class-enum-type>
2133// <class-enum-type> ::= <name>
2134void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2135 mangleName(T->getDecl());
2136}
2137
2138// <type> ::= <class-enum-type>
2139// <class-enum-type> ::= <name>
2140void CXXNameMangler::mangleType(const EnumType *T) {
2141 mangleType(static_cast<const TagType*>(T));
2142}
2143void CXXNameMangler::mangleType(const RecordType *T) {
2144 mangleType(static_cast<const TagType*>(T));
2145}
2146void CXXNameMangler::mangleType(const TagType *T) {
2147 mangleName(T->getDecl());
2148}
2149
2150// <type> ::= <array-type>
2151// <array-type> ::= A <positive dimension number> _ <element type>
2152// ::= A [<dimension expression>] _ <element type>
2153void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2154 Out << 'A' << T->getSize() << '_';
2155 mangleType(T->getElementType());
2156}
2157void CXXNameMangler::mangleType(const VariableArrayType *T) {
2158 Out << 'A';
2159 // decayed vla types (size 0) will just be skipped.
2160 if (T->getSizeExpr())
2161 mangleExpression(T->getSizeExpr());
2162 Out << '_';
2163 mangleType(T->getElementType());
2164}
2165void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2166 Out << 'A';
2167 mangleExpression(T->getSizeExpr());
2168 Out << '_';
2169 mangleType(T->getElementType());
2170}
2171void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2172 Out << "A_";
2173 mangleType(T->getElementType());
2174}
2175
2176// <type> ::= <pointer-to-member-type>
2177// <pointer-to-member-type> ::= M <class type> <member type>
2178void CXXNameMangler::mangleType(const MemberPointerType *T) {
2179 Out << 'M';
2180 mangleType(QualType(T->getClass(), 0));
2181 QualType PointeeType = T->getPointeeType();
2182 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2183 mangleType(FPT);
2184
2185 // Itanium C++ ABI 5.1.8:
2186 //
2187 // The type of a non-static member function is considered to be different,
2188 // for the purposes of substitution, from the type of a namespace-scope or
2189 // static member function whose type appears similar. The types of two
2190 // non-static member functions are considered to be different, for the
2191 // purposes of substitution, if the functions are members of different
2192 // classes. In other words, for the purposes of substitution, the class of
2193 // which the function is a member is considered part of the type of
2194 // function.
2195
2196 // Given that we already substitute member function pointers as a
2197 // whole, the net effect of this rule is just to unconditionally
2198 // suppress substitution on the function type in a member pointer.
2199 // We increment the SeqID here to emulate adding an entry to the
2200 // substitution table.
2201 ++SeqID;
2202 } else
2203 mangleType(PointeeType);
2204}
2205
2206// <type> ::= <template-param>
2207void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2208 mangleTemplateParameter(T->getIndex());
2209}
2210
2211// <type> ::= <template-param>
2212void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2213 // FIXME: not clear how to mangle this!
2214 // template <class T...> class A {
2215 // template <class U...> void foo(T(*)(U) x...);
2216 // };
2217 Out << "_SUBSTPACK_";
2218}
2219
2220// <type> ::= P <type> # pointer-to
2221void CXXNameMangler::mangleType(const PointerType *T) {
2222 Out << 'P';
2223 mangleType(T->getPointeeType());
2224}
2225void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2226 Out << 'P';
2227 mangleType(T->getPointeeType());
2228}
2229
2230// <type> ::= R <type> # reference-to
2231void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2232 Out << 'R';
2233 mangleType(T->getPointeeType());
2234}
2235
2236// <type> ::= O <type> # rvalue reference-to (C++0x)
2237void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2238 Out << 'O';
2239 mangleType(T->getPointeeType());
2240}
2241
2242// <type> ::= C <type> # complex pair (C 2000)
2243void CXXNameMangler::mangleType(const ComplexType *T) {
2244 Out << 'C';
2245 mangleType(T->getElementType());
2246}
2247
2248// ARM's ABI for Neon vector types specifies that they should be mangled as
2249// if they are structs (to match ARM's initial implementation). The
2250// vector type must be one of the special types predefined by ARM.
2251void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2252 QualType EltType = T->getElementType();
2253 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002254 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2256 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002257 case BuiltinType::SChar:
2258 case BuiltinType::UChar:
2259 EltName = "poly8_t";
2260 break;
2261 case BuiltinType::Short:
2262 case BuiltinType::UShort:
2263 EltName = "poly16_t";
2264 break;
2265 case BuiltinType::ULongLong:
2266 EltName = "poly64_t";
2267 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2269 }
2270 } else {
2271 switch (cast<BuiltinType>(EltType)->getKind()) {
2272 case BuiltinType::SChar: EltName = "int8_t"; break;
2273 case BuiltinType::UChar: EltName = "uint8_t"; break;
2274 case BuiltinType::Short: EltName = "int16_t"; break;
2275 case BuiltinType::UShort: EltName = "uint16_t"; break;
2276 case BuiltinType::Int: EltName = "int32_t"; break;
2277 case BuiltinType::UInt: EltName = "uint32_t"; break;
2278 case BuiltinType::LongLong: EltName = "int64_t"; break;
2279 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002280 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002282 case BuiltinType::Half: EltName = "float16_t";break;
2283 default:
2284 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 }
2286 }
Craig Topper36250ad2014-05-12 05:36:57 +00002287 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 unsigned BitSize = (T->getNumElements() *
2289 getASTContext().getTypeSize(EltType));
2290 if (BitSize == 64)
2291 BaseName = "__simd64_";
2292 else {
2293 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2294 BaseName = "__simd128_";
2295 }
2296 Out << strlen(BaseName) + strlen(EltName);
2297 Out << BaseName << EltName;
2298}
2299
Tim Northover2fe823a2013-08-01 09:23:19 +00002300static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2301 switch (EltType->getKind()) {
2302 case BuiltinType::SChar:
2303 return "Int8";
2304 case BuiltinType::Short:
2305 return "Int16";
2306 case BuiltinType::Int:
2307 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002308 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002309 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002310 return "Int64";
2311 case BuiltinType::UChar:
2312 return "Uint8";
2313 case BuiltinType::UShort:
2314 return "Uint16";
2315 case BuiltinType::UInt:
2316 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002317 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002318 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002319 return "Uint64";
2320 case BuiltinType::Half:
2321 return "Float16";
2322 case BuiltinType::Float:
2323 return "Float32";
2324 case BuiltinType::Double:
2325 return "Float64";
2326 default:
2327 llvm_unreachable("Unexpected vector element base type");
2328 }
2329}
2330
2331// AArch64's ABI for Neon vector types specifies that they should be mangled as
2332// the equivalent internal name. The vector type must be one of the special
2333// types predefined by ARM.
2334void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2335 QualType EltType = T->getElementType();
2336 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2337 unsigned BitSize =
2338 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002339 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002340
2341 assert((BitSize == 64 || BitSize == 128) &&
2342 "Neon vector type not 64 or 128 bits");
2343
Tim Northover2fe823a2013-08-01 09:23:19 +00002344 StringRef EltName;
2345 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2346 switch (cast<BuiltinType>(EltType)->getKind()) {
2347 case BuiltinType::UChar:
2348 EltName = "Poly8";
2349 break;
2350 case BuiltinType::UShort:
2351 EltName = "Poly16";
2352 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002353 case BuiltinType::ULong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002354 EltName = "Poly64";
2355 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002356 default:
2357 llvm_unreachable("unexpected Neon polynomial vector element type");
2358 }
2359 } else
2360 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2361
2362 std::string TypeName =
2363 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2364 Out << TypeName.length() << TypeName;
2365}
2366
Guy Benyei11169dd2012-12-18 14:30:41 +00002367// GNU extension: vector types
2368// <type> ::= <vector-type>
2369// <vector-type> ::= Dv <positive dimension number> _
2370// <extended element type>
2371// ::= Dv [<dimension expression>] _ <element type>
2372// <extended element type> ::= <element type>
2373// ::= p # AltiVec vector pixel
2374// ::= b # Altivec vector bool
2375void CXXNameMangler::mangleType(const VectorType *T) {
2376 if ((T->getVectorKind() == VectorType::NeonVector ||
2377 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002378 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002379 llvm::Triple::ArchType Arch =
2380 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002381 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002382 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002383 mangleAArch64NeonVectorType(T);
2384 else
2385 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 return;
2387 }
2388 Out << "Dv" << T->getNumElements() << '_';
2389 if (T->getVectorKind() == VectorType::AltiVecPixel)
2390 Out << 'p';
2391 else if (T->getVectorKind() == VectorType::AltiVecBool)
2392 Out << 'b';
2393 else
2394 mangleType(T->getElementType());
2395}
2396void CXXNameMangler::mangleType(const ExtVectorType *T) {
2397 mangleType(static_cast<const VectorType*>(T));
2398}
2399void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2400 Out << "Dv";
2401 mangleExpression(T->getSizeExpr());
2402 Out << '_';
2403 mangleType(T->getElementType());
2404}
2405
2406void CXXNameMangler::mangleType(const PackExpansionType *T) {
2407 // <type> ::= Dp <type> # pack expansion (C++0x)
2408 Out << "Dp";
2409 mangleType(T->getPattern());
2410}
2411
2412void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2413 mangleSourceName(T->getDecl()->getIdentifier());
2414}
2415
2416void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman5f508952013-06-18 22:41:37 +00002417 if (!T->qual_empty()) {
2418 // Mangle protocol qualifiers.
2419 SmallString<64> QualStr;
2420 llvm::raw_svector_ostream QualOS(QualStr);
2421 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002422 for (const auto *I : T->quals()) {
2423 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002424 QualOS << name.size() << name;
2425 }
2426 QualOS.flush();
2427 Out << 'U' << QualStr.size() << QualStr;
2428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 mangleType(T->getBaseType());
2430}
2431
2432void CXXNameMangler::mangleType(const BlockPointerType *T) {
2433 Out << "U13block_pointer";
2434 mangleType(T->getPointeeType());
2435}
2436
2437void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2438 // Mangle injected class name types as if the user had written the
2439 // specialization out fully. It may not actually be possible to see
2440 // this mangling, though.
2441 mangleType(T->getInjectedSpecializationType());
2442}
2443
2444void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2445 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2446 mangleName(TD, T->getArgs(), T->getNumArgs());
2447 } else {
2448 if (mangleSubstitution(QualType(T, 0)))
2449 return;
2450
2451 mangleTemplatePrefix(T->getTemplateName());
2452
2453 // FIXME: GCC does not appear to mangle the template arguments when
2454 // the template in question is a dependent template name. Should we
2455 // emulate that badness?
2456 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2457 addSubstitution(QualType(T, 0));
2458 }
2459}
2460
2461void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002462 // Proposal by cxx-abi-dev, 2014-03-26
2463 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2464 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002465 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002466 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002467 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002468 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002469 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002470 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002471 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002472 switch (T->getKeyword()) {
2473 case ETK_Typename:
2474 break;
2475 case ETK_Struct:
2476 case ETK_Class:
2477 case ETK_Interface:
2478 Out << "Ts";
2479 break;
2480 case ETK_Union:
2481 Out << "Tu";
2482 break;
2483 case ETK_Enum:
2484 Out << "Te";
2485 break;
2486 default:
2487 llvm_unreachable("unexpected keyword for dependent type name");
2488 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002489 // Typename types are always nested
2490 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002492 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 Out << 'E';
2494}
2495
2496void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2497 // Dependently-scoped template types are nested if they have a prefix.
2498 Out << 'N';
2499
2500 // TODO: avoid making this TemplateName.
2501 TemplateName Prefix =
2502 getASTContext().getDependentTemplateName(T->getQualifier(),
2503 T->getIdentifier());
2504 mangleTemplatePrefix(Prefix);
2505
2506 // FIXME: GCC does not appear to mangle the template arguments when
2507 // the template in question is a dependent template name. Should we
2508 // emulate that badness?
2509 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2510 Out << 'E';
2511}
2512
2513void CXXNameMangler::mangleType(const TypeOfType *T) {
2514 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2515 // "extension with parameters" mangling.
2516 Out << "u6typeof";
2517}
2518
2519void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2520 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2521 // "extension with parameters" mangling.
2522 Out << "u6typeof";
2523}
2524
2525void CXXNameMangler::mangleType(const DecltypeType *T) {
2526 Expr *E = T->getUnderlyingExpr();
2527
2528 // type ::= Dt <expression> E # decltype of an id-expression
2529 // # or class member access
2530 // ::= DT <expression> E # decltype of an expression
2531
2532 // This purports to be an exhaustive list of id-expressions and
2533 // class member accesses. Note that we do not ignore parentheses;
2534 // parentheses change the semantics of decltype for these
2535 // expressions (and cause the mangler to use the other form).
2536 if (isa<DeclRefExpr>(E) ||
2537 isa<MemberExpr>(E) ||
2538 isa<UnresolvedLookupExpr>(E) ||
2539 isa<DependentScopeDeclRefExpr>(E) ||
2540 isa<CXXDependentScopeMemberExpr>(E) ||
2541 isa<UnresolvedMemberExpr>(E))
2542 Out << "Dt";
2543 else
2544 Out << "DT";
2545 mangleExpression(E);
2546 Out << 'E';
2547}
2548
2549void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2550 // If this is dependent, we need to record that. If not, we simply
2551 // mangle it as the underlying type since they are equivalent.
2552 if (T->isDependentType()) {
2553 Out << 'U';
2554
2555 switch (T->getUTTKind()) {
2556 case UnaryTransformType::EnumUnderlyingType:
2557 Out << "3eut";
2558 break;
2559 }
2560 }
2561
2562 mangleType(T->getUnderlyingType());
2563}
2564
2565void CXXNameMangler::mangleType(const AutoType *T) {
2566 QualType D = T->getDeducedType();
2567 // <builtin-type> ::= Da # dependent auto
2568 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002569 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 else
2571 mangleType(D);
2572}
2573
2574void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002575 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 // (Until there's a standardized mangling...)
2577 Out << "U7_Atomic";
2578 mangleType(T->getValueType());
2579}
2580
2581void CXXNameMangler::mangleIntegerLiteral(QualType T,
2582 const llvm::APSInt &Value) {
2583 // <expr-primary> ::= L <type> <value number> E # integer literal
2584 Out << 'L';
2585
2586 mangleType(T);
2587 if (T->isBooleanType()) {
2588 // Boolean values are encoded as 0/1.
2589 Out << (Value.getBoolValue() ? '1' : '0');
2590 } else {
2591 mangleNumber(Value);
2592 }
2593 Out << 'E';
2594
2595}
2596
David Majnemer1dabfdc2015-02-14 13:23:54 +00002597void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2598 // Ignore member expressions involving anonymous unions.
2599 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2600 if (!RT->getDecl()->isAnonymousStructOrUnion())
2601 break;
2602 const auto *ME = dyn_cast<MemberExpr>(Base);
2603 if (!ME)
2604 break;
2605 Base = ME->getBase();
2606 IsArrow = ME->isArrow();
2607 }
2608
2609 if (Base->isImplicitCXXThis()) {
2610 // Note: GCC mangles member expressions to the implicit 'this' as
2611 // *this., whereas we represent them as this->. The Itanium C++ ABI
2612 // does not specify anything here, so we follow GCC.
2613 Out << "dtdefpT";
2614 } else {
2615 Out << (IsArrow ? "pt" : "dt");
2616 mangleExpression(Base);
2617 }
2618}
2619
Guy Benyei11169dd2012-12-18 14:30:41 +00002620/// Mangles a member expression.
2621void CXXNameMangler::mangleMemberExpr(const Expr *base,
2622 bool isArrow,
2623 NestedNameSpecifier *qualifier,
2624 NamedDecl *firstQualifierLookup,
2625 DeclarationName member,
2626 unsigned arity) {
2627 // <expression> ::= dt <expression> <unresolved-name>
2628 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002629 if (base)
2630 mangleMemberExprBase(base, isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2632}
2633
2634/// Look at the callee of the given call expression and determine if
2635/// it's a parenthesized id-expression which would have triggered ADL
2636/// otherwise.
2637static bool isParenthesizedADLCallee(const CallExpr *call) {
2638 const Expr *callee = call->getCallee();
2639 const Expr *fn = callee->IgnoreParens();
2640
2641 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2642 // too, but for those to appear in the callee, it would have to be
2643 // parenthesized.
2644 if (callee == fn) return false;
2645
2646 // Must be an unresolved lookup.
2647 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2648 if (!lookup) return false;
2649
2650 assert(!lookup->requiresADL());
2651
2652 // Must be an unqualified lookup.
2653 if (lookup->getQualifier()) return false;
2654
2655 // Must not have found a class member. Note that if one is a class
2656 // member, they're all class members.
2657 if (lookup->getNumDecls() > 0 &&
2658 (*lookup->decls_begin())->isCXXClassMember())
2659 return false;
2660
2661 // Otherwise, ADL would have been triggered.
2662 return true;
2663}
2664
David Majnemer9c775c72014-09-23 04:27:55 +00002665void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2666 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2667 Out << CastEncoding;
2668 mangleType(ECE->getType());
2669 mangleExpression(ECE->getSubExpr());
2670}
2671
Richard Smith520449d2015-02-05 06:15:50 +00002672void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2673 if (auto *Syntactic = InitList->getSyntacticForm())
2674 InitList = Syntactic;
2675 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2676 mangleExpression(InitList->getInit(i));
2677}
2678
Guy Benyei11169dd2012-12-18 14:30:41 +00002679void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2680 // <expression> ::= <unary operator-name> <expression>
2681 // ::= <binary operator-name> <expression> <expression>
2682 // ::= <trinary operator-name> <expression> <expression> <expression>
2683 // ::= cv <type> expression # conversion with one argument
2684 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002685 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2686 // ::= sc <type> <expression> # static_cast<type> (expression)
2687 // ::= cc <type> <expression> # const_cast<type> (expression)
2688 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 // ::= st <type> # sizeof (a type)
2690 // ::= at <type> # alignof (a type)
2691 // ::= <template-param>
2692 // ::= <function-param>
2693 // ::= sr <type> <unqualified-name> # dependent name
2694 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2695 // ::= ds <expression> <expression> # expr.*expr
2696 // ::= sZ <template-param> # size of a parameter pack
2697 // ::= sZ <function-param> # size of a function parameter pack
2698 // ::= <expr-primary>
2699 // <expr-primary> ::= L <type> <value number> E # integer literal
2700 // ::= L <type <value float> E # floating literal
2701 // ::= L <mangled-name> E # external name
2702 // ::= fpT # 'this' expression
2703 QualType ImplicitlyConvertedToType;
2704
2705recurse:
2706 switch (E->getStmtClass()) {
2707 case Expr::NoStmtClass:
2708#define ABSTRACT_STMT(Type)
2709#define EXPR(Type, Base)
2710#define STMT(Type, Base) \
2711 case Expr::Type##Class:
2712#include "clang/AST/StmtNodes.inc"
2713 // fallthrough
2714
2715 // These all can only appear in local or variable-initialization
2716 // contexts and so should never appear in a mangling.
2717 case Expr::AddrLabelExprClass:
2718 case Expr::DesignatedInitExprClass:
2719 case Expr::ImplicitValueInitExprClass:
2720 case Expr::ParenListExprClass:
2721 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002722 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002723 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 llvm_unreachable("unexpected statement kind");
2725
2726 // FIXME: invent manglings for all these.
2727 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 case Expr::ChooseExprClass:
2729 case Expr::CompoundLiteralExprClass:
2730 case Expr::ExtVectorElementExprClass:
2731 case Expr::GenericSelectionExprClass:
2732 case Expr::ObjCEncodeExprClass:
2733 case Expr::ObjCIsaExprClass:
2734 case Expr::ObjCIvarRefExprClass:
2735 case Expr::ObjCMessageExprClass:
2736 case Expr::ObjCPropertyRefExprClass:
2737 case Expr::ObjCProtocolExprClass:
2738 case Expr::ObjCSelectorExprClass:
2739 case Expr::ObjCStringLiteralClass:
2740 case Expr::ObjCBoxedExprClass:
2741 case Expr::ObjCArrayLiteralClass:
2742 case Expr::ObjCDictionaryLiteralClass:
2743 case Expr::ObjCSubscriptRefExprClass:
2744 case Expr::ObjCIndirectCopyRestoreExprClass:
2745 case Expr::OffsetOfExprClass:
2746 case Expr::PredefinedExprClass:
2747 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002748 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 case Expr::TypeTraitExprClass:
2751 case Expr::ArrayTypeTraitExprClass:
2752 case Expr::ExpressionTraitExprClass:
2753 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 case Expr::CUDAKernelCallExprClass:
2755 case Expr::AsTypeExprClass:
2756 case Expr::PseudoObjectExprClass:
2757 case Expr::AtomicExprClass:
2758 {
2759 // As bad as this diagnostic is, it's better than crashing.
2760 DiagnosticsEngine &Diags = Context.getDiags();
2761 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2762 "cannot yet mangle expression type %0");
2763 Diags.Report(E->getExprLoc(), DiagID)
2764 << E->getStmtClassName() << E->getSourceRange();
2765 break;
2766 }
2767
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002768 case Expr::CXXUuidofExprClass: {
2769 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2770 if (UE->isTypeOperand()) {
2771 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2772 Out << "u8__uuidoft";
2773 mangleType(UuidT);
2774 } else {
2775 Expr *UuidExp = UE->getExprOperand();
2776 Out << "u8__uuidofz";
2777 mangleExpression(UuidExp, Arity);
2778 }
2779 break;
2780 }
2781
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 // Even gcc-4.5 doesn't mangle this.
2783 case Expr::BinaryConditionalOperatorClass: {
2784 DiagnosticsEngine &Diags = Context.getDiags();
2785 unsigned DiagID =
2786 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2787 "?: operator with omitted middle operand cannot be mangled");
2788 Diags.Report(E->getExprLoc(), DiagID)
2789 << E->getStmtClassName() << E->getSourceRange();
2790 break;
2791 }
2792
2793 // These are used for internal purposes and cannot be meaningfully mangled.
2794 case Expr::OpaqueValueExprClass:
2795 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2796
2797 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002799 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 Out << "E";
2801 break;
2802 }
2803
2804 case Expr::CXXDefaultArgExprClass:
2805 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2806 break;
2807
Richard Smith852c9db2013-04-20 22:23:05 +00002808 case Expr::CXXDefaultInitExprClass:
2809 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2810 break;
2811
Richard Smithcc1b96d2013-06-12 22:31:48 +00002812 case Expr::CXXStdInitializerListExprClass:
2813 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2814 break;
2815
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 case Expr::SubstNonTypeTemplateParmExprClass:
2817 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2818 Arity);
2819 break;
2820
2821 case Expr::UserDefinedLiteralClass:
2822 // We follow g++'s approach of mangling a UDL as a call to the literal
2823 // operator.
2824 case Expr::CXXMemberCallExprClass: // fallthrough
2825 case Expr::CallExprClass: {
2826 const CallExpr *CE = cast<CallExpr>(E);
2827
2828 // <expression> ::= cp <simple-id> <expression>* E
2829 // We use this mangling only when the call would use ADL except
2830 // for being parenthesized. Per discussion with David
2831 // Vandervoorde, 2011.04.25.
2832 if (isParenthesizedADLCallee(CE)) {
2833 Out << "cp";
2834 // The callee here is a parenthesized UnresolvedLookupExpr with
2835 // no qualifier and should always get mangled as a <simple-id>
2836 // anyway.
2837
2838 // <expression> ::= cl <expression>* E
2839 } else {
2840 Out << "cl";
2841 }
2842
2843 mangleExpression(CE->getCallee(), CE->getNumArgs());
2844 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2845 mangleExpression(CE->getArg(I));
2846 Out << 'E';
2847 break;
2848 }
2849
2850 case Expr::CXXNewExprClass: {
2851 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2852 if (New->isGlobalNew()) Out << "gs";
2853 Out << (New->isArray() ? "na" : "nw");
2854 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2855 E = New->placement_arg_end(); I != E; ++I)
2856 mangleExpression(*I);
2857 Out << '_';
2858 mangleType(New->getAllocatedType());
2859 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2861 Out << "il";
2862 else
2863 Out << "pi";
2864 const Expr *Init = New->getInitializer();
2865 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2866 // Directly inline the initializers.
2867 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2868 E = CCE->arg_end();
2869 I != E; ++I)
2870 mangleExpression(*I);
2871 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2872 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2873 mangleExpression(PLE->getExpr(i));
2874 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2875 isa<InitListExpr>(Init)) {
2876 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002877 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 } else
2879 mangleExpression(Init);
2880 }
2881 Out << 'E';
2882 break;
2883 }
2884
David Majnemer1dabfdc2015-02-14 13:23:54 +00002885 case Expr::CXXPseudoDestructorExprClass: {
2886 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2887 if (const Expr *Base = PDE->getBase())
2888 mangleMemberExprBase(Base, PDE->isArrow());
2889 if (NestedNameSpecifier *Qualifier = PDE->getQualifier())
2890 mangleUnresolvedPrefix(Qualifier, /*FirstQualifierLookup=*/nullptr);
2891 // <base-unresolved-name> ::= dn <destructor-name>
2892 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00002893 QualType DestroyedType = PDE->getDestroyedType();
2894 mangleDestructorName(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00002895 break;
2896 }
2897
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 case Expr::MemberExprClass: {
2899 const MemberExpr *ME = cast<MemberExpr>(E);
2900 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002901 ME->getQualifier(), nullptr,
2902 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 break;
2904 }
2905
2906 case Expr::UnresolvedMemberExprClass: {
2907 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2908 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002909 ME->getQualifier(), nullptr, ME->getMemberName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 Arity);
2911 if (ME->hasExplicitTemplateArgs())
2912 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2913 break;
2914 }
2915
2916 case Expr::CXXDependentScopeMemberExprClass: {
2917 const CXXDependentScopeMemberExpr *ME
2918 = cast<CXXDependentScopeMemberExpr>(E);
2919 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2920 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2921 ME->getMember(), Arity);
2922 if (ME->hasExplicitTemplateArgs())
2923 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2924 break;
2925 }
2926
2927 case Expr::UnresolvedLookupExprClass: {
2928 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00002929 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002930
2931 // All the <unresolved-name> productions end in a
2932 // base-unresolved-name, where <template-args> are just tacked
2933 // onto the end.
2934 if (ULE->hasExplicitTemplateArgs())
2935 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2936 break;
2937 }
2938
2939 case Expr::CXXUnresolvedConstructExprClass: {
2940 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2941 unsigned N = CE->arg_size();
2942
2943 Out << "cv";
2944 mangleType(CE->getType());
2945 if (N != 1) Out << '_';
2946 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2947 if (N != 1) Out << 'E';
2948 break;
2949 }
2950
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00002952 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00002953 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00002954 assert(
2955 CE->getNumArgs() >= 1 &&
2956 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2957 "implicit CXXConstructExpr must have one argument");
2958 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2959 }
2960 Out << "il";
2961 for (auto *E : CE->arguments())
2962 mangleExpression(E);
2963 Out << "E";
2964 break;
2965 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002966
Richard Smith520449d2015-02-05 06:15:50 +00002967 case Expr::CXXTemporaryObjectExprClass: {
2968 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2969 unsigned N = CE->getNumArgs();
2970 bool List = CE->isListInitialization();
2971
2972 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 Out << "tl";
2974 else
2975 Out << "cv";
2976 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002977 if (!List && N != 1)
2978 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00002979 if (CE->isStdInitListInitialization()) {
2980 // We implicitly created a std::initializer_list<T> for the first argument
2981 // of a constructor of type U in an expression of the form U{a, b, c}.
2982 // Strip all the semantic gunk off the initializer list.
2983 auto *SILE =
2984 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2985 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2986 mangleInitListElements(ILE);
2987 } else {
2988 for (auto *E : CE->arguments())
2989 mangleExpression(E);
2990 }
Richard Smith520449d2015-02-05 06:15:50 +00002991 if (List || N != 1)
2992 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 break;
2994 }
2995
2996 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00002997 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002999 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 break;
3001
3002 case Expr::CXXNoexceptExprClass:
3003 Out << "nx";
3004 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3005 break;
3006
3007 case Expr::UnaryExprOrTypeTraitExprClass: {
3008 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3009
3010 if (!SAE->isInstantiationDependent()) {
3011 // Itanium C++ ABI:
3012 // If the operand of a sizeof or alignof operator is not
3013 // instantiation-dependent it is encoded as an integer literal
3014 // reflecting the result of the operator.
3015 //
3016 // If the result of the operator is implicitly converted to a known
3017 // integer type, that type is used for the literal; otherwise, the type
3018 // of std::size_t or std::ptrdiff_t is used.
3019 QualType T = (ImplicitlyConvertedToType.isNull() ||
3020 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3021 : ImplicitlyConvertedToType;
3022 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3023 mangleIntegerLiteral(T, V);
3024 break;
3025 }
3026
3027 switch(SAE->getKind()) {
3028 case UETT_SizeOf:
3029 Out << 's';
3030 break;
3031 case UETT_AlignOf:
3032 Out << 'a';
3033 break;
3034 case UETT_VecStep:
3035 DiagnosticsEngine &Diags = Context.getDiags();
3036 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3037 "cannot yet mangle vec_step expression");
3038 Diags.Report(DiagID);
3039 return;
3040 }
3041 if (SAE->isArgumentType()) {
3042 Out << 't';
3043 mangleType(SAE->getArgumentType());
3044 } else {
3045 Out << 'z';
3046 mangleExpression(SAE->getArgumentExpr());
3047 }
3048 break;
3049 }
3050
3051 case Expr::CXXThrowExprClass: {
3052 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003053 // <expression> ::= tw <expression> # throw expression
3054 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 if (TE->getSubExpr()) {
3056 Out << "tw";
3057 mangleExpression(TE->getSubExpr());
3058 } else {
3059 Out << "tr";
3060 }
3061 break;
3062 }
3063
3064 case Expr::CXXTypeidExprClass: {
3065 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003066 // <expression> ::= ti <type> # typeid (type)
3067 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 if (TIE->isTypeOperand()) {
3069 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003070 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 } else {
3072 Out << "te";
3073 mangleExpression(TIE->getExprOperand());
3074 }
3075 break;
3076 }
3077
3078 case Expr::CXXDeleteExprClass: {
3079 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003080 // <expression> ::= [gs] dl <expression> # [::] delete expr
3081 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 if (DE->isGlobalDelete()) Out << "gs";
3083 Out << (DE->isArrayForm() ? "da" : "dl");
3084 mangleExpression(DE->getArgument());
3085 break;
3086 }
3087
3088 case Expr::UnaryOperatorClass: {
3089 const UnaryOperator *UO = cast<UnaryOperator>(E);
3090 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3091 /*Arity=*/1);
3092 mangleExpression(UO->getSubExpr());
3093 break;
3094 }
3095
3096 case Expr::ArraySubscriptExprClass: {
3097 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3098
3099 // Array subscript is treated as a syntactically weird form of
3100 // binary operator.
3101 Out << "ix";
3102 mangleExpression(AE->getLHS());
3103 mangleExpression(AE->getRHS());
3104 break;
3105 }
3106
3107 case Expr::CompoundAssignOperatorClass: // fallthrough
3108 case Expr::BinaryOperatorClass: {
3109 const BinaryOperator *BO = cast<BinaryOperator>(E);
3110 if (BO->getOpcode() == BO_PtrMemD)
3111 Out << "ds";
3112 else
3113 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3114 /*Arity=*/2);
3115 mangleExpression(BO->getLHS());
3116 mangleExpression(BO->getRHS());
3117 break;
3118 }
3119
3120 case Expr::ConditionalOperatorClass: {
3121 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3122 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3123 mangleExpression(CO->getCond());
3124 mangleExpression(CO->getLHS(), Arity);
3125 mangleExpression(CO->getRHS(), Arity);
3126 break;
3127 }
3128
3129 case Expr::ImplicitCastExprClass: {
3130 ImplicitlyConvertedToType = E->getType();
3131 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3132 goto recurse;
3133 }
3134
3135 case Expr::ObjCBridgedCastExprClass: {
3136 // Mangle ownership casts as a vendor extended operator __bridge,
3137 // __bridge_transfer, or __bridge_retain.
3138 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3139 Out << "v1U" << Kind.size() << Kind;
3140 }
3141 // Fall through to mangle the cast itself.
3142
3143 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003144 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003146
Richard Smith520449d2015-02-05 06:15:50 +00003147 case Expr::CXXFunctionalCastExprClass: {
3148 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3149 // FIXME: Add isImplicit to CXXConstructExpr.
3150 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3151 if (CCE->getParenOrBraceRange().isInvalid())
3152 Sub = CCE->getArg(0)->IgnoreImplicit();
3153 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3154 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3155 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3156 Out << "tl";
3157 mangleType(E->getType());
3158 mangleInitListElements(IL);
3159 Out << "E";
3160 } else {
3161 mangleCastExpression(E, "cv");
3162 }
3163 break;
3164 }
3165
David Majnemer9c775c72014-09-23 04:27:55 +00003166 case Expr::CXXStaticCastExprClass:
3167 mangleCastExpression(E, "sc");
3168 break;
3169 case Expr::CXXDynamicCastExprClass:
3170 mangleCastExpression(E, "dc");
3171 break;
3172 case Expr::CXXReinterpretCastExprClass:
3173 mangleCastExpression(E, "rc");
3174 break;
3175 case Expr::CXXConstCastExprClass:
3176 mangleCastExpression(E, "cc");
3177 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003178
3179 case Expr::CXXOperatorCallExprClass: {
3180 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3181 unsigned NumArgs = CE->getNumArgs();
3182 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3183 // Mangle the arguments.
3184 for (unsigned i = 0; i != NumArgs; ++i)
3185 mangleExpression(CE->getArg(i));
3186 break;
3187 }
3188
3189 case Expr::ParenExprClass:
3190 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3191 break;
3192
3193 case Expr::DeclRefExprClass: {
3194 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3195
3196 switch (D->getKind()) {
3197 default:
3198 // <expr-primary> ::= L <mangled-name> E # external name
3199 Out << 'L';
3200 mangle(D, "_Z");
3201 Out << 'E';
3202 break;
3203
3204 case Decl::ParmVar:
3205 mangleFunctionParam(cast<ParmVarDecl>(D));
3206 break;
3207
3208 case Decl::EnumConstant: {
3209 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3210 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3211 break;
3212 }
3213
3214 case Decl::NonTypeTemplateParm: {
3215 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3216 mangleTemplateParameter(PD->getIndex());
3217 break;
3218 }
3219
3220 }
3221
3222 break;
3223 }
3224
3225 case Expr::SubstNonTypeTemplateParmPackExprClass:
3226 // FIXME: not clear how to mangle this!
3227 // template <unsigned N...> class A {
3228 // template <class U...> void foo(U (&x)[N]...);
3229 // };
3230 Out << "_SUBSTPACK_";
3231 break;
3232
3233 case Expr::FunctionParmPackExprClass: {
3234 // FIXME: not clear how to mangle this!
3235 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3236 Out << "v110_SUBSTPACK";
3237 mangleFunctionParam(FPPE->getParameterPack());
3238 break;
3239 }
3240
3241 case Expr::DependentScopeDeclRefExprClass: {
3242 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00003243 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
3244 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003245
3246 // All the <unresolved-name> productions end in a
3247 // base-unresolved-name, where <template-args> are just tacked
3248 // onto the end.
3249 if (DRE->hasExplicitTemplateArgs())
3250 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3251 break;
3252 }
3253
3254 case Expr::CXXBindTemporaryExprClass:
3255 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3256 break;
3257
3258 case Expr::ExprWithCleanupsClass:
3259 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3260 break;
3261
3262 case Expr::FloatingLiteralClass: {
3263 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3264 Out << 'L';
3265 mangleType(FL->getType());
3266 mangleFloat(FL->getValue());
3267 Out << 'E';
3268 break;
3269 }
3270
3271 case Expr::CharacterLiteralClass:
3272 Out << 'L';
3273 mangleType(E->getType());
3274 Out << cast<CharacterLiteral>(E)->getValue();
3275 Out << 'E';
3276 break;
3277
3278 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3279 case Expr::ObjCBoolLiteralExprClass:
3280 Out << "Lb";
3281 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3282 Out << 'E';
3283 break;
3284
3285 case Expr::CXXBoolLiteralExprClass:
3286 Out << "Lb";
3287 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3288 Out << 'E';
3289 break;
3290
3291 case Expr::IntegerLiteralClass: {
3292 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3293 if (E->getType()->isSignedIntegerType())
3294 Value.setIsSigned(true);
3295 mangleIntegerLiteral(E->getType(), Value);
3296 break;
3297 }
3298
3299 case Expr::ImaginaryLiteralClass: {
3300 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3301 // Mangle as if a complex literal.
3302 // Proposal from David Vandevoorde, 2010.06.30.
3303 Out << 'L';
3304 mangleType(E->getType());
3305 if (const FloatingLiteral *Imag =
3306 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3307 // Mangle a floating-point zero of the appropriate type.
3308 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3309 Out << '_';
3310 mangleFloat(Imag->getValue());
3311 } else {
3312 Out << "0_";
3313 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3314 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3315 Value.setIsSigned(true);
3316 mangleNumber(Value);
3317 }
3318 Out << 'E';
3319 break;
3320 }
3321
3322 case Expr::StringLiteralClass: {
3323 // Revised proposal from David Vandervoorde, 2010.07.15.
3324 Out << 'L';
3325 assert(isa<ConstantArrayType>(E->getType()));
3326 mangleType(E->getType());
3327 Out << 'E';
3328 break;
3329 }
3330
3331 case Expr::GNUNullExprClass:
3332 // FIXME: should this really be mangled the same as nullptr?
3333 // fallthrough
3334
3335 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 Out << "LDnE";
3337 break;
3338 }
3339
3340 case Expr::PackExpansionExprClass:
3341 Out << "sp";
3342 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3343 break;
3344
3345 case Expr::SizeOfPackExprClass: {
3346 Out << "sZ";
3347 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3348 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3349 mangleTemplateParameter(TTP->getIndex());
3350 else if (const NonTypeTemplateParmDecl *NTTP
3351 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3352 mangleTemplateParameter(NTTP->getIndex());
3353 else if (const TemplateTemplateParmDecl *TempTP
3354 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3355 mangleTemplateParameter(TempTP->getIndex());
3356 else
3357 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3358 break;
3359 }
Richard Smith0f0af192014-11-08 05:07:16 +00003360
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 case Expr::MaterializeTemporaryExprClass: {
3362 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3363 break;
3364 }
Richard Smith0f0af192014-11-08 05:07:16 +00003365
3366 case Expr::CXXFoldExprClass: {
3367 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003368 if (FE->isLeftFold())
3369 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003370 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003371 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003372
3373 if (FE->getOperator() == BO_PtrMemD)
3374 Out << "ds";
3375 else
3376 mangleOperatorName(
3377 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3378 /*Arity=*/2);
3379
3380 if (FE->getLHS())
3381 mangleExpression(FE->getLHS());
3382 if (FE->getRHS())
3383 mangleExpression(FE->getRHS());
3384 break;
3385 }
3386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 case Expr::CXXThisExprClass:
3388 Out << "fpT";
3389 break;
3390 }
3391}
3392
3393/// Mangle an expression which refers to a parameter variable.
3394///
3395/// <expression> ::= <function-param>
3396/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3397/// <function-param> ::= fp <top-level CV-qualifiers>
3398/// <parameter-2 non-negative number> _ # L == 0, I > 0
3399/// <function-param> ::= fL <L-1 non-negative number>
3400/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3401/// <function-param> ::= fL <L-1 non-negative number>
3402/// p <top-level CV-qualifiers>
3403/// <I-1 non-negative number> _ # L > 0, I > 0
3404///
3405/// L is the nesting depth of the parameter, defined as 1 if the
3406/// parameter comes from the innermost function prototype scope
3407/// enclosing the current context, 2 if from the next enclosing
3408/// function prototype scope, and so on, with one special case: if
3409/// we've processed the full parameter clause for the innermost
3410/// function type, then L is one less. This definition conveniently
3411/// makes it irrelevant whether a function's result type was written
3412/// trailing or leading, but is otherwise overly complicated; the
3413/// numbering was first designed without considering references to
3414/// parameter in locations other than return types, and then the
3415/// mangling had to be generalized without changing the existing
3416/// manglings.
3417///
3418/// I is the zero-based index of the parameter within its parameter
3419/// declaration clause. Note that the original ABI document describes
3420/// this using 1-based ordinals.
3421void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3422 unsigned parmDepth = parm->getFunctionScopeDepth();
3423 unsigned parmIndex = parm->getFunctionScopeIndex();
3424
3425 // Compute 'L'.
3426 // parmDepth does not include the declaring function prototype.
3427 // FunctionTypeDepth does account for that.
3428 assert(parmDepth < FunctionTypeDepth.getDepth());
3429 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3430 if (FunctionTypeDepth.isInResultType())
3431 nestingDepth--;
3432
3433 if (nestingDepth == 0) {
3434 Out << "fp";
3435 } else {
3436 Out << "fL" << (nestingDepth - 1) << 'p';
3437 }
3438
3439 // Top-level qualifiers. We don't have to worry about arrays here,
3440 // because parameters declared as arrays should already have been
3441 // transformed to have pointer type. FIXME: apparently these don't
3442 // get mangled if used as an rvalue of a known non-class type?
3443 assert(!parm->getType()->isArrayType()
3444 && "parameter's type is still an array type?");
3445 mangleQualifiers(parm->getType().getQualifiers());
3446
3447 // Parameter index.
3448 if (parmIndex != 0) {
3449 Out << (parmIndex - 1);
3450 }
3451 Out << '_';
3452}
3453
3454void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3455 // <ctor-dtor-name> ::= C1 # complete object constructor
3456 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003458 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003459 switch (T) {
3460 case Ctor_Complete:
3461 Out << "C1";
3462 break;
3463 case Ctor_Base:
3464 Out << "C2";
3465 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003466 case Ctor_Comdat:
3467 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 break;
3469 }
3470}
3471
3472void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3473 // <ctor-dtor-name> ::= D0 # deleting destructor
3474 // ::= D1 # complete object destructor
3475 // ::= D2 # base object destructor
3476 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003477 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 switch (T) {
3479 case Dtor_Deleting:
3480 Out << "D0";
3481 break;
3482 case Dtor_Complete:
3483 Out << "D1";
3484 break;
3485 case Dtor_Base:
3486 Out << "D2";
3487 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003488 case Dtor_Comdat:
3489 Out << "D5";
3490 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 }
3492}
3493
3494void CXXNameMangler::mangleTemplateArgs(
3495 const ASTTemplateArgumentListInfo &TemplateArgs) {
3496 // <template-args> ::= I <template-arg>+ E
3497 Out << 'I';
3498 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3499 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3500 Out << 'E';
3501}
3502
3503void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3504 // <template-args> ::= I <template-arg>+ E
3505 Out << 'I';
3506 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3507 mangleTemplateArg(AL[i]);
3508 Out << 'E';
3509}
3510
3511void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3512 unsigned NumTemplateArgs) {
3513 // <template-args> ::= I <template-arg>+ E
3514 Out << 'I';
3515 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3516 mangleTemplateArg(TemplateArgs[i]);
3517 Out << 'E';
3518}
3519
3520void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3521 // <template-arg> ::= <type> # type or template
3522 // ::= X <expression> E # expression
3523 // ::= <expr-primary> # simple expressions
3524 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 if (!A.isInstantiationDependent() || A.isDependent())
3526 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3527
3528 switch (A.getKind()) {
3529 case TemplateArgument::Null:
3530 llvm_unreachable("Cannot mangle NULL template argument");
3531
3532 case TemplateArgument::Type:
3533 mangleType(A.getAsType());
3534 break;
3535 case TemplateArgument::Template:
3536 // This is mangled as <type>.
3537 mangleType(A.getAsTemplate());
3538 break;
3539 case TemplateArgument::TemplateExpansion:
3540 // <type> ::= Dp <type> # pack expansion (C++0x)
3541 Out << "Dp";
3542 mangleType(A.getAsTemplateOrTemplatePattern());
3543 break;
3544 case TemplateArgument::Expression: {
3545 // It's possible to end up with a DeclRefExpr here in certain
3546 // dependent cases, in which case we should mangle as a
3547 // declaration.
3548 const Expr *E = A.getAsExpr()->IgnoreParens();
3549 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3550 const ValueDecl *D = DRE->getDecl();
3551 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3552 Out << "L";
3553 mangle(D, "_Z");
3554 Out << 'E';
3555 break;
3556 }
3557 }
3558
3559 Out << 'X';
3560 mangleExpression(E);
3561 Out << 'E';
3562 break;
3563 }
3564 case TemplateArgument::Integral:
3565 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3566 break;
3567 case TemplateArgument::Declaration: {
3568 // <expr-primary> ::= L <mangled-name> E # external name
3569 // Clang produces AST's where pointer-to-member-function expressions
3570 // and pointer-to-function expressions are represented as a declaration not
3571 // an expression. We compensate for it here to produce the correct mangling.
3572 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003573 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 if (compensateMangling) {
3575 Out << 'X';
3576 mangleOperatorName(OO_Amp, 1);
3577 }
3578
3579 Out << 'L';
3580 // References to external entities use the mangled name; if the name would
3581 // not normally be manged then mangle it as unqualified.
3582 //
3583 // FIXME: The ABI specifies that external names here should have _Z, but
3584 // gcc leaves this off.
3585 if (compensateMangling)
3586 mangle(D, "_Z");
3587 else
3588 mangle(D, "Z");
3589 Out << 'E';
3590
3591 if (compensateMangling)
3592 Out << 'E';
3593
3594 break;
3595 }
3596 case TemplateArgument::NullPtr: {
3597 // <expr-primary> ::= L <type> 0 E
3598 Out << 'L';
3599 mangleType(A.getNullPtrType());
3600 Out << "0E";
3601 break;
3602 }
3603 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003604 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003606 for (const auto &P : A.pack_elements())
3607 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 Out << 'E';
3609 }
3610 }
3611}
3612
3613void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3614 // <template-param> ::= T_ # first template parameter
3615 // ::= T <parameter-2 non-negative number> _
3616 if (Index == 0)
3617 Out << "T_";
3618 else
3619 Out << 'T' << (Index - 1) << '_';
3620}
3621
David Majnemer3b3bdb52014-05-06 22:49:16 +00003622void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3623 if (SeqID == 1)
3624 Out << '0';
3625 else if (SeqID > 1) {
3626 SeqID--;
3627
3628 // <seq-id> is encoded in base-36, using digits and upper case letters.
3629 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003630 MutableArrayRef<char> BufferRef(Buffer);
3631 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003632
3633 for (; SeqID != 0; SeqID /= 36) {
3634 unsigned C = SeqID % 36;
3635 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3636 }
3637
3638 Out.write(I.base(), I - BufferRef.rbegin());
3639 }
3640 Out << '_';
3641}
3642
Guy Benyei11169dd2012-12-18 14:30:41 +00003643void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3644 bool result = mangleSubstitution(type);
3645 assert(result && "no existing substitution for type");
3646 (void) result;
3647}
3648
3649void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3650 bool result = mangleSubstitution(tname);
3651 assert(result && "no existing substitution for template name");
3652 (void) result;
3653}
3654
3655// <substitution> ::= S <seq-id> _
3656// ::= S_
3657bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3658 // Try one of the standard substitutions first.
3659 if (mangleStandardSubstitution(ND))
3660 return true;
3661
3662 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3663 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3664}
3665
3666/// \brief Determine whether the given type has any qualifiers that are
3667/// relevant for substitutions.
3668static bool hasMangledSubstitutionQualifiers(QualType T) {
3669 Qualifiers Qs = T.getQualifiers();
3670 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3671}
3672
3673bool CXXNameMangler::mangleSubstitution(QualType T) {
3674 if (!hasMangledSubstitutionQualifiers(T)) {
3675 if (const RecordType *RT = T->getAs<RecordType>())
3676 return mangleSubstitution(RT->getDecl());
3677 }
3678
3679 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3680
3681 return mangleSubstitution(TypePtr);
3682}
3683
3684bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3685 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3686 return mangleSubstitution(TD);
3687
3688 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3689 return mangleSubstitution(
3690 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3691}
3692
3693bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3694 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3695 if (I == Substitutions.end())
3696 return false;
3697
3698 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003699 Out << 'S';
3700 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003701
3702 return true;
3703}
3704
3705static bool isCharType(QualType T) {
3706 if (T.isNull())
3707 return false;
3708
3709 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3710 T->isSpecificBuiltinType(BuiltinType::Char_U);
3711}
3712
3713/// isCharSpecialization - Returns whether a given type is a template
3714/// specialization of a given name with a single argument of type char.
3715static bool isCharSpecialization(QualType T, const char *Name) {
3716 if (T.isNull())
3717 return false;
3718
3719 const RecordType *RT = T->getAs<RecordType>();
3720 if (!RT)
3721 return false;
3722
3723 const ClassTemplateSpecializationDecl *SD =
3724 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3725 if (!SD)
3726 return false;
3727
3728 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3729 return false;
3730
3731 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3732 if (TemplateArgs.size() != 1)
3733 return false;
3734
3735 if (!isCharType(TemplateArgs[0].getAsType()))
3736 return false;
3737
3738 return SD->getIdentifier()->getName() == Name;
3739}
3740
3741template <std::size_t StrLen>
3742static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3743 const char (&Str)[StrLen]) {
3744 if (!SD->getIdentifier()->isStr(Str))
3745 return false;
3746
3747 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3748 if (TemplateArgs.size() != 2)
3749 return false;
3750
3751 if (!isCharType(TemplateArgs[0].getAsType()))
3752 return false;
3753
3754 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3755 return false;
3756
3757 return true;
3758}
3759
3760bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3761 // <substitution> ::= St # ::std::
3762 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3763 if (isStd(NS)) {
3764 Out << "St";
3765 return true;
3766 }
3767 }
3768
3769 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3770 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3771 return false;
3772
3773 // <substitution> ::= Sa # ::std::allocator
3774 if (TD->getIdentifier()->isStr("allocator")) {
3775 Out << "Sa";
3776 return true;
3777 }
3778
3779 // <<substitution> ::= Sb # ::std::basic_string
3780 if (TD->getIdentifier()->isStr("basic_string")) {
3781 Out << "Sb";
3782 return true;
3783 }
3784 }
3785
3786 if (const ClassTemplateSpecializationDecl *SD =
3787 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3788 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3789 return false;
3790
3791 // <substitution> ::= Ss # ::std::basic_string<char,
3792 // ::std::char_traits<char>,
3793 // ::std::allocator<char> >
3794 if (SD->getIdentifier()->isStr("basic_string")) {
3795 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3796
3797 if (TemplateArgs.size() != 3)
3798 return false;
3799
3800 if (!isCharType(TemplateArgs[0].getAsType()))
3801 return false;
3802
3803 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3804 return false;
3805
3806 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3807 return false;
3808
3809 Out << "Ss";
3810 return true;
3811 }
3812
3813 // <substitution> ::= Si # ::std::basic_istream<char,
3814 // ::std::char_traits<char> >
3815 if (isStreamCharSpecialization(SD, "basic_istream")) {
3816 Out << "Si";
3817 return true;
3818 }
3819
3820 // <substitution> ::= So # ::std::basic_ostream<char,
3821 // ::std::char_traits<char> >
3822 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3823 Out << "So";
3824 return true;
3825 }
3826
3827 // <substitution> ::= Sd # ::std::basic_iostream<char,
3828 // ::std::char_traits<char> >
3829 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3830 Out << "Sd";
3831 return true;
3832 }
3833 }
3834 return false;
3835}
3836
3837void CXXNameMangler::addSubstitution(QualType T) {
3838 if (!hasMangledSubstitutionQualifiers(T)) {
3839 if (const RecordType *RT = T->getAs<RecordType>()) {
3840 addSubstitution(RT->getDecl());
3841 return;
3842 }
3843 }
3844
3845 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3846 addSubstitution(TypePtr);
3847}
3848
3849void CXXNameMangler::addSubstitution(TemplateName Template) {
3850 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3851 return addSubstitution(TD);
3852
3853 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3854 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3855}
3856
3857void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3858 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3859 Substitutions[Ptr] = SeqID++;
3860}
3861
3862//
3863
3864/// \brief Mangles the name of the declaration D and emits that name to the
3865/// given output stream.
3866///
3867/// If the declaration D requires a mangled name, this routine will emit that
3868/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3869/// and this routine will return false. In this case, the caller should just
3870/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3871/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003872void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3873 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3875 "Invalid mangleName() call, argument is not a variable or function!");
3876 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3877 "Invalid mangleName() call on 'structor decl!");
3878
3879 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3880 getASTContext().getSourceManager(),
3881 "Mangling declaration");
3882
3883 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003884 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003885}
3886
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003887void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3888 CXXCtorType Type,
3889 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 CXXNameMangler Mangler(*this, Out, D, Type);
3891 Mangler.mangle(D);
3892}
3893
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003894void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3895 CXXDtorType Type,
3896 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 CXXNameMangler Mangler(*this, Out, D, Type);
3898 Mangler.mangle(D);
3899}
3900
Rafael Espindola1e4df922014-09-16 15:18:21 +00003901void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3902 raw_ostream &Out) {
3903 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3904 Mangler.mangle(D);
3905}
3906
3907void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3908 raw_ostream &Out) {
3909 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3910 Mangler.mangle(D);
3911}
3912
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003913void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3914 const ThunkInfo &Thunk,
3915 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003916 // <special-name> ::= T <call-offset> <base encoding>
3917 // # base is the nominal target function of thunk
3918 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3919 // # base is the nominal target function of thunk
3920 // # first call-offset is 'this' adjustment
3921 // # second call-offset is result adjustment
3922
3923 assert(!isa<CXXDestructorDecl>(MD) &&
3924 "Use mangleCXXDtor for destructor decls!");
3925 CXXNameMangler Mangler(*this, Out);
3926 Mangler.getStream() << "_ZT";
3927 if (!Thunk.Return.isEmpty())
3928 Mangler.getStream() << 'c';
3929
3930 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003931 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3932 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3933
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 // Mangle the return pointer adjustment if there is one.
3935 if (!Thunk.Return.isEmpty())
3936 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003937 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3938
Guy Benyei11169dd2012-12-18 14:30:41 +00003939 Mangler.mangleFunctionEncoding(MD);
3940}
3941
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003942void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3943 const CXXDestructorDecl *DD, CXXDtorType Type,
3944 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 // <special-name> ::= T <call-offset> <base encoding>
3946 // # base is the nominal target function of thunk
3947 CXXNameMangler Mangler(*this, Out, DD, Type);
3948 Mangler.getStream() << "_ZT";
3949
3950 // Mangle the 'this' pointer adjustment.
3951 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003952 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003953
3954 Mangler.mangleFunctionEncoding(DD);
3955}
3956
3957/// mangleGuardVariable - Returns the mangled name for a guard variable
3958/// for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003959void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3960 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 // <special-name> ::= GV <object name> # Guard variable for one-time
3962 // # initialization
3963 CXXNameMangler Mangler(*this, Out);
3964 Mangler.getStream() << "_ZGV";
3965 Mangler.mangleName(D);
3966}
3967
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003968void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3969 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003970 // These symbols are internal in the Itanium ABI, so the names don't matter.
3971 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3972 // avoid duplicate symbols.
3973 Out << "__cxx_global_var_init";
3974}
3975
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003976void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3977 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003978 // Prefix the mangling of D with __dtor_.
3979 CXXNameMangler Mangler(*this, Out);
3980 Mangler.getStream() << "__dtor_";
3981 if (shouldMangleDeclName(D))
3982 Mangler.mangle(D);
3983 else
3984 Mangler.getStream() << D->getName();
3985}
3986
Reid Kleckner1d59f992015-01-22 01:36:17 +00003987void ItaniumMangleContextImpl::mangleSEHFilterExpression(
3988 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3989 CXXNameMangler Mangler(*this, Out);
3990 Mangler.getStream() << "__filt_";
3991 if (shouldMangleDeclName(EnclosingDecl))
3992 Mangler.mangle(EnclosingDecl);
3993 else
3994 Mangler.getStream() << EnclosingDecl->getName();
3995}
3996
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003997void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
3998 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003999 // <special-name> ::= TH <object name>
4000 CXXNameMangler Mangler(*this, Out);
4001 Mangler.getStream() << "_ZTH";
4002 Mangler.mangleName(D);
4003}
4004
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004005void
4006ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4007 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004008 // <special-name> ::= TW <object name>
4009 CXXNameMangler Mangler(*this, Out);
4010 Mangler.getStream() << "_ZTW";
4011 Mangler.mangleName(D);
4012}
4013
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004014void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004015 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004016 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 // We match the GCC mangling here.
4018 // <special-name> ::= GR <object name>
4019 CXXNameMangler Mangler(*this, Out);
4020 Mangler.getStream() << "_ZGR";
4021 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004022 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004023 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004024}
4025
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004026void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4027 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004028 // <special-name> ::= TV <type> # virtual table
4029 CXXNameMangler Mangler(*this, Out);
4030 Mangler.getStream() << "_ZTV";
4031 Mangler.mangleNameOrStandardSubstitution(RD);
4032}
4033
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004034void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4035 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004036 // <special-name> ::= TT <type> # VTT structure
4037 CXXNameMangler Mangler(*this, Out);
4038 Mangler.getStream() << "_ZTT";
4039 Mangler.mangleNameOrStandardSubstitution(RD);
4040}
4041
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004042void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4043 int64_t Offset,
4044 const CXXRecordDecl *Type,
4045 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 // <special-name> ::= TC <type> <offset number> _ <base type>
4047 CXXNameMangler Mangler(*this, Out);
4048 Mangler.getStream() << "_ZTC";
4049 Mangler.mangleNameOrStandardSubstitution(RD);
4050 Mangler.getStream() << Offset;
4051 Mangler.getStream() << '_';
4052 Mangler.mangleNameOrStandardSubstitution(Type);
4053}
4054
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004055void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 // <special-name> ::= TI <type> # typeinfo structure
4057 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4058 CXXNameMangler Mangler(*this, Out);
4059 Mangler.getStream() << "_ZTI";
4060 Mangler.mangleType(Ty);
4061}
4062
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004063void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4064 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4066 CXXNameMangler Mangler(*this, Out);
4067 Mangler.getStream() << "_ZTS";
4068 Mangler.mangleType(Ty);
4069}
4070
Reid Klecknercc99e262013-11-19 23:23:00 +00004071void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4072 mangleCXXRTTIName(Ty, Out);
4073}
4074
David Majnemer58e5bee2014-03-24 21:43:36 +00004075void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4076 llvm_unreachable("Can't mangle string literals");
4077}
4078
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004079ItaniumMangleContext *
4080ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4081 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004082}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004083