blob: 5e079960ae1162b59f2ed361e29926fcb1373691 [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"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000025#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/ABI.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36#define MANGLE_CHECKER 0
37
38#if MANGLE_CHECKER
39#include <cxxabi.h>
40#endif
41
42using namespace clang;
43
44namespace {
45
Justin Bognere8d762e2015-05-22 06:48:13 +000046/// Retrieve the declaration context that should be used when mangling the given
47/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000048static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49 // The ABI assumes that lambda closure types that occur within
50 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
52 // not the case: the lambda closure type ends up living in the context
53 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Eli Friedman0cd23352013-07-10 01:33:19 +000061
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
67 }
Guy Benyei11169dd2012-12-18 14:30:41 +000068
Eli Friedman95f50122013-07-02 17:52:28 +000069 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000070 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
Eli Friedman95f50122013-07-02 17:52:28 +000073
David Majnemerf8c02e62015-02-18 19:08:11 +000074 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
Eli Friedman95f50122013-07-02 17:52:28 +000082 return DC;
Guy Benyei11169dd2012-12-18 14:30:41 +000083}
84
85static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87}
Eli Friedman95f50122013-07-02 17:52:28 +000088
89static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91}
92
Eli Friedmaneecc09a2013-07-05 20:27:40 +000093static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000094 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000095 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000096 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000097 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000098 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000100 }
Craig Topper36250ad2014-05-12 05:36:57 +0000101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102}
103
104static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109}
110
111static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114}
David Majnemer2206bf52014-03-05 08:57:59 +0000115
116static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122}
123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124static const unsigned UnknownArity = ~0U;
125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000130
Guy Benyei11169dd2012-12-18 14:30:41 +0000131public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000135
Guy Benyei11169dd2012-12-18 14:30:41 +0000136 /// @name Mangler Entry Points
137 /// @{
138
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000162
Rafael Espindola1e4df922014-09-16 15:18:21 +0000163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
David Majnemer58e5bee2014-03-24 21:43:36 +0000177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
217
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
223
Justin Bognere8d762e2015-05-22 06:48:13 +0000224 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225 unsigned SeqID;
226
227 class FunctionTypeDepthState {
228 unsigned Bits;
229
230 enum { InResultTypeMask = 1 };
231
232 public:
233 FunctionTypeDepthState() : Bits(0) {}
234
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
237 return Bits >> 1;
238 }
239
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
243 }
244
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
248 return tmp;
249 }
250
251 void enterResultType() {
252 Bits |= InResultTypeMask;
253 }
254
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
257 }
258
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
261 Bits = saved.Bits;
262 }
263
264 } FunctionTypeDepth;
265
266 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
267
268 ASTContext &getASTContext() const { return Context.getASTContext(); }
269
270public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000271 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000272 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000273 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
274 SeqID(0) {
275 // These can't be mangled without a ctor type or dtor type.
276 assert(!D || (!isa<CXXDestructorDecl>(D) &&
277 !isa<CXXConstructorDecl>(D)));
278 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 const CXXConstructorDecl *D, CXXCtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000283 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000284 const CXXDestructorDecl *D, CXXDtorType Type)
285 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
286 SeqID(0) { }
287
288#if MANGLE_CHECKER
289 ~CXXNameMangler() {
290 if (Out.str()[0] == '\01')
291 return;
292
293 int status = 0;
294 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
295 assert(status == 0 && "Could not demangle mangled name!");
296 free(result);
297 }
298#endif
299 raw_ostream &getStream() { return Out; }
300
David Majnemer7ff7eb72015-02-18 07:47:09 +0000301 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
303 void mangleNumber(const llvm::APSInt &I);
304 void mangleNumber(int64_t Number);
305 void mangleFloat(const llvm::APFloat &F);
306 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000307 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 void mangleName(const NamedDecl *ND);
309 void mangleType(QualType T);
310 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
311
312private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000313
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 bool mangleSubstitution(const NamedDecl *ND);
315 bool mangleSubstitution(QualType T);
316 bool mangleSubstitution(TemplateName Template);
317 bool mangleSubstitution(uintptr_t Ptr);
318
319 void mangleExistingSubstitution(QualType type);
320 void mangleExistingSubstitution(TemplateName name);
321
322 bool mangleStandardSubstitution(const NamedDecl *ND);
323
324 void addSubstitution(const NamedDecl *ND) {
325 ND = cast<NamedDecl>(ND->getCanonicalDecl());
326
327 addSubstitution(reinterpret_cast<uintptr_t>(ND));
328 }
329 void addSubstitution(QualType T);
330 void addSubstitution(TemplateName Template);
331 void addSubstitution(uintptr_t Ptr);
332
333 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 bool recursive = false);
335 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000336 DeclarationName name,
337 unsigned KnownArity = UnknownArity);
338
339 void mangleName(const TemplateDecl *TD,
340 const TemplateArgument *TemplateArgs,
341 unsigned NumTemplateArgs);
342 void mangleUnqualifiedName(const NamedDecl *ND) {
343 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
344 }
345 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
346 unsigned KnownArity);
347 void mangleUnscopedName(const NamedDecl *ND);
348 void mangleUnscopedTemplateName(const TemplateDecl *ND);
349 void mangleUnscopedTemplateName(TemplateName);
350 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000351 void mangleLocalName(const Decl *D);
352 void mangleBlockForPrefix(const BlockDecl *Block);
353 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 void mangleLambda(const CXXRecordDecl *Lambda);
355 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
356 bool NoFunction=false);
357 void mangleNestedName(const TemplateDecl *TD,
358 const TemplateArgument *TemplateArgs,
359 unsigned NumTemplateArgs);
360 void manglePrefix(NestedNameSpecifier *qualifier);
361 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
362 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000363 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000365 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
366 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000367 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000369 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 void mangleQualifiers(Qualifiers Quals);
371 void mangleRefQualifier(RefQualifierKind RefQualifier);
372
373 void mangleObjCMethodName(const ObjCMethodDecl *MD);
374
375 // Declare manglers for every type class.
376#define ABSTRACT_TYPE(CLASS, PARENT)
377#define NON_CANONICAL_TYPE(CLASS, PARENT)
378#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
379#include "clang/AST/TypeNodes.def"
380
381 void mangleType(const TagType*);
382 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000383 static StringRef getCallingConvQualifierName(CallingConv CC);
384 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
385 void mangleExtFunctionInfo(const FunctionType *T);
386 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000387 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000389 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000390
391 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000392 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 void mangleMemberExpr(const Expr *base, bool isArrow,
394 NestedNameSpecifier *qualifier,
395 NamedDecl *firstQualifierLookup,
396 DeclarationName name,
397 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000398 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000399 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000400 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
401 void mangleCXXCtorType(CXXCtorType T);
402 void mangleCXXDtorType(CXXDtorType T);
403
James Y Knight04ec5bf2015-12-24 02:59:37 +0000404 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
405 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000406 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
407 unsigned NumTemplateArgs);
408 void mangleTemplateArgs(const TemplateArgumentList &AL);
409 void mangleTemplateArg(TemplateArgument A);
410
411 void mangleTemplateParameter(unsigned Index);
412
413 void mangleFunctionParam(const ParmVarDecl *parm);
414};
415
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000416}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
Rafael Espindola002667c2013-10-16 01:40:34 +0000418bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000420 if (FD) {
421 LanguageLinkage L = FD->getLanguageLinkage();
422 // Overloadable functions need mangling.
423 if (FD->hasAttr<OverloadableAttr>())
424 return true;
425
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000426 // "main" is not mangled.
427 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000428 return false;
429
430 // C++ functions and those whose names are not a simple identifier need
431 // mangling.
432 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
433 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000434
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000435 // C functions are not mangled.
436 if (L == CLanguageLinkage)
437 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000438 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000439
440 // Otherwise, no mangling is done outside C++ mode.
441 if (!getASTContext().getLangOpts().CPlusPlus)
442 return false;
443
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000444 const VarDecl *VD = dyn_cast<VarDecl>(D);
445 if (VD) {
446 // C variables are not mangled.
447 if (VD->isExternC())
448 return false;
449
450 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 const DeclContext *DC = getEffectiveDeclContext(D);
452 // Check for extern variable declared locally.
453 if (DC->isFunctionOrMethod() && D->hasLinkage())
454 while (!DC->isNamespace() && !DC->isTranslationUnit())
455 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000456 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
457 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 return false;
459 }
460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 return true;
462}
463
David Majnemer7ff7eb72015-02-18 07:47:09 +0000464void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 // <mangled-name> ::= _Z <encoding>
466 // ::= <data name>
467 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000468 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
470 mangleFunctionEncoding(FD);
471 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
472 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000473 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
474 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000475 else
476 mangleName(cast<FieldDecl>(D));
477}
478
479void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
480 // <encoding> ::= <function name> <bare-function-type>
481 mangleName(FD);
482
483 // Don't mangle in the type if this isn't a decl we should typically mangle.
484 if (!Context.shouldMangleDeclName(FD))
485 return;
486
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000487 if (FD->hasAttr<EnableIfAttr>()) {
488 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
489 Out << "Ua9enable_ifI";
490 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
491 // it here.
492 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
493 E = FD->getAttrs().rend();
494 I != E; ++I) {
495 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
496 if (!EIA)
497 continue;
498 Out << 'X';
499 mangleExpression(EIA->getCond());
500 Out << 'E';
501 }
502 Out << 'E';
503 FunctionTypeDepth.pop(Saved);
504 }
505
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 // Whether the mangling of a function type includes the return type depends on
507 // the context and the nature of the function. The rules for deciding whether
508 // the return type is included are:
509 //
510 // 1. Template functions (names or types) have return types encoded, with
511 // the exceptions listed below.
512 // 2. Function types not appearing as part of a function name mangling,
513 // e.g. parameters, pointer types, etc., have return type encoded, with the
514 // exceptions listed below.
515 // 3. Non-template function names do not have return types encoded.
516 //
517 // The exceptions mentioned in (1) and (2) above, for which the return type is
518 // never included, are
519 // 1. Constructors.
520 // 2. Destructors.
521 // 3. Conversion operator functions, e.g. operator int.
522 bool MangleReturnType = false;
523 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
524 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
525 isa<CXXConversionDecl>(FD)))
526 MangleReturnType = true;
527
528 // Mangle the type of the primary template.
529 FD = PrimaryTemplate->getTemplatedDecl();
530 }
531
John McCall07daf722016-03-01 22:18:03 +0000532 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000533 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000534}
535
536static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
537 while (isa<LinkageSpecDecl>(DC)) {
538 DC = getEffectiveParentContext(DC);
539 }
540
541 return DC;
542}
543
Justin Bognere8d762e2015-05-22 06:48:13 +0000544/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000545static bool isStd(const NamespaceDecl *NS) {
546 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
547 ->isTranslationUnit())
548 return false;
549
550 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
551 return II && II->isStr("std");
552}
553
554// isStdNamespace - Return whether a given decl context is a toplevel 'std'
555// namespace.
556static bool isStdNamespace(const DeclContext *DC) {
557 if (!DC->isNamespace())
558 return false;
559
560 return isStd(cast<NamespaceDecl>(DC));
561}
562
563static const TemplateDecl *
564isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
565 // Check if we have a function template.
566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
567 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
568 TemplateArgs = FD->getTemplateSpecializationArgs();
569 return TD;
570 }
571 }
572
573 // Check if we have a class template.
574 if (const ClassTemplateSpecializationDecl *Spec =
575 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
576 TemplateArgs = &Spec->getTemplateArgs();
577 return Spec->getSpecializedTemplate();
578 }
579
Larisse Voufo39a1e502013-08-06 01:03:05 +0000580 // Check if we have a variable template.
581 if (const VarTemplateSpecializationDecl *Spec =
582 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
583 TemplateArgs = &Spec->getTemplateArgs();
584 return Spec->getSpecializedTemplate();
585 }
586
Craig Topper36250ad2014-05-12 05:36:57 +0000587 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000588}
589
Guy Benyei11169dd2012-12-18 14:30:41 +0000590void CXXNameMangler::mangleName(const NamedDecl *ND) {
591 // <name> ::= <nested-name>
592 // ::= <unscoped-name>
593 // ::= <unscoped-template-name> <template-args>
594 // ::= <local-name>
595 //
596 const DeclContext *DC = getEffectiveDeclContext(ND);
597
598 // If this is an extern variable declared locally, the relevant DeclContext
599 // is that of the containing namespace, or the translation unit.
600 // FIXME: This is a hack; extern variables declared locally should have
601 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000602 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 while (!DC->isNamespace() && !DC->isTranslationUnit())
604 DC = getEffectiveParentContext(DC);
605 else if (GetLocalClassDecl(ND)) {
606 mangleLocalName(ND);
607 return;
608 }
609
610 DC = IgnoreLinkageSpecDecls(DC);
611
612 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
613 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000614 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
616 mangleUnscopedTemplateName(TD);
617 mangleTemplateArgs(*TemplateArgs);
618 return;
619 }
620
621 mangleUnscopedName(ND);
622 return;
623 }
624
Eli Friedman95f50122013-07-02 17:52:28 +0000625 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000626 mangleLocalName(ND);
627 return;
628 }
629
630 mangleNestedName(ND, DC);
631}
632void CXXNameMangler::mangleName(const TemplateDecl *TD,
633 const TemplateArgument *TemplateArgs,
634 unsigned NumTemplateArgs) {
635 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
636
637 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
638 mangleUnscopedTemplateName(TD);
639 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
640 } else {
641 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
642 }
643}
644
645void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
646 // <unscoped-name> ::= <unqualified-name>
647 // ::= St <unqualified-name> # ::std::
648
649 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
650 Out << "St";
651
652 mangleUnqualifiedName(ND);
653}
654
655void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
656 // <unscoped-template-name> ::= <unscoped-name>
657 // ::= <substitution>
658 if (mangleSubstitution(ND))
659 return;
660
661 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000662 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000664 else
665 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000666
Guy Benyei11169dd2012-12-18 14:30:41 +0000667 addSubstitution(ND);
668}
669
670void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
671 // <unscoped-template-name> ::= <unscoped-name>
672 // ::= <substitution>
673 if (TemplateDecl *TD = Template.getAsTemplateDecl())
674 return mangleUnscopedTemplateName(TD);
675
676 if (mangleSubstitution(Template))
677 return;
678
679 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
680 assert(Dependent && "Not a dependent template name?");
681 if (const IdentifierInfo *Id = Dependent->getIdentifier())
682 mangleSourceName(Id);
683 else
684 mangleOperatorName(Dependent->getOperator(), UnknownArity);
685
686 addSubstitution(Template);
687}
688
689void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
690 // ABI:
691 // Floating-point literals are encoded using a fixed-length
692 // lowercase hexadecimal string corresponding to the internal
693 // representation (IEEE on Itanium), high-order bytes first,
694 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
695 // on Itanium.
696 // The 'without leading zeroes' thing seems to be an editorial
697 // mistake; see the discussion on cxx-abi-dev beginning on
698 // 2012-01-16.
699
700 // Our requirements here are just barely weird enough to justify
701 // using a custom algorithm instead of post-processing APInt::toString().
702
703 llvm::APInt valueBits = f.bitcastToAPInt();
704 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
705 assert(numCharacters != 0);
706
707 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000708 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000709
710 // Fill the buffer left-to-right.
711 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
712 // The bit-index of the next hex digit.
713 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
714
715 // Project out 4 bits starting at 'digitIndex'.
716 llvm::integerPart hexDigit
717 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
718 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
719 hexDigit &= 0xF;
720
721 // Map that over to a lowercase hex digit.
722 static const char charForHex[16] = {
723 '0', '1', '2', '3', '4', '5', '6', '7',
724 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
725 };
726 buffer[stringIndex] = charForHex[hexDigit];
727 }
728
729 Out.write(buffer.data(), numCharacters);
730}
731
732void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
733 if (Value.isSigned() && Value.isNegative()) {
734 Out << 'n';
735 Value.abs().print(Out, /*signed*/ false);
736 } else {
737 Value.print(Out, /*signed*/ false);
738 }
739}
740
741void CXXNameMangler::mangleNumber(int64_t Number) {
742 // <number> ::= [n] <non-negative decimal integer>
743 if (Number < 0) {
744 Out << 'n';
745 Number = -Number;
746 }
747
748 Out << Number;
749}
750
751void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
752 // <call-offset> ::= h <nv-offset> _
753 // ::= v <v-offset> _
754 // <nv-offset> ::= <offset number> # non-virtual base override
755 // <v-offset> ::= <offset number> _ <virtual offset number>
756 // # virtual base override, with vcall offset
757 if (!Virtual) {
758 Out << 'h';
759 mangleNumber(NonVirtual);
760 Out << '_';
761 return;
762 }
763
764 Out << 'v';
765 mangleNumber(NonVirtual);
766 Out << '_';
767 mangleNumber(Virtual);
768 Out << '_';
769}
770
771void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000772 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (!mangleSubstitution(QualType(TST, 0))) {
774 mangleTemplatePrefix(TST->getTemplateName());
775
776 // FIXME: GCC does not appear to mangle the template arguments when
777 // the template in question is a dependent template name. Should we
778 // emulate that badness?
779 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
780 addSubstitution(QualType(TST, 0));
781 }
David Majnemera88b3592015-02-18 02:28:01 +0000782 } else if (const auto *DTST =
783 type->getAs<DependentTemplateSpecializationType>()) {
784 if (!mangleSubstitution(QualType(DTST, 0))) {
785 TemplateName Template = getASTContext().getDependentTemplateName(
786 DTST->getQualifier(), DTST->getIdentifier());
787 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000788
David Majnemera88b3592015-02-18 02:28:01 +0000789 // FIXME: GCC does not appear to mangle the template arguments when
790 // the template in question is a dependent template name. Should we
791 // emulate that badness?
792 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
793 addSubstitution(QualType(DTST, 0));
794 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 } else {
796 // We use the QualType mangle type variant here because it handles
797 // substitutions.
798 mangleType(type);
799 }
800}
801
802/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
803///
Guy Benyei11169dd2012-12-18 14:30:41 +0000804/// \param recursive - true if this is being called recursively,
805/// i.e. if there is more prefix "to the right".
806void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 bool recursive) {
808
809 // x, ::x
810 // <unresolved-name> ::= [gs] <base-unresolved-name>
811
812 // T::x / decltype(p)::x
813 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
814
815 // T::N::x /decltype(p)::N::x
816 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
817 // <base-unresolved-name>
818
819 // A::x, N::y, A<T>::z; "gs" means leading "::"
820 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
821 // <base-unresolved-name>
822
823 switch (qualifier->getKind()) {
824 case NestedNameSpecifier::Global:
825 Out << "gs";
826
827 // We want an 'sr' unless this is the entire NNS.
828 if (recursive)
829 Out << "sr";
830
831 // We never want an 'E' here.
832 return;
833
Nikola Smiljanic67860242014-09-26 00:28:20 +0000834 case NestedNameSpecifier::Super:
835 llvm_unreachable("Can't mangle __super specifier");
836
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 case NestedNameSpecifier::Namespace:
838 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000839 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 /*recursive*/ true);
841 else
842 Out << "sr";
843 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
844 break;
845 case NestedNameSpecifier::NamespaceAlias:
846 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000847 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 /*recursive*/ true);
849 else
850 Out << "sr";
851 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
852 break;
853
854 case NestedNameSpecifier::TypeSpec:
855 case NestedNameSpecifier::TypeSpecWithTemplate: {
856 const Type *type = qualifier->getAsType();
857
858 // We only want to use an unresolved-type encoding if this is one of:
859 // - a decltype
860 // - a template type parameter
861 // - a template template parameter with arguments
862 // In all of these cases, we should have no prefix.
863 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000864 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 /*recursive*/ true);
866 } else {
867 // Otherwise, all the cases want this.
868 Out << "sr";
869 }
870
David Majnemerb8014dd2015-02-19 02:16:16 +0000871 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 return;
873
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 break;
875 }
876
877 case NestedNameSpecifier::Identifier:
878 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000879 if (qualifier->getPrefix())
880 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000882 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000884
885 mangleSourceName(qualifier->getAsIdentifier());
886 break;
887 }
888
889 // If this was the innermost part of the NNS, and we fell out to
890 // here, append an 'E'.
891 if (!recursive)
892 Out << 'E';
893}
894
895/// Mangle an unresolved-name, which is generally used for names which
896/// weren't resolved to specific entities.
897void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000898 DeclarationName name,
899 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000900 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000901 switch (name.getNameKind()) {
902 // <base-unresolved-name> ::= <simple-id>
903 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000904 mangleSourceName(name.getAsIdentifierInfo());
905 break;
906 // <base-unresolved-name> ::= dn <destructor-name>
907 case DeclarationName::CXXDestructorName:
908 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000909 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000910 break;
911 // <base-unresolved-name> ::= on <operator-name>
912 case DeclarationName::CXXConversionFunctionName:
913 case DeclarationName::CXXLiteralOperatorName:
914 case DeclarationName::CXXOperatorName:
915 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000916 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000917 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000918 case DeclarationName::CXXConstructorName:
919 llvm_unreachable("Can't mangle a constructor name!");
920 case DeclarationName::CXXUsingDirective:
921 llvm_unreachable("Can't mangle a using directive name!");
922 case DeclarationName::ObjCMultiArgSelector:
923 case DeclarationName::ObjCOneArgSelector:
924 case DeclarationName::ObjCZeroArgSelector:
925 llvm_unreachable("Can't mangle Objective-C selector names here!");
926 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000927}
928
Guy Benyei11169dd2012-12-18 14:30:41 +0000929void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
930 DeclarationName Name,
931 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000932 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 // <unqualified-name> ::= <operator-name>
934 // ::= <ctor-dtor-name>
935 // ::= <source-name>
936 switch (Name.getNameKind()) {
937 case DeclarationName::Identifier: {
938 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
939 // We must avoid conflicts between internally- and externally-
940 // linked variable and function declaration names in the same TU:
941 // void test() { extern void foo(); }
942 // static void foo();
943 // This naming convention is the same as that followed by GCC,
944 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000945 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 getEffectiveDeclContext(ND)->isFileContext())
947 Out << 'L';
948
949 mangleSourceName(II);
950 break;
951 }
952
953 // Otherwise, an anonymous entity. We must have a declaration.
954 assert(ND && "mangling empty name without declaration");
955
956 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
957 if (NS->isAnonymousNamespace()) {
958 // This is how gcc mangles these names.
959 Out << "12_GLOBAL__N_1";
960 break;
961 }
962 }
963
964 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
965 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000966 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000968
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 // Itanium C++ ABI 5.1.2:
970 //
971 // For the purposes of mangling, the name of an anonymous union is
972 // considered to be the name of the first named data member found by a
973 // pre-order, depth-first, declaration-order walk of the data members of
974 // the anonymous union. If there is no such data member (i.e., if all of
975 // the data members in the union are unnamed), then there is no way for
976 // a program to refer to the anonymous union, and there is therefore no
977 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000978 assert(RD->isAnonymousStructOrUnion()
979 && "Expected anonymous struct or union!");
980 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000981
982 // It's actually possible for various reasons for us to get here
983 // with an empty anonymous struct / union. Fortunately, it
984 // doesn't really matter what name we generate.
985 if (!FD) break;
986 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000987
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 mangleSourceName(FD->getIdentifier());
989 break;
990 }
John McCall924046f2013-04-10 06:08:21 +0000991
992 // Class extensions have no name as a category, and it's possible
993 // for them to be the semantic parent of certain declarations
994 // (primarily, tag decls defined within declarations). Such
995 // declarations will always have internal linkage, so the name
996 // doesn't really matter, but we shouldn't crash on them. For
997 // safety, just handle all ObjC containers here.
998 if (isa<ObjCContainerDecl>(ND))
999 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001000
1001 // We must have an anonymous struct.
1002 const TagDecl *TD = cast<TagDecl>(ND);
1003 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1004 assert(TD->getDeclContext() == D->getDeclContext() &&
1005 "Typedef should not be in another decl context!");
1006 assert(D->getDeclName().getAsIdentifierInfo() &&
1007 "Typedef was not named!");
1008 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1009 break;
1010 }
1011
1012 // <unnamed-type-name> ::= <closure-type-name>
1013 //
1014 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1015 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1016 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1017 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1018 mangleLambda(Record);
1019 break;
1020 }
1021 }
1022
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001023 if (TD->isExternallyVisible()) {
1024 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001026 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001027 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 Out << '_';
1029 break;
1030 }
1031
1032 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001033 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034
1035 // Mangle it as a source name in the form
1036 // [n] $_<id>
1037 // where n is the length of the string.
1038 SmallString<8> Str;
1039 Str += "$_";
1040 Str += llvm::utostr(AnonStructId);
1041
1042 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001043 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 break;
1045 }
1046
1047 case DeclarationName::ObjCZeroArgSelector:
1048 case DeclarationName::ObjCOneArgSelector:
1049 case DeclarationName::ObjCMultiArgSelector:
1050 llvm_unreachable("Can't mangle Objective-C selector names here!");
1051
1052 case DeclarationName::CXXConstructorName:
1053 if (ND == Structor)
1054 // If the named decl is the C++ constructor we're mangling, use the type
1055 // we were given.
1056 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1057 else
1058 // Otherwise, use the complete constructor name. This is relevant if a
1059 // class with a constructor is declared within a constructor.
1060 mangleCXXCtorType(Ctor_Complete);
1061 break;
1062
1063 case DeclarationName::CXXDestructorName:
1064 if (ND == Structor)
1065 // If the named decl is the C++ destructor we're mangling, use the type we
1066 // were given.
1067 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1068 else
1069 // Otherwise, use the complete destructor name. This is relevant if a
1070 // class with a destructor is declared within a destructor.
1071 mangleCXXDtorType(Dtor_Complete);
1072 break;
1073
David Majnemera88b3592015-02-18 02:28:01 +00001074 case DeclarationName::CXXOperatorName:
1075 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 Arity = cast<FunctionDecl>(ND)->getNumParams();
1077
David Majnemera88b3592015-02-18 02:28:01 +00001078 // If we have a member function, we need to include the 'this' pointer.
1079 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1080 if (!MD->isStatic())
1081 Arity++;
1082 }
1083 // FALLTHROUGH
1084 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001085 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001086 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 break;
1088
1089 case DeclarationName::CXXUsingDirective:
1090 llvm_unreachable("Can't mangle a using directive name!");
1091 }
1092}
1093
1094void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1095 // <source-name> ::= <positive length number> <identifier>
1096 // <number> ::= [n] <non-negative decimal integer>
1097 // <identifier> ::= <unqualified source code identifier>
1098 Out << II->getLength() << II->getName();
1099}
1100
1101void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1102 const DeclContext *DC,
1103 bool NoFunction) {
1104 // <nested-name>
1105 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1106 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1107 // <template-args> E
1108
1109 Out << 'N';
1110 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001111 Qualifiers MethodQuals =
1112 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1113 // We do not consider restrict a distinguishing attribute for overloading
1114 // purposes so we must not mangle it.
1115 MethodQuals.removeRestrict();
1116 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 mangleRefQualifier(Method->getRefQualifier());
1118 }
1119
1120 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001121 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001123 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 mangleTemplateArgs(*TemplateArgs);
1125 }
1126 else {
1127 manglePrefix(DC, NoFunction);
1128 mangleUnqualifiedName(ND);
1129 }
1130
1131 Out << 'E';
1132}
1133void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1134 const TemplateArgument *TemplateArgs,
1135 unsigned NumTemplateArgs) {
1136 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1137
1138 Out << 'N';
1139
1140 mangleTemplatePrefix(TD);
1141 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1142
1143 Out << 'E';
1144}
1145
Eli Friedman95f50122013-07-02 17:52:28 +00001146void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1148 // := Z <function encoding> E s [<discriminator>]
1149 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1150 // _ <entity name>
1151 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001152 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001153 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001154 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001155
1156 Out << 'Z';
1157
Eli Friedman92821742013-07-02 02:01:18 +00001158 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1159 mangleObjCMethodName(MD);
1160 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001161 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001162 else
1163 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001164
Eli Friedman92821742013-07-02 02:01:18 +00001165 Out << 'E';
1166
1167 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 // The parameter number is omitted for the last parameter, 0 for the
1169 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1170 // <entity name> will of course contain a <closure-type-name>: Its
1171 // numbering will be local to the particular argument in which it appears
1172 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001173 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1174 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001176 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 if (const FunctionDecl *Func
1178 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1179 Out << 'd';
1180 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1181 if (Num > 1)
1182 mangleNumber(Num - 2);
1183 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 }
1185 }
1186 }
1187
1188 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001189 // equality ok because RD derived from ND above
1190 if (D == RD) {
1191 mangleUnqualifiedName(RD);
1192 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1193 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1194 mangleUnqualifiedBlock(BD);
1195 } else {
1196 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001197 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001198 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001199 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1200 // Mangle a block in a default parameter; see above explanation for
1201 // lambdas.
1202 if (const ParmVarDecl *Parm
1203 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1204 if (const FunctionDecl *Func
1205 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1206 Out << 'd';
1207 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1208 if (Num > 1)
1209 mangleNumber(Num - 2);
1210 Out << '_';
1211 }
1212 }
1213
1214 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001215 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001216 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001218
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001219 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1220 unsigned disc;
1221 if (Context.getNextDiscriminator(ND, disc)) {
1222 if (disc < 10)
1223 Out << '_' << disc;
1224 else
1225 Out << "__" << disc << '_';
1226 }
1227 }
Eli Friedman95f50122013-07-02 17:52:28 +00001228}
1229
1230void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1231 if (GetLocalClassDecl(Block)) {
1232 mangleLocalName(Block);
1233 return;
1234 }
1235 const DeclContext *DC = getEffectiveDeclContext(Block);
1236 if (isLocalContainerContext(DC)) {
1237 mangleLocalName(Block);
1238 return;
1239 }
1240 manglePrefix(getEffectiveDeclContext(Block));
1241 mangleUnqualifiedBlock(Block);
1242}
1243
1244void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1245 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1246 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1247 Context->getDeclContext()->isRecord()) {
1248 if (const IdentifierInfo *Name
1249 = cast<NamedDecl>(Context)->getIdentifier()) {
1250 mangleSourceName(Name);
1251 Out << 'M';
1252 }
1253 }
1254 }
1255
1256 // If we have a block mangling number, use it.
1257 unsigned Number = Block->getBlockManglingNumber();
1258 // Otherwise, just make up a number. It doesn't matter what it is because
1259 // the symbol in question isn't externally visible.
1260 if (!Number)
1261 Number = Context.getBlockId(Block, false);
1262 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001263 if (Number > 0)
1264 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001265 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001266}
1267
1268void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1269 // If the context of a closure type is an initializer for a class member
1270 // (static or nonstatic), it is encoded in a qualified name with a final
1271 // <prefix> of the form:
1272 //
1273 // <data-member-prefix> := <member source-name> M
1274 //
1275 // Technically, the data-member-prefix is part of the <prefix>. However,
1276 // since a closure type will always be mangled with a prefix, it's easier
1277 // to emit that last part of the prefix here.
1278 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1279 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1280 Context->getDeclContext()->isRecord()) {
1281 if (const IdentifierInfo *Name
1282 = cast<NamedDecl>(Context)->getIdentifier()) {
1283 mangleSourceName(Name);
1284 Out << 'M';
1285 }
1286 }
1287 }
1288
1289 Out << "Ul";
1290 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1291 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001292 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1293 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 Out << "E";
1295
1296 // The number is omitted for the first closure type with a given
1297 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1298 // (in lexical order) with that same <lambda-sig> and context.
1299 //
1300 // The AST keeps track of the number for us.
1301 unsigned Number = Lambda->getLambdaManglingNumber();
1302 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1303 if (Number > 1)
1304 mangleNumber(Number - 2);
1305 Out << '_';
1306}
1307
1308void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1309 switch (qualifier->getKind()) {
1310 case NestedNameSpecifier::Global:
1311 // nothing
1312 return;
1313
Nikola Smiljanic67860242014-09-26 00:28:20 +00001314 case NestedNameSpecifier::Super:
1315 llvm_unreachable("Can't mangle __super specifier");
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 case NestedNameSpecifier::Namespace:
1318 mangleName(qualifier->getAsNamespace());
1319 return;
1320
1321 case NestedNameSpecifier::NamespaceAlias:
1322 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1323 return;
1324
1325 case NestedNameSpecifier::TypeSpec:
1326 case NestedNameSpecifier::TypeSpecWithTemplate:
1327 manglePrefix(QualType(qualifier->getAsType(), 0));
1328 return;
1329
1330 case NestedNameSpecifier::Identifier:
1331 // Member expressions can have these without prefixes, but that
1332 // should end up in mangleUnresolvedPrefix instead.
1333 assert(qualifier->getPrefix());
1334 manglePrefix(qualifier->getPrefix());
1335
1336 mangleSourceName(qualifier->getAsIdentifier());
1337 return;
1338 }
1339
1340 llvm_unreachable("unexpected nested name specifier");
1341}
1342
1343void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1344 // <prefix> ::= <prefix> <unqualified-name>
1345 // ::= <template-prefix> <template-args>
1346 // ::= <template-param>
1347 // ::= # empty
1348 // ::= <substitution>
1349
1350 DC = IgnoreLinkageSpecDecls(DC);
1351
1352 if (DC->isTranslationUnit())
1353 return;
1354
Eli Friedman95f50122013-07-02 17:52:28 +00001355 if (NoFunction && isLocalContainerContext(DC))
1356 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001357
Eli Friedman95f50122013-07-02 17:52:28 +00001358 assert(!isLocalContainerContext(DC));
1359
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 const NamedDecl *ND = cast<NamedDecl>(DC);
1361 if (mangleSubstitution(ND))
1362 return;
1363
1364 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001365 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1367 mangleTemplatePrefix(TD);
1368 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001369 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1371 mangleUnqualifiedName(ND);
1372 }
1373
1374 addSubstitution(ND);
1375}
1376
1377void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1378 // <template-prefix> ::= <prefix> <template unqualified-name>
1379 // ::= <template-param>
1380 // ::= <substitution>
1381 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1382 return mangleTemplatePrefix(TD);
1383
1384 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1385 manglePrefix(Qualified->getQualifier());
1386
1387 if (OverloadedTemplateStorage *Overloaded
1388 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001389 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 UnknownArity);
1391 return;
1392 }
1393
1394 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1395 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001396 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1397 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 mangleUnscopedTemplateName(Template);
1399}
1400
Eli Friedman86af13f02013-07-05 18:41:30 +00001401void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1402 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 // <template-prefix> ::= <prefix> <template unqualified-name>
1404 // ::= <template-param>
1405 // ::= <substitution>
1406 // <template-template-param> ::= <template-param>
1407 // <substitution>
1408
1409 if (mangleSubstitution(ND))
1410 return;
1411
1412 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001413 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001415 } else {
1416 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1417 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 }
1419
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 addSubstitution(ND);
1421}
1422
1423/// Mangles a template name under the production <type>. Required for
1424/// template template arguments.
1425/// <type> ::= <class-enum-type>
1426/// ::= <template-param>
1427/// ::= <substitution>
1428void CXXNameMangler::mangleType(TemplateName TN) {
1429 if (mangleSubstitution(TN))
1430 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001431
1432 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001433
1434 switch (TN.getKind()) {
1435 case TemplateName::QualifiedTemplate:
1436 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1437 goto HaveDecl;
1438
1439 case TemplateName::Template:
1440 TD = TN.getAsTemplateDecl();
1441 goto HaveDecl;
1442
1443 HaveDecl:
1444 if (isa<TemplateTemplateParmDecl>(TD))
1445 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1446 else
1447 mangleName(TD);
1448 break;
1449
1450 case TemplateName::OverloadedTemplate:
1451 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1452
1453 case TemplateName::DependentTemplate: {
1454 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1455 assert(Dependent->isIdentifier());
1456
1457 // <class-enum-type> ::= <name>
1458 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001459 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 mangleSourceName(Dependent->getIdentifier());
1461 break;
1462 }
1463
1464 case TemplateName::SubstTemplateTemplateParm: {
1465 // Substituted template parameters are mangled as the substituted
1466 // template. This will check for the substitution twice, which is
1467 // fine, but we have to return early so that we don't try to *add*
1468 // the substitution twice.
1469 SubstTemplateTemplateParmStorage *subst
1470 = TN.getAsSubstTemplateTemplateParm();
1471 mangleType(subst->getReplacement());
1472 return;
1473 }
1474
1475 case TemplateName::SubstTemplateTemplateParmPack: {
1476 // FIXME: not clear how to mangle this!
1477 // template <template <class> class T...> class A {
1478 // template <template <class> class U...> void foo(B<T,U> x...);
1479 // };
1480 Out << "_SUBSTPACK_";
1481 break;
1482 }
1483 }
1484
1485 addSubstitution(TN);
1486}
1487
David Majnemerb8014dd2015-02-19 02:16:16 +00001488bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1489 StringRef Prefix) {
1490 // Only certain other types are valid as prefixes; enumerate them.
1491 switch (Ty->getTypeClass()) {
1492 case Type::Builtin:
1493 case Type::Complex:
1494 case Type::Adjusted:
1495 case Type::Decayed:
1496 case Type::Pointer:
1497 case Type::BlockPointer:
1498 case Type::LValueReference:
1499 case Type::RValueReference:
1500 case Type::MemberPointer:
1501 case Type::ConstantArray:
1502 case Type::IncompleteArray:
1503 case Type::VariableArray:
1504 case Type::DependentSizedArray:
1505 case Type::DependentSizedExtVector:
1506 case Type::Vector:
1507 case Type::ExtVector:
1508 case Type::FunctionProto:
1509 case Type::FunctionNoProto:
1510 case Type::Paren:
1511 case Type::Attributed:
1512 case Type::Auto:
1513 case Type::PackExpansion:
1514 case Type::ObjCObject:
1515 case Type::ObjCInterface:
1516 case Type::ObjCObjectPointer:
1517 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001518 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001519 llvm_unreachable("type is illegal as a nested name specifier");
1520
1521 case Type::SubstTemplateTypeParmPack:
1522 // FIXME: not clear how to mangle this!
1523 // template <class T...> class A {
1524 // template <class U...> void foo(decltype(T::foo(U())) x...);
1525 // };
1526 Out << "_SUBSTPACK_";
1527 break;
1528
1529 // <unresolved-type> ::= <template-param>
1530 // ::= <decltype>
1531 // ::= <template-template-param> <template-args>
1532 // (this last is not official yet)
1533 case Type::TypeOfExpr:
1534 case Type::TypeOf:
1535 case Type::Decltype:
1536 case Type::TemplateTypeParm:
1537 case Type::UnaryTransform:
1538 case Type::SubstTemplateTypeParm:
1539 unresolvedType:
1540 // Some callers want a prefix before the mangled type.
1541 Out << Prefix;
1542
1543 // This seems to do everything we want. It's not really
1544 // sanctioned for a substituted template parameter, though.
1545 mangleType(Ty);
1546
1547 // We never want to print 'E' directly after an unresolved-type,
1548 // so we return directly.
1549 return true;
1550
1551 case Type::Typedef:
1552 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1553 break;
1554
1555 case Type::UnresolvedUsing:
1556 mangleSourceName(
1557 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1558 break;
1559
1560 case Type::Enum:
1561 case Type::Record:
1562 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1563 break;
1564
1565 case Type::TemplateSpecialization: {
1566 const TemplateSpecializationType *TST =
1567 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001568 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001569 switch (TN.getKind()) {
1570 case TemplateName::Template:
1571 case TemplateName::QualifiedTemplate: {
1572 TemplateDecl *TD = TN.getAsTemplateDecl();
1573
1574 // If the base is a template template parameter, this is an
1575 // unresolved type.
1576 assert(TD && "no template for template specialization type");
1577 if (isa<TemplateTemplateParmDecl>(TD))
1578 goto unresolvedType;
1579
1580 mangleSourceName(TD->getIdentifier());
1581 break;
David Majnemera88b3592015-02-18 02:28:01 +00001582 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001583
1584 case TemplateName::OverloadedTemplate:
1585 case TemplateName::DependentTemplate:
1586 llvm_unreachable("invalid base for a template specialization type");
1587
1588 case TemplateName::SubstTemplateTemplateParm: {
1589 SubstTemplateTemplateParmStorage *subst =
1590 TN.getAsSubstTemplateTemplateParm();
1591 mangleExistingSubstitution(subst->getReplacement());
1592 break;
1593 }
1594
1595 case TemplateName::SubstTemplateTemplateParmPack: {
1596 // FIXME: not clear how to mangle this!
1597 // template <template <class U> class T...> class A {
1598 // template <class U...> void foo(decltype(T<U>::foo) x...);
1599 // };
1600 Out << "_SUBSTPACK_";
1601 break;
1602 }
1603 }
1604
David Majnemera88b3592015-02-18 02:28:01 +00001605 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001606 break;
David Majnemera88b3592015-02-18 02:28:01 +00001607 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001608
1609 case Type::InjectedClassName:
1610 mangleSourceName(
1611 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1612 break;
1613
1614 case Type::DependentName:
1615 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1616 break;
1617
1618 case Type::DependentTemplateSpecialization: {
1619 const DependentTemplateSpecializationType *DTST =
1620 cast<DependentTemplateSpecializationType>(Ty);
1621 mangleSourceName(DTST->getIdentifier());
1622 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1623 break;
1624 }
1625
1626 case Type::Elaborated:
1627 return mangleUnresolvedTypeOrSimpleId(
1628 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1629 }
1630
1631 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001632}
1633
1634void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1635 switch (Name.getNameKind()) {
1636 case DeclarationName::CXXConstructorName:
1637 case DeclarationName::CXXDestructorName:
1638 case DeclarationName::CXXUsingDirective:
1639 case DeclarationName::Identifier:
1640 case DeclarationName::ObjCMultiArgSelector:
1641 case DeclarationName::ObjCOneArgSelector:
1642 case DeclarationName::ObjCZeroArgSelector:
1643 llvm_unreachable("Not an operator name");
1644
1645 case DeclarationName::CXXConversionFunctionName:
1646 // <operator-name> ::= cv <type> # (cast)
1647 Out << "cv";
1648 mangleType(Name.getCXXNameType());
1649 break;
1650
1651 case DeclarationName::CXXLiteralOperatorName:
1652 Out << "li";
1653 mangleSourceName(Name.getCXXLiteralIdentifier());
1654 return;
1655
1656 case DeclarationName::CXXOperatorName:
1657 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1658 break;
1659 }
1660}
1661
1662
1663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664void
1665CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1666 switch (OO) {
1667 // <operator-name> ::= nw # new
1668 case OO_New: Out << "nw"; break;
1669 // ::= na # new[]
1670 case OO_Array_New: Out << "na"; break;
1671 // ::= dl # delete
1672 case OO_Delete: Out << "dl"; break;
1673 // ::= da # delete[]
1674 case OO_Array_Delete: Out << "da"; break;
1675 // ::= ps # + (unary)
1676 // ::= pl # + (binary or unknown)
1677 case OO_Plus:
1678 Out << (Arity == 1? "ps" : "pl"); break;
1679 // ::= ng # - (unary)
1680 // ::= mi # - (binary or unknown)
1681 case OO_Minus:
1682 Out << (Arity == 1? "ng" : "mi"); break;
1683 // ::= ad # & (unary)
1684 // ::= an # & (binary or unknown)
1685 case OO_Amp:
1686 Out << (Arity == 1? "ad" : "an"); break;
1687 // ::= de # * (unary)
1688 // ::= ml # * (binary or unknown)
1689 case OO_Star:
1690 // Use binary when unknown.
1691 Out << (Arity == 1? "de" : "ml"); break;
1692 // ::= co # ~
1693 case OO_Tilde: Out << "co"; break;
1694 // ::= dv # /
1695 case OO_Slash: Out << "dv"; break;
1696 // ::= rm # %
1697 case OO_Percent: Out << "rm"; break;
1698 // ::= or # |
1699 case OO_Pipe: Out << "or"; break;
1700 // ::= eo # ^
1701 case OO_Caret: Out << "eo"; break;
1702 // ::= aS # =
1703 case OO_Equal: Out << "aS"; break;
1704 // ::= pL # +=
1705 case OO_PlusEqual: Out << "pL"; break;
1706 // ::= mI # -=
1707 case OO_MinusEqual: Out << "mI"; break;
1708 // ::= mL # *=
1709 case OO_StarEqual: Out << "mL"; break;
1710 // ::= dV # /=
1711 case OO_SlashEqual: Out << "dV"; break;
1712 // ::= rM # %=
1713 case OO_PercentEqual: Out << "rM"; break;
1714 // ::= aN # &=
1715 case OO_AmpEqual: Out << "aN"; break;
1716 // ::= oR # |=
1717 case OO_PipeEqual: Out << "oR"; break;
1718 // ::= eO # ^=
1719 case OO_CaretEqual: Out << "eO"; break;
1720 // ::= ls # <<
1721 case OO_LessLess: Out << "ls"; break;
1722 // ::= rs # >>
1723 case OO_GreaterGreater: Out << "rs"; break;
1724 // ::= lS # <<=
1725 case OO_LessLessEqual: Out << "lS"; break;
1726 // ::= rS # >>=
1727 case OO_GreaterGreaterEqual: Out << "rS"; break;
1728 // ::= eq # ==
1729 case OO_EqualEqual: Out << "eq"; break;
1730 // ::= ne # !=
1731 case OO_ExclaimEqual: Out << "ne"; break;
1732 // ::= lt # <
1733 case OO_Less: Out << "lt"; break;
1734 // ::= gt # >
1735 case OO_Greater: Out << "gt"; break;
1736 // ::= le # <=
1737 case OO_LessEqual: Out << "le"; break;
1738 // ::= ge # >=
1739 case OO_GreaterEqual: Out << "ge"; break;
1740 // ::= nt # !
1741 case OO_Exclaim: Out << "nt"; break;
1742 // ::= aa # &&
1743 case OO_AmpAmp: Out << "aa"; break;
1744 // ::= oo # ||
1745 case OO_PipePipe: Out << "oo"; break;
1746 // ::= pp # ++
1747 case OO_PlusPlus: Out << "pp"; break;
1748 // ::= mm # --
1749 case OO_MinusMinus: Out << "mm"; break;
1750 // ::= cm # ,
1751 case OO_Comma: Out << "cm"; break;
1752 // ::= pm # ->*
1753 case OO_ArrowStar: Out << "pm"; break;
1754 // ::= pt # ->
1755 case OO_Arrow: Out << "pt"; break;
1756 // ::= cl # ()
1757 case OO_Call: Out << "cl"; break;
1758 // ::= ix # []
1759 case OO_Subscript: Out << "ix"; break;
1760
1761 // ::= qu # ?
1762 // The conditional operator can't be overloaded, but we still handle it when
1763 // mangling expressions.
1764 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00001765 // Proposal on cxx-abi-dev, 2015-10-21.
1766 // ::= aw # co_await
1767 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001768
1769 case OO_None:
1770 case NUM_OVERLOADED_OPERATORS:
1771 llvm_unreachable("Not an overloaded operator");
1772 }
1773}
1774
1775void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
John McCall07daf722016-03-01 22:18:03 +00001776 // Vendor qualifiers come first.
Guy Benyei11169dd2012-12-18 14:30:41 +00001777
John McCall07daf722016-03-01 22:18:03 +00001778 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001780 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 //
David Tweed31d09b02013-09-13 12:04:22 +00001782 // <type> ::= U <target-addrspace>
1783 // <type> ::= U <OpenCL-addrspace>
1784 // <type> ::= U <CUDA-addrspace>
1785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001787 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001788
1789 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1790 // <target-addrspace> ::= "AS" <address-space-number>
1791 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00001792 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00001793 } else {
1794 switch (AS) {
1795 default: llvm_unreachable("Not a language specific address space");
1796 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1797 case LangAS::opencl_global: ASString = "CLglobal"; break;
1798 case LangAS::opencl_local: ASString = "CLlocal"; break;
1799 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1800 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1801 case LangAS::cuda_device: ASString = "CUdevice"; break;
1802 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1803 case LangAS::cuda_shared: ASString = "CUshared"; break;
1804 }
1805 }
John McCall07daf722016-03-01 22:18:03 +00001806 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 }
John McCall07daf722016-03-01 22:18:03 +00001808
1809 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 switch (Quals.getObjCLifetime()) {
1811 // Objective-C ARC Extension:
1812 //
1813 // <type> ::= U "__strong"
1814 // <type> ::= U "__weak"
1815 // <type> ::= U "__autoreleasing"
1816 case Qualifiers::OCL_None:
1817 break;
1818
1819 case Qualifiers::OCL_Weak:
John McCall07daf722016-03-01 22:18:03 +00001820 mangleVendorQualifier("__weak");
Guy Benyei11169dd2012-12-18 14:30:41 +00001821 break;
1822
1823 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00001824 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 break;
1826
1827 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00001828 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 break;
1830
1831 case Qualifiers::OCL_ExplicitNone:
1832 // The __unsafe_unretained qualifier is *not* mangled, so that
1833 // __unsafe_unretained types in ARC produce the same manglings as the
1834 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1835 // better ABI compatibility.
1836 //
1837 // It's safe to do this because unqualified 'id' won't show up
1838 // in any type signatures that need to be mangled.
1839 break;
1840 }
John McCall07daf722016-03-01 22:18:03 +00001841
1842 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1843 if (Quals.hasRestrict())
1844 Out << 'r';
1845 if (Quals.hasVolatile())
1846 Out << 'V';
1847 if (Quals.hasConst())
1848 Out << 'K';
1849}
1850
1851void CXXNameMangler::mangleVendorQualifier(StringRef name) {
1852 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
1854
1855void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1856 // <ref-qualifier> ::= R # lvalue reference
1857 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 switch (RefQualifier) {
1859 case RQ_None:
1860 break;
1861
1862 case RQ_LValue:
1863 Out << 'R';
1864 break;
1865
1866 case RQ_RValue:
1867 Out << 'O';
1868 break;
1869 }
1870}
1871
1872void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1873 Context.mangleObjCMethodName(MD, Out);
1874}
1875
David Majnemereea02ee2014-11-28 22:22:46 +00001876static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1877 if (Quals)
1878 return true;
1879 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1880 return true;
1881 if (Ty->isOpenCLSpecificType())
1882 return true;
1883 if (Ty->isBuiltinType())
1884 return false;
1885
1886 return true;
1887}
1888
Guy Benyei11169dd2012-12-18 14:30:41 +00001889void CXXNameMangler::mangleType(QualType T) {
1890 // If our type is instantiation-dependent but not dependent, we mangle
1891 // it as it was written in the source, removing any top-level sugar.
1892 // Otherwise, use the canonical type.
1893 //
1894 // FIXME: This is an approximation of the instantiation-dependent name
1895 // mangling rules, since we should really be using the type as written and
1896 // augmented via semantic analysis (i.e., with implicit conversions and
1897 // default template arguments) for any instantiation-dependent type.
1898 // Unfortunately, that requires several changes to our AST:
1899 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1900 // uniqued, so that we can handle substitutions properly
1901 // - Default template arguments will need to be represented in the
1902 // TemplateSpecializationType, since they need to be mangled even though
1903 // they aren't written.
1904 // - Conversions on non-type template arguments need to be expressed, since
1905 // they can affect the mangling of sizeof/alignof.
1906 if (!T->isInstantiationDependentType() || T->isDependentType())
1907 T = T.getCanonicalType();
1908 else {
1909 // Desugar any types that are purely sugar.
1910 do {
1911 // Don't desugar through template specialization types that aren't
1912 // type aliases. We need to mangle the template arguments as written.
1913 if (const TemplateSpecializationType *TST
1914 = dyn_cast<TemplateSpecializationType>(T))
1915 if (!TST->isTypeAlias())
1916 break;
1917
1918 QualType Desugared
1919 = T.getSingleStepDesugaredType(Context.getASTContext());
1920 if (Desugared == T)
1921 break;
1922
1923 T = Desugared;
1924 } while (true);
1925 }
1926 SplitQualType split = T.split();
1927 Qualifiers quals = split.Quals;
1928 const Type *ty = split.Ty;
1929
David Majnemereea02ee2014-11-28 22:22:46 +00001930 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 if (isSubstitutable && mangleSubstitution(T))
1932 return;
1933
1934 // If we're mangling a qualified array type, push the qualifiers to
1935 // the element type.
1936 if (quals && isa<ArrayType>(T)) {
1937 ty = Context.getASTContext().getAsArrayType(T);
1938 quals = Qualifiers();
1939
1940 // Note that we don't update T: we want to add the
1941 // substitution at the original type.
1942 }
1943
1944 if (quals) {
1945 mangleQualifiers(quals);
1946 // Recurse: even if the qualified type isn't yet substitutable,
1947 // the unqualified type might be.
1948 mangleType(QualType(ty, 0));
1949 } else {
1950 switch (ty->getTypeClass()) {
1951#define ABSTRACT_TYPE(CLASS, PARENT)
1952#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1953 case Type::CLASS: \
1954 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1955 return;
1956#define TYPE(CLASS, PARENT) \
1957 case Type::CLASS: \
1958 mangleType(static_cast<const CLASS##Type*>(ty)); \
1959 break;
1960#include "clang/AST/TypeNodes.def"
1961 }
1962 }
1963
1964 // Add the substitution.
1965 if (isSubstitutable)
1966 addSubstitution(T);
1967}
1968
1969void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1970 if (!mangleStandardSubstitution(ND))
1971 mangleName(ND);
1972}
1973
1974void CXXNameMangler::mangleType(const BuiltinType *T) {
1975 // <type> ::= <builtin-type>
1976 // <builtin-type> ::= v # void
1977 // ::= w # wchar_t
1978 // ::= b # bool
1979 // ::= c # char
1980 // ::= a # signed char
1981 // ::= h # unsigned char
1982 // ::= s # short
1983 // ::= t # unsigned short
1984 // ::= i # int
1985 // ::= j # unsigned int
1986 // ::= l # long
1987 // ::= m # unsigned long
1988 // ::= x # long long, __int64
1989 // ::= y # unsigned long long, __int64
1990 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001991 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 // ::= f # float
1993 // ::= d # double
1994 // ::= e # long double, __float80
1995 // UNSUPPORTED: ::= g # __float128
1996 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1997 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1998 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1999 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2000 // ::= Di # char32_t
2001 // ::= Ds # char16_t
2002 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2003 // ::= u <source-name> # vendor extended type
2004 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002005 case BuiltinType::Void:
2006 Out << 'v';
2007 break;
2008 case BuiltinType::Bool:
2009 Out << 'b';
2010 break;
2011 case BuiltinType::Char_U:
2012 case BuiltinType::Char_S:
2013 Out << 'c';
2014 break;
2015 case BuiltinType::UChar:
2016 Out << 'h';
2017 break;
2018 case BuiltinType::UShort:
2019 Out << 't';
2020 break;
2021 case BuiltinType::UInt:
2022 Out << 'j';
2023 break;
2024 case BuiltinType::ULong:
2025 Out << 'm';
2026 break;
2027 case BuiltinType::ULongLong:
2028 Out << 'y';
2029 break;
2030 case BuiltinType::UInt128:
2031 Out << 'o';
2032 break;
2033 case BuiltinType::SChar:
2034 Out << 'a';
2035 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002036 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002037 case BuiltinType::WChar_U:
2038 Out << 'w';
2039 break;
2040 case BuiltinType::Char16:
2041 Out << "Ds";
2042 break;
2043 case BuiltinType::Char32:
2044 Out << "Di";
2045 break;
2046 case BuiltinType::Short:
2047 Out << 's';
2048 break;
2049 case BuiltinType::Int:
2050 Out << 'i';
2051 break;
2052 case BuiltinType::Long:
2053 Out << 'l';
2054 break;
2055 case BuiltinType::LongLong:
2056 Out << 'x';
2057 break;
2058 case BuiltinType::Int128:
2059 Out << 'n';
2060 break;
2061 case BuiltinType::Half:
2062 Out << "Dh";
2063 break;
2064 case BuiltinType::Float:
2065 Out << 'f';
2066 break;
2067 case BuiltinType::Double:
2068 Out << 'd';
2069 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002070 case BuiltinType::LongDouble:
2071 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2072 ? 'g'
2073 : 'e');
2074 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002075 case BuiltinType::NullPtr:
2076 Out << "Dn";
2077 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002078
2079#define BUILTIN_TYPE(Id, SingletonId)
2080#define PLACEHOLDER_TYPE(Id, SingletonId) \
2081 case BuiltinType::Id:
2082#include "clang/AST/BuiltinTypes.def"
2083 case BuiltinType::Dependent:
2084 llvm_unreachable("mangling a placeholder type");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002085 case BuiltinType::ObjCId:
2086 Out << "11objc_object";
2087 break;
2088 case BuiltinType::ObjCClass:
2089 Out << "10objc_class";
2090 break;
2091 case BuiltinType::ObjCSel:
2092 Out << "13objc_selector";
2093 break;
2094 case BuiltinType::OCLImage1d:
2095 Out << "11ocl_image1d";
2096 break;
2097 case BuiltinType::OCLImage1dArray:
2098 Out << "16ocl_image1darray";
2099 break;
2100 case BuiltinType::OCLImage1dBuffer:
2101 Out << "17ocl_image1dbuffer";
2102 break;
2103 case BuiltinType::OCLImage2d:
2104 Out << "11ocl_image2d";
2105 break;
2106 case BuiltinType::OCLImage2dArray:
2107 Out << "16ocl_image2darray";
2108 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002109 case BuiltinType::OCLImage2dDepth:
2110 Out << "16ocl_image2ddepth";
2111 break;
2112 case BuiltinType::OCLImage2dArrayDepth:
2113 Out << "21ocl_image2darraydepth";
2114 break;
2115 case BuiltinType::OCLImage2dMSAA:
2116 Out << "15ocl_image2dmsaa";
2117 break;
2118 case BuiltinType::OCLImage2dArrayMSAA:
2119 Out << "20ocl_image2darraymsaa";
2120 break;
2121 case BuiltinType::OCLImage2dMSAADepth:
2122 Out << "20ocl_image2dmsaadepth";
2123 break;
2124 case BuiltinType::OCLImage2dArrayMSAADepth:
Richard Smith8467c872016-02-03 01:43:59 +00002125 Out << "25ocl_image2darraymsaadepth";
Alexey Bader9c8453f2015-09-15 11:18:52 +00002126 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002127 case BuiltinType::OCLImage3d:
2128 Out << "11ocl_image3d";
2129 break;
2130 case BuiltinType::OCLSampler:
2131 Out << "11ocl_sampler";
2132 break;
2133 case BuiltinType::OCLEvent:
2134 Out << "9ocl_event";
2135 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002136 case BuiltinType::OCLClkEvent:
2137 Out << "12ocl_clkevent";
2138 break;
2139 case BuiltinType::OCLQueue:
2140 Out << "9ocl_queue";
2141 break;
2142 case BuiltinType::OCLNDRange:
2143 Out << "11ocl_ndrange";
2144 break;
2145 case BuiltinType::OCLReserveID:
2146 Out << "13ocl_reserveid";
2147 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 }
2149}
2150
John McCall07daf722016-03-01 22:18:03 +00002151StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2152 switch (CC) {
2153 case CC_C:
2154 return "";
2155
2156 case CC_X86StdCall:
2157 case CC_X86FastCall:
2158 case CC_X86ThisCall:
2159 case CC_X86VectorCall:
2160 case CC_X86Pascal:
2161 case CC_X86_64Win64:
2162 case CC_X86_64SysV:
2163 case CC_AAPCS:
2164 case CC_AAPCS_VFP:
2165 case CC_IntelOclBicc:
2166 case CC_SpirFunction:
2167 case CC_SpirKernel:
2168 // FIXME: we should be mangling all of the above.
2169 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002170
2171 case CC_Swift:
2172 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002173 }
2174 llvm_unreachable("bad calling convention");
2175}
2176
2177void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2178 // Fast path.
2179 if (T->getExtInfo() == FunctionType::ExtInfo())
2180 return;
2181
2182 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2183 // This will get more complicated in the future if we mangle other
2184 // things here; but for now, since we mangle ns_returns_retained as
2185 // a qualifier on the result type, we can get away with this:
2186 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2187 if (!CCQualifier.empty())
2188 mangleVendorQualifier(CCQualifier);
2189
2190 // FIXME: regparm
2191 // FIXME: noreturn
2192}
2193
2194void
2195CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2196 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2197
2198 // Note that these are *not* substitution candidates. Demanglers might
2199 // have trouble with this if the parameter type is fully substituted.
2200
John McCall477f2bb2016-03-03 06:39:32 +00002201 switch (PI.getABI()) {
2202 case ParameterABI::Ordinary:
2203 break;
2204
2205 // All of these start with "swift", so they come before "ns_consumed".
2206 case ParameterABI::SwiftContext:
2207 case ParameterABI::SwiftErrorResult:
2208 case ParameterABI::SwiftIndirectResult:
2209 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2210 break;
2211 }
2212
John McCall07daf722016-03-01 22:18:03 +00002213 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002214 mangleVendorQualifier("ns_consumed");
John McCall07daf722016-03-01 22:18:03 +00002215}
2216
Guy Benyei11169dd2012-12-18 14:30:41 +00002217// <type> ::= <function-type>
2218// <function-type> ::= [<CV-qualifiers>] F [Y]
2219// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002220void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002221 mangleExtFunctionInfo(T);
2222
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2224 // e.g. "const" in "int (A::*)() const".
2225 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2226
2227 Out << 'F';
2228
2229 // FIXME: We don't have enough information in the AST to produce the 'Y'
2230 // encoding for extern "C" function types.
2231 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2232
2233 // Mangle the ref-qualifier, if present.
2234 mangleRefQualifier(T->getRefQualifier());
2235
2236 Out << 'E';
2237}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002238
Guy Benyei11169dd2012-12-18 14:30:41 +00002239void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002240 // Function types without prototypes can arise when mangling a function type
2241 // within an overloadable function in C. We mangle these as the absence of any
2242 // parameter types (not even an empty parameter list).
2243 Out << 'F';
2244
2245 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2246
2247 FunctionTypeDepth.enterResultType();
2248 mangleType(T->getReturnType());
2249 FunctionTypeDepth.leaveResultType();
2250
2251 FunctionTypeDepth.pop(saved);
2252 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002253}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002254
John McCall07daf722016-03-01 22:18:03 +00002255void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002256 bool MangleReturnType,
2257 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 // Record that we're in a function type. See mangleFunctionParam
2259 // for details on what we're trying to achieve here.
2260 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2261
2262 // <bare-function-type> ::= <signature type>+
2263 if (MangleReturnType) {
2264 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002265
2266 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2267 if (Proto->getExtInfo().getProducesResult())
2268 mangleVendorQualifier("ns_returns_retained");
2269
2270 // Mangle the return type without any direct ARC ownership qualifiers.
2271 QualType ReturnTy = Proto->getReturnType();
2272 if (ReturnTy.getObjCLifetime()) {
2273 auto SplitReturnTy = ReturnTy.split();
2274 SplitReturnTy.Quals.removeObjCLifetime();
2275 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2276 }
2277 mangleType(ReturnTy);
2278
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 FunctionTypeDepth.leaveResultType();
2280 }
2281
Alp Toker9cacbab2014-01-20 20:26:09 +00002282 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 // <builtin-type> ::= v # void
2284 Out << 'v';
2285
2286 FunctionTypeDepth.pop(saved);
2287 return;
2288 }
2289
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002290 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2291 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002292 // Mangle extended parameter info as order-sensitive qualifiers here.
2293 if (Proto->hasExtParameterInfos()) {
2294 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2295 }
2296
2297 // Mangle the type.
2298 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002299 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2300
2301 if (FD) {
2302 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2303 // Attr can only take 1 character, so we can hardcode the length below.
2304 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2305 Out << "U17pass_object_size" << Attr->getType();
2306 }
2307 }
2308 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002309
2310 FunctionTypeDepth.pop(saved);
2311
2312 // <builtin-type> ::= z # ellipsis
2313 if (Proto->isVariadic())
2314 Out << 'z';
2315}
2316
2317// <type> ::= <class-enum-type>
2318// <class-enum-type> ::= <name>
2319void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2320 mangleName(T->getDecl());
2321}
2322
2323// <type> ::= <class-enum-type>
2324// <class-enum-type> ::= <name>
2325void CXXNameMangler::mangleType(const EnumType *T) {
2326 mangleType(static_cast<const TagType*>(T));
2327}
2328void CXXNameMangler::mangleType(const RecordType *T) {
2329 mangleType(static_cast<const TagType*>(T));
2330}
2331void CXXNameMangler::mangleType(const TagType *T) {
2332 mangleName(T->getDecl());
2333}
2334
2335// <type> ::= <array-type>
2336// <array-type> ::= A <positive dimension number> _ <element type>
2337// ::= A [<dimension expression>] _ <element type>
2338void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2339 Out << 'A' << T->getSize() << '_';
2340 mangleType(T->getElementType());
2341}
2342void CXXNameMangler::mangleType(const VariableArrayType *T) {
2343 Out << 'A';
2344 // decayed vla types (size 0) will just be skipped.
2345 if (T->getSizeExpr())
2346 mangleExpression(T->getSizeExpr());
2347 Out << '_';
2348 mangleType(T->getElementType());
2349}
2350void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2351 Out << 'A';
2352 mangleExpression(T->getSizeExpr());
2353 Out << '_';
2354 mangleType(T->getElementType());
2355}
2356void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2357 Out << "A_";
2358 mangleType(T->getElementType());
2359}
2360
2361// <type> ::= <pointer-to-member-type>
2362// <pointer-to-member-type> ::= M <class type> <member type>
2363void CXXNameMangler::mangleType(const MemberPointerType *T) {
2364 Out << 'M';
2365 mangleType(QualType(T->getClass(), 0));
2366 QualType PointeeType = T->getPointeeType();
2367 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2368 mangleType(FPT);
2369
2370 // Itanium C++ ABI 5.1.8:
2371 //
2372 // The type of a non-static member function is considered to be different,
2373 // for the purposes of substitution, from the type of a namespace-scope or
2374 // static member function whose type appears similar. The types of two
2375 // non-static member functions are considered to be different, for the
2376 // purposes of substitution, if the functions are members of different
2377 // classes. In other words, for the purposes of substitution, the class of
2378 // which the function is a member is considered part of the type of
2379 // function.
2380
2381 // Given that we already substitute member function pointers as a
2382 // whole, the net effect of this rule is just to unconditionally
2383 // suppress substitution on the function type in a member pointer.
2384 // We increment the SeqID here to emulate adding an entry to the
2385 // substitution table.
2386 ++SeqID;
2387 } else
2388 mangleType(PointeeType);
2389}
2390
2391// <type> ::= <template-param>
2392void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2393 mangleTemplateParameter(T->getIndex());
2394}
2395
2396// <type> ::= <template-param>
2397void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2398 // FIXME: not clear how to mangle this!
2399 // template <class T...> class A {
2400 // template <class U...> void foo(T(*)(U) x...);
2401 // };
2402 Out << "_SUBSTPACK_";
2403}
2404
2405// <type> ::= P <type> # pointer-to
2406void CXXNameMangler::mangleType(const PointerType *T) {
2407 Out << 'P';
2408 mangleType(T->getPointeeType());
2409}
2410void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2411 Out << 'P';
2412 mangleType(T->getPointeeType());
2413}
2414
2415// <type> ::= R <type> # reference-to
2416void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2417 Out << 'R';
2418 mangleType(T->getPointeeType());
2419}
2420
2421// <type> ::= O <type> # rvalue reference-to (C++0x)
2422void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2423 Out << 'O';
2424 mangleType(T->getPointeeType());
2425}
2426
2427// <type> ::= C <type> # complex pair (C 2000)
2428void CXXNameMangler::mangleType(const ComplexType *T) {
2429 Out << 'C';
2430 mangleType(T->getElementType());
2431}
2432
2433// ARM's ABI for Neon vector types specifies that they should be mangled as
2434// if they are structs (to match ARM's initial implementation). The
2435// vector type must be one of the special types predefined by ARM.
2436void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2437 QualType EltType = T->getElementType();
2438 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002439 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2441 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002442 case BuiltinType::SChar:
2443 case BuiltinType::UChar:
2444 EltName = "poly8_t";
2445 break;
2446 case BuiltinType::Short:
2447 case BuiltinType::UShort:
2448 EltName = "poly16_t";
2449 break;
2450 case BuiltinType::ULongLong:
2451 EltName = "poly64_t";
2452 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2454 }
2455 } else {
2456 switch (cast<BuiltinType>(EltType)->getKind()) {
2457 case BuiltinType::SChar: EltName = "int8_t"; break;
2458 case BuiltinType::UChar: EltName = "uint8_t"; break;
2459 case BuiltinType::Short: EltName = "int16_t"; break;
2460 case BuiltinType::UShort: EltName = "uint16_t"; break;
2461 case BuiltinType::Int: EltName = "int32_t"; break;
2462 case BuiltinType::UInt: EltName = "uint32_t"; break;
2463 case BuiltinType::LongLong: EltName = "int64_t"; break;
2464 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002465 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002467 case BuiltinType::Half: EltName = "float16_t";break;
2468 default:
2469 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 }
2471 }
Craig Topper36250ad2014-05-12 05:36:57 +00002472 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 unsigned BitSize = (T->getNumElements() *
2474 getASTContext().getTypeSize(EltType));
2475 if (BitSize == 64)
2476 BaseName = "__simd64_";
2477 else {
2478 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2479 BaseName = "__simd128_";
2480 }
2481 Out << strlen(BaseName) + strlen(EltName);
2482 Out << BaseName << EltName;
2483}
2484
Tim Northover2fe823a2013-08-01 09:23:19 +00002485static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2486 switch (EltType->getKind()) {
2487 case BuiltinType::SChar:
2488 return "Int8";
2489 case BuiltinType::Short:
2490 return "Int16";
2491 case BuiltinType::Int:
2492 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002493 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002494 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002495 return "Int64";
2496 case BuiltinType::UChar:
2497 return "Uint8";
2498 case BuiltinType::UShort:
2499 return "Uint16";
2500 case BuiltinType::UInt:
2501 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002502 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002503 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002504 return "Uint64";
2505 case BuiltinType::Half:
2506 return "Float16";
2507 case BuiltinType::Float:
2508 return "Float32";
2509 case BuiltinType::Double:
2510 return "Float64";
2511 default:
2512 llvm_unreachable("Unexpected vector element base type");
2513 }
2514}
2515
2516// AArch64's ABI for Neon vector types specifies that they should be mangled as
2517// the equivalent internal name. The vector type must be one of the special
2518// types predefined by ARM.
2519void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2520 QualType EltType = T->getElementType();
2521 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2522 unsigned BitSize =
2523 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002524 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002525
2526 assert((BitSize == 64 || BitSize == 128) &&
2527 "Neon vector type not 64 or 128 bits");
2528
Tim Northover2fe823a2013-08-01 09:23:19 +00002529 StringRef EltName;
2530 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2531 switch (cast<BuiltinType>(EltType)->getKind()) {
2532 case BuiltinType::UChar:
2533 EltName = "Poly8";
2534 break;
2535 case BuiltinType::UShort:
2536 EltName = "Poly16";
2537 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002538 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002539 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002540 EltName = "Poly64";
2541 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002542 default:
2543 llvm_unreachable("unexpected Neon polynomial vector element type");
2544 }
2545 } else
2546 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2547
2548 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00002549 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00002550 Out << TypeName.length() << TypeName;
2551}
2552
Guy Benyei11169dd2012-12-18 14:30:41 +00002553// GNU extension: vector types
2554// <type> ::= <vector-type>
2555// <vector-type> ::= Dv <positive dimension number> _
2556// <extended element type>
2557// ::= Dv [<dimension expression>] _ <element type>
2558// <extended element type> ::= <element type>
2559// ::= p # AltiVec vector pixel
2560// ::= b # Altivec vector bool
2561void CXXNameMangler::mangleType(const VectorType *T) {
2562 if ((T->getVectorKind() == VectorType::NeonVector ||
2563 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002564 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002565 llvm::Triple::ArchType Arch =
2566 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002567 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002568 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002569 mangleAArch64NeonVectorType(T);
2570 else
2571 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 return;
2573 }
2574 Out << "Dv" << T->getNumElements() << '_';
2575 if (T->getVectorKind() == VectorType::AltiVecPixel)
2576 Out << 'p';
2577 else if (T->getVectorKind() == VectorType::AltiVecBool)
2578 Out << 'b';
2579 else
2580 mangleType(T->getElementType());
2581}
2582void CXXNameMangler::mangleType(const ExtVectorType *T) {
2583 mangleType(static_cast<const VectorType*>(T));
2584}
2585void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2586 Out << "Dv";
2587 mangleExpression(T->getSizeExpr());
2588 Out << '_';
2589 mangleType(T->getElementType());
2590}
2591
2592void CXXNameMangler::mangleType(const PackExpansionType *T) {
2593 // <type> ::= Dp <type> # pack expansion (C++0x)
2594 Out << "Dp";
2595 mangleType(T->getPattern());
2596}
2597
2598void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2599 mangleSourceName(T->getDecl()->getIdentifier());
2600}
2601
2602void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002603 // Treat __kindof as a vendor extended type qualifier.
2604 if (T->isKindOfType())
2605 Out << "U8__kindof";
2606
Eli Friedman5f508952013-06-18 22:41:37 +00002607 if (!T->qual_empty()) {
2608 // Mangle protocol qualifiers.
2609 SmallString<64> QualStr;
2610 llvm::raw_svector_ostream QualOS(QualStr);
2611 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002612 for (const auto *I : T->quals()) {
2613 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002614 QualOS << name.size() << name;
2615 }
Eli Friedman5f508952013-06-18 22:41:37 +00002616 Out << 'U' << QualStr.size() << QualStr;
2617 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002620
2621 if (T->isSpecialized()) {
2622 // Mangle type arguments as I <type>+ E
2623 Out << 'I';
2624 for (auto typeArg : T->getTypeArgs())
2625 mangleType(typeArg);
2626 Out << 'E';
2627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002628}
2629
2630void CXXNameMangler::mangleType(const BlockPointerType *T) {
2631 Out << "U13block_pointer";
2632 mangleType(T->getPointeeType());
2633}
2634
2635void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2636 // Mangle injected class name types as if the user had written the
2637 // specialization out fully. It may not actually be possible to see
2638 // this mangling, though.
2639 mangleType(T->getInjectedSpecializationType());
2640}
2641
2642void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2643 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2644 mangleName(TD, T->getArgs(), T->getNumArgs());
2645 } else {
2646 if (mangleSubstitution(QualType(T, 0)))
2647 return;
2648
2649 mangleTemplatePrefix(T->getTemplateName());
2650
2651 // FIXME: GCC does not appear to mangle the template arguments when
2652 // the template in question is a dependent template name. Should we
2653 // emulate that badness?
2654 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2655 addSubstitution(QualType(T, 0));
2656 }
2657}
2658
2659void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002660 // Proposal by cxx-abi-dev, 2014-03-26
2661 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2662 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002663 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002664 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002665 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002666 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002667 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002668 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002669 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002670 switch (T->getKeyword()) {
2671 case ETK_Typename:
2672 break;
2673 case ETK_Struct:
2674 case ETK_Class:
2675 case ETK_Interface:
2676 Out << "Ts";
2677 break;
2678 case ETK_Union:
2679 Out << "Tu";
2680 break;
2681 case ETK_Enum:
2682 Out << "Te";
2683 break;
2684 default:
2685 llvm_unreachable("unexpected keyword for dependent type name");
2686 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002687 // Typename types are always nested
2688 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002690 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 Out << 'E';
2692}
2693
2694void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2695 // Dependently-scoped template types are nested if they have a prefix.
2696 Out << 'N';
2697
2698 // TODO: avoid making this TemplateName.
2699 TemplateName Prefix =
2700 getASTContext().getDependentTemplateName(T->getQualifier(),
2701 T->getIdentifier());
2702 mangleTemplatePrefix(Prefix);
2703
2704 // FIXME: GCC does not appear to mangle the template arguments when
2705 // the template in question is a dependent template name. Should we
2706 // emulate that badness?
2707 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2708 Out << 'E';
2709}
2710
2711void CXXNameMangler::mangleType(const TypeOfType *T) {
2712 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2713 // "extension with parameters" mangling.
2714 Out << "u6typeof";
2715}
2716
2717void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2718 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2719 // "extension with parameters" mangling.
2720 Out << "u6typeof";
2721}
2722
2723void CXXNameMangler::mangleType(const DecltypeType *T) {
2724 Expr *E = T->getUnderlyingExpr();
2725
2726 // type ::= Dt <expression> E # decltype of an id-expression
2727 // # or class member access
2728 // ::= DT <expression> E # decltype of an expression
2729
2730 // This purports to be an exhaustive list of id-expressions and
2731 // class member accesses. Note that we do not ignore parentheses;
2732 // parentheses change the semantics of decltype for these
2733 // expressions (and cause the mangler to use the other form).
2734 if (isa<DeclRefExpr>(E) ||
2735 isa<MemberExpr>(E) ||
2736 isa<UnresolvedLookupExpr>(E) ||
2737 isa<DependentScopeDeclRefExpr>(E) ||
2738 isa<CXXDependentScopeMemberExpr>(E) ||
2739 isa<UnresolvedMemberExpr>(E))
2740 Out << "Dt";
2741 else
2742 Out << "DT";
2743 mangleExpression(E);
2744 Out << 'E';
2745}
2746
2747void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2748 // If this is dependent, we need to record that. If not, we simply
2749 // mangle it as the underlying type since they are equivalent.
2750 if (T->isDependentType()) {
2751 Out << 'U';
2752
2753 switch (T->getUTTKind()) {
2754 case UnaryTransformType::EnumUnderlyingType:
2755 Out << "3eut";
2756 break;
2757 }
2758 }
2759
2760 mangleType(T->getUnderlyingType());
2761}
2762
2763void CXXNameMangler::mangleType(const AutoType *T) {
2764 QualType D = T->getDeducedType();
2765 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00002766 if (D.isNull()) {
2767 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2768 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00002769 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00002770 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 mangleType(D);
2772}
2773
2774void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002775 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 // (Until there's a standardized mangling...)
2777 Out << "U7_Atomic";
2778 mangleType(T->getValueType());
2779}
2780
Xiuli Pan9c14e282016-01-09 12:53:17 +00002781void CXXNameMangler::mangleType(const PipeType *T) {
2782 // Pipe type mangling rules are described in SPIR 2.0 specification
2783 // A.1 Data types and A.3 Summary of changes
2784 // <type> ::= 8ocl_pipe
2785 Out << "8ocl_pipe";
2786}
2787
Guy Benyei11169dd2012-12-18 14:30:41 +00002788void CXXNameMangler::mangleIntegerLiteral(QualType T,
2789 const llvm::APSInt &Value) {
2790 // <expr-primary> ::= L <type> <value number> E # integer literal
2791 Out << 'L';
2792
2793 mangleType(T);
2794 if (T->isBooleanType()) {
2795 // Boolean values are encoded as 0/1.
2796 Out << (Value.getBoolValue() ? '1' : '0');
2797 } else {
2798 mangleNumber(Value);
2799 }
2800 Out << 'E';
2801
2802}
2803
David Majnemer1dabfdc2015-02-14 13:23:54 +00002804void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2805 // Ignore member expressions involving anonymous unions.
2806 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2807 if (!RT->getDecl()->isAnonymousStructOrUnion())
2808 break;
2809 const auto *ME = dyn_cast<MemberExpr>(Base);
2810 if (!ME)
2811 break;
2812 Base = ME->getBase();
2813 IsArrow = ME->isArrow();
2814 }
2815
2816 if (Base->isImplicitCXXThis()) {
2817 // Note: GCC mangles member expressions to the implicit 'this' as
2818 // *this., whereas we represent them as this->. The Itanium C++ ABI
2819 // does not specify anything here, so we follow GCC.
2820 Out << "dtdefpT";
2821 } else {
2822 Out << (IsArrow ? "pt" : "dt");
2823 mangleExpression(Base);
2824 }
2825}
2826
Guy Benyei11169dd2012-12-18 14:30:41 +00002827/// Mangles a member expression.
2828void CXXNameMangler::mangleMemberExpr(const Expr *base,
2829 bool isArrow,
2830 NestedNameSpecifier *qualifier,
2831 NamedDecl *firstQualifierLookup,
2832 DeclarationName member,
2833 unsigned arity) {
2834 // <expression> ::= dt <expression> <unresolved-name>
2835 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002836 if (base)
2837 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002838 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002839}
2840
2841/// Look at the callee of the given call expression and determine if
2842/// it's a parenthesized id-expression which would have triggered ADL
2843/// otherwise.
2844static bool isParenthesizedADLCallee(const CallExpr *call) {
2845 const Expr *callee = call->getCallee();
2846 const Expr *fn = callee->IgnoreParens();
2847
2848 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2849 // too, but for those to appear in the callee, it would have to be
2850 // parenthesized.
2851 if (callee == fn) return false;
2852
2853 // Must be an unresolved lookup.
2854 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2855 if (!lookup) return false;
2856
2857 assert(!lookup->requiresADL());
2858
2859 // Must be an unqualified lookup.
2860 if (lookup->getQualifier()) return false;
2861
2862 // Must not have found a class member. Note that if one is a class
2863 // member, they're all class members.
2864 if (lookup->getNumDecls() > 0 &&
2865 (*lookup->decls_begin())->isCXXClassMember())
2866 return false;
2867
2868 // Otherwise, ADL would have been triggered.
2869 return true;
2870}
2871
David Majnemer9c775c72014-09-23 04:27:55 +00002872void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2873 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2874 Out << CastEncoding;
2875 mangleType(ECE->getType());
2876 mangleExpression(ECE->getSubExpr());
2877}
2878
Richard Smith520449d2015-02-05 06:15:50 +00002879void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2880 if (auto *Syntactic = InitList->getSyntacticForm())
2881 InitList = Syntactic;
2882 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2883 mangleExpression(InitList->getInit(i));
2884}
2885
Guy Benyei11169dd2012-12-18 14:30:41 +00002886void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2887 // <expression> ::= <unary operator-name> <expression>
2888 // ::= <binary operator-name> <expression> <expression>
2889 // ::= <trinary operator-name> <expression> <expression> <expression>
2890 // ::= cv <type> expression # conversion with one argument
2891 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002892 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2893 // ::= sc <type> <expression> # static_cast<type> (expression)
2894 // ::= cc <type> <expression> # const_cast<type> (expression)
2895 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 // ::= st <type> # sizeof (a type)
2897 // ::= at <type> # alignof (a type)
2898 // ::= <template-param>
2899 // ::= <function-param>
2900 // ::= sr <type> <unqualified-name> # dependent name
2901 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2902 // ::= ds <expression> <expression> # expr.*expr
2903 // ::= sZ <template-param> # size of a parameter pack
2904 // ::= sZ <function-param> # size of a function parameter pack
2905 // ::= <expr-primary>
2906 // <expr-primary> ::= L <type> <value number> E # integer literal
2907 // ::= L <type <value float> E # floating literal
2908 // ::= L <mangled-name> E # external name
2909 // ::= fpT # 'this' expression
2910 QualType ImplicitlyConvertedToType;
2911
2912recurse:
2913 switch (E->getStmtClass()) {
2914 case Expr::NoStmtClass:
2915#define ABSTRACT_STMT(Type)
2916#define EXPR(Type, Base)
2917#define STMT(Type, Base) \
2918 case Expr::Type##Class:
2919#include "clang/AST/StmtNodes.inc"
2920 // fallthrough
2921
2922 // These all can only appear in local or variable-initialization
2923 // contexts and so should never appear in a mangling.
2924 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002925 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002927 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 case Expr::ParenListExprClass:
2929 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002930 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002931 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002932 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002933 case Expr::OMPArraySectionExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 llvm_unreachable("unexpected statement kind");
2935
2936 // FIXME: invent manglings for all these.
2937 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 case Expr::ChooseExprClass:
2939 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002940 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 case Expr::ExtVectorElementExprClass:
2942 case Expr::GenericSelectionExprClass:
2943 case Expr::ObjCEncodeExprClass:
2944 case Expr::ObjCIsaExprClass:
2945 case Expr::ObjCIvarRefExprClass:
2946 case Expr::ObjCMessageExprClass:
2947 case Expr::ObjCPropertyRefExprClass:
2948 case Expr::ObjCProtocolExprClass:
2949 case Expr::ObjCSelectorExprClass:
2950 case Expr::ObjCStringLiteralClass:
2951 case Expr::ObjCBoxedExprClass:
2952 case Expr::ObjCArrayLiteralClass:
2953 case Expr::ObjCDictionaryLiteralClass:
2954 case Expr::ObjCSubscriptRefExprClass:
2955 case Expr::ObjCIndirectCopyRestoreExprClass:
2956 case Expr::OffsetOfExprClass:
2957 case Expr::PredefinedExprClass:
2958 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002959 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 case Expr::TypeTraitExprClass:
2962 case Expr::ArrayTypeTraitExprClass:
2963 case Expr::ExpressionTraitExprClass:
2964 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 case Expr::CUDAKernelCallExprClass:
2966 case Expr::AsTypeExprClass:
2967 case Expr::PseudoObjectExprClass:
2968 case Expr::AtomicExprClass:
2969 {
2970 // As bad as this diagnostic is, it's better than crashing.
2971 DiagnosticsEngine &Diags = Context.getDiags();
2972 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2973 "cannot yet mangle expression type %0");
2974 Diags.Report(E->getExprLoc(), DiagID)
2975 << E->getStmtClassName() << E->getSourceRange();
2976 break;
2977 }
2978
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002979 case Expr::CXXUuidofExprClass: {
2980 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2981 if (UE->isTypeOperand()) {
2982 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2983 Out << "u8__uuidoft";
2984 mangleType(UuidT);
2985 } else {
2986 Expr *UuidExp = UE->getExprOperand();
2987 Out << "u8__uuidofz";
2988 mangleExpression(UuidExp, Arity);
2989 }
2990 break;
2991 }
2992
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 // Even gcc-4.5 doesn't mangle this.
2994 case Expr::BinaryConditionalOperatorClass: {
2995 DiagnosticsEngine &Diags = Context.getDiags();
2996 unsigned DiagID =
2997 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2998 "?: operator with omitted middle operand cannot be mangled");
2999 Diags.Report(E->getExprLoc(), DiagID)
3000 << E->getStmtClassName() << E->getSourceRange();
3001 break;
3002 }
3003
3004 // These are used for internal purposes and cannot be meaningfully mangled.
3005 case Expr::OpaqueValueExprClass:
3006 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3007
3008 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003010 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 Out << "E";
3012 break;
3013 }
3014
3015 case Expr::CXXDefaultArgExprClass:
3016 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3017 break;
3018
Richard Smith852c9db2013-04-20 22:23:05 +00003019 case Expr::CXXDefaultInitExprClass:
3020 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3021 break;
3022
Richard Smithcc1b96d2013-06-12 22:31:48 +00003023 case Expr::CXXStdInitializerListExprClass:
3024 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3025 break;
3026
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 case Expr::SubstNonTypeTemplateParmExprClass:
3028 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3029 Arity);
3030 break;
3031
3032 case Expr::UserDefinedLiteralClass:
3033 // We follow g++'s approach of mangling a UDL as a call to the literal
3034 // operator.
3035 case Expr::CXXMemberCallExprClass: // fallthrough
3036 case Expr::CallExprClass: {
3037 const CallExpr *CE = cast<CallExpr>(E);
3038
3039 // <expression> ::= cp <simple-id> <expression>* E
3040 // We use this mangling only when the call would use ADL except
3041 // for being parenthesized. Per discussion with David
3042 // Vandervoorde, 2011.04.25.
3043 if (isParenthesizedADLCallee(CE)) {
3044 Out << "cp";
3045 // The callee here is a parenthesized UnresolvedLookupExpr with
3046 // no qualifier and should always get mangled as a <simple-id>
3047 // anyway.
3048
3049 // <expression> ::= cl <expression>* E
3050 } else {
3051 Out << "cl";
3052 }
3053
David Majnemer67a8ec62015-02-19 21:41:48 +00003054 unsigned CallArity = CE->getNumArgs();
3055 for (const Expr *Arg : CE->arguments())
3056 if (isa<PackExpansionExpr>(Arg))
3057 CallArity = UnknownArity;
3058
3059 mangleExpression(CE->getCallee(), CallArity);
3060 for (const Expr *Arg : CE->arguments())
3061 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 Out << 'E';
3063 break;
3064 }
3065
3066 case Expr::CXXNewExprClass: {
3067 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3068 if (New->isGlobalNew()) Out << "gs";
3069 Out << (New->isArray() ? "na" : "nw");
3070 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3071 E = New->placement_arg_end(); I != E; ++I)
3072 mangleExpression(*I);
3073 Out << '_';
3074 mangleType(New->getAllocatedType());
3075 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3077 Out << "il";
3078 else
3079 Out << "pi";
3080 const Expr *Init = New->getInitializer();
3081 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3082 // Directly inline the initializers.
3083 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3084 E = CCE->arg_end();
3085 I != E; ++I)
3086 mangleExpression(*I);
3087 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3088 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3089 mangleExpression(PLE->getExpr(i));
3090 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3091 isa<InitListExpr>(Init)) {
3092 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003093 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 } else
3095 mangleExpression(Init);
3096 }
3097 Out << 'E';
3098 break;
3099 }
3100
David Majnemer1dabfdc2015-02-14 13:23:54 +00003101 case Expr::CXXPseudoDestructorExprClass: {
3102 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3103 if (const Expr *Base = PDE->getBase())
3104 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003105 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3106 QualType ScopeType;
3107 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3108 if (Qualifier) {
3109 mangleUnresolvedPrefix(Qualifier,
3110 /*Recursive=*/true);
3111 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3112 Out << 'E';
3113 } else {
3114 Out << "sr";
3115 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3116 Out << 'E';
3117 }
3118 } else if (Qualifier) {
3119 mangleUnresolvedPrefix(Qualifier);
3120 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003121 // <base-unresolved-name> ::= dn <destructor-name>
3122 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003123 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003124 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003125 break;
3126 }
3127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 case Expr::MemberExprClass: {
3129 const MemberExpr *ME = cast<MemberExpr>(E);
3130 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003131 ME->getQualifier(), nullptr,
3132 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 break;
3134 }
3135
3136 case Expr::UnresolvedMemberExprClass: {
3137 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003138 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3139 ME->isArrow(), ME->getQualifier(), nullptr,
3140 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003142 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 break;
3144 }
3145
3146 case Expr::CXXDependentScopeMemberExprClass: {
3147 const CXXDependentScopeMemberExpr *ME
3148 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003149 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3150 ME->isArrow(), ME->getQualifier(),
3151 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 ME->getMember(), Arity);
3153 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003154 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 break;
3156 }
3157
3158 case Expr::UnresolvedLookupExprClass: {
3159 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003160 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003161
3162 // All the <unresolved-name> productions end in a
3163 // base-unresolved-name, where <template-args> are just tacked
3164 // onto the end.
3165 if (ULE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003166 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 break;
3168 }
3169
3170 case Expr::CXXUnresolvedConstructExprClass: {
3171 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3172 unsigned N = CE->arg_size();
3173
3174 Out << "cv";
3175 mangleType(CE->getType());
3176 if (N != 1) Out << '_';
3177 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3178 if (N != 1) Out << 'E';
3179 break;
3180 }
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003183 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003184 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003185 assert(
3186 CE->getNumArgs() >= 1 &&
3187 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3188 "implicit CXXConstructExpr must have one argument");
3189 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3190 }
3191 Out << "il";
3192 for (auto *E : CE->arguments())
3193 mangleExpression(E);
3194 Out << "E";
3195 break;
3196 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003197
Richard Smith520449d2015-02-05 06:15:50 +00003198 case Expr::CXXTemporaryObjectExprClass: {
3199 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3200 unsigned N = CE->getNumArgs();
3201 bool List = CE->isListInitialization();
3202
3203 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 Out << "tl";
3205 else
3206 Out << "cv";
3207 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003208 if (!List && N != 1)
3209 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003210 if (CE->isStdInitListInitialization()) {
3211 // We implicitly created a std::initializer_list<T> for the first argument
3212 // of a constructor of type U in an expression of the form U{a, b, c}.
3213 // Strip all the semantic gunk off the initializer list.
3214 auto *SILE =
3215 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3216 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3217 mangleInitListElements(ILE);
3218 } else {
3219 for (auto *E : CE->arguments())
3220 mangleExpression(E);
3221 }
Richard Smith520449d2015-02-05 06:15:50 +00003222 if (List || N != 1)
3223 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 break;
3225 }
3226
3227 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003228 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003230 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 break;
3232
3233 case Expr::CXXNoexceptExprClass:
3234 Out << "nx";
3235 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3236 break;
3237
3238 case Expr::UnaryExprOrTypeTraitExprClass: {
3239 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3240
3241 if (!SAE->isInstantiationDependent()) {
3242 // Itanium C++ ABI:
3243 // If the operand of a sizeof or alignof operator is not
3244 // instantiation-dependent it is encoded as an integer literal
3245 // reflecting the result of the operator.
3246 //
3247 // If the result of the operator is implicitly converted to a known
3248 // integer type, that type is used for the literal; otherwise, the type
3249 // of std::size_t or std::ptrdiff_t is used.
3250 QualType T = (ImplicitlyConvertedToType.isNull() ||
3251 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3252 : ImplicitlyConvertedToType;
3253 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3254 mangleIntegerLiteral(T, V);
3255 break;
3256 }
3257
3258 switch(SAE->getKind()) {
3259 case UETT_SizeOf:
3260 Out << 's';
3261 break;
3262 case UETT_AlignOf:
3263 Out << 'a';
3264 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003265 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 DiagnosticsEngine &Diags = Context.getDiags();
3267 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3268 "cannot yet mangle vec_step expression");
3269 Diags.Report(DiagID);
3270 return;
3271 }
Alexey Bataev00396512015-07-02 03:40:19 +00003272 case UETT_OpenMPRequiredSimdAlign:
3273 DiagnosticsEngine &Diags = Context.getDiags();
3274 unsigned DiagID = Diags.getCustomDiagID(
3275 DiagnosticsEngine::Error,
3276 "cannot yet mangle __builtin_omp_required_simd_align expression");
3277 Diags.Report(DiagID);
3278 return;
3279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 if (SAE->isArgumentType()) {
3281 Out << 't';
3282 mangleType(SAE->getArgumentType());
3283 } else {
3284 Out << 'z';
3285 mangleExpression(SAE->getArgumentExpr());
3286 }
3287 break;
3288 }
3289
3290 case Expr::CXXThrowExprClass: {
3291 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003292 // <expression> ::= tw <expression> # throw expression
3293 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 if (TE->getSubExpr()) {
3295 Out << "tw";
3296 mangleExpression(TE->getSubExpr());
3297 } else {
3298 Out << "tr";
3299 }
3300 break;
3301 }
3302
3303 case Expr::CXXTypeidExprClass: {
3304 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003305 // <expression> ::= ti <type> # typeid (type)
3306 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 if (TIE->isTypeOperand()) {
3308 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003309 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 } else {
3311 Out << "te";
3312 mangleExpression(TIE->getExprOperand());
3313 }
3314 break;
3315 }
3316
3317 case Expr::CXXDeleteExprClass: {
3318 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003319 // <expression> ::= [gs] dl <expression> # [::] delete expr
3320 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 if (DE->isGlobalDelete()) Out << "gs";
3322 Out << (DE->isArrayForm() ? "da" : "dl");
3323 mangleExpression(DE->getArgument());
3324 break;
3325 }
3326
3327 case Expr::UnaryOperatorClass: {
3328 const UnaryOperator *UO = cast<UnaryOperator>(E);
3329 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3330 /*Arity=*/1);
3331 mangleExpression(UO->getSubExpr());
3332 break;
3333 }
3334
3335 case Expr::ArraySubscriptExprClass: {
3336 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3337
3338 // Array subscript is treated as a syntactically weird form of
3339 // binary operator.
3340 Out << "ix";
3341 mangleExpression(AE->getLHS());
3342 mangleExpression(AE->getRHS());
3343 break;
3344 }
3345
3346 case Expr::CompoundAssignOperatorClass: // fallthrough
3347 case Expr::BinaryOperatorClass: {
3348 const BinaryOperator *BO = cast<BinaryOperator>(E);
3349 if (BO->getOpcode() == BO_PtrMemD)
3350 Out << "ds";
3351 else
3352 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3353 /*Arity=*/2);
3354 mangleExpression(BO->getLHS());
3355 mangleExpression(BO->getRHS());
3356 break;
3357 }
3358
3359 case Expr::ConditionalOperatorClass: {
3360 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3361 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3362 mangleExpression(CO->getCond());
3363 mangleExpression(CO->getLHS(), Arity);
3364 mangleExpression(CO->getRHS(), Arity);
3365 break;
3366 }
3367
3368 case Expr::ImplicitCastExprClass: {
3369 ImplicitlyConvertedToType = E->getType();
3370 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3371 goto recurse;
3372 }
3373
3374 case Expr::ObjCBridgedCastExprClass: {
3375 // Mangle ownership casts as a vendor extended operator __bridge,
3376 // __bridge_transfer, or __bridge_retain.
3377 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3378 Out << "v1U" << Kind.size() << Kind;
3379 }
3380 // Fall through to mangle the cast itself.
3381
3382 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003383 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003385
Richard Smith520449d2015-02-05 06:15:50 +00003386 case Expr::CXXFunctionalCastExprClass: {
3387 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3388 // FIXME: Add isImplicit to CXXConstructExpr.
3389 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3390 if (CCE->getParenOrBraceRange().isInvalid())
3391 Sub = CCE->getArg(0)->IgnoreImplicit();
3392 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3393 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3394 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3395 Out << "tl";
3396 mangleType(E->getType());
3397 mangleInitListElements(IL);
3398 Out << "E";
3399 } else {
3400 mangleCastExpression(E, "cv");
3401 }
3402 break;
3403 }
3404
David Majnemer9c775c72014-09-23 04:27:55 +00003405 case Expr::CXXStaticCastExprClass:
3406 mangleCastExpression(E, "sc");
3407 break;
3408 case Expr::CXXDynamicCastExprClass:
3409 mangleCastExpression(E, "dc");
3410 break;
3411 case Expr::CXXReinterpretCastExprClass:
3412 mangleCastExpression(E, "rc");
3413 break;
3414 case Expr::CXXConstCastExprClass:
3415 mangleCastExpression(E, "cc");
3416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
3418 case Expr::CXXOperatorCallExprClass: {
3419 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3420 unsigned NumArgs = CE->getNumArgs();
3421 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3422 // Mangle the arguments.
3423 for (unsigned i = 0; i != NumArgs; ++i)
3424 mangleExpression(CE->getArg(i));
3425 break;
3426 }
3427
3428 case Expr::ParenExprClass:
3429 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3430 break;
3431
3432 case Expr::DeclRefExprClass: {
3433 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3434
3435 switch (D->getKind()) {
3436 default:
3437 // <expr-primary> ::= L <mangled-name> E # external name
3438 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003439 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 Out << 'E';
3441 break;
3442
3443 case Decl::ParmVar:
3444 mangleFunctionParam(cast<ParmVarDecl>(D));
3445 break;
3446
3447 case Decl::EnumConstant: {
3448 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3449 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3450 break;
3451 }
3452
3453 case Decl::NonTypeTemplateParm: {
3454 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3455 mangleTemplateParameter(PD->getIndex());
3456 break;
3457 }
3458
3459 }
3460
3461 break;
3462 }
3463
3464 case Expr::SubstNonTypeTemplateParmPackExprClass:
3465 // FIXME: not clear how to mangle this!
3466 // template <unsigned N...> class A {
3467 // template <class U...> void foo(U (&x)[N]...);
3468 // };
3469 Out << "_SUBSTPACK_";
3470 break;
3471
3472 case Expr::FunctionParmPackExprClass: {
3473 // FIXME: not clear how to mangle this!
3474 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3475 Out << "v110_SUBSTPACK";
3476 mangleFunctionParam(FPPE->getParameterPack());
3477 break;
3478 }
3479
3480 case Expr::DependentScopeDeclRefExprClass: {
3481 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003482 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003483
3484 // All the <unresolved-name> productions end in a
3485 // base-unresolved-name, where <template-args> are just tacked
3486 // onto the end.
3487 if (DRE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003488 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 break;
3490 }
3491
3492 case Expr::CXXBindTemporaryExprClass:
3493 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3494 break;
3495
3496 case Expr::ExprWithCleanupsClass:
3497 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3498 break;
3499
3500 case Expr::FloatingLiteralClass: {
3501 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3502 Out << 'L';
3503 mangleType(FL->getType());
3504 mangleFloat(FL->getValue());
3505 Out << 'E';
3506 break;
3507 }
3508
3509 case Expr::CharacterLiteralClass:
3510 Out << 'L';
3511 mangleType(E->getType());
3512 Out << cast<CharacterLiteral>(E)->getValue();
3513 Out << 'E';
3514 break;
3515
3516 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3517 case Expr::ObjCBoolLiteralExprClass:
3518 Out << "Lb";
3519 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3520 Out << 'E';
3521 break;
3522
3523 case Expr::CXXBoolLiteralExprClass:
3524 Out << "Lb";
3525 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3526 Out << 'E';
3527 break;
3528
3529 case Expr::IntegerLiteralClass: {
3530 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3531 if (E->getType()->isSignedIntegerType())
3532 Value.setIsSigned(true);
3533 mangleIntegerLiteral(E->getType(), Value);
3534 break;
3535 }
3536
3537 case Expr::ImaginaryLiteralClass: {
3538 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3539 // Mangle as if a complex literal.
3540 // Proposal from David Vandevoorde, 2010.06.30.
3541 Out << 'L';
3542 mangleType(E->getType());
3543 if (const FloatingLiteral *Imag =
3544 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3545 // Mangle a floating-point zero of the appropriate type.
3546 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3547 Out << '_';
3548 mangleFloat(Imag->getValue());
3549 } else {
3550 Out << "0_";
3551 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3552 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3553 Value.setIsSigned(true);
3554 mangleNumber(Value);
3555 }
3556 Out << 'E';
3557 break;
3558 }
3559
3560 case Expr::StringLiteralClass: {
3561 // Revised proposal from David Vandervoorde, 2010.07.15.
3562 Out << 'L';
3563 assert(isa<ConstantArrayType>(E->getType()));
3564 mangleType(E->getType());
3565 Out << 'E';
3566 break;
3567 }
3568
3569 case Expr::GNUNullExprClass:
3570 // FIXME: should this really be mangled the same as nullptr?
3571 // fallthrough
3572
3573 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 Out << "LDnE";
3575 break;
3576 }
3577
3578 case Expr::PackExpansionExprClass:
3579 Out << "sp";
3580 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3581 break;
3582
3583 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003584 auto *SPE = cast<SizeOfPackExpr>(E);
3585 if (SPE->isPartiallySubstituted()) {
3586 Out << "sP";
3587 for (const auto &A : SPE->getPartialArguments())
3588 mangleTemplateArg(A);
3589 Out << "E";
3590 break;
3591 }
3592
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003594 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3596 mangleTemplateParameter(TTP->getIndex());
3597 else if (const NonTypeTemplateParmDecl *NTTP
3598 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3599 mangleTemplateParameter(NTTP->getIndex());
3600 else if (const TemplateTemplateParmDecl *TempTP
3601 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3602 mangleTemplateParameter(TempTP->getIndex());
3603 else
3604 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3605 break;
3606 }
Richard Smith0f0af192014-11-08 05:07:16 +00003607
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 case Expr::MaterializeTemporaryExprClass: {
3609 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3610 break;
3611 }
Richard Smith0f0af192014-11-08 05:07:16 +00003612
3613 case Expr::CXXFoldExprClass: {
3614 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003615 if (FE->isLeftFold())
3616 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003617 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003618 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003619
3620 if (FE->getOperator() == BO_PtrMemD)
3621 Out << "ds";
3622 else
3623 mangleOperatorName(
3624 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3625 /*Arity=*/2);
3626
3627 if (FE->getLHS())
3628 mangleExpression(FE->getLHS());
3629 if (FE->getRHS())
3630 mangleExpression(FE->getRHS());
3631 break;
3632 }
3633
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 case Expr::CXXThisExprClass:
3635 Out << "fpT";
3636 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00003637
3638 case Expr::CoawaitExprClass:
3639 // FIXME: Propose a non-vendor mangling.
3640 Out << "v18co_await";
3641 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3642 break;
3643
3644 case Expr::CoyieldExprClass:
3645 // FIXME: Propose a non-vendor mangling.
3646 Out << "v18co_yield";
3647 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3648 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 }
3650}
3651
3652/// Mangle an expression which refers to a parameter variable.
3653///
3654/// <expression> ::= <function-param>
3655/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3656/// <function-param> ::= fp <top-level CV-qualifiers>
3657/// <parameter-2 non-negative number> _ # L == 0, I > 0
3658/// <function-param> ::= fL <L-1 non-negative number>
3659/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3660/// <function-param> ::= fL <L-1 non-negative number>
3661/// p <top-level CV-qualifiers>
3662/// <I-1 non-negative number> _ # L > 0, I > 0
3663///
3664/// L is the nesting depth of the parameter, defined as 1 if the
3665/// parameter comes from the innermost function prototype scope
3666/// enclosing the current context, 2 if from the next enclosing
3667/// function prototype scope, and so on, with one special case: if
3668/// we've processed the full parameter clause for the innermost
3669/// function type, then L is one less. This definition conveniently
3670/// makes it irrelevant whether a function's result type was written
3671/// trailing or leading, but is otherwise overly complicated; the
3672/// numbering was first designed without considering references to
3673/// parameter in locations other than return types, and then the
3674/// mangling had to be generalized without changing the existing
3675/// manglings.
3676///
3677/// I is the zero-based index of the parameter within its parameter
3678/// declaration clause. Note that the original ABI document describes
3679/// this using 1-based ordinals.
3680void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3681 unsigned parmDepth = parm->getFunctionScopeDepth();
3682 unsigned parmIndex = parm->getFunctionScopeIndex();
3683
3684 // Compute 'L'.
3685 // parmDepth does not include the declaring function prototype.
3686 // FunctionTypeDepth does account for that.
3687 assert(parmDepth < FunctionTypeDepth.getDepth());
3688 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3689 if (FunctionTypeDepth.isInResultType())
3690 nestingDepth--;
3691
3692 if (nestingDepth == 0) {
3693 Out << "fp";
3694 } else {
3695 Out << "fL" << (nestingDepth - 1) << 'p';
3696 }
3697
3698 // Top-level qualifiers. We don't have to worry about arrays here,
3699 // because parameters declared as arrays should already have been
3700 // transformed to have pointer type. FIXME: apparently these don't
3701 // get mangled if used as an rvalue of a known non-class type?
3702 assert(!parm->getType()->isArrayType()
3703 && "parameter's type is still an array type?");
3704 mangleQualifiers(parm->getType().getQualifiers());
3705
3706 // Parameter index.
3707 if (parmIndex != 0) {
3708 Out << (parmIndex - 1);
3709 }
3710 Out << '_';
3711}
3712
3713void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3714 // <ctor-dtor-name> ::= C1 # complete object constructor
3715 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003717 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003718 switch (T) {
3719 case Ctor_Complete:
3720 Out << "C1";
3721 break;
3722 case Ctor_Base:
3723 Out << "C2";
3724 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003725 case Ctor_Comdat:
3726 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003728 case Ctor_DefaultClosure:
3729 case Ctor_CopyingClosure:
3730 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 }
3732}
3733
3734void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3735 // <ctor-dtor-name> ::= D0 # deleting destructor
3736 // ::= D1 # complete object destructor
3737 // ::= D2 # base object destructor
3738 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003739 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003740 switch (T) {
3741 case Dtor_Deleting:
3742 Out << "D0";
3743 break;
3744 case Dtor_Complete:
3745 Out << "D1";
3746 break;
3747 case Dtor_Base:
3748 Out << "D2";
3749 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003750 case Dtor_Comdat:
3751 Out << "D5";
3752 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 }
3754}
3755
James Y Knight04ec5bf2015-12-24 02:59:37 +00003756void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3757 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 // <template-args> ::= I <template-arg>+ E
3759 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00003760 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3761 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 Out << 'E';
3763}
3764
3765void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3766 // <template-args> ::= I <template-arg>+ E
3767 Out << 'I';
3768 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3769 mangleTemplateArg(AL[i]);
3770 Out << 'E';
3771}
3772
3773void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3774 unsigned NumTemplateArgs) {
3775 // <template-args> ::= I <template-arg>+ E
3776 Out << 'I';
3777 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3778 mangleTemplateArg(TemplateArgs[i]);
3779 Out << 'E';
3780}
3781
3782void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3783 // <template-arg> ::= <type> # type or template
3784 // ::= X <expression> E # expression
3785 // ::= <expr-primary> # simple expressions
3786 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 if (!A.isInstantiationDependent() || A.isDependent())
3788 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3789
3790 switch (A.getKind()) {
3791 case TemplateArgument::Null:
3792 llvm_unreachable("Cannot mangle NULL template argument");
3793
3794 case TemplateArgument::Type:
3795 mangleType(A.getAsType());
3796 break;
3797 case TemplateArgument::Template:
3798 // This is mangled as <type>.
3799 mangleType(A.getAsTemplate());
3800 break;
3801 case TemplateArgument::TemplateExpansion:
3802 // <type> ::= Dp <type> # pack expansion (C++0x)
3803 Out << "Dp";
3804 mangleType(A.getAsTemplateOrTemplatePattern());
3805 break;
3806 case TemplateArgument::Expression: {
3807 // It's possible to end up with a DeclRefExpr here in certain
3808 // dependent cases, in which case we should mangle as a
3809 // declaration.
3810 const Expr *E = A.getAsExpr()->IgnoreParens();
3811 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3812 const ValueDecl *D = DRE->getDecl();
3813 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003814 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003815 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 Out << 'E';
3817 break;
3818 }
3819 }
3820
3821 Out << 'X';
3822 mangleExpression(E);
3823 Out << 'E';
3824 break;
3825 }
3826 case TemplateArgument::Integral:
3827 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3828 break;
3829 case TemplateArgument::Declaration: {
3830 // <expr-primary> ::= L <mangled-name> E # external name
3831 // Clang produces AST's where pointer-to-member-function expressions
3832 // and pointer-to-function expressions are represented as a declaration not
3833 // an expression. We compensate for it here to produce the correct mangling.
3834 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003835 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 if (compensateMangling) {
3837 Out << 'X';
3838 mangleOperatorName(OO_Amp, 1);
3839 }
3840
3841 Out << 'L';
3842 // References to external entities use the mangled name; if the name would
3843 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003844 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003845 Out << 'E';
3846
3847 if (compensateMangling)
3848 Out << 'E';
3849
3850 break;
3851 }
3852 case TemplateArgument::NullPtr: {
3853 // <expr-primary> ::= L <type> 0 E
3854 Out << 'L';
3855 mangleType(A.getNullPtrType());
3856 Out << "0E";
3857 break;
3858 }
3859 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003860 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003861 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003862 for (const auto &P : A.pack_elements())
3863 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 Out << 'E';
3865 }
3866 }
3867}
3868
3869void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3870 // <template-param> ::= T_ # first template parameter
3871 // ::= T <parameter-2 non-negative number> _
3872 if (Index == 0)
3873 Out << "T_";
3874 else
3875 Out << 'T' << (Index - 1) << '_';
3876}
3877
David Majnemer3b3bdb52014-05-06 22:49:16 +00003878void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3879 if (SeqID == 1)
3880 Out << '0';
3881 else if (SeqID > 1) {
3882 SeqID--;
3883
3884 // <seq-id> is encoded in base-36, using digits and upper case letters.
3885 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003886 MutableArrayRef<char> BufferRef(Buffer);
3887 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003888
3889 for (; SeqID != 0; SeqID /= 36) {
3890 unsigned C = SeqID % 36;
3891 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3892 }
3893
3894 Out.write(I.base(), I - BufferRef.rbegin());
3895 }
3896 Out << '_';
3897}
3898
Guy Benyei11169dd2012-12-18 14:30:41 +00003899void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3900 bool result = mangleSubstitution(type);
3901 assert(result && "no existing substitution for type");
3902 (void) result;
3903}
3904
3905void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3906 bool result = mangleSubstitution(tname);
3907 assert(result && "no existing substitution for template name");
3908 (void) result;
3909}
3910
3911// <substitution> ::= S <seq-id> _
3912// ::= S_
3913bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3914 // Try one of the standard substitutions first.
3915 if (mangleStandardSubstitution(ND))
3916 return true;
3917
3918 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3919 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3920}
3921
Justin Bognere8d762e2015-05-22 06:48:13 +00003922/// Determine whether the given type has any qualifiers that are relevant for
3923/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003924static bool hasMangledSubstitutionQualifiers(QualType T) {
3925 Qualifiers Qs = T.getQualifiers();
3926 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3927}
3928
3929bool CXXNameMangler::mangleSubstitution(QualType T) {
3930 if (!hasMangledSubstitutionQualifiers(T)) {
3931 if (const RecordType *RT = T->getAs<RecordType>())
3932 return mangleSubstitution(RT->getDecl());
3933 }
3934
3935 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3936
3937 return mangleSubstitution(TypePtr);
3938}
3939
3940bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3941 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3942 return mangleSubstitution(TD);
3943
3944 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3945 return mangleSubstitution(
3946 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3947}
3948
3949bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3950 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3951 if (I == Substitutions.end())
3952 return false;
3953
3954 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003955 Out << 'S';
3956 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003957
3958 return true;
3959}
3960
3961static bool isCharType(QualType T) {
3962 if (T.isNull())
3963 return false;
3964
3965 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3966 T->isSpecificBuiltinType(BuiltinType::Char_U);
3967}
3968
Justin Bognere8d762e2015-05-22 06:48:13 +00003969/// Returns whether a given type is a template specialization of a given name
3970/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003971static bool isCharSpecialization(QualType T, const char *Name) {
3972 if (T.isNull())
3973 return false;
3974
3975 const RecordType *RT = T->getAs<RecordType>();
3976 if (!RT)
3977 return false;
3978
3979 const ClassTemplateSpecializationDecl *SD =
3980 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3981 if (!SD)
3982 return false;
3983
3984 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3985 return false;
3986
3987 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3988 if (TemplateArgs.size() != 1)
3989 return false;
3990
3991 if (!isCharType(TemplateArgs[0].getAsType()))
3992 return false;
3993
3994 return SD->getIdentifier()->getName() == Name;
3995}
3996
3997template <std::size_t StrLen>
3998static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3999 const char (&Str)[StrLen]) {
4000 if (!SD->getIdentifier()->isStr(Str))
4001 return false;
4002
4003 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4004 if (TemplateArgs.size() != 2)
4005 return false;
4006
4007 if (!isCharType(TemplateArgs[0].getAsType()))
4008 return false;
4009
4010 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4011 return false;
4012
4013 return true;
4014}
4015
4016bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4017 // <substitution> ::= St # ::std::
4018 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4019 if (isStd(NS)) {
4020 Out << "St";
4021 return true;
4022 }
4023 }
4024
4025 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4026 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4027 return false;
4028
4029 // <substitution> ::= Sa # ::std::allocator
4030 if (TD->getIdentifier()->isStr("allocator")) {
4031 Out << "Sa";
4032 return true;
4033 }
4034
4035 // <<substitution> ::= Sb # ::std::basic_string
4036 if (TD->getIdentifier()->isStr("basic_string")) {
4037 Out << "Sb";
4038 return true;
4039 }
4040 }
4041
4042 if (const ClassTemplateSpecializationDecl *SD =
4043 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4044 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4045 return false;
4046
4047 // <substitution> ::= Ss # ::std::basic_string<char,
4048 // ::std::char_traits<char>,
4049 // ::std::allocator<char> >
4050 if (SD->getIdentifier()->isStr("basic_string")) {
4051 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4052
4053 if (TemplateArgs.size() != 3)
4054 return false;
4055
4056 if (!isCharType(TemplateArgs[0].getAsType()))
4057 return false;
4058
4059 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4060 return false;
4061
4062 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4063 return false;
4064
4065 Out << "Ss";
4066 return true;
4067 }
4068
4069 // <substitution> ::= Si # ::std::basic_istream<char,
4070 // ::std::char_traits<char> >
4071 if (isStreamCharSpecialization(SD, "basic_istream")) {
4072 Out << "Si";
4073 return true;
4074 }
4075
4076 // <substitution> ::= So # ::std::basic_ostream<char,
4077 // ::std::char_traits<char> >
4078 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4079 Out << "So";
4080 return true;
4081 }
4082
4083 // <substitution> ::= Sd # ::std::basic_iostream<char,
4084 // ::std::char_traits<char> >
4085 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4086 Out << "Sd";
4087 return true;
4088 }
4089 }
4090 return false;
4091}
4092
4093void CXXNameMangler::addSubstitution(QualType T) {
4094 if (!hasMangledSubstitutionQualifiers(T)) {
4095 if (const RecordType *RT = T->getAs<RecordType>()) {
4096 addSubstitution(RT->getDecl());
4097 return;
4098 }
4099 }
4100
4101 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4102 addSubstitution(TypePtr);
4103}
4104
4105void CXXNameMangler::addSubstitution(TemplateName Template) {
4106 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4107 return addSubstitution(TD);
4108
4109 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4110 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4111}
4112
4113void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4114 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4115 Substitutions[Ptr] = SeqID++;
4116}
4117
4118//
4119
Justin Bognere8d762e2015-05-22 06:48:13 +00004120/// Mangles the name of the declaration D and emits that name to the given
4121/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004122///
4123/// If the declaration D requires a mangled name, this routine will emit that
4124/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4125/// and this routine will return false. In this case, the caller should just
4126/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4127/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004128void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4129 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4131 "Invalid mangleName() call, argument is not a variable or function!");
4132 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4133 "Invalid mangleName() call on 'structor decl!");
4134
4135 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4136 getASTContext().getSourceManager(),
4137 "Mangling declaration");
4138
4139 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004140 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004141}
4142
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004143void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4144 CXXCtorType Type,
4145 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 CXXNameMangler Mangler(*this, Out, D, Type);
4147 Mangler.mangle(D);
4148}
4149
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004150void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4151 CXXDtorType Type,
4152 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 CXXNameMangler Mangler(*this, Out, D, Type);
4154 Mangler.mangle(D);
4155}
4156
Rafael Espindola1e4df922014-09-16 15:18:21 +00004157void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4158 raw_ostream &Out) {
4159 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4160 Mangler.mangle(D);
4161}
4162
4163void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4164 raw_ostream &Out) {
4165 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4166 Mangler.mangle(D);
4167}
4168
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004169void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4170 const ThunkInfo &Thunk,
4171 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 // <special-name> ::= T <call-offset> <base encoding>
4173 // # base is the nominal target function of thunk
4174 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4175 // # base is the nominal target function of thunk
4176 // # first call-offset is 'this' adjustment
4177 // # second call-offset is result adjustment
4178
4179 assert(!isa<CXXDestructorDecl>(MD) &&
4180 "Use mangleCXXDtor for destructor decls!");
4181 CXXNameMangler Mangler(*this, Out);
4182 Mangler.getStream() << "_ZT";
4183 if (!Thunk.Return.isEmpty())
4184 Mangler.getStream() << 'c';
4185
4186 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004187 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4188 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4189
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 // Mangle the return pointer adjustment if there is one.
4191 if (!Thunk.Return.isEmpty())
4192 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004193 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4194
Guy Benyei11169dd2012-12-18 14:30:41 +00004195 Mangler.mangleFunctionEncoding(MD);
4196}
4197
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004198void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4199 const CXXDestructorDecl *DD, CXXDtorType Type,
4200 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 // <special-name> ::= T <call-offset> <base encoding>
4202 // # base is the nominal target function of thunk
4203 CXXNameMangler Mangler(*this, Out, DD, Type);
4204 Mangler.getStream() << "_ZT";
4205
4206 // Mangle the 'this' pointer adjustment.
4207 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004208 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004209
4210 Mangler.mangleFunctionEncoding(DD);
4211}
4212
Justin Bognere8d762e2015-05-22 06:48:13 +00004213/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004214void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4215 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 // <special-name> ::= GV <object name> # Guard variable for one-time
4217 // # initialization
4218 CXXNameMangler Mangler(*this, Out);
4219 Mangler.getStream() << "_ZGV";
4220 Mangler.mangleName(D);
4221}
4222
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004223void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4224 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004225 // These symbols are internal in the Itanium ABI, so the names don't matter.
4226 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4227 // avoid duplicate symbols.
4228 Out << "__cxx_global_var_init";
4229}
4230
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004231void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4232 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004233 // Prefix the mangling of D with __dtor_.
4234 CXXNameMangler Mangler(*this, Out);
4235 Mangler.getStream() << "__dtor_";
4236 if (shouldMangleDeclName(D))
4237 Mangler.mangle(D);
4238 else
4239 Mangler.getStream() << D->getName();
4240}
4241
Reid Kleckner1d59f992015-01-22 01:36:17 +00004242void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4243 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4244 CXXNameMangler Mangler(*this, Out);
4245 Mangler.getStream() << "__filt_";
4246 if (shouldMangleDeclName(EnclosingDecl))
4247 Mangler.mangle(EnclosingDecl);
4248 else
4249 Mangler.getStream() << EnclosingDecl->getName();
4250}
4251
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004252void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4253 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4254 CXXNameMangler Mangler(*this, Out);
4255 Mangler.getStream() << "__fin_";
4256 if (shouldMangleDeclName(EnclosingDecl))
4257 Mangler.mangle(EnclosingDecl);
4258 else
4259 Mangler.getStream() << EnclosingDecl->getName();
4260}
4261
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004262void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4263 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004264 // <special-name> ::= TH <object name>
4265 CXXNameMangler Mangler(*this, Out);
4266 Mangler.getStream() << "_ZTH";
4267 Mangler.mangleName(D);
4268}
4269
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004270void
4271ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4272 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004273 // <special-name> ::= TW <object name>
4274 CXXNameMangler Mangler(*this, Out);
4275 Mangler.getStream() << "_ZTW";
4276 Mangler.mangleName(D);
4277}
4278
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004279void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004280 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004281 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 // We match the GCC mangling here.
4283 // <special-name> ::= GR <object name>
4284 CXXNameMangler Mangler(*this, Out);
4285 Mangler.getStream() << "_ZGR";
4286 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004287 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004288 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004289}
4290
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004291void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4292 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 // <special-name> ::= TV <type> # virtual table
4294 CXXNameMangler Mangler(*this, Out);
4295 Mangler.getStream() << "_ZTV";
4296 Mangler.mangleNameOrStandardSubstitution(RD);
4297}
4298
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004299void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4300 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 // <special-name> ::= TT <type> # VTT structure
4302 CXXNameMangler Mangler(*this, Out);
4303 Mangler.getStream() << "_ZTT";
4304 Mangler.mangleNameOrStandardSubstitution(RD);
4305}
4306
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004307void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4308 int64_t Offset,
4309 const CXXRecordDecl *Type,
4310 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 // <special-name> ::= TC <type> <offset number> _ <base type>
4312 CXXNameMangler Mangler(*this, Out);
4313 Mangler.getStream() << "_ZTC";
4314 Mangler.mangleNameOrStandardSubstitution(RD);
4315 Mangler.getStream() << Offset;
4316 Mangler.getStream() << '_';
4317 Mangler.mangleNameOrStandardSubstitution(Type);
4318}
4319
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004320void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 // <special-name> ::= TI <type> # typeinfo structure
4322 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4323 CXXNameMangler Mangler(*this, Out);
4324 Mangler.getStream() << "_ZTI";
4325 Mangler.mangleType(Ty);
4326}
4327
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004328void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4329 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4331 CXXNameMangler Mangler(*this, Out);
4332 Mangler.getStream() << "_ZTS";
4333 Mangler.mangleType(Ty);
4334}
4335
Reid Klecknercc99e262013-11-19 23:23:00 +00004336void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4337 mangleCXXRTTIName(Ty, Out);
4338}
4339
David Majnemer58e5bee2014-03-24 21:43:36 +00004340void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4341 llvm_unreachable("Can't mangle string literals");
4342}
4343
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004344ItaniumMangleContext *
4345ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4346 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004347}