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