blob: 68f76f54eda1179a909ee5fbdcb5be30e6c485b3 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements C++ name mangling according to the Itanium C++ ABI,
11// which is used in GCC 3.2 and newer (and many compilers that are
12// ABI-compatible with GCC):
13//
David Majnemer98559942013-12-13 00:54:42 +000014// http://mentorembedded.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
16//===----------------------------------------------------------------------===//
17#include "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000024#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/ABI.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
35#define MANGLE_CHECKER 0
36
37#if MANGLE_CHECKER
38#include <cxxabi.h>
39#endif
40
41using namespace clang;
42
43namespace {
44
Justin Bognere8d762e2015-05-22 06:48:13 +000045/// Retrieve the declaration context that should be used when mangling the given
46/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000047static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
55 if (RD->isLambda())
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
59 }
Eli Friedman0cd23352013-07-10 01:33:19 +000060
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
66 }
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Eli Friedman95f50122013-07-02 17:52:28 +000068 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
71
David Majnemerf8c02e62015-02-18 19:08:11 +000072 if (const auto *VD = dyn_cast<VarDecl>(D))
73 if (VD->isExternC())
74 return VD->getASTContext().getTranslationUnitDecl();
75
76 if (const auto *FD = dyn_cast<FunctionDecl>(D))
77 if (FD->isExternC())
78 return FD->getASTContext().getTranslationUnitDecl();
79
Eli Friedman95f50122013-07-02 17:52:28 +000080 return DC;
Guy Benyei11169dd2012-12-18 14:30:41 +000081}
82
83static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
84 return getEffectiveDeclContext(cast<Decl>(DC));
85}
Eli Friedman95f50122013-07-02 17:52:28 +000086
87static bool isLocalContainerContext(const DeclContext *DC) {
88 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
89}
90
Eli Friedmaneecc09a2013-07-05 20:27:40 +000091static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000092 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000093 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000094 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000095 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000096 D = cast<Decl>(DC);
97 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000098 }
Craig Topper36250ad2014-05-12 05:36:57 +000099 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000100}
101
102static const FunctionDecl *getStructor(const FunctionDecl *fn) {
103 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
104 return ftd->getTemplatedDecl();
105
106 return fn;
107}
108
109static const NamedDecl *getStructor(const NamedDecl *decl) {
110 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
111 return (fn ? getStructor(fn) : decl);
112}
David Majnemer2206bf52014-03-05 08:57:59 +0000113
114static bool isLambda(const NamedDecl *ND) {
115 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
116 if (!Record)
117 return false;
118
119 return Record->isLambda();
120}
121
Guy Benyei11169dd2012-12-18 14:30:41 +0000122static const unsigned UnknownArity = ~0U;
123
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000124class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000125 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000127 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000128
Guy Benyei11169dd2012-12-18 14:30:41 +0000129public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000130 explicit ItaniumMangleContextImpl(ASTContext &Context,
131 DiagnosticsEngine &Diags)
132 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000133
Guy Benyei11169dd2012-12-18 14:30:41 +0000134 /// @name Mangler Entry Points
135 /// @{
136
Craig Toppercbce6e92014-03-11 06:22:39 +0000137 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000138 bool shouldMangleStringLiteral(const StringLiteral *) override {
139 return false;
140 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000141 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
142 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
143 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000144 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000146 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000147 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
148 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000149 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
150 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000152 const CXXRecordDecl *Type, raw_ostream &) override;
153 void mangleCXXRTTI(QualType T, raw_ostream &) override;
154 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
155 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000157 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160
Rafael Espindola1e4df922014-09-16 15:18:21 +0000161 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
162 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000163 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
164 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
165 void mangleDynamicAtExitDestructor(const VarDecl *D,
166 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000167 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
168 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000169 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000171 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
172 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
173 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000174
David Majnemer58e5bee2014-03-24 21:43:36 +0000175 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
176
Guy Benyei11169dd2012-12-18 14:30:41 +0000177 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000178 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000179 if (isLambda(ND))
180 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000181
182 // Anonymous tags are already numbered.
183 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
184 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
185 return false;
186 }
187
188 // Use the canonical number for externally visible decls.
189 if (ND->isExternallyVisible()) {
190 unsigned discriminator = getASTContext().getManglingNumber(ND);
191 if (discriminator == 1)
192 return false;
193 disc = discriminator - 2;
194 return true;
195 }
196
197 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000199 if (!discriminator) {
200 const DeclContext *DC = getEffectiveDeclContext(ND);
201 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
202 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 if (discriminator == 1)
204 return false;
205 disc = discriminator-2;
206 return true;
207 }
208 /// @}
209};
210
Justin Bognere8d762e2015-05-22 06:48:13 +0000211/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000212class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000213 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000214 raw_ostream &Out;
215
216 /// The "structor" is the top-level declaration being mangled, if
217 /// that's not a template specialization; otherwise it's the pattern
218 /// for that specialization.
219 const NamedDecl *Structor;
220 unsigned StructorType;
221
Justin Bognere8d762e2015-05-22 06:48:13 +0000222 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000223 unsigned SeqID;
224
225 class FunctionTypeDepthState {
226 unsigned Bits;
227
228 enum { InResultTypeMask = 1 };
229
230 public:
231 FunctionTypeDepthState() : Bits(0) {}
232
233 /// The number of function types we're inside.
234 unsigned getDepth() const {
235 return Bits >> 1;
236 }
237
238 /// True if we're in the return type of the innermost function type.
239 bool isInResultType() const {
240 return Bits & InResultTypeMask;
241 }
242
243 FunctionTypeDepthState push() {
244 FunctionTypeDepthState tmp = *this;
245 Bits = (Bits & ~InResultTypeMask) + 2;
246 return tmp;
247 }
248
249 void enterResultType() {
250 Bits |= InResultTypeMask;
251 }
252
253 void leaveResultType() {
254 Bits &= ~InResultTypeMask;
255 }
256
257 void pop(FunctionTypeDepthState saved) {
258 assert(getDepth() == saved.getDepth() + 1);
259 Bits = saved.Bits;
260 }
261
262 } FunctionTypeDepth;
263
264 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
265
266 ASTContext &getASTContext() const { return Context.getASTContext(); }
267
268public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000269 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000270 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000271 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
272 SeqID(0) {
273 // These can't be mangled without a ctor type or dtor type.
274 assert(!D || (!isa<CXXDestructorDecl>(D) &&
275 !isa<CXXConstructorDecl>(D)));
276 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000277 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000278 const CXXConstructorDecl *D, CXXCtorType Type)
279 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
280 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000281 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000282 const CXXDestructorDecl *D, CXXDtorType Type)
283 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
284 SeqID(0) { }
285
286#if MANGLE_CHECKER
287 ~CXXNameMangler() {
288 if (Out.str()[0] == '\01')
289 return;
290
291 int status = 0;
292 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
293 assert(status == 0 && "Could not demangle mangled name!");
294 free(result);
295 }
296#endif
297 raw_ostream &getStream() { return Out; }
298
David Majnemer7ff7eb72015-02-18 07:47:09 +0000299 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
301 void mangleNumber(const llvm::APSInt &I);
302 void mangleNumber(int64_t Number);
303 void mangleFloat(const llvm::APFloat &F);
304 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000305 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 void mangleName(const NamedDecl *ND);
307 void mangleType(QualType T);
308 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
309
310private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000311
Guy Benyei11169dd2012-12-18 14:30:41 +0000312 bool mangleSubstitution(const NamedDecl *ND);
313 bool mangleSubstitution(QualType T);
314 bool mangleSubstitution(TemplateName Template);
315 bool mangleSubstitution(uintptr_t Ptr);
316
317 void mangleExistingSubstitution(QualType type);
318 void mangleExistingSubstitution(TemplateName name);
319
320 bool mangleStandardSubstitution(const NamedDecl *ND);
321
322 void addSubstitution(const NamedDecl *ND) {
323 ND = cast<NamedDecl>(ND->getCanonicalDecl());
324
325 addSubstitution(reinterpret_cast<uintptr_t>(ND));
326 }
327 void addSubstitution(QualType T);
328 void addSubstitution(TemplateName Template);
329 void addSubstitution(uintptr_t Ptr);
330
331 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000332 bool recursive = false);
333 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 DeclarationName name,
335 unsigned KnownArity = UnknownArity);
336
337 void mangleName(const TemplateDecl *TD,
338 const TemplateArgument *TemplateArgs,
339 unsigned NumTemplateArgs);
340 void mangleUnqualifiedName(const NamedDecl *ND) {
341 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
342 }
343 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
344 unsigned KnownArity);
345 void mangleUnscopedName(const NamedDecl *ND);
346 void mangleUnscopedTemplateName(const TemplateDecl *ND);
347 void mangleUnscopedTemplateName(TemplateName);
348 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000349 void mangleLocalName(const Decl *D);
350 void mangleBlockForPrefix(const BlockDecl *Block);
351 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 void mangleLambda(const CXXRecordDecl *Lambda);
353 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
354 bool NoFunction=false);
355 void mangleNestedName(const TemplateDecl *TD,
356 const TemplateArgument *TemplateArgs,
357 unsigned NumTemplateArgs);
358 void manglePrefix(NestedNameSpecifier *qualifier);
359 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
360 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000361 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000363 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
364 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000365 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000367 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 void mangleQualifiers(Qualifiers Quals);
369 void mangleRefQualifier(RefQualifierKind RefQualifier);
370
371 void mangleObjCMethodName(const ObjCMethodDecl *MD);
372
373 // Declare manglers for every type class.
374#define ABSTRACT_TYPE(CLASS, PARENT)
375#define NON_CANONICAL_TYPE(CLASS, PARENT)
376#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
377#include "clang/AST/TypeNodes.def"
378
379 void mangleType(const TagType*);
380 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000381 static StringRef getCallingConvQualifierName(CallingConv CC);
382 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
383 void mangleExtFunctionInfo(const FunctionType *T);
384 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000385 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000387 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000388
389 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000390 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000391 void mangleMemberExpr(const Expr *base, bool isArrow,
392 NestedNameSpecifier *qualifier,
393 NamedDecl *firstQualifierLookup,
394 DeclarationName name,
395 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000396 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000397 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
399 void mangleCXXCtorType(CXXCtorType T);
400 void mangleCXXDtorType(CXXDtorType T);
401
James Y Knight04ec5bf2015-12-24 02:59:37 +0000402 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
403 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000404 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
405 unsigned NumTemplateArgs);
406 void mangleTemplateArgs(const TemplateArgumentList &AL);
407 void mangleTemplateArg(TemplateArgument A);
408
409 void mangleTemplateParameter(unsigned Index);
410
411 void mangleFunctionParam(const ParmVarDecl *parm);
412};
413
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000414}
Guy Benyei11169dd2012-12-18 14:30:41 +0000415
Rafael Espindola002667c2013-10-16 01:40:34 +0000416bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000418 if (FD) {
419 LanguageLinkage L = FD->getLanguageLinkage();
420 // Overloadable functions need mangling.
421 if (FD->hasAttr<OverloadableAttr>())
422 return true;
423
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000424 // "main" is not mangled.
425 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000426 return false;
427
428 // C++ functions and those whose names are not a simple identifier need
429 // mangling.
430 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
431 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000432
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000433 // C functions are not mangled.
434 if (L == CLanguageLinkage)
435 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000436 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000437
438 // Otherwise, no mangling is done outside C++ mode.
439 if (!getASTContext().getLangOpts().CPlusPlus)
440 return false;
441
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000442 const VarDecl *VD = dyn_cast<VarDecl>(D);
443 if (VD) {
444 // C variables are not mangled.
445 if (VD->isExternC())
446 return false;
447
448 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000449 const DeclContext *DC = getEffectiveDeclContext(D);
450 // Check for extern variable declared locally.
451 if (DC->isFunctionOrMethod() && D->hasLinkage())
452 while (!DC->isNamespace() && !DC->isTranslationUnit())
453 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000454 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
455 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 return false;
457 }
458
Guy Benyei11169dd2012-12-18 14:30:41 +0000459 return true;
460}
461
David Majnemer7ff7eb72015-02-18 07:47:09 +0000462void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 // <mangled-name> ::= _Z <encoding>
464 // ::= <data name>
465 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000466 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
468 mangleFunctionEncoding(FD);
469 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
470 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000471 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
472 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000473 else
474 mangleName(cast<FieldDecl>(D));
475}
476
477void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
478 // <encoding> ::= <function name> <bare-function-type>
479 mangleName(FD);
480
481 // Don't mangle in the type if this isn't a decl we should typically mangle.
482 if (!Context.shouldMangleDeclName(FD))
483 return;
484
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000485 if (FD->hasAttr<EnableIfAttr>()) {
486 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
487 Out << "Ua9enable_ifI";
488 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
489 // it here.
490 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
491 E = FD->getAttrs().rend();
492 I != E; ++I) {
493 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
494 if (!EIA)
495 continue;
496 Out << 'X';
497 mangleExpression(EIA->getCond());
498 Out << 'E';
499 }
500 Out << 'E';
501 FunctionTypeDepth.pop(Saved);
502 }
503
Guy Benyei11169dd2012-12-18 14:30:41 +0000504 // Whether the mangling of a function type includes the return type depends on
505 // the context and the nature of the function. The rules for deciding whether
506 // the return type is included are:
507 //
508 // 1. Template functions (names or types) have return types encoded, with
509 // the exceptions listed below.
510 // 2. Function types not appearing as part of a function name mangling,
511 // e.g. parameters, pointer types, etc., have return type encoded, with the
512 // exceptions listed below.
513 // 3. Non-template function names do not have return types encoded.
514 //
515 // The exceptions mentioned in (1) and (2) above, for which the return type is
516 // never included, are
517 // 1. Constructors.
518 // 2. Destructors.
519 // 3. Conversion operator functions, e.g. operator int.
520 bool MangleReturnType = false;
521 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
522 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
523 isa<CXXConversionDecl>(FD)))
524 MangleReturnType = true;
525
526 // Mangle the type of the primary template.
527 FD = PrimaryTemplate->getTemplatedDecl();
528 }
529
John McCall07daf722016-03-01 22:18:03 +0000530 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000531 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000532}
533
534static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
535 while (isa<LinkageSpecDecl>(DC)) {
536 DC = getEffectiveParentContext(DC);
537 }
538
539 return DC;
540}
541
Justin Bognere8d762e2015-05-22 06:48:13 +0000542/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000543static bool isStd(const NamespaceDecl *NS) {
544 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
545 ->isTranslationUnit())
546 return false;
547
548 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
549 return II && II->isStr("std");
550}
551
552// isStdNamespace - Return whether a given decl context is a toplevel 'std'
553// namespace.
554static bool isStdNamespace(const DeclContext *DC) {
555 if (!DC->isNamespace())
556 return false;
557
558 return isStd(cast<NamespaceDecl>(DC));
559}
560
561static const TemplateDecl *
562isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
563 // Check if we have a function template.
564 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
565 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
566 TemplateArgs = FD->getTemplateSpecializationArgs();
567 return TD;
568 }
569 }
570
571 // Check if we have a class template.
572 if (const ClassTemplateSpecializationDecl *Spec =
573 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
574 TemplateArgs = &Spec->getTemplateArgs();
575 return Spec->getSpecializedTemplate();
576 }
577
Larisse Voufo39a1e502013-08-06 01:03:05 +0000578 // Check if we have a variable template.
579 if (const VarTemplateSpecializationDecl *Spec =
580 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
581 TemplateArgs = &Spec->getTemplateArgs();
582 return Spec->getSpecializedTemplate();
583 }
584
Craig Topper36250ad2014-05-12 05:36:57 +0000585 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586}
587
Guy Benyei11169dd2012-12-18 14:30:41 +0000588void CXXNameMangler::mangleName(const NamedDecl *ND) {
589 // <name> ::= <nested-name>
590 // ::= <unscoped-name>
591 // ::= <unscoped-template-name> <template-args>
592 // ::= <local-name>
593 //
594 const DeclContext *DC = getEffectiveDeclContext(ND);
595
596 // If this is an extern variable declared locally, the relevant DeclContext
597 // is that of the containing namespace, or the translation unit.
598 // FIXME: This is a hack; extern variables declared locally should have
599 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000600 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 while (!DC->isNamespace() && !DC->isTranslationUnit())
602 DC = getEffectiveParentContext(DC);
603 else if (GetLocalClassDecl(ND)) {
604 mangleLocalName(ND);
605 return;
606 }
607
608 DC = IgnoreLinkageSpecDecls(DC);
609
610 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
611 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000612 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
614 mangleUnscopedTemplateName(TD);
615 mangleTemplateArgs(*TemplateArgs);
616 return;
617 }
618
619 mangleUnscopedName(ND);
620 return;
621 }
622
Eli Friedman95f50122013-07-02 17:52:28 +0000623 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 mangleLocalName(ND);
625 return;
626 }
627
628 mangleNestedName(ND, DC);
629}
630void CXXNameMangler::mangleName(const TemplateDecl *TD,
631 const TemplateArgument *TemplateArgs,
632 unsigned NumTemplateArgs) {
633 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
634
635 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
636 mangleUnscopedTemplateName(TD);
637 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
638 } else {
639 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
640 }
641}
642
643void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
644 // <unscoped-name> ::= <unqualified-name>
645 // ::= St <unqualified-name> # ::std::
646
647 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
648 Out << "St";
649
650 mangleUnqualifiedName(ND);
651}
652
653void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
654 // <unscoped-template-name> ::= <unscoped-name>
655 // ::= <substitution>
656 if (mangleSubstitution(ND))
657 return;
658
659 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000660 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000661 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000662 else
663 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000664
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 addSubstitution(ND);
666}
667
668void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
669 // <unscoped-template-name> ::= <unscoped-name>
670 // ::= <substitution>
671 if (TemplateDecl *TD = Template.getAsTemplateDecl())
672 return mangleUnscopedTemplateName(TD);
673
674 if (mangleSubstitution(Template))
675 return;
676
677 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
678 assert(Dependent && "Not a dependent template name?");
679 if (const IdentifierInfo *Id = Dependent->getIdentifier())
680 mangleSourceName(Id);
681 else
682 mangleOperatorName(Dependent->getOperator(), UnknownArity);
683
684 addSubstitution(Template);
685}
686
687void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
688 // ABI:
689 // Floating-point literals are encoded using a fixed-length
690 // lowercase hexadecimal string corresponding to the internal
691 // representation (IEEE on Itanium), high-order bytes first,
692 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
693 // on Itanium.
694 // The 'without leading zeroes' thing seems to be an editorial
695 // mistake; see the discussion on cxx-abi-dev beginning on
696 // 2012-01-16.
697
698 // Our requirements here are just barely weird enough to justify
699 // using a custom algorithm instead of post-processing APInt::toString().
700
701 llvm::APInt valueBits = f.bitcastToAPInt();
702 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
703 assert(numCharacters != 0);
704
705 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000706 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000707
708 // Fill the buffer left-to-right.
709 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
710 // The bit-index of the next hex digit.
711 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
712
713 // Project out 4 bits starting at 'digitIndex'.
714 llvm::integerPart hexDigit
715 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
716 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
717 hexDigit &= 0xF;
718
719 // Map that over to a lowercase hex digit.
720 static const char charForHex[16] = {
721 '0', '1', '2', '3', '4', '5', '6', '7',
722 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
723 };
724 buffer[stringIndex] = charForHex[hexDigit];
725 }
726
727 Out.write(buffer.data(), numCharacters);
728}
729
730void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
731 if (Value.isSigned() && Value.isNegative()) {
732 Out << 'n';
733 Value.abs().print(Out, /*signed*/ false);
734 } else {
735 Value.print(Out, /*signed*/ false);
736 }
737}
738
739void CXXNameMangler::mangleNumber(int64_t Number) {
740 // <number> ::= [n] <non-negative decimal integer>
741 if (Number < 0) {
742 Out << 'n';
743 Number = -Number;
744 }
745
746 Out << Number;
747}
748
749void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
750 // <call-offset> ::= h <nv-offset> _
751 // ::= v <v-offset> _
752 // <nv-offset> ::= <offset number> # non-virtual base override
753 // <v-offset> ::= <offset number> _ <virtual offset number>
754 // # virtual base override, with vcall offset
755 if (!Virtual) {
756 Out << 'h';
757 mangleNumber(NonVirtual);
758 Out << '_';
759 return;
760 }
761
762 Out << 'v';
763 mangleNumber(NonVirtual);
764 Out << '_';
765 mangleNumber(Virtual);
766 Out << '_';
767}
768
769void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000770 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 if (!mangleSubstitution(QualType(TST, 0))) {
772 mangleTemplatePrefix(TST->getTemplateName());
773
774 // FIXME: GCC does not appear to mangle the template arguments when
775 // the template in question is a dependent template name. Should we
776 // emulate that badness?
777 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
778 addSubstitution(QualType(TST, 0));
779 }
David Majnemera88b3592015-02-18 02:28:01 +0000780 } else if (const auto *DTST =
781 type->getAs<DependentTemplateSpecializationType>()) {
782 if (!mangleSubstitution(QualType(DTST, 0))) {
783 TemplateName Template = getASTContext().getDependentTemplateName(
784 DTST->getQualifier(), DTST->getIdentifier());
785 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000786
David Majnemera88b3592015-02-18 02:28:01 +0000787 // FIXME: GCC does not appear to mangle the template arguments when
788 // the template in question is a dependent template name. Should we
789 // emulate that badness?
790 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
791 addSubstitution(QualType(DTST, 0));
792 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 } else {
794 // We use the QualType mangle type variant here because it handles
795 // substitutions.
796 mangleType(type);
797 }
798}
799
800/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
801///
Guy Benyei11169dd2012-12-18 14:30:41 +0000802/// \param recursive - true if this is being called recursively,
803/// i.e. if there is more prefix "to the right".
804void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 bool recursive) {
806
807 // x, ::x
808 // <unresolved-name> ::= [gs] <base-unresolved-name>
809
810 // T::x / decltype(p)::x
811 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
812
813 // T::N::x /decltype(p)::N::x
814 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
815 // <base-unresolved-name>
816
817 // A::x, N::y, A<T>::z; "gs" means leading "::"
818 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
819 // <base-unresolved-name>
820
821 switch (qualifier->getKind()) {
822 case NestedNameSpecifier::Global:
823 Out << "gs";
824
825 // We want an 'sr' unless this is the entire NNS.
826 if (recursive)
827 Out << "sr";
828
829 // We never want an 'E' here.
830 return;
831
Nikola Smiljanic67860242014-09-26 00:28:20 +0000832 case NestedNameSpecifier::Super:
833 llvm_unreachable("Can't mangle __super specifier");
834
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 case NestedNameSpecifier::Namespace:
836 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000837 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 /*recursive*/ true);
839 else
840 Out << "sr";
841 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
842 break;
843 case NestedNameSpecifier::NamespaceAlias:
844 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000845 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000846 /*recursive*/ true);
847 else
848 Out << "sr";
849 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
850 break;
851
852 case NestedNameSpecifier::TypeSpec:
853 case NestedNameSpecifier::TypeSpecWithTemplate: {
854 const Type *type = qualifier->getAsType();
855
856 // We only want to use an unresolved-type encoding if this is one of:
857 // - a decltype
858 // - a template type parameter
859 // - a template template parameter with arguments
860 // In all of these cases, we should have no prefix.
861 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000862 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 /*recursive*/ true);
864 } else {
865 // Otherwise, all the cases want this.
866 Out << "sr";
867 }
868
David Majnemerb8014dd2015-02-19 02:16:16 +0000869 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 return;
871
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 break;
873 }
874
875 case NestedNameSpecifier::Identifier:
876 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000877 if (qualifier->getPrefix())
878 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000879 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000880 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000882
883 mangleSourceName(qualifier->getAsIdentifier());
884 break;
885 }
886
887 // If this was the innermost part of the NNS, and we fell out to
888 // here, append an 'E'.
889 if (!recursive)
890 Out << 'E';
891}
892
893/// Mangle an unresolved-name, which is generally used for names which
894/// weren't resolved to specific entities.
895void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 DeclarationName name,
897 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000898 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000899 switch (name.getNameKind()) {
900 // <base-unresolved-name> ::= <simple-id>
901 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000902 mangleSourceName(name.getAsIdentifierInfo());
903 break;
904 // <base-unresolved-name> ::= dn <destructor-name>
905 case DeclarationName::CXXDestructorName:
906 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000907 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000908 break;
909 // <base-unresolved-name> ::= on <operator-name>
910 case DeclarationName::CXXConversionFunctionName:
911 case DeclarationName::CXXLiteralOperatorName:
912 case DeclarationName::CXXOperatorName:
913 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000914 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000915 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000916 case DeclarationName::CXXConstructorName:
917 llvm_unreachable("Can't mangle a constructor name!");
918 case DeclarationName::CXXUsingDirective:
919 llvm_unreachable("Can't mangle a using directive name!");
920 case DeclarationName::ObjCMultiArgSelector:
921 case DeclarationName::ObjCOneArgSelector:
922 case DeclarationName::ObjCZeroArgSelector:
923 llvm_unreachable("Can't mangle Objective-C selector names here!");
924 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000925}
926
Guy Benyei11169dd2012-12-18 14:30:41 +0000927void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
928 DeclarationName Name,
929 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000930 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000931 // <unqualified-name> ::= <operator-name>
932 // ::= <ctor-dtor-name>
933 // ::= <source-name>
934 switch (Name.getNameKind()) {
935 case DeclarationName::Identifier: {
936 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
937 // We must avoid conflicts between internally- and externally-
938 // linked variable and function declaration names in the same TU:
939 // void test() { extern void foo(); }
940 // static void foo();
941 // This naming convention is the same as that followed by GCC,
942 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000943 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 getEffectiveDeclContext(ND)->isFileContext())
945 Out << 'L';
946
947 mangleSourceName(II);
948 break;
949 }
950
951 // Otherwise, an anonymous entity. We must have a declaration.
952 assert(ND && "mangling empty name without declaration");
953
954 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
955 if (NS->isAnonymousNamespace()) {
956 // This is how gcc mangles these names.
957 Out << "12_GLOBAL__N_1";
958 break;
959 }
960 }
961
962 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
963 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000964 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000966
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 // Itanium C++ ABI 5.1.2:
968 //
969 // For the purposes of mangling, the name of an anonymous union is
970 // considered to be the name of the first named data member found by a
971 // pre-order, depth-first, declaration-order walk of the data members of
972 // the anonymous union. If there is no such data member (i.e., if all of
973 // the data members in the union are unnamed), then there is no way for
974 // a program to refer to the anonymous union, and there is therefore no
975 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000976 assert(RD->isAnonymousStructOrUnion()
977 && "Expected anonymous struct or union!");
978 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000979
980 // It's actually possible for various reasons for us to get here
981 // with an empty anonymous struct / union. Fortunately, it
982 // doesn't really matter what name we generate.
983 if (!FD) break;
984 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000985
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 mangleSourceName(FD->getIdentifier());
987 break;
988 }
John McCall924046f2013-04-10 06:08:21 +0000989
990 // Class extensions have no name as a category, and it's possible
991 // for them to be the semantic parent of certain declarations
992 // (primarily, tag decls defined within declarations). Such
993 // declarations will always have internal linkage, so the name
994 // doesn't really matter, but we shouldn't crash on them. For
995 // safety, just handle all ObjC containers here.
996 if (isa<ObjCContainerDecl>(ND))
997 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000998
999 // We must have an anonymous struct.
1000 const TagDecl *TD = cast<TagDecl>(ND);
1001 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1002 assert(TD->getDeclContext() == D->getDeclContext() &&
1003 "Typedef should not be in another decl context!");
1004 assert(D->getDeclName().getAsIdentifierInfo() &&
1005 "Typedef was not named!");
1006 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1007 break;
1008 }
1009
1010 // <unnamed-type-name> ::= <closure-type-name>
1011 //
1012 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1013 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1014 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1015 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1016 mangleLambda(Record);
1017 break;
1018 }
1019 }
1020
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001021 if (TD->isExternallyVisible()) {
1022 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001024 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001025 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 Out << '_';
1027 break;
1028 }
1029
1030 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001031 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032
1033 // Mangle it as a source name in the form
1034 // [n] $_<id>
1035 // where n is the length of the string.
1036 SmallString<8> Str;
1037 Str += "$_";
1038 Str += llvm::utostr(AnonStructId);
1039
1040 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001041 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001042 break;
1043 }
1044
1045 case DeclarationName::ObjCZeroArgSelector:
1046 case DeclarationName::ObjCOneArgSelector:
1047 case DeclarationName::ObjCMultiArgSelector:
1048 llvm_unreachable("Can't mangle Objective-C selector names here!");
1049
1050 case DeclarationName::CXXConstructorName:
1051 if (ND == Structor)
1052 // If the named decl is the C++ constructor we're mangling, use the type
1053 // we were given.
1054 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1055 else
1056 // Otherwise, use the complete constructor name. This is relevant if a
1057 // class with a constructor is declared within a constructor.
1058 mangleCXXCtorType(Ctor_Complete);
1059 break;
1060
1061 case DeclarationName::CXXDestructorName:
1062 if (ND == Structor)
1063 // If the named decl is the C++ destructor we're mangling, use the type we
1064 // were given.
1065 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1066 else
1067 // Otherwise, use the complete destructor name. This is relevant if a
1068 // class with a destructor is declared within a destructor.
1069 mangleCXXDtorType(Dtor_Complete);
1070 break;
1071
David Majnemera88b3592015-02-18 02:28:01 +00001072 case DeclarationName::CXXOperatorName:
1073 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 Arity = cast<FunctionDecl>(ND)->getNumParams();
1075
David Majnemera88b3592015-02-18 02:28:01 +00001076 // If we have a member function, we need to include the 'this' pointer.
1077 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1078 if (!MD->isStatic())
1079 Arity++;
1080 }
1081 // FALLTHROUGH
1082 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001083 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001084 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001085 break;
1086
1087 case DeclarationName::CXXUsingDirective:
1088 llvm_unreachable("Can't mangle a using directive name!");
1089 }
1090}
1091
1092void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1093 // <source-name> ::= <positive length number> <identifier>
1094 // <number> ::= [n] <non-negative decimal integer>
1095 // <identifier> ::= <unqualified source code identifier>
1096 Out << II->getLength() << II->getName();
1097}
1098
1099void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1100 const DeclContext *DC,
1101 bool NoFunction) {
1102 // <nested-name>
1103 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1104 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1105 // <template-args> E
1106
1107 Out << 'N';
1108 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001109 Qualifiers MethodQuals =
1110 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1111 // We do not consider restrict a distinguishing attribute for overloading
1112 // purposes so we must not mangle it.
1113 MethodQuals.removeRestrict();
1114 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 mangleRefQualifier(Method->getRefQualifier());
1116 }
1117
1118 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001119 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001121 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 mangleTemplateArgs(*TemplateArgs);
1123 }
1124 else {
1125 manglePrefix(DC, NoFunction);
1126 mangleUnqualifiedName(ND);
1127 }
1128
1129 Out << 'E';
1130}
1131void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1132 const TemplateArgument *TemplateArgs,
1133 unsigned NumTemplateArgs) {
1134 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1135
1136 Out << 'N';
1137
1138 mangleTemplatePrefix(TD);
1139 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1140
1141 Out << 'E';
1142}
1143
Eli Friedman95f50122013-07-02 17:52:28 +00001144void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001145 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1146 // := Z <function encoding> E s [<discriminator>]
1147 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1148 // _ <entity name>
1149 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001150 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001151 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001152 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001153
1154 Out << 'Z';
1155
Eli Friedman92821742013-07-02 02:01:18 +00001156 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1157 mangleObjCMethodName(MD);
1158 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001159 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001160 else
1161 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001162
Eli Friedman92821742013-07-02 02:01:18 +00001163 Out << 'E';
1164
1165 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 // The parameter number is omitted for the last parameter, 0 for the
1167 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1168 // <entity name> will of course contain a <closure-type-name>: Its
1169 // numbering will be local to the particular argument in which it appears
1170 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001171 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1172 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001174 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 if (const FunctionDecl *Func
1176 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1177 Out << 'd';
1178 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1179 if (Num > 1)
1180 mangleNumber(Num - 2);
1181 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 }
1183 }
1184 }
1185
1186 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001187 // equality ok because RD derived from ND above
1188 if (D == RD) {
1189 mangleUnqualifiedName(RD);
1190 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1191 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1192 mangleUnqualifiedBlock(BD);
1193 } else {
1194 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001195 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001196 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001197 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1198 // Mangle a block in a default parameter; see above explanation for
1199 // lambdas.
1200 if (const ParmVarDecl *Parm
1201 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1202 if (const FunctionDecl *Func
1203 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1204 Out << 'd';
1205 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1206 if (Num > 1)
1207 mangleNumber(Num - 2);
1208 Out << '_';
1209 }
1210 }
1211
1212 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001213 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001214 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001216
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001217 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1218 unsigned disc;
1219 if (Context.getNextDiscriminator(ND, disc)) {
1220 if (disc < 10)
1221 Out << '_' << disc;
1222 else
1223 Out << "__" << disc << '_';
1224 }
1225 }
Eli Friedman95f50122013-07-02 17:52:28 +00001226}
1227
1228void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1229 if (GetLocalClassDecl(Block)) {
1230 mangleLocalName(Block);
1231 return;
1232 }
1233 const DeclContext *DC = getEffectiveDeclContext(Block);
1234 if (isLocalContainerContext(DC)) {
1235 mangleLocalName(Block);
1236 return;
1237 }
1238 manglePrefix(getEffectiveDeclContext(Block));
1239 mangleUnqualifiedBlock(Block);
1240}
1241
1242void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1243 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1244 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1245 Context->getDeclContext()->isRecord()) {
1246 if (const IdentifierInfo *Name
1247 = cast<NamedDecl>(Context)->getIdentifier()) {
1248 mangleSourceName(Name);
1249 Out << 'M';
1250 }
1251 }
1252 }
1253
1254 // If we have a block mangling number, use it.
1255 unsigned Number = Block->getBlockManglingNumber();
1256 // Otherwise, just make up a number. It doesn't matter what it is because
1257 // the symbol in question isn't externally visible.
1258 if (!Number)
1259 Number = Context.getBlockId(Block, false);
1260 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001261 if (Number > 0)
1262 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001263 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001264}
1265
1266void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1267 // If the context of a closure type is an initializer for a class member
1268 // (static or nonstatic), it is encoded in a qualified name with a final
1269 // <prefix> of the form:
1270 //
1271 // <data-member-prefix> := <member source-name> M
1272 //
1273 // Technically, the data-member-prefix is part of the <prefix>. However,
1274 // since a closure type will always be mangled with a prefix, it's easier
1275 // to emit that last part of the prefix here.
1276 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1277 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1278 Context->getDeclContext()->isRecord()) {
1279 if (const IdentifierInfo *Name
1280 = cast<NamedDecl>(Context)->getIdentifier()) {
1281 mangleSourceName(Name);
1282 Out << 'M';
1283 }
1284 }
1285 }
1286
1287 Out << "Ul";
1288 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1289 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001290 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1291 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001292 Out << "E";
1293
1294 // The number is omitted for the first closure type with a given
1295 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1296 // (in lexical order) with that same <lambda-sig> and context.
1297 //
1298 // The AST keeps track of the number for us.
1299 unsigned Number = Lambda->getLambdaManglingNumber();
1300 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1301 if (Number > 1)
1302 mangleNumber(Number - 2);
1303 Out << '_';
1304}
1305
1306void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1307 switch (qualifier->getKind()) {
1308 case NestedNameSpecifier::Global:
1309 // nothing
1310 return;
1311
Nikola Smiljanic67860242014-09-26 00:28:20 +00001312 case NestedNameSpecifier::Super:
1313 llvm_unreachable("Can't mangle __super specifier");
1314
Guy Benyei11169dd2012-12-18 14:30:41 +00001315 case NestedNameSpecifier::Namespace:
1316 mangleName(qualifier->getAsNamespace());
1317 return;
1318
1319 case NestedNameSpecifier::NamespaceAlias:
1320 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1321 return;
1322
1323 case NestedNameSpecifier::TypeSpec:
1324 case NestedNameSpecifier::TypeSpecWithTemplate:
1325 manglePrefix(QualType(qualifier->getAsType(), 0));
1326 return;
1327
1328 case NestedNameSpecifier::Identifier:
1329 // Member expressions can have these without prefixes, but that
1330 // should end up in mangleUnresolvedPrefix instead.
1331 assert(qualifier->getPrefix());
1332 manglePrefix(qualifier->getPrefix());
1333
1334 mangleSourceName(qualifier->getAsIdentifier());
1335 return;
1336 }
1337
1338 llvm_unreachable("unexpected nested name specifier");
1339}
1340
1341void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1342 // <prefix> ::= <prefix> <unqualified-name>
1343 // ::= <template-prefix> <template-args>
1344 // ::= <template-param>
1345 // ::= # empty
1346 // ::= <substitution>
1347
1348 DC = IgnoreLinkageSpecDecls(DC);
1349
1350 if (DC->isTranslationUnit())
1351 return;
1352
Eli Friedman95f50122013-07-02 17:52:28 +00001353 if (NoFunction && isLocalContainerContext(DC))
1354 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001355
Eli Friedman95f50122013-07-02 17:52:28 +00001356 assert(!isLocalContainerContext(DC));
1357
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 const NamedDecl *ND = cast<NamedDecl>(DC);
1359 if (mangleSubstitution(ND))
1360 return;
1361
1362 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001363 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001364 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1365 mangleTemplatePrefix(TD);
1366 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001367 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1369 mangleUnqualifiedName(ND);
1370 }
1371
1372 addSubstitution(ND);
1373}
1374
1375void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1376 // <template-prefix> ::= <prefix> <template unqualified-name>
1377 // ::= <template-param>
1378 // ::= <substitution>
1379 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1380 return mangleTemplatePrefix(TD);
1381
1382 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1383 manglePrefix(Qualified->getQualifier());
1384
1385 if (OverloadedTemplateStorage *Overloaded
1386 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001387 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 UnknownArity);
1389 return;
1390 }
1391
1392 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1393 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001394 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1395 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 mangleUnscopedTemplateName(Template);
1397}
1398
Eli Friedman86af13f02013-07-05 18:41:30 +00001399void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1400 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 // <template-prefix> ::= <prefix> <template unqualified-name>
1402 // ::= <template-param>
1403 // ::= <substitution>
1404 // <template-template-param> ::= <template-param>
1405 // <substitution>
1406
1407 if (mangleSubstitution(ND))
1408 return;
1409
1410 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001411 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001413 } else {
1414 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1415 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 }
1417
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 addSubstitution(ND);
1419}
1420
1421/// Mangles a template name under the production <type>. Required for
1422/// template template arguments.
1423/// <type> ::= <class-enum-type>
1424/// ::= <template-param>
1425/// ::= <substitution>
1426void CXXNameMangler::mangleType(TemplateName TN) {
1427 if (mangleSubstitution(TN))
1428 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001429
1430 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001431
1432 switch (TN.getKind()) {
1433 case TemplateName::QualifiedTemplate:
1434 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1435 goto HaveDecl;
1436
1437 case TemplateName::Template:
1438 TD = TN.getAsTemplateDecl();
1439 goto HaveDecl;
1440
1441 HaveDecl:
1442 if (isa<TemplateTemplateParmDecl>(TD))
1443 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1444 else
1445 mangleName(TD);
1446 break;
1447
1448 case TemplateName::OverloadedTemplate:
1449 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1450
1451 case TemplateName::DependentTemplate: {
1452 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1453 assert(Dependent->isIdentifier());
1454
1455 // <class-enum-type> ::= <name>
1456 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001457 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 mangleSourceName(Dependent->getIdentifier());
1459 break;
1460 }
1461
1462 case TemplateName::SubstTemplateTemplateParm: {
1463 // Substituted template parameters are mangled as the substituted
1464 // template. This will check for the substitution twice, which is
1465 // fine, but we have to return early so that we don't try to *add*
1466 // the substitution twice.
1467 SubstTemplateTemplateParmStorage *subst
1468 = TN.getAsSubstTemplateTemplateParm();
1469 mangleType(subst->getReplacement());
1470 return;
1471 }
1472
1473 case TemplateName::SubstTemplateTemplateParmPack: {
1474 // FIXME: not clear how to mangle this!
1475 // template <template <class> class T...> class A {
1476 // template <template <class> class U...> void foo(B<T,U> x...);
1477 // };
1478 Out << "_SUBSTPACK_";
1479 break;
1480 }
1481 }
1482
1483 addSubstitution(TN);
1484}
1485
David Majnemerb8014dd2015-02-19 02:16:16 +00001486bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1487 StringRef Prefix) {
1488 // Only certain other types are valid as prefixes; enumerate them.
1489 switch (Ty->getTypeClass()) {
1490 case Type::Builtin:
1491 case Type::Complex:
1492 case Type::Adjusted:
1493 case Type::Decayed:
1494 case Type::Pointer:
1495 case Type::BlockPointer:
1496 case Type::LValueReference:
1497 case Type::RValueReference:
1498 case Type::MemberPointer:
1499 case Type::ConstantArray:
1500 case Type::IncompleteArray:
1501 case Type::VariableArray:
1502 case Type::DependentSizedArray:
1503 case Type::DependentSizedExtVector:
1504 case Type::Vector:
1505 case Type::ExtVector:
1506 case Type::FunctionProto:
1507 case Type::FunctionNoProto:
1508 case Type::Paren:
1509 case Type::Attributed:
1510 case Type::Auto:
1511 case Type::PackExpansion:
1512 case Type::ObjCObject:
1513 case Type::ObjCInterface:
1514 case Type::ObjCObjectPointer:
1515 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001516 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001517 llvm_unreachable("type is illegal as a nested name specifier");
1518
1519 case Type::SubstTemplateTypeParmPack:
1520 // FIXME: not clear how to mangle this!
1521 // template <class T...> class A {
1522 // template <class U...> void foo(decltype(T::foo(U())) x...);
1523 // };
1524 Out << "_SUBSTPACK_";
1525 break;
1526
1527 // <unresolved-type> ::= <template-param>
1528 // ::= <decltype>
1529 // ::= <template-template-param> <template-args>
1530 // (this last is not official yet)
1531 case Type::TypeOfExpr:
1532 case Type::TypeOf:
1533 case Type::Decltype:
1534 case Type::TemplateTypeParm:
1535 case Type::UnaryTransform:
1536 case Type::SubstTemplateTypeParm:
1537 unresolvedType:
1538 // Some callers want a prefix before the mangled type.
1539 Out << Prefix;
1540
1541 // This seems to do everything we want. It's not really
1542 // sanctioned for a substituted template parameter, though.
1543 mangleType(Ty);
1544
1545 // We never want to print 'E' directly after an unresolved-type,
1546 // so we return directly.
1547 return true;
1548
1549 case Type::Typedef:
1550 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1551 break;
1552
1553 case Type::UnresolvedUsing:
1554 mangleSourceName(
1555 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1556 break;
1557
1558 case Type::Enum:
1559 case Type::Record:
1560 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1561 break;
1562
1563 case Type::TemplateSpecialization: {
1564 const TemplateSpecializationType *TST =
1565 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001566 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001567 switch (TN.getKind()) {
1568 case TemplateName::Template:
1569 case TemplateName::QualifiedTemplate: {
1570 TemplateDecl *TD = TN.getAsTemplateDecl();
1571
1572 // If the base is a template template parameter, this is an
1573 // unresolved type.
1574 assert(TD && "no template for template specialization type");
1575 if (isa<TemplateTemplateParmDecl>(TD))
1576 goto unresolvedType;
1577
1578 mangleSourceName(TD->getIdentifier());
1579 break;
David Majnemera88b3592015-02-18 02:28:01 +00001580 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001581
1582 case TemplateName::OverloadedTemplate:
1583 case TemplateName::DependentTemplate:
1584 llvm_unreachable("invalid base for a template specialization type");
1585
1586 case TemplateName::SubstTemplateTemplateParm: {
1587 SubstTemplateTemplateParmStorage *subst =
1588 TN.getAsSubstTemplateTemplateParm();
1589 mangleExistingSubstitution(subst->getReplacement());
1590 break;
1591 }
1592
1593 case TemplateName::SubstTemplateTemplateParmPack: {
1594 // FIXME: not clear how to mangle this!
1595 // template <template <class U> class T...> class A {
1596 // template <class U...> void foo(decltype(T<U>::foo) x...);
1597 // };
1598 Out << "_SUBSTPACK_";
1599 break;
1600 }
1601 }
1602
David Majnemera88b3592015-02-18 02:28:01 +00001603 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001604 break;
David Majnemera88b3592015-02-18 02:28:01 +00001605 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001606
1607 case Type::InjectedClassName:
1608 mangleSourceName(
1609 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1610 break;
1611
1612 case Type::DependentName:
1613 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1614 break;
1615
1616 case Type::DependentTemplateSpecialization: {
1617 const DependentTemplateSpecializationType *DTST =
1618 cast<DependentTemplateSpecializationType>(Ty);
1619 mangleSourceName(DTST->getIdentifier());
1620 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1621 break;
1622 }
1623
1624 case Type::Elaborated:
1625 return mangleUnresolvedTypeOrSimpleId(
1626 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1627 }
1628
1629 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001630}
1631
1632void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1633 switch (Name.getNameKind()) {
1634 case DeclarationName::CXXConstructorName:
1635 case DeclarationName::CXXDestructorName:
1636 case DeclarationName::CXXUsingDirective:
1637 case DeclarationName::Identifier:
1638 case DeclarationName::ObjCMultiArgSelector:
1639 case DeclarationName::ObjCOneArgSelector:
1640 case DeclarationName::ObjCZeroArgSelector:
1641 llvm_unreachable("Not an operator name");
1642
1643 case DeclarationName::CXXConversionFunctionName:
1644 // <operator-name> ::= cv <type> # (cast)
1645 Out << "cv";
1646 mangleType(Name.getCXXNameType());
1647 break;
1648
1649 case DeclarationName::CXXLiteralOperatorName:
1650 Out << "li";
1651 mangleSourceName(Name.getCXXLiteralIdentifier());
1652 return;
1653
1654 case DeclarationName::CXXOperatorName:
1655 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1656 break;
1657 }
1658}
1659
1660
1661
Guy Benyei11169dd2012-12-18 14:30:41 +00001662void
1663CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1664 switch (OO) {
1665 // <operator-name> ::= nw # new
1666 case OO_New: Out << "nw"; break;
1667 // ::= na # new[]
1668 case OO_Array_New: Out << "na"; break;
1669 // ::= dl # delete
1670 case OO_Delete: Out << "dl"; break;
1671 // ::= da # delete[]
1672 case OO_Array_Delete: Out << "da"; break;
1673 // ::= ps # + (unary)
1674 // ::= pl # + (binary or unknown)
1675 case OO_Plus:
1676 Out << (Arity == 1? "ps" : "pl"); break;
1677 // ::= ng # - (unary)
1678 // ::= mi # - (binary or unknown)
1679 case OO_Minus:
1680 Out << (Arity == 1? "ng" : "mi"); break;
1681 // ::= ad # & (unary)
1682 // ::= an # & (binary or unknown)
1683 case OO_Amp:
1684 Out << (Arity == 1? "ad" : "an"); break;
1685 // ::= de # * (unary)
1686 // ::= ml # * (binary or unknown)
1687 case OO_Star:
1688 // Use binary when unknown.
1689 Out << (Arity == 1? "de" : "ml"); break;
1690 // ::= co # ~
1691 case OO_Tilde: Out << "co"; break;
1692 // ::= dv # /
1693 case OO_Slash: Out << "dv"; break;
1694 // ::= rm # %
1695 case OO_Percent: Out << "rm"; break;
1696 // ::= or # |
1697 case OO_Pipe: Out << "or"; break;
1698 // ::= eo # ^
1699 case OO_Caret: Out << "eo"; break;
1700 // ::= aS # =
1701 case OO_Equal: Out << "aS"; break;
1702 // ::= pL # +=
1703 case OO_PlusEqual: Out << "pL"; break;
1704 // ::= mI # -=
1705 case OO_MinusEqual: Out << "mI"; break;
1706 // ::= mL # *=
1707 case OO_StarEqual: Out << "mL"; break;
1708 // ::= dV # /=
1709 case OO_SlashEqual: Out << "dV"; break;
1710 // ::= rM # %=
1711 case OO_PercentEqual: Out << "rM"; break;
1712 // ::= aN # &=
1713 case OO_AmpEqual: Out << "aN"; break;
1714 // ::= oR # |=
1715 case OO_PipeEqual: Out << "oR"; break;
1716 // ::= eO # ^=
1717 case OO_CaretEqual: Out << "eO"; break;
1718 // ::= ls # <<
1719 case OO_LessLess: Out << "ls"; break;
1720 // ::= rs # >>
1721 case OO_GreaterGreater: Out << "rs"; break;
1722 // ::= lS # <<=
1723 case OO_LessLessEqual: Out << "lS"; break;
1724 // ::= rS # >>=
1725 case OO_GreaterGreaterEqual: Out << "rS"; break;
1726 // ::= eq # ==
1727 case OO_EqualEqual: Out << "eq"; break;
1728 // ::= ne # !=
1729 case OO_ExclaimEqual: Out << "ne"; break;
1730 // ::= lt # <
1731 case OO_Less: Out << "lt"; break;
1732 // ::= gt # >
1733 case OO_Greater: Out << "gt"; break;
1734 // ::= le # <=
1735 case OO_LessEqual: Out << "le"; break;
1736 // ::= ge # >=
1737 case OO_GreaterEqual: Out << "ge"; break;
1738 // ::= nt # !
1739 case OO_Exclaim: Out << "nt"; break;
1740 // ::= aa # &&
1741 case OO_AmpAmp: Out << "aa"; break;
1742 // ::= oo # ||
1743 case OO_PipePipe: Out << "oo"; break;
1744 // ::= pp # ++
1745 case OO_PlusPlus: Out << "pp"; break;
1746 // ::= mm # --
1747 case OO_MinusMinus: Out << "mm"; break;
1748 // ::= cm # ,
1749 case OO_Comma: Out << "cm"; break;
1750 // ::= pm # ->*
1751 case OO_ArrowStar: Out << "pm"; break;
1752 // ::= pt # ->
1753 case OO_Arrow: Out << "pt"; break;
1754 // ::= cl # ()
1755 case OO_Call: Out << "cl"; break;
1756 // ::= ix # []
1757 case OO_Subscript: Out << "ix"; break;
1758
1759 // ::= qu # ?
1760 // The conditional operator can't be overloaded, but we still handle it when
1761 // mangling expressions.
1762 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00001763 // Proposal on cxx-abi-dev, 2015-10-21.
1764 // ::= aw # co_await
1765 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001766
1767 case OO_None:
1768 case NUM_OVERLOADED_OPERATORS:
1769 llvm_unreachable("Not an overloaded operator");
1770 }
1771}
1772
1773void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
John McCall07daf722016-03-01 22:18:03 +00001774 // Vendor qualifiers come first.
Guy Benyei11169dd2012-12-18 14:30:41 +00001775
John McCall07daf722016-03-01 22:18:03 +00001776 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001778 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 //
David Tweed31d09b02013-09-13 12:04:22 +00001780 // <type> ::= U <target-addrspace>
1781 // <type> ::= U <OpenCL-addrspace>
1782 // <type> ::= U <CUDA-addrspace>
1783
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001785 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001786
1787 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1788 // <target-addrspace> ::= "AS" <address-space-number>
1789 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00001790 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00001791 } else {
1792 switch (AS) {
1793 default: llvm_unreachable("Not a language specific address space");
1794 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1795 case LangAS::opencl_global: ASString = "CLglobal"; break;
1796 case LangAS::opencl_local: ASString = "CLlocal"; break;
1797 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1798 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1799 case LangAS::cuda_device: ASString = "CUdevice"; break;
1800 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1801 case LangAS::cuda_shared: ASString = "CUshared"; break;
1802 }
1803 }
John McCall07daf722016-03-01 22:18:03 +00001804 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 }
John McCall07daf722016-03-01 22:18:03 +00001806
1807 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 switch (Quals.getObjCLifetime()) {
1809 // Objective-C ARC Extension:
1810 //
1811 // <type> ::= U "__strong"
1812 // <type> ::= U "__weak"
1813 // <type> ::= U "__autoreleasing"
1814 case Qualifiers::OCL_None:
1815 break;
1816
1817 case Qualifiers::OCL_Weak:
John McCall07daf722016-03-01 22:18:03 +00001818 mangleVendorQualifier("__weak");
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 break;
1820
1821 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00001822 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 break;
1824
1825 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00001826 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 break;
1828
1829 case Qualifiers::OCL_ExplicitNone:
1830 // The __unsafe_unretained qualifier is *not* mangled, so that
1831 // __unsafe_unretained types in ARC produce the same manglings as the
1832 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1833 // better ABI compatibility.
1834 //
1835 // It's safe to do this because unqualified 'id' won't show up
1836 // in any type signatures that need to be mangled.
1837 break;
1838 }
John McCall07daf722016-03-01 22:18:03 +00001839
1840 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1841 if (Quals.hasRestrict())
1842 Out << 'r';
1843 if (Quals.hasVolatile())
1844 Out << 'V';
1845 if (Quals.hasConst())
1846 Out << 'K';
1847}
1848
1849void CXXNameMangler::mangleVendorQualifier(StringRef name) {
1850 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00001851}
1852
1853void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1854 // <ref-qualifier> ::= R # lvalue reference
1855 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 switch (RefQualifier) {
1857 case RQ_None:
1858 break;
1859
1860 case RQ_LValue:
1861 Out << 'R';
1862 break;
1863
1864 case RQ_RValue:
1865 Out << 'O';
1866 break;
1867 }
1868}
1869
1870void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1871 Context.mangleObjCMethodName(MD, Out);
1872}
1873
David Majnemereea02ee2014-11-28 22:22:46 +00001874static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1875 if (Quals)
1876 return true;
1877 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1878 return true;
1879 if (Ty->isOpenCLSpecificType())
1880 return true;
1881 if (Ty->isBuiltinType())
1882 return false;
1883
1884 return true;
1885}
1886
Guy Benyei11169dd2012-12-18 14:30:41 +00001887void CXXNameMangler::mangleType(QualType T) {
1888 // If our type is instantiation-dependent but not dependent, we mangle
1889 // it as it was written in the source, removing any top-level sugar.
1890 // Otherwise, use the canonical type.
1891 //
1892 // FIXME: This is an approximation of the instantiation-dependent name
1893 // mangling rules, since we should really be using the type as written and
1894 // augmented via semantic analysis (i.e., with implicit conversions and
1895 // default template arguments) for any instantiation-dependent type.
1896 // Unfortunately, that requires several changes to our AST:
1897 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1898 // uniqued, so that we can handle substitutions properly
1899 // - Default template arguments will need to be represented in the
1900 // TemplateSpecializationType, since they need to be mangled even though
1901 // they aren't written.
1902 // - Conversions on non-type template arguments need to be expressed, since
1903 // they can affect the mangling of sizeof/alignof.
1904 if (!T->isInstantiationDependentType() || T->isDependentType())
1905 T = T.getCanonicalType();
1906 else {
1907 // Desugar any types that are purely sugar.
1908 do {
1909 // Don't desugar through template specialization types that aren't
1910 // type aliases. We need to mangle the template arguments as written.
1911 if (const TemplateSpecializationType *TST
1912 = dyn_cast<TemplateSpecializationType>(T))
1913 if (!TST->isTypeAlias())
1914 break;
1915
1916 QualType Desugared
1917 = T.getSingleStepDesugaredType(Context.getASTContext());
1918 if (Desugared == T)
1919 break;
1920
1921 T = Desugared;
1922 } while (true);
1923 }
1924 SplitQualType split = T.split();
1925 Qualifiers quals = split.Quals;
1926 const Type *ty = split.Ty;
1927
David Majnemereea02ee2014-11-28 22:22:46 +00001928 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 if (isSubstitutable && mangleSubstitution(T))
1930 return;
1931
1932 // If we're mangling a qualified array type, push the qualifiers to
1933 // the element type.
1934 if (quals && isa<ArrayType>(T)) {
1935 ty = Context.getASTContext().getAsArrayType(T);
1936 quals = Qualifiers();
1937
1938 // Note that we don't update T: we want to add the
1939 // substitution at the original type.
1940 }
1941
1942 if (quals) {
1943 mangleQualifiers(quals);
1944 // Recurse: even if the qualified type isn't yet substitutable,
1945 // the unqualified type might be.
1946 mangleType(QualType(ty, 0));
1947 } else {
1948 switch (ty->getTypeClass()) {
1949#define ABSTRACT_TYPE(CLASS, PARENT)
1950#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1951 case Type::CLASS: \
1952 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1953 return;
1954#define TYPE(CLASS, PARENT) \
1955 case Type::CLASS: \
1956 mangleType(static_cast<const CLASS##Type*>(ty)); \
1957 break;
1958#include "clang/AST/TypeNodes.def"
1959 }
1960 }
1961
1962 // Add the substitution.
1963 if (isSubstitutable)
1964 addSubstitution(T);
1965}
1966
1967void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1968 if (!mangleStandardSubstitution(ND))
1969 mangleName(ND);
1970}
1971
1972void CXXNameMangler::mangleType(const BuiltinType *T) {
1973 // <type> ::= <builtin-type>
1974 // <builtin-type> ::= v # void
1975 // ::= w # wchar_t
1976 // ::= b # bool
1977 // ::= c # char
1978 // ::= a # signed char
1979 // ::= h # unsigned char
1980 // ::= s # short
1981 // ::= t # unsigned short
1982 // ::= i # int
1983 // ::= j # unsigned int
1984 // ::= l # long
1985 // ::= m # unsigned long
1986 // ::= x # long long, __int64
1987 // ::= y # unsigned long long, __int64
1988 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001989 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 // ::= f # float
1991 // ::= d # double
1992 // ::= e # long double, __float80
1993 // UNSUPPORTED: ::= g # __float128
1994 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1995 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1996 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1997 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1998 // ::= Di # char32_t
1999 // ::= Ds # char16_t
2000 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2001 // ::= u <source-name> # vendor extended type
2002 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002003 case BuiltinType::Void:
2004 Out << 'v';
2005 break;
2006 case BuiltinType::Bool:
2007 Out << 'b';
2008 break;
2009 case BuiltinType::Char_U:
2010 case BuiltinType::Char_S:
2011 Out << 'c';
2012 break;
2013 case BuiltinType::UChar:
2014 Out << 'h';
2015 break;
2016 case BuiltinType::UShort:
2017 Out << 't';
2018 break;
2019 case BuiltinType::UInt:
2020 Out << 'j';
2021 break;
2022 case BuiltinType::ULong:
2023 Out << 'm';
2024 break;
2025 case BuiltinType::ULongLong:
2026 Out << 'y';
2027 break;
2028 case BuiltinType::UInt128:
2029 Out << 'o';
2030 break;
2031 case BuiltinType::SChar:
2032 Out << 'a';
2033 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002035 case BuiltinType::WChar_U:
2036 Out << 'w';
2037 break;
2038 case BuiltinType::Char16:
2039 Out << "Ds";
2040 break;
2041 case BuiltinType::Char32:
2042 Out << "Di";
2043 break;
2044 case BuiltinType::Short:
2045 Out << 's';
2046 break;
2047 case BuiltinType::Int:
2048 Out << 'i';
2049 break;
2050 case BuiltinType::Long:
2051 Out << 'l';
2052 break;
2053 case BuiltinType::LongLong:
2054 Out << 'x';
2055 break;
2056 case BuiltinType::Int128:
2057 Out << 'n';
2058 break;
2059 case BuiltinType::Half:
2060 Out << "Dh";
2061 break;
2062 case BuiltinType::Float:
2063 Out << 'f';
2064 break;
2065 case BuiltinType::Double:
2066 Out << 'd';
2067 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002068 case BuiltinType::LongDouble:
2069 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2070 ? 'g'
2071 : 'e');
2072 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002073 case BuiltinType::NullPtr:
2074 Out << "Dn";
2075 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002076
2077#define BUILTIN_TYPE(Id, SingletonId)
2078#define PLACEHOLDER_TYPE(Id, SingletonId) \
2079 case BuiltinType::Id:
2080#include "clang/AST/BuiltinTypes.def"
2081 case BuiltinType::Dependent:
2082 llvm_unreachable("mangling a placeholder type");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002083 case BuiltinType::ObjCId:
2084 Out << "11objc_object";
2085 break;
2086 case BuiltinType::ObjCClass:
2087 Out << "10objc_class";
2088 break;
2089 case BuiltinType::ObjCSel:
2090 Out << "13objc_selector";
2091 break;
2092 case BuiltinType::OCLImage1d:
2093 Out << "11ocl_image1d";
2094 break;
2095 case BuiltinType::OCLImage1dArray:
2096 Out << "16ocl_image1darray";
2097 break;
2098 case BuiltinType::OCLImage1dBuffer:
2099 Out << "17ocl_image1dbuffer";
2100 break;
2101 case BuiltinType::OCLImage2d:
2102 Out << "11ocl_image2d";
2103 break;
2104 case BuiltinType::OCLImage2dArray:
2105 Out << "16ocl_image2darray";
2106 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002107 case BuiltinType::OCLImage2dDepth:
2108 Out << "16ocl_image2ddepth";
2109 break;
2110 case BuiltinType::OCLImage2dArrayDepth:
2111 Out << "21ocl_image2darraydepth";
2112 break;
2113 case BuiltinType::OCLImage2dMSAA:
2114 Out << "15ocl_image2dmsaa";
2115 break;
2116 case BuiltinType::OCLImage2dArrayMSAA:
2117 Out << "20ocl_image2darraymsaa";
2118 break;
2119 case BuiltinType::OCLImage2dMSAADepth:
2120 Out << "20ocl_image2dmsaadepth";
2121 break;
2122 case BuiltinType::OCLImage2dArrayMSAADepth:
Richard Smith8467c872016-02-03 01:43:59 +00002123 Out << "25ocl_image2darraymsaadepth";
Alexey Bader9c8453f2015-09-15 11:18:52 +00002124 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002125 case BuiltinType::OCLImage3d:
2126 Out << "11ocl_image3d";
2127 break;
2128 case BuiltinType::OCLSampler:
2129 Out << "11ocl_sampler";
2130 break;
2131 case BuiltinType::OCLEvent:
2132 Out << "9ocl_event";
2133 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002134 case BuiltinType::OCLClkEvent:
2135 Out << "12ocl_clkevent";
2136 break;
2137 case BuiltinType::OCLQueue:
2138 Out << "9ocl_queue";
2139 break;
2140 case BuiltinType::OCLNDRange:
2141 Out << "11ocl_ndrange";
2142 break;
2143 case BuiltinType::OCLReserveID:
2144 Out << "13ocl_reserveid";
2145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 }
2147}
2148
John McCall07daf722016-03-01 22:18:03 +00002149StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2150 switch (CC) {
2151 case CC_C:
2152 return "";
2153
2154 case CC_X86StdCall:
2155 case CC_X86FastCall:
2156 case CC_X86ThisCall:
2157 case CC_X86VectorCall:
2158 case CC_X86Pascal:
2159 case CC_X86_64Win64:
2160 case CC_X86_64SysV:
2161 case CC_AAPCS:
2162 case CC_AAPCS_VFP:
2163 case CC_IntelOclBicc:
2164 case CC_SpirFunction:
2165 case CC_SpirKernel:
2166 // FIXME: we should be mangling all of the above.
2167 return "";
2168 }
2169 llvm_unreachable("bad calling convention");
2170}
2171
2172void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2173 // Fast path.
2174 if (T->getExtInfo() == FunctionType::ExtInfo())
2175 return;
2176
2177 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2178 // This will get more complicated in the future if we mangle other
2179 // things here; but for now, since we mangle ns_returns_retained as
2180 // a qualifier on the result type, we can get away with this:
2181 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2182 if (!CCQualifier.empty())
2183 mangleVendorQualifier(CCQualifier);
2184
2185 // FIXME: regparm
2186 // FIXME: noreturn
2187}
2188
2189void
2190CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2191 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2192
2193 // Note that these are *not* substitution candidates. Demanglers might
2194 // have trouble with this if the parameter type is fully substituted.
2195
2196 if (PI.isConsumed())
2197 Out << "U11ns_consumed";
2198}
2199
Guy Benyei11169dd2012-12-18 14:30:41 +00002200// <type> ::= <function-type>
2201// <function-type> ::= [<CV-qualifiers>] F [Y]
2202// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002203void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002204 mangleExtFunctionInfo(T);
2205
Guy Benyei11169dd2012-12-18 14:30:41 +00002206 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2207 // e.g. "const" in "int (A::*)() const".
2208 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2209
2210 Out << 'F';
2211
2212 // FIXME: We don't have enough information in the AST to produce the 'Y'
2213 // encoding for extern "C" function types.
2214 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2215
2216 // Mangle the ref-qualifier, if present.
2217 mangleRefQualifier(T->getRefQualifier());
2218
2219 Out << 'E';
2220}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002221
Guy Benyei11169dd2012-12-18 14:30:41 +00002222void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002223 // Function types without prototypes can arise when mangling a function type
2224 // within an overloadable function in C. We mangle these as the absence of any
2225 // parameter types (not even an empty parameter list).
2226 Out << 'F';
2227
2228 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2229
2230 FunctionTypeDepth.enterResultType();
2231 mangleType(T->getReturnType());
2232 FunctionTypeDepth.leaveResultType();
2233
2234 FunctionTypeDepth.pop(saved);
2235 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002236}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002237
John McCall07daf722016-03-01 22:18:03 +00002238void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002239 bool MangleReturnType,
2240 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 // Record that we're in a function type. See mangleFunctionParam
2242 // for details on what we're trying to achieve here.
2243 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2244
2245 // <bare-function-type> ::= <signature type>+
2246 if (MangleReturnType) {
2247 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002248
2249 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2250 if (Proto->getExtInfo().getProducesResult())
2251 mangleVendorQualifier("ns_returns_retained");
2252
2253 // Mangle the return type without any direct ARC ownership qualifiers.
2254 QualType ReturnTy = Proto->getReturnType();
2255 if (ReturnTy.getObjCLifetime()) {
2256 auto SplitReturnTy = ReturnTy.split();
2257 SplitReturnTy.Quals.removeObjCLifetime();
2258 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2259 }
2260 mangleType(ReturnTy);
2261
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 FunctionTypeDepth.leaveResultType();
2263 }
2264
Alp Toker9cacbab2014-01-20 20:26:09 +00002265 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 // <builtin-type> ::= v # void
2267 Out << 'v';
2268
2269 FunctionTypeDepth.pop(saved);
2270 return;
2271 }
2272
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002273 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2274 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002275 // Mangle extended parameter info as order-sensitive qualifiers here.
2276 if (Proto->hasExtParameterInfos()) {
2277 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2278 }
2279
2280 // Mangle the type.
2281 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002282 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2283
2284 if (FD) {
2285 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2286 // Attr can only take 1 character, so we can hardcode the length below.
2287 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2288 Out << "U17pass_object_size" << Attr->getType();
2289 }
2290 }
2291 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002292
2293 FunctionTypeDepth.pop(saved);
2294
2295 // <builtin-type> ::= z # ellipsis
2296 if (Proto->isVariadic())
2297 Out << 'z';
2298}
2299
2300// <type> ::= <class-enum-type>
2301// <class-enum-type> ::= <name>
2302void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2303 mangleName(T->getDecl());
2304}
2305
2306// <type> ::= <class-enum-type>
2307// <class-enum-type> ::= <name>
2308void CXXNameMangler::mangleType(const EnumType *T) {
2309 mangleType(static_cast<const TagType*>(T));
2310}
2311void CXXNameMangler::mangleType(const RecordType *T) {
2312 mangleType(static_cast<const TagType*>(T));
2313}
2314void CXXNameMangler::mangleType(const TagType *T) {
2315 mangleName(T->getDecl());
2316}
2317
2318// <type> ::= <array-type>
2319// <array-type> ::= A <positive dimension number> _ <element type>
2320// ::= A [<dimension expression>] _ <element type>
2321void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2322 Out << 'A' << T->getSize() << '_';
2323 mangleType(T->getElementType());
2324}
2325void CXXNameMangler::mangleType(const VariableArrayType *T) {
2326 Out << 'A';
2327 // decayed vla types (size 0) will just be skipped.
2328 if (T->getSizeExpr())
2329 mangleExpression(T->getSizeExpr());
2330 Out << '_';
2331 mangleType(T->getElementType());
2332}
2333void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2334 Out << 'A';
2335 mangleExpression(T->getSizeExpr());
2336 Out << '_';
2337 mangleType(T->getElementType());
2338}
2339void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2340 Out << "A_";
2341 mangleType(T->getElementType());
2342}
2343
2344// <type> ::= <pointer-to-member-type>
2345// <pointer-to-member-type> ::= M <class type> <member type>
2346void CXXNameMangler::mangleType(const MemberPointerType *T) {
2347 Out << 'M';
2348 mangleType(QualType(T->getClass(), 0));
2349 QualType PointeeType = T->getPointeeType();
2350 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2351 mangleType(FPT);
2352
2353 // Itanium C++ ABI 5.1.8:
2354 //
2355 // The type of a non-static member function is considered to be different,
2356 // for the purposes of substitution, from the type of a namespace-scope or
2357 // static member function whose type appears similar. The types of two
2358 // non-static member functions are considered to be different, for the
2359 // purposes of substitution, if the functions are members of different
2360 // classes. In other words, for the purposes of substitution, the class of
2361 // which the function is a member is considered part of the type of
2362 // function.
2363
2364 // Given that we already substitute member function pointers as a
2365 // whole, the net effect of this rule is just to unconditionally
2366 // suppress substitution on the function type in a member pointer.
2367 // We increment the SeqID here to emulate adding an entry to the
2368 // substitution table.
2369 ++SeqID;
2370 } else
2371 mangleType(PointeeType);
2372}
2373
2374// <type> ::= <template-param>
2375void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2376 mangleTemplateParameter(T->getIndex());
2377}
2378
2379// <type> ::= <template-param>
2380void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2381 // FIXME: not clear how to mangle this!
2382 // template <class T...> class A {
2383 // template <class U...> void foo(T(*)(U) x...);
2384 // };
2385 Out << "_SUBSTPACK_";
2386}
2387
2388// <type> ::= P <type> # pointer-to
2389void CXXNameMangler::mangleType(const PointerType *T) {
2390 Out << 'P';
2391 mangleType(T->getPointeeType());
2392}
2393void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2394 Out << 'P';
2395 mangleType(T->getPointeeType());
2396}
2397
2398// <type> ::= R <type> # reference-to
2399void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2400 Out << 'R';
2401 mangleType(T->getPointeeType());
2402}
2403
2404// <type> ::= O <type> # rvalue reference-to (C++0x)
2405void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2406 Out << 'O';
2407 mangleType(T->getPointeeType());
2408}
2409
2410// <type> ::= C <type> # complex pair (C 2000)
2411void CXXNameMangler::mangleType(const ComplexType *T) {
2412 Out << 'C';
2413 mangleType(T->getElementType());
2414}
2415
2416// ARM's ABI for Neon vector types specifies that they should be mangled as
2417// if they are structs (to match ARM's initial implementation). The
2418// vector type must be one of the special types predefined by ARM.
2419void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2420 QualType EltType = T->getElementType();
2421 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002422 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2424 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002425 case BuiltinType::SChar:
2426 case BuiltinType::UChar:
2427 EltName = "poly8_t";
2428 break;
2429 case BuiltinType::Short:
2430 case BuiltinType::UShort:
2431 EltName = "poly16_t";
2432 break;
2433 case BuiltinType::ULongLong:
2434 EltName = "poly64_t";
2435 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2437 }
2438 } else {
2439 switch (cast<BuiltinType>(EltType)->getKind()) {
2440 case BuiltinType::SChar: EltName = "int8_t"; break;
2441 case BuiltinType::UChar: EltName = "uint8_t"; break;
2442 case BuiltinType::Short: EltName = "int16_t"; break;
2443 case BuiltinType::UShort: EltName = "uint16_t"; break;
2444 case BuiltinType::Int: EltName = "int32_t"; break;
2445 case BuiltinType::UInt: EltName = "uint32_t"; break;
2446 case BuiltinType::LongLong: EltName = "int64_t"; break;
2447 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002448 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002450 case BuiltinType::Half: EltName = "float16_t";break;
2451 default:
2452 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 }
2454 }
Craig Topper36250ad2014-05-12 05:36:57 +00002455 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 unsigned BitSize = (T->getNumElements() *
2457 getASTContext().getTypeSize(EltType));
2458 if (BitSize == 64)
2459 BaseName = "__simd64_";
2460 else {
2461 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2462 BaseName = "__simd128_";
2463 }
2464 Out << strlen(BaseName) + strlen(EltName);
2465 Out << BaseName << EltName;
2466}
2467
Tim Northover2fe823a2013-08-01 09:23:19 +00002468static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2469 switch (EltType->getKind()) {
2470 case BuiltinType::SChar:
2471 return "Int8";
2472 case BuiltinType::Short:
2473 return "Int16";
2474 case BuiltinType::Int:
2475 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002476 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002477 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002478 return "Int64";
2479 case BuiltinType::UChar:
2480 return "Uint8";
2481 case BuiltinType::UShort:
2482 return "Uint16";
2483 case BuiltinType::UInt:
2484 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002485 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002486 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002487 return "Uint64";
2488 case BuiltinType::Half:
2489 return "Float16";
2490 case BuiltinType::Float:
2491 return "Float32";
2492 case BuiltinType::Double:
2493 return "Float64";
2494 default:
2495 llvm_unreachable("Unexpected vector element base type");
2496 }
2497}
2498
2499// AArch64's ABI for Neon vector types specifies that they should be mangled as
2500// the equivalent internal name. The vector type must be one of the special
2501// types predefined by ARM.
2502void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2503 QualType EltType = T->getElementType();
2504 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2505 unsigned BitSize =
2506 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002507 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002508
2509 assert((BitSize == 64 || BitSize == 128) &&
2510 "Neon vector type not 64 or 128 bits");
2511
Tim Northover2fe823a2013-08-01 09:23:19 +00002512 StringRef EltName;
2513 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2514 switch (cast<BuiltinType>(EltType)->getKind()) {
2515 case BuiltinType::UChar:
2516 EltName = "Poly8";
2517 break;
2518 case BuiltinType::UShort:
2519 EltName = "Poly16";
2520 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002521 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002522 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002523 EltName = "Poly64";
2524 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002525 default:
2526 llvm_unreachable("unexpected Neon polynomial vector element type");
2527 }
2528 } else
2529 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2530
2531 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00002532 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00002533 Out << TypeName.length() << TypeName;
2534}
2535
Guy Benyei11169dd2012-12-18 14:30:41 +00002536// GNU extension: vector types
2537// <type> ::= <vector-type>
2538// <vector-type> ::= Dv <positive dimension number> _
2539// <extended element type>
2540// ::= Dv [<dimension expression>] _ <element type>
2541// <extended element type> ::= <element type>
2542// ::= p # AltiVec vector pixel
2543// ::= b # Altivec vector bool
2544void CXXNameMangler::mangleType(const VectorType *T) {
2545 if ((T->getVectorKind() == VectorType::NeonVector ||
2546 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002547 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002548 llvm::Triple::ArchType Arch =
2549 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002550 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002551 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002552 mangleAArch64NeonVectorType(T);
2553 else
2554 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 return;
2556 }
2557 Out << "Dv" << T->getNumElements() << '_';
2558 if (T->getVectorKind() == VectorType::AltiVecPixel)
2559 Out << 'p';
2560 else if (T->getVectorKind() == VectorType::AltiVecBool)
2561 Out << 'b';
2562 else
2563 mangleType(T->getElementType());
2564}
2565void CXXNameMangler::mangleType(const ExtVectorType *T) {
2566 mangleType(static_cast<const VectorType*>(T));
2567}
2568void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2569 Out << "Dv";
2570 mangleExpression(T->getSizeExpr());
2571 Out << '_';
2572 mangleType(T->getElementType());
2573}
2574
2575void CXXNameMangler::mangleType(const PackExpansionType *T) {
2576 // <type> ::= Dp <type> # pack expansion (C++0x)
2577 Out << "Dp";
2578 mangleType(T->getPattern());
2579}
2580
2581void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2582 mangleSourceName(T->getDecl()->getIdentifier());
2583}
2584
2585void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002586 // Treat __kindof as a vendor extended type qualifier.
2587 if (T->isKindOfType())
2588 Out << "U8__kindof";
2589
Eli Friedman5f508952013-06-18 22:41:37 +00002590 if (!T->qual_empty()) {
2591 // Mangle protocol qualifiers.
2592 SmallString<64> QualStr;
2593 llvm::raw_svector_ostream QualOS(QualStr);
2594 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002595 for (const auto *I : T->quals()) {
2596 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002597 QualOS << name.size() << name;
2598 }
Eli Friedman5f508952013-06-18 22:41:37 +00002599 Out << 'U' << QualStr.size() << QualStr;
2600 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002603
2604 if (T->isSpecialized()) {
2605 // Mangle type arguments as I <type>+ E
2606 Out << 'I';
2607 for (auto typeArg : T->getTypeArgs())
2608 mangleType(typeArg);
2609 Out << 'E';
2610 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002611}
2612
2613void CXXNameMangler::mangleType(const BlockPointerType *T) {
2614 Out << "U13block_pointer";
2615 mangleType(T->getPointeeType());
2616}
2617
2618void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2619 // Mangle injected class name types as if the user had written the
2620 // specialization out fully. It may not actually be possible to see
2621 // this mangling, though.
2622 mangleType(T->getInjectedSpecializationType());
2623}
2624
2625void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2626 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2627 mangleName(TD, T->getArgs(), T->getNumArgs());
2628 } else {
2629 if (mangleSubstitution(QualType(T, 0)))
2630 return;
2631
2632 mangleTemplatePrefix(T->getTemplateName());
2633
2634 // FIXME: GCC does not appear to mangle the template arguments when
2635 // the template in question is a dependent template name. Should we
2636 // emulate that badness?
2637 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2638 addSubstitution(QualType(T, 0));
2639 }
2640}
2641
2642void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002643 // Proposal by cxx-abi-dev, 2014-03-26
2644 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2645 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002646 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002647 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002648 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002649 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002650 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002651 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002652 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002653 switch (T->getKeyword()) {
2654 case ETK_Typename:
2655 break;
2656 case ETK_Struct:
2657 case ETK_Class:
2658 case ETK_Interface:
2659 Out << "Ts";
2660 break;
2661 case ETK_Union:
2662 Out << "Tu";
2663 break;
2664 case ETK_Enum:
2665 Out << "Te";
2666 break;
2667 default:
2668 llvm_unreachable("unexpected keyword for dependent type name");
2669 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002670 // Typename types are always nested
2671 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002673 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 Out << 'E';
2675}
2676
2677void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2678 // Dependently-scoped template types are nested if they have a prefix.
2679 Out << 'N';
2680
2681 // TODO: avoid making this TemplateName.
2682 TemplateName Prefix =
2683 getASTContext().getDependentTemplateName(T->getQualifier(),
2684 T->getIdentifier());
2685 mangleTemplatePrefix(Prefix);
2686
2687 // FIXME: GCC does not appear to mangle the template arguments when
2688 // the template in question is a dependent template name. Should we
2689 // emulate that badness?
2690 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2691 Out << 'E';
2692}
2693
2694void CXXNameMangler::mangleType(const TypeOfType *T) {
2695 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2696 // "extension with parameters" mangling.
2697 Out << "u6typeof";
2698}
2699
2700void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2701 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2702 // "extension with parameters" mangling.
2703 Out << "u6typeof";
2704}
2705
2706void CXXNameMangler::mangleType(const DecltypeType *T) {
2707 Expr *E = T->getUnderlyingExpr();
2708
2709 // type ::= Dt <expression> E # decltype of an id-expression
2710 // # or class member access
2711 // ::= DT <expression> E # decltype of an expression
2712
2713 // This purports to be an exhaustive list of id-expressions and
2714 // class member accesses. Note that we do not ignore parentheses;
2715 // parentheses change the semantics of decltype for these
2716 // expressions (and cause the mangler to use the other form).
2717 if (isa<DeclRefExpr>(E) ||
2718 isa<MemberExpr>(E) ||
2719 isa<UnresolvedLookupExpr>(E) ||
2720 isa<DependentScopeDeclRefExpr>(E) ||
2721 isa<CXXDependentScopeMemberExpr>(E) ||
2722 isa<UnresolvedMemberExpr>(E))
2723 Out << "Dt";
2724 else
2725 Out << "DT";
2726 mangleExpression(E);
2727 Out << 'E';
2728}
2729
2730void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2731 // If this is dependent, we need to record that. If not, we simply
2732 // mangle it as the underlying type since they are equivalent.
2733 if (T->isDependentType()) {
2734 Out << 'U';
2735
2736 switch (T->getUTTKind()) {
2737 case UnaryTransformType::EnumUnderlyingType:
2738 Out << "3eut";
2739 break;
2740 }
2741 }
2742
2743 mangleType(T->getUnderlyingType());
2744}
2745
2746void CXXNameMangler::mangleType(const AutoType *T) {
2747 QualType D = T->getDeducedType();
2748 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00002749 if (D.isNull()) {
2750 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2751 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00002752 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00002753 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 mangleType(D);
2755}
2756
2757void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002758 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 // (Until there's a standardized mangling...)
2760 Out << "U7_Atomic";
2761 mangleType(T->getValueType());
2762}
2763
Xiuli Pan9c14e282016-01-09 12:53:17 +00002764void CXXNameMangler::mangleType(const PipeType *T) {
2765 // Pipe type mangling rules are described in SPIR 2.0 specification
2766 // A.1 Data types and A.3 Summary of changes
2767 // <type> ::= 8ocl_pipe
2768 Out << "8ocl_pipe";
2769}
2770
Guy Benyei11169dd2012-12-18 14:30:41 +00002771void CXXNameMangler::mangleIntegerLiteral(QualType T,
2772 const llvm::APSInt &Value) {
2773 // <expr-primary> ::= L <type> <value number> E # integer literal
2774 Out << 'L';
2775
2776 mangleType(T);
2777 if (T->isBooleanType()) {
2778 // Boolean values are encoded as 0/1.
2779 Out << (Value.getBoolValue() ? '1' : '0');
2780 } else {
2781 mangleNumber(Value);
2782 }
2783 Out << 'E';
2784
2785}
2786
David Majnemer1dabfdc2015-02-14 13:23:54 +00002787void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2788 // Ignore member expressions involving anonymous unions.
2789 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2790 if (!RT->getDecl()->isAnonymousStructOrUnion())
2791 break;
2792 const auto *ME = dyn_cast<MemberExpr>(Base);
2793 if (!ME)
2794 break;
2795 Base = ME->getBase();
2796 IsArrow = ME->isArrow();
2797 }
2798
2799 if (Base->isImplicitCXXThis()) {
2800 // Note: GCC mangles member expressions to the implicit 'this' as
2801 // *this., whereas we represent them as this->. The Itanium C++ ABI
2802 // does not specify anything here, so we follow GCC.
2803 Out << "dtdefpT";
2804 } else {
2805 Out << (IsArrow ? "pt" : "dt");
2806 mangleExpression(Base);
2807 }
2808}
2809
Guy Benyei11169dd2012-12-18 14:30:41 +00002810/// Mangles a member expression.
2811void CXXNameMangler::mangleMemberExpr(const Expr *base,
2812 bool isArrow,
2813 NestedNameSpecifier *qualifier,
2814 NamedDecl *firstQualifierLookup,
2815 DeclarationName member,
2816 unsigned arity) {
2817 // <expression> ::= dt <expression> <unresolved-name>
2818 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002819 if (base)
2820 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002821 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002822}
2823
2824/// Look at the callee of the given call expression and determine if
2825/// it's a parenthesized id-expression which would have triggered ADL
2826/// otherwise.
2827static bool isParenthesizedADLCallee(const CallExpr *call) {
2828 const Expr *callee = call->getCallee();
2829 const Expr *fn = callee->IgnoreParens();
2830
2831 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2832 // too, but for those to appear in the callee, it would have to be
2833 // parenthesized.
2834 if (callee == fn) return false;
2835
2836 // Must be an unresolved lookup.
2837 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2838 if (!lookup) return false;
2839
2840 assert(!lookup->requiresADL());
2841
2842 // Must be an unqualified lookup.
2843 if (lookup->getQualifier()) return false;
2844
2845 // Must not have found a class member. Note that if one is a class
2846 // member, they're all class members.
2847 if (lookup->getNumDecls() > 0 &&
2848 (*lookup->decls_begin())->isCXXClassMember())
2849 return false;
2850
2851 // Otherwise, ADL would have been triggered.
2852 return true;
2853}
2854
David Majnemer9c775c72014-09-23 04:27:55 +00002855void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2856 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2857 Out << CastEncoding;
2858 mangleType(ECE->getType());
2859 mangleExpression(ECE->getSubExpr());
2860}
2861
Richard Smith520449d2015-02-05 06:15:50 +00002862void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2863 if (auto *Syntactic = InitList->getSyntacticForm())
2864 InitList = Syntactic;
2865 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2866 mangleExpression(InitList->getInit(i));
2867}
2868
Guy Benyei11169dd2012-12-18 14:30:41 +00002869void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2870 // <expression> ::= <unary operator-name> <expression>
2871 // ::= <binary operator-name> <expression> <expression>
2872 // ::= <trinary operator-name> <expression> <expression> <expression>
2873 // ::= cv <type> expression # conversion with one argument
2874 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002875 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2876 // ::= sc <type> <expression> # static_cast<type> (expression)
2877 // ::= cc <type> <expression> # const_cast<type> (expression)
2878 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 // ::= st <type> # sizeof (a type)
2880 // ::= at <type> # alignof (a type)
2881 // ::= <template-param>
2882 // ::= <function-param>
2883 // ::= sr <type> <unqualified-name> # dependent name
2884 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2885 // ::= ds <expression> <expression> # expr.*expr
2886 // ::= sZ <template-param> # size of a parameter pack
2887 // ::= sZ <function-param> # size of a function parameter pack
2888 // ::= <expr-primary>
2889 // <expr-primary> ::= L <type> <value number> E # integer literal
2890 // ::= L <type <value float> E # floating literal
2891 // ::= L <mangled-name> E # external name
2892 // ::= fpT # 'this' expression
2893 QualType ImplicitlyConvertedToType;
2894
2895recurse:
2896 switch (E->getStmtClass()) {
2897 case Expr::NoStmtClass:
2898#define ABSTRACT_STMT(Type)
2899#define EXPR(Type, Base)
2900#define STMT(Type, Base) \
2901 case Expr::Type##Class:
2902#include "clang/AST/StmtNodes.inc"
2903 // fallthrough
2904
2905 // These all can only appear in local or variable-initialization
2906 // contexts and so should never appear in a mangling.
2907 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002908 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002910 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 case Expr::ParenListExprClass:
2912 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002913 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002914 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002915 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002916 case Expr::OMPArraySectionExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 llvm_unreachable("unexpected statement kind");
2918
2919 // FIXME: invent manglings for all these.
2920 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 case Expr::ChooseExprClass:
2922 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002923 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 case Expr::ExtVectorElementExprClass:
2925 case Expr::GenericSelectionExprClass:
2926 case Expr::ObjCEncodeExprClass:
2927 case Expr::ObjCIsaExprClass:
2928 case Expr::ObjCIvarRefExprClass:
2929 case Expr::ObjCMessageExprClass:
2930 case Expr::ObjCPropertyRefExprClass:
2931 case Expr::ObjCProtocolExprClass:
2932 case Expr::ObjCSelectorExprClass:
2933 case Expr::ObjCStringLiteralClass:
2934 case Expr::ObjCBoxedExprClass:
2935 case Expr::ObjCArrayLiteralClass:
2936 case Expr::ObjCDictionaryLiteralClass:
2937 case Expr::ObjCSubscriptRefExprClass:
2938 case Expr::ObjCIndirectCopyRestoreExprClass:
2939 case Expr::OffsetOfExprClass:
2940 case Expr::PredefinedExprClass:
2941 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002942 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 case Expr::TypeTraitExprClass:
2945 case Expr::ArrayTypeTraitExprClass:
2946 case Expr::ExpressionTraitExprClass:
2947 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 case Expr::CUDAKernelCallExprClass:
2949 case Expr::AsTypeExprClass:
2950 case Expr::PseudoObjectExprClass:
2951 case Expr::AtomicExprClass:
2952 {
2953 // As bad as this diagnostic is, it's better than crashing.
2954 DiagnosticsEngine &Diags = Context.getDiags();
2955 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2956 "cannot yet mangle expression type %0");
2957 Diags.Report(E->getExprLoc(), DiagID)
2958 << E->getStmtClassName() << E->getSourceRange();
2959 break;
2960 }
2961
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002962 case Expr::CXXUuidofExprClass: {
2963 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2964 if (UE->isTypeOperand()) {
2965 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2966 Out << "u8__uuidoft";
2967 mangleType(UuidT);
2968 } else {
2969 Expr *UuidExp = UE->getExprOperand();
2970 Out << "u8__uuidofz";
2971 mangleExpression(UuidExp, Arity);
2972 }
2973 break;
2974 }
2975
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 // Even gcc-4.5 doesn't mangle this.
2977 case Expr::BinaryConditionalOperatorClass: {
2978 DiagnosticsEngine &Diags = Context.getDiags();
2979 unsigned DiagID =
2980 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2981 "?: operator with omitted middle operand cannot be mangled");
2982 Diags.Report(E->getExprLoc(), DiagID)
2983 << E->getStmtClassName() << E->getSourceRange();
2984 break;
2985 }
2986
2987 // These are used for internal purposes and cannot be meaningfully mangled.
2988 case Expr::OpaqueValueExprClass:
2989 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2990
2991 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002993 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 Out << "E";
2995 break;
2996 }
2997
2998 case Expr::CXXDefaultArgExprClass:
2999 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3000 break;
3001
Richard Smith852c9db2013-04-20 22:23:05 +00003002 case Expr::CXXDefaultInitExprClass:
3003 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3004 break;
3005
Richard Smithcc1b96d2013-06-12 22:31:48 +00003006 case Expr::CXXStdInitializerListExprClass:
3007 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3008 break;
3009
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 case Expr::SubstNonTypeTemplateParmExprClass:
3011 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3012 Arity);
3013 break;
3014
3015 case Expr::UserDefinedLiteralClass:
3016 // We follow g++'s approach of mangling a UDL as a call to the literal
3017 // operator.
3018 case Expr::CXXMemberCallExprClass: // fallthrough
3019 case Expr::CallExprClass: {
3020 const CallExpr *CE = cast<CallExpr>(E);
3021
3022 // <expression> ::= cp <simple-id> <expression>* E
3023 // We use this mangling only when the call would use ADL except
3024 // for being parenthesized. Per discussion with David
3025 // Vandervoorde, 2011.04.25.
3026 if (isParenthesizedADLCallee(CE)) {
3027 Out << "cp";
3028 // The callee here is a parenthesized UnresolvedLookupExpr with
3029 // no qualifier and should always get mangled as a <simple-id>
3030 // anyway.
3031
3032 // <expression> ::= cl <expression>* E
3033 } else {
3034 Out << "cl";
3035 }
3036
David Majnemer67a8ec62015-02-19 21:41:48 +00003037 unsigned CallArity = CE->getNumArgs();
3038 for (const Expr *Arg : CE->arguments())
3039 if (isa<PackExpansionExpr>(Arg))
3040 CallArity = UnknownArity;
3041
3042 mangleExpression(CE->getCallee(), CallArity);
3043 for (const Expr *Arg : CE->arguments())
3044 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 Out << 'E';
3046 break;
3047 }
3048
3049 case Expr::CXXNewExprClass: {
3050 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3051 if (New->isGlobalNew()) Out << "gs";
3052 Out << (New->isArray() ? "na" : "nw");
3053 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3054 E = New->placement_arg_end(); I != E; ++I)
3055 mangleExpression(*I);
3056 Out << '_';
3057 mangleType(New->getAllocatedType());
3058 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3060 Out << "il";
3061 else
3062 Out << "pi";
3063 const Expr *Init = New->getInitializer();
3064 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3065 // Directly inline the initializers.
3066 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3067 E = CCE->arg_end();
3068 I != E; ++I)
3069 mangleExpression(*I);
3070 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3071 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3072 mangleExpression(PLE->getExpr(i));
3073 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3074 isa<InitListExpr>(Init)) {
3075 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003076 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 } else
3078 mangleExpression(Init);
3079 }
3080 Out << 'E';
3081 break;
3082 }
3083
David Majnemer1dabfdc2015-02-14 13:23:54 +00003084 case Expr::CXXPseudoDestructorExprClass: {
3085 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3086 if (const Expr *Base = PDE->getBase())
3087 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003088 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3089 QualType ScopeType;
3090 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3091 if (Qualifier) {
3092 mangleUnresolvedPrefix(Qualifier,
3093 /*Recursive=*/true);
3094 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3095 Out << 'E';
3096 } else {
3097 Out << "sr";
3098 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3099 Out << 'E';
3100 }
3101 } else if (Qualifier) {
3102 mangleUnresolvedPrefix(Qualifier);
3103 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003104 // <base-unresolved-name> ::= dn <destructor-name>
3105 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003106 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003107 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003108 break;
3109 }
3110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 case Expr::MemberExprClass: {
3112 const MemberExpr *ME = cast<MemberExpr>(E);
3113 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003114 ME->getQualifier(), nullptr,
3115 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 break;
3117 }
3118
3119 case Expr::UnresolvedMemberExprClass: {
3120 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003121 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3122 ME->isArrow(), ME->getQualifier(), nullptr,
3123 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003125 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 break;
3127 }
3128
3129 case Expr::CXXDependentScopeMemberExprClass: {
3130 const CXXDependentScopeMemberExpr *ME
3131 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003132 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3133 ME->isArrow(), ME->getQualifier(),
3134 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 ME->getMember(), Arity);
3136 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003137 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 break;
3139 }
3140
3141 case Expr::UnresolvedLookupExprClass: {
3142 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003143 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003144
3145 // All the <unresolved-name> productions end in a
3146 // base-unresolved-name, where <template-args> are just tacked
3147 // onto the end.
3148 if (ULE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003149 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 break;
3151 }
3152
3153 case Expr::CXXUnresolvedConstructExprClass: {
3154 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3155 unsigned N = CE->arg_size();
3156
3157 Out << "cv";
3158 mangleType(CE->getType());
3159 if (N != 1) Out << '_';
3160 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3161 if (N != 1) Out << 'E';
3162 break;
3163 }
3164
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003166 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003167 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003168 assert(
3169 CE->getNumArgs() >= 1 &&
3170 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3171 "implicit CXXConstructExpr must have one argument");
3172 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3173 }
3174 Out << "il";
3175 for (auto *E : CE->arguments())
3176 mangleExpression(E);
3177 Out << "E";
3178 break;
3179 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003180
Richard Smith520449d2015-02-05 06:15:50 +00003181 case Expr::CXXTemporaryObjectExprClass: {
3182 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3183 unsigned N = CE->getNumArgs();
3184 bool List = CE->isListInitialization();
3185
3186 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 Out << "tl";
3188 else
3189 Out << "cv";
3190 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003191 if (!List && N != 1)
3192 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003193 if (CE->isStdInitListInitialization()) {
3194 // We implicitly created a std::initializer_list<T> for the first argument
3195 // of a constructor of type U in an expression of the form U{a, b, c}.
3196 // Strip all the semantic gunk off the initializer list.
3197 auto *SILE =
3198 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3199 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3200 mangleInitListElements(ILE);
3201 } else {
3202 for (auto *E : CE->arguments())
3203 mangleExpression(E);
3204 }
Richard Smith520449d2015-02-05 06:15:50 +00003205 if (List || N != 1)
3206 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 break;
3208 }
3209
3210 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003211 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003213 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 break;
3215
3216 case Expr::CXXNoexceptExprClass:
3217 Out << "nx";
3218 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3219 break;
3220
3221 case Expr::UnaryExprOrTypeTraitExprClass: {
3222 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3223
3224 if (!SAE->isInstantiationDependent()) {
3225 // Itanium C++ ABI:
3226 // If the operand of a sizeof or alignof operator is not
3227 // instantiation-dependent it is encoded as an integer literal
3228 // reflecting the result of the operator.
3229 //
3230 // If the result of the operator is implicitly converted to a known
3231 // integer type, that type is used for the literal; otherwise, the type
3232 // of std::size_t or std::ptrdiff_t is used.
3233 QualType T = (ImplicitlyConvertedToType.isNull() ||
3234 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3235 : ImplicitlyConvertedToType;
3236 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3237 mangleIntegerLiteral(T, V);
3238 break;
3239 }
3240
3241 switch(SAE->getKind()) {
3242 case UETT_SizeOf:
3243 Out << 's';
3244 break;
3245 case UETT_AlignOf:
3246 Out << 'a';
3247 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003248 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 DiagnosticsEngine &Diags = Context.getDiags();
3250 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3251 "cannot yet mangle vec_step expression");
3252 Diags.Report(DiagID);
3253 return;
3254 }
Alexey Bataev00396512015-07-02 03:40:19 +00003255 case UETT_OpenMPRequiredSimdAlign:
3256 DiagnosticsEngine &Diags = Context.getDiags();
3257 unsigned DiagID = Diags.getCustomDiagID(
3258 DiagnosticsEngine::Error,
3259 "cannot yet mangle __builtin_omp_required_simd_align expression");
3260 Diags.Report(DiagID);
3261 return;
3262 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 if (SAE->isArgumentType()) {
3264 Out << 't';
3265 mangleType(SAE->getArgumentType());
3266 } else {
3267 Out << 'z';
3268 mangleExpression(SAE->getArgumentExpr());
3269 }
3270 break;
3271 }
3272
3273 case Expr::CXXThrowExprClass: {
3274 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003275 // <expression> ::= tw <expression> # throw expression
3276 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 if (TE->getSubExpr()) {
3278 Out << "tw";
3279 mangleExpression(TE->getSubExpr());
3280 } else {
3281 Out << "tr";
3282 }
3283 break;
3284 }
3285
3286 case Expr::CXXTypeidExprClass: {
3287 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003288 // <expression> ::= ti <type> # typeid (type)
3289 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 if (TIE->isTypeOperand()) {
3291 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003292 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 } else {
3294 Out << "te";
3295 mangleExpression(TIE->getExprOperand());
3296 }
3297 break;
3298 }
3299
3300 case Expr::CXXDeleteExprClass: {
3301 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003302 // <expression> ::= [gs] dl <expression> # [::] delete expr
3303 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 if (DE->isGlobalDelete()) Out << "gs";
3305 Out << (DE->isArrayForm() ? "da" : "dl");
3306 mangleExpression(DE->getArgument());
3307 break;
3308 }
3309
3310 case Expr::UnaryOperatorClass: {
3311 const UnaryOperator *UO = cast<UnaryOperator>(E);
3312 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3313 /*Arity=*/1);
3314 mangleExpression(UO->getSubExpr());
3315 break;
3316 }
3317
3318 case Expr::ArraySubscriptExprClass: {
3319 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3320
3321 // Array subscript is treated as a syntactically weird form of
3322 // binary operator.
3323 Out << "ix";
3324 mangleExpression(AE->getLHS());
3325 mangleExpression(AE->getRHS());
3326 break;
3327 }
3328
3329 case Expr::CompoundAssignOperatorClass: // fallthrough
3330 case Expr::BinaryOperatorClass: {
3331 const BinaryOperator *BO = cast<BinaryOperator>(E);
3332 if (BO->getOpcode() == BO_PtrMemD)
3333 Out << "ds";
3334 else
3335 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3336 /*Arity=*/2);
3337 mangleExpression(BO->getLHS());
3338 mangleExpression(BO->getRHS());
3339 break;
3340 }
3341
3342 case Expr::ConditionalOperatorClass: {
3343 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3344 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3345 mangleExpression(CO->getCond());
3346 mangleExpression(CO->getLHS(), Arity);
3347 mangleExpression(CO->getRHS(), Arity);
3348 break;
3349 }
3350
3351 case Expr::ImplicitCastExprClass: {
3352 ImplicitlyConvertedToType = E->getType();
3353 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3354 goto recurse;
3355 }
3356
3357 case Expr::ObjCBridgedCastExprClass: {
3358 // Mangle ownership casts as a vendor extended operator __bridge,
3359 // __bridge_transfer, or __bridge_retain.
3360 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3361 Out << "v1U" << Kind.size() << Kind;
3362 }
3363 // Fall through to mangle the cast itself.
3364
3365 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003366 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003368
Richard Smith520449d2015-02-05 06:15:50 +00003369 case Expr::CXXFunctionalCastExprClass: {
3370 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3371 // FIXME: Add isImplicit to CXXConstructExpr.
3372 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3373 if (CCE->getParenOrBraceRange().isInvalid())
3374 Sub = CCE->getArg(0)->IgnoreImplicit();
3375 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3376 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3377 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3378 Out << "tl";
3379 mangleType(E->getType());
3380 mangleInitListElements(IL);
3381 Out << "E";
3382 } else {
3383 mangleCastExpression(E, "cv");
3384 }
3385 break;
3386 }
3387
David Majnemer9c775c72014-09-23 04:27:55 +00003388 case Expr::CXXStaticCastExprClass:
3389 mangleCastExpression(E, "sc");
3390 break;
3391 case Expr::CXXDynamicCastExprClass:
3392 mangleCastExpression(E, "dc");
3393 break;
3394 case Expr::CXXReinterpretCastExprClass:
3395 mangleCastExpression(E, "rc");
3396 break;
3397 case Expr::CXXConstCastExprClass:
3398 mangleCastExpression(E, "cc");
3399 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003400
3401 case Expr::CXXOperatorCallExprClass: {
3402 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3403 unsigned NumArgs = CE->getNumArgs();
3404 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3405 // Mangle the arguments.
3406 for (unsigned i = 0; i != NumArgs; ++i)
3407 mangleExpression(CE->getArg(i));
3408 break;
3409 }
3410
3411 case Expr::ParenExprClass:
3412 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3413 break;
3414
3415 case Expr::DeclRefExprClass: {
3416 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3417
3418 switch (D->getKind()) {
3419 default:
3420 // <expr-primary> ::= L <mangled-name> E # external name
3421 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003422 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 Out << 'E';
3424 break;
3425
3426 case Decl::ParmVar:
3427 mangleFunctionParam(cast<ParmVarDecl>(D));
3428 break;
3429
3430 case Decl::EnumConstant: {
3431 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3432 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3433 break;
3434 }
3435
3436 case Decl::NonTypeTemplateParm: {
3437 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3438 mangleTemplateParameter(PD->getIndex());
3439 break;
3440 }
3441
3442 }
3443
3444 break;
3445 }
3446
3447 case Expr::SubstNonTypeTemplateParmPackExprClass:
3448 // FIXME: not clear how to mangle this!
3449 // template <unsigned N...> class A {
3450 // template <class U...> void foo(U (&x)[N]...);
3451 // };
3452 Out << "_SUBSTPACK_";
3453 break;
3454
3455 case Expr::FunctionParmPackExprClass: {
3456 // FIXME: not clear how to mangle this!
3457 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3458 Out << "v110_SUBSTPACK";
3459 mangleFunctionParam(FPPE->getParameterPack());
3460 break;
3461 }
3462
3463 case Expr::DependentScopeDeclRefExprClass: {
3464 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003465 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003466
3467 // All the <unresolved-name> productions end in a
3468 // base-unresolved-name, where <template-args> are just tacked
3469 // onto the end.
3470 if (DRE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003471 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 break;
3473 }
3474
3475 case Expr::CXXBindTemporaryExprClass:
3476 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3477 break;
3478
3479 case Expr::ExprWithCleanupsClass:
3480 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3481 break;
3482
3483 case Expr::FloatingLiteralClass: {
3484 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3485 Out << 'L';
3486 mangleType(FL->getType());
3487 mangleFloat(FL->getValue());
3488 Out << 'E';
3489 break;
3490 }
3491
3492 case Expr::CharacterLiteralClass:
3493 Out << 'L';
3494 mangleType(E->getType());
3495 Out << cast<CharacterLiteral>(E)->getValue();
3496 Out << 'E';
3497 break;
3498
3499 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3500 case Expr::ObjCBoolLiteralExprClass:
3501 Out << "Lb";
3502 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3503 Out << 'E';
3504 break;
3505
3506 case Expr::CXXBoolLiteralExprClass:
3507 Out << "Lb";
3508 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3509 Out << 'E';
3510 break;
3511
3512 case Expr::IntegerLiteralClass: {
3513 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3514 if (E->getType()->isSignedIntegerType())
3515 Value.setIsSigned(true);
3516 mangleIntegerLiteral(E->getType(), Value);
3517 break;
3518 }
3519
3520 case Expr::ImaginaryLiteralClass: {
3521 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3522 // Mangle as if a complex literal.
3523 // Proposal from David Vandevoorde, 2010.06.30.
3524 Out << 'L';
3525 mangleType(E->getType());
3526 if (const FloatingLiteral *Imag =
3527 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3528 // Mangle a floating-point zero of the appropriate type.
3529 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3530 Out << '_';
3531 mangleFloat(Imag->getValue());
3532 } else {
3533 Out << "0_";
3534 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3535 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3536 Value.setIsSigned(true);
3537 mangleNumber(Value);
3538 }
3539 Out << 'E';
3540 break;
3541 }
3542
3543 case Expr::StringLiteralClass: {
3544 // Revised proposal from David Vandervoorde, 2010.07.15.
3545 Out << 'L';
3546 assert(isa<ConstantArrayType>(E->getType()));
3547 mangleType(E->getType());
3548 Out << 'E';
3549 break;
3550 }
3551
3552 case Expr::GNUNullExprClass:
3553 // FIXME: should this really be mangled the same as nullptr?
3554 // fallthrough
3555
3556 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 Out << "LDnE";
3558 break;
3559 }
3560
3561 case Expr::PackExpansionExprClass:
3562 Out << "sp";
3563 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3564 break;
3565
3566 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003567 auto *SPE = cast<SizeOfPackExpr>(E);
3568 if (SPE->isPartiallySubstituted()) {
3569 Out << "sP";
3570 for (const auto &A : SPE->getPartialArguments())
3571 mangleTemplateArg(A);
3572 Out << "E";
3573 break;
3574 }
3575
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003577 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3579 mangleTemplateParameter(TTP->getIndex());
3580 else if (const NonTypeTemplateParmDecl *NTTP
3581 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3582 mangleTemplateParameter(NTTP->getIndex());
3583 else if (const TemplateTemplateParmDecl *TempTP
3584 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3585 mangleTemplateParameter(TempTP->getIndex());
3586 else
3587 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3588 break;
3589 }
Richard Smith0f0af192014-11-08 05:07:16 +00003590
Guy Benyei11169dd2012-12-18 14:30:41 +00003591 case Expr::MaterializeTemporaryExprClass: {
3592 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3593 break;
3594 }
Richard Smith0f0af192014-11-08 05:07:16 +00003595
3596 case Expr::CXXFoldExprClass: {
3597 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003598 if (FE->isLeftFold())
3599 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003600 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003601 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003602
3603 if (FE->getOperator() == BO_PtrMemD)
3604 Out << "ds";
3605 else
3606 mangleOperatorName(
3607 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3608 /*Arity=*/2);
3609
3610 if (FE->getLHS())
3611 mangleExpression(FE->getLHS());
3612 if (FE->getRHS())
3613 mangleExpression(FE->getRHS());
3614 break;
3615 }
3616
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 case Expr::CXXThisExprClass:
3618 Out << "fpT";
3619 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00003620
3621 case Expr::CoawaitExprClass:
3622 // FIXME: Propose a non-vendor mangling.
3623 Out << "v18co_await";
3624 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3625 break;
3626
3627 case Expr::CoyieldExprClass:
3628 // FIXME: Propose a non-vendor mangling.
3629 Out << "v18co_yield";
3630 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3631 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 }
3633}
3634
3635/// Mangle an expression which refers to a parameter variable.
3636///
3637/// <expression> ::= <function-param>
3638/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3639/// <function-param> ::= fp <top-level CV-qualifiers>
3640/// <parameter-2 non-negative number> _ # L == 0, I > 0
3641/// <function-param> ::= fL <L-1 non-negative number>
3642/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3643/// <function-param> ::= fL <L-1 non-negative number>
3644/// p <top-level CV-qualifiers>
3645/// <I-1 non-negative number> _ # L > 0, I > 0
3646///
3647/// L is the nesting depth of the parameter, defined as 1 if the
3648/// parameter comes from the innermost function prototype scope
3649/// enclosing the current context, 2 if from the next enclosing
3650/// function prototype scope, and so on, with one special case: if
3651/// we've processed the full parameter clause for the innermost
3652/// function type, then L is one less. This definition conveniently
3653/// makes it irrelevant whether a function's result type was written
3654/// trailing or leading, but is otherwise overly complicated; the
3655/// numbering was first designed without considering references to
3656/// parameter in locations other than return types, and then the
3657/// mangling had to be generalized without changing the existing
3658/// manglings.
3659///
3660/// I is the zero-based index of the parameter within its parameter
3661/// declaration clause. Note that the original ABI document describes
3662/// this using 1-based ordinals.
3663void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3664 unsigned parmDepth = parm->getFunctionScopeDepth();
3665 unsigned parmIndex = parm->getFunctionScopeIndex();
3666
3667 // Compute 'L'.
3668 // parmDepth does not include the declaring function prototype.
3669 // FunctionTypeDepth does account for that.
3670 assert(parmDepth < FunctionTypeDepth.getDepth());
3671 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3672 if (FunctionTypeDepth.isInResultType())
3673 nestingDepth--;
3674
3675 if (nestingDepth == 0) {
3676 Out << "fp";
3677 } else {
3678 Out << "fL" << (nestingDepth - 1) << 'p';
3679 }
3680
3681 // Top-level qualifiers. We don't have to worry about arrays here,
3682 // because parameters declared as arrays should already have been
3683 // transformed to have pointer type. FIXME: apparently these don't
3684 // get mangled if used as an rvalue of a known non-class type?
3685 assert(!parm->getType()->isArrayType()
3686 && "parameter's type is still an array type?");
3687 mangleQualifiers(parm->getType().getQualifiers());
3688
3689 // Parameter index.
3690 if (parmIndex != 0) {
3691 Out << (parmIndex - 1);
3692 }
3693 Out << '_';
3694}
3695
3696void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3697 // <ctor-dtor-name> ::= C1 # complete object constructor
3698 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003700 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 switch (T) {
3702 case Ctor_Complete:
3703 Out << "C1";
3704 break;
3705 case Ctor_Base:
3706 Out << "C2";
3707 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003708 case Ctor_Comdat:
3709 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003711 case Ctor_DefaultClosure:
3712 case Ctor_CopyingClosure:
3713 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 }
3715}
3716
3717void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3718 // <ctor-dtor-name> ::= D0 # deleting destructor
3719 // ::= D1 # complete object destructor
3720 // ::= D2 # base object destructor
3721 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003722 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 switch (T) {
3724 case Dtor_Deleting:
3725 Out << "D0";
3726 break;
3727 case Dtor_Complete:
3728 Out << "D1";
3729 break;
3730 case Dtor_Base:
3731 Out << "D2";
3732 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003733 case Dtor_Comdat:
3734 Out << "D5";
3735 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 }
3737}
3738
James Y Knight04ec5bf2015-12-24 02:59:37 +00003739void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3740 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003741 // <template-args> ::= I <template-arg>+ E
3742 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00003743 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3744 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 Out << 'E';
3746}
3747
3748void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3749 // <template-args> ::= I <template-arg>+ E
3750 Out << 'I';
3751 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3752 mangleTemplateArg(AL[i]);
3753 Out << 'E';
3754}
3755
3756void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3757 unsigned NumTemplateArgs) {
3758 // <template-args> ::= I <template-arg>+ E
3759 Out << 'I';
3760 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3761 mangleTemplateArg(TemplateArgs[i]);
3762 Out << 'E';
3763}
3764
3765void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3766 // <template-arg> ::= <type> # type or template
3767 // ::= X <expression> E # expression
3768 // ::= <expr-primary> # simple expressions
3769 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 if (!A.isInstantiationDependent() || A.isDependent())
3771 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3772
3773 switch (A.getKind()) {
3774 case TemplateArgument::Null:
3775 llvm_unreachable("Cannot mangle NULL template argument");
3776
3777 case TemplateArgument::Type:
3778 mangleType(A.getAsType());
3779 break;
3780 case TemplateArgument::Template:
3781 // This is mangled as <type>.
3782 mangleType(A.getAsTemplate());
3783 break;
3784 case TemplateArgument::TemplateExpansion:
3785 // <type> ::= Dp <type> # pack expansion (C++0x)
3786 Out << "Dp";
3787 mangleType(A.getAsTemplateOrTemplatePattern());
3788 break;
3789 case TemplateArgument::Expression: {
3790 // It's possible to end up with a DeclRefExpr here in certain
3791 // dependent cases, in which case we should mangle as a
3792 // declaration.
3793 const Expr *E = A.getAsExpr()->IgnoreParens();
3794 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3795 const ValueDecl *D = DRE->getDecl();
3796 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003797 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003798 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003799 Out << 'E';
3800 break;
3801 }
3802 }
3803
3804 Out << 'X';
3805 mangleExpression(E);
3806 Out << 'E';
3807 break;
3808 }
3809 case TemplateArgument::Integral:
3810 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3811 break;
3812 case TemplateArgument::Declaration: {
3813 // <expr-primary> ::= L <mangled-name> E # external name
3814 // Clang produces AST's where pointer-to-member-function expressions
3815 // and pointer-to-function expressions are represented as a declaration not
3816 // an expression. We compensate for it here to produce the correct mangling.
3817 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003818 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 if (compensateMangling) {
3820 Out << 'X';
3821 mangleOperatorName(OO_Amp, 1);
3822 }
3823
3824 Out << 'L';
3825 // References to external entities use the mangled name; if the name would
3826 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003827 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 Out << 'E';
3829
3830 if (compensateMangling)
3831 Out << 'E';
3832
3833 break;
3834 }
3835 case TemplateArgument::NullPtr: {
3836 // <expr-primary> ::= L <type> 0 E
3837 Out << 'L';
3838 mangleType(A.getNullPtrType());
3839 Out << "0E";
3840 break;
3841 }
3842 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003843 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003845 for (const auto &P : A.pack_elements())
3846 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003847 Out << 'E';
3848 }
3849 }
3850}
3851
3852void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3853 // <template-param> ::= T_ # first template parameter
3854 // ::= T <parameter-2 non-negative number> _
3855 if (Index == 0)
3856 Out << "T_";
3857 else
3858 Out << 'T' << (Index - 1) << '_';
3859}
3860
David Majnemer3b3bdb52014-05-06 22:49:16 +00003861void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3862 if (SeqID == 1)
3863 Out << '0';
3864 else if (SeqID > 1) {
3865 SeqID--;
3866
3867 // <seq-id> is encoded in base-36, using digits and upper case letters.
3868 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003869 MutableArrayRef<char> BufferRef(Buffer);
3870 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003871
3872 for (; SeqID != 0; SeqID /= 36) {
3873 unsigned C = SeqID % 36;
3874 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3875 }
3876
3877 Out.write(I.base(), I - BufferRef.rbegin());
3878 }
3879 Out << '_';
3880}
3881
Guy Benyei11169dd2012-12-18 14:30:41 +00003882void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3883 bool result = mangleSubstitution(type);
3884 assert(result && "no existing substitution for type");
3885 (void) result;
3886}
3887
3888void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3889 bool result = mangleSubstitution(tname);
3890 assert(result && "no existing substitution for template name");
3891 (void) result;
3892}
3893
3894// <substitution> ::= S <seq-id> _
3895// ::= S_
3896bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3897 // Try one of the standard substitutions first.
3898 if (mangleStandardSubstitution(ND))
3899 return true;
3900
3901 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3902 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3903}
3904
Justin Bognere8d762e2015-05-22 06:48:13 +00003905/// Determine whether the given type has any qualifiers that are relevant for
3906/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003907static bool hasMangledSubstitutionQualifiers(QualType T) {
3908 Qualifiers Qs = T.getQualifiers();
3909 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3910}
3911
3912bool CXXNameMangler::mangleSubstitution(QualType T) {
3913 if (!hasMangledSubstitutionQualifiers(T)) {
3914 if (const RecordType *RT = T->getAs<RecordType>())
3915 return mangleSubstitution(RT->getDecl());
3916 }
3917
3918 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3919
3920 return mangleSubstitution(TypePtr);
3921}
3922
3923bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3924 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3925 return mangleSubstitution(TD);
3926
3927 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3928 return mangleSubstitution(
3929 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3930}
3931
3932bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3933 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3934 if (I == Substitutions.end())
3935 return false;
3936
3937 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003938 Out << 'S';
3939 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003940
3941 return true;
3942}
3943
3944static bool isCharType(QualType T) {
3945 if (T.isNull())
3946 return false;
3947
3948 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3949 T->isSpecificBuiltinType(BuiltinType::Char_U);
3950}
3951
Justin Bognere8d762e2015-05-22 06:48:13 +00003952/// Returns whether a given type is a template specialization of a given name
3953/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003954static bool isCharSpecialization(QualType T, const char *Name) {
3955 if (T.isNull())
3956 return false;
3957
3958 const RecordType *RT = T->getAs<RecordType>();
3959 if (!RT)
3960 return false;
3961
3962 const ClassTemplateSpecializationDecl *SD =
3963 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3964 if (!SD)
3965 return false;
3966
3967 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3968 return false;
3969
3970 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3971 if (TemplateArgs.size() != 1)
3972 return false;
3973
3974 if (!isCharType(TemplateArgs[0].getAsType()))
3975 return false;
3976
3977 return SD->getIdentifier()->getName() == Name;
3978}
3979
3980template <std::size_t StrLen>
3981static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3982 const char (&Str)[StrLen]) {
3983 if (!SD->getIdentifier()->isStr(Str))
3984 return false;
3985
3986 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3987 if (TemplateArgs.size() != 2)
3988 return false;
3989
3990 if (!isCharType(TemplateArgs[0].getAsType()))
3991 return false;
3992
3993 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3994 return false;
3995
3996 return true;
3997}
3998
3999bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4000 // <substitution> ::= St # ::std::
4001 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4002 if (isStd(NS)) {
4003 Out << "St";
4004 return true;
4005 }
4006 }
4007
4008 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4009 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4010 return false;
4011
4012 // <substitution> ::= Sa # ::std::allocator
4013 if (TD->getIdentifier()->isStr("allocator")) {
4014 Out << "Sa";
4015 return true;
4016 }
4017
4018 // <<substitution> ::= Sb # ::std::basic_string
4019 if (TD->getIdentifier()->isStr("basic_string")) {
4020 Out << "Sb";
4021 return true;
4022 }
4023 }
4024
4025 if (const ClassTemplateSpecializationDecl *SD =
4026 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4027 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4028 return false;
4029
4030 // <substitution> ::= Ss # ::std::basic_string<char,
4031 // ::std::char_traits<char>,
4032 // ::std::allocator<char> >
4033 if (SD->getIdentifier()->isStr("basic_string")) {
4034 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4035
4036 if (TemplateArgs.size() != 3)
4037 return false;
4038
4039 if (!isCharType(TemplateArgs[0].getAsType()))
4040 return false;
4041
4042 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4043 return false;
4044
4045 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4046 return false;
4047
4048 Out << "Ss";
4049 return true;
4050 }
4051
4052 // <substitution> ::= Si # ::std::basic_istream<char,
4053 // ::std::char_traits<char> >
4054 if (isStreamCharSpecialization(SD, "basic_istream")) {
4055 Out << "Si";
4056 return true;
4057 }
4058
4059 // <substitution> ::= So # ::std::basic_ostream<char,
4060 // ::std::char_traits<char> >
4061 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4062 Out << "So";
4063 return true;
4064 }
4065
4066 // <substitution> ::= Sd # ::std::basic_iostream<char,
4067 // ::std::char_traits<char> >
4068 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4069 Out << "Sd";
4070 return true;
4071 }
4072 }
4073 return false;
4074}
4075
4076void CXXNameMangler::addSubstitution(QualType T) {
4077 if (!hasMangledSubstitutionQualifiers(T)) {
4078 if (const RecordType *RT = T->getAs<RecordType>()) {
4079 addSubstitution(RT->getDecl());
4080 return;
4081 }
4082 }
4083
4084 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4085 addSubstitution(TypePtr);
4086}
4087
4088void CXXNameMangler::addSubstitution(TemplateName Template) {
4089 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4090 return addSubstitution(TD);
4091
4092 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4093 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4094}
4095
4096void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4097 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4098 Substitutions[Ptr] = SeqID++;
4099}
4100
4101//
4102
Justin Bognere8d762e2015-05-22 06:48:13 +00004103/// Mangles the name of the declaration D and emits that name to the given
4104/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004105///
4106/// If the declaration D requires a mangled name, this routine will emit that
4107/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4108/// and this routine will return false. In this case, the caller should just
4109/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4110/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004111void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4112 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4114 "Invalid mangleName() call, argument is not a variable or function!");
4115 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4116 "Invalid mangleName() call on 'structor decl!");
4117
4118 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4119 getASTContext().getSourceManager(),
4120 "Mangling declaration");
4121
4122 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004123 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124}
4125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004126void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4127 CXXCtorType Type,
4128 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 CXXNameMangler Mangler(*this, Out, D, Type);
4130 Mangler.mangle(D);
4131}
4132
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004133void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4134 CXXDtorType Type,
4135 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 CXXNameMangler Mangler(*this, Out, D, Type);
4137 Mangler.mangle(D);
4138}
4139
Rafael Espindola1e4df922014-09-16 15:18:21 +00004140void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4141 raw_ostream &Out) {
4142 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4143 Mangler.mangle(D);
4144}
4145
4146void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4147 raw_ostream &Out) {
4148 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4149 Mangler.mangle(D);
4150}
4151
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004152void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4153 const ThunkInfo &Thunk,
4154 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 // <special-name> ::= T <call-offset> <base encoding>
4156 // # base is the nominal target function of thunk
4157 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4158 // # base is the nominal target function of thunk
4159 // # first call-offset is 'this' adjustment
4160 // # second call-offset is result adjustment
4161
4162 assert(!isa<CXXDestructorDecl>(MD) &&
4163 "Use mangleCXXDtor for destructor decls!");
4164 CXXNameMangler Mangler(*this, Out);
4165 Mangler.getStream() << "_ZT";
4166 if (!Thunk.Return.isEmpty())
4167 Mangler.getStream() << 'c';
4168
4169 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004170 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4171 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4172
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 // Mangle the return pointer adjustment if there is one.
4174 if (!Thunk.Return.isEmpty())
4175 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004176 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4177
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 Mangler.mangleFunctionEncoding(MD);
4179}
4180
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004181void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4182 const CXXDestructorDecl *DD, CXXDtorType Type,
4183 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 // <special-name> ::= T <call-offset> <base encoding>
4185 // # base is the nominal target function of thunk
4186 CXXNameMangler Mangler(*this, Out, DD, Type);
4187 Mangler.getStream() << "_ZT";
4188
4189 // Mangle the 'this' pointer adjustment.
4190 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004191 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004192
4193 Mangler.mangleFunctionEncoding(DD);
4194}
4195
Justin Bognere8d762e2015-05-22 06:48:13 +00004196/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004197void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4198 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 // <special-name> ::= GV <object name> # Guard variable for one-time
4200 // # initialization
4201 CXXNameMangler Mangler(*this, Out);
4202 Mangler.getStream() << "_ZGV";
4203 Mangler.mangleName(D);
4204}
4205
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004206void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4207 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004208 // These symbols are internal in the Itanium ABI, so the names don't matter.
4209 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4210 // avoid duplicate symbols.
4211 Out << "__cxx_global_var_init";
4212}
4213
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004214void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4215 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004216 // Prefix the mangling of D with __dtor_.
4217 CXXNameMangler Mangler(*this, Out);
4218 Mangler.getStream() << "__dtor_";
4219 if (shouldMangleDeclName(D))
4220 Mangler.mangle(D);
4221 else
4222 Mangler.getStream() << D->getName();
4223}
4224
Reid Kleckner1d59f992015-01-22 01:36:17 +00004225void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4226 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4227 CXXNameMangler Mangler(*this, Out);
4228 Mangler.getStream() << "__filt_";
4229 if (shouldMangleDeclName(EnclosingDecl))
4230 Mangler.mangle(EnclosingDecl);
4231 else
4232 Mangler.getStream() << EnclosingDecl->getName();
4233}
4234
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004235void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4236 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4237 CXXNameMangler Mangler(*this, Out);
4238 Mangler.getStream() << "__fin_";
4239 if (shouldMangleDeclName(EnclosingDecl))
4240 Mangler.mangle(EnclosingDecl);
4241 else
4242 Mangler.getStream() << EnclosingDecl->getName();
4243}
4244
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004245void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4246 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004247 // <special-name> ::= TH <object name>
4248 CXXNameMangler Mangler(*this, Out);
4249 Mangler.getStream() << "_ZTH";
4250 Mangler.mangleName(D);
4251}
4252
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004253void
4254ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4255 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004256 // <special-name> ::= TW <object name>
4257 CXXNameMangler Mangler(*this, Out);
4258 Mangler.getStream() << "_ZTW";
4259 Mangler.mangleName(D);
4260}
4261
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004262void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004263 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004264 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 // We match the GCC mangling here.
4266 // <special-name> ::= GR <object name>
4267 CXXNameMangler Mangler(*this, Out);
4268 Mangler.getStream() << "_ZGR";
4269 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004270 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004271 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004272}
4273
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004274void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4275 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 // <special-name> ::= TV <type> # virtual table
4277 CXXNameMangler Mangler(*this, Out);
4278 Mangler.getStream() << "_ZTV";
4279 Mangler.mangleNameOrStandardSubstitution(RD);
4280}
4281
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004282void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4283 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 // <special-name> ::= TT <type> # VTT structure
4285 CXXNameMangler Mangler(*this, Out);
4286 Mangler.getStream() << "_ZTT";
4287 Mangler.mangleNameOrStandardSubstitution(RD);
4288}
4289
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004290void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4291 int64_t Offset,
4292 const CXXRecordDecl *Type,
4293 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 // <special-name> ::= TC <type> <offset number> _ <base type>
4295 CXXNameMangler Mangler(*this, Out);
4296 Mangler.getStream() << "_ZTC";
4297 Mangler.mangleNameOrStandardSubstitution(RD);
4298 Mangler.getStream() << Offset;
4299 Mangler.getStream() << '_';
4300 Mangler.mangleNameOrStandardSubstitution(Type);
4301}
4302
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004303void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 // <special-name> ::= TI <type> # typeinfo structure
4305 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4306 CXXNameMangler Mangler(*this, Out);
4307 Mangler.getStream() << "_ZTI";
4308 Mangler.mangleType(Ty);
4309}
4310
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004311void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4312 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4314 CXXNameMangler Mangler(*this, Out);
4315 Mangler.getStream() << "_ZTS";
4316 Mangler.mangleType(Ty);
4317}
4318
Reid Klecknercc99e262013-11-19 23:23:00 +00004319void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4320 mangleCXXRTTIName(Ty, Out);
4321}
4322
David Majnemer58e5bee2014-03-24 21:43:36 +00004323void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4324 llvm_unreachable("Can't mangle string literals");
4325}
4326
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004327ItaniumMangleContext *
4328ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4329 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004330}