blob: 7f362f6f42043c06e3c4f1ca9f1a4221448c1f77 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements C++ name mangling according to the Itanium C++ ABI,
11// which is used in GCC 3.2 and newer (and many compilers that are
12// ABI-compatible with GCC):
13//
David Majnemer98559942013-12-13 00:54:42 +000014// http://mentorembedded.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
16//===----------------------------------------------------------------------===//
17#include "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000025#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/ABI.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36#define MANGLE_CHECKER 0
37
38#if MANGLE_CHECKER
39#include <cxxabi.h>
40#endif
41
42using namespace clang;
43
44namespace {
45
Justin Bognere8d762e2015-05-22 06:48:13 +000046/// Retrieve the declaration context that should be used when mangling the given
47/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000048static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49 // The ABI assumes that lambda closure types that occur within
50 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
52 // not the case: the lambda closure type ends up living in the context
53 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Eli Friedman0cd23352013-07-10 01:33:19 +000061
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
67 }
Guy Benyei11169dd2012-12-18 14:30:41 +000068
Eli Friedman95f50122013-07-02 17:52:28 +000069 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000070 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
Eli Friedman95f50122013-07-02 17:52:28 +000073
David Majnemerf8c02e62015-02-18 19:08:11 +000074 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
Richard Smithec24bbe2016-04-29 01:23:20 +000082 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000083}
84
85static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87}
Eli Friedman95f50122013-07-02 17:52:28 +000088
89static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91}
92
Eli Friedmaneecc09a2013-07-05 20:27:40 +000093static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000094 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000095 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000096 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000097 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000098 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000100 }
Craig Topper36250ad2014-05-12 05:36:57 +0000101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102}
103
104static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109}
110
111static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114}
David Majnemer2206bf52014-03-05 08:57:59 +0000115
116static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122}
123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124static const unsigned UnknownArity = ~0U;
125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000130
Guy Benyei11169dd2012-12-18 14:30:41 +0000131public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000135
Guy Benyei11169dd2012-12-18 14:30:41 +0000136 /// @name Mangler Entry Points
137 /// @{
138
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000162
Rafael Espindola1e4df922014-09-16 15:18:21 +0000163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
David Majnemer58e5bee2014-03-24 21:43:36 +0000177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000223
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType;
229
Justin Bognere8d762e2015-05-22 06:48:13 +0000230 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000231 unsigned SeqID;
232
233 class FunctionTypeDepthState {
234 unsigned Bits;
235
236 enum { InResultTypeMask = 1 };
237
238 public:
239 FunctionTypeDepthState() : Bits(0) {}
240
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
243 return Bits >> 1;
244 }
245
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
249 }
250
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
254 return tmp;
255 }
256
257 void enterResultType() {
258 Bits |= InResultTypeMask;
259 }
260
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
263 }
264
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
267 Bits = saved.Bits;
268 }
269
270 } FunctionTypeDepth;
271
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
277
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
280 // track.
281 class AbiTagState final {
282 public:
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284 Parent = LinkHead;
285 LinkHead = this;
286 }
287
288 // No copy, no move.
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
291
292 ~AbiTagState() { pop(); }
293
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
298 assert(
299 !AdditionalAbiTags &&
300 "only function and variables need a list of additional abi tags");
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
305 }
306 // Don't emit abi tags for namespaces.
307 return;
308 }
309 }
310
311 AbiTagList TagList;
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
317 }
318
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
324 }
325
326 std::sort(TagList.begin(), TagList.end());
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
360 if (Parent) {
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
366 }
367 LinkHead = Parent;
368 }
369
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
384
385 ASTContext &getASTContext() const { return Context.getASTContext(); }
386
387public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000388 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000389 const NamedDecl *D = nullptr, bool NullOut_ = false)
390 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
391 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 // These can't be mangled without a ctor type or dtor type.
393 assert(!D || (!isa<CXXDestructorDecl>(D) &&
394 !isa<CXXConstructorDecl>(D)));
395 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000396 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000397 const CXXConstructorDecl *D, CXXCtorType Type)
398 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000399 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000400 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000401 const CXXDestructorDecl *D, CXXDtorType Type)
402 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000403 SeqID(0), AbiTagsRoot(AbiTags) { }
404
405 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
406 : Context(Outer.Context), Out(Out_), NullOut(false),
407 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000408 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
409 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000410
411 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
412 : Context(Outer.Context), Out(Out_), NullOut(true),
413 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000414 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
415 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
417#if MANGLE_CHECKER
418 ~CXXNameMangler() {
419 if (Out.str()[0] == '\01')
420 return;
421
422 int status = 0;
423 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
424 assert(status == 0 && "Could not demangle mangled name!");
425 free(result);
426 }
427#endif
428 raw_ostream &getStream() { return Out; }
429
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000430 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
431 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
432
David Majnemer7ff7eb72015-02-18 07:47:09 +0000433 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000434 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
435 void mangleNumber(const llvm::APSInt &I);
436 void mangleNumber(int64_t Number);
437 void mangleFloat(const llvm::APFloat &F);
438 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000439 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 void mangleName(const NamedDecl *ND);
441 void mangleType(QualType T);
442 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
443
444private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000445
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 bool mangleSubstitution(const NamedDecl *ND);
447 bool mangleSubstitution(QualType T);
448 bool mangleSubstitution(TemplateName Template);
449 bool mangleSubstitution(uintptr_t Ptr);
450
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 void mangleExistingSubstitution(TemplateName name);
452
453 bool mangleStandardSubstitution(const NamedDecl *ND);
454
455 void addSubstitution(const NamedDecl *ND) {
456 ND = cast<NamedDecl>(ND->getCanonicalDecl());
457
458 addSubstitution(reinterpret_cast<uintptr_t>(ND));
459 }
460 void addSubstitution(QualType T);
461 void addSubstitution(TemplateName Template);
462 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000463 // Destructive copy substitutions from other mangler.
464 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000465
466 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 bool recursive = false);
468 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000470 const TemplateArgumentLoc *TemplateArgs,
471 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000472 unsigned KnownArity = UnknownArity);
473
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000474 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
475
476 void mangleNameWithAbiTags(const NamedDecl *ND,
477 const AbiTagList *AdditionalAbiTags);
478 void mangleTemplateName(const TemplateDecl *TD,
479 const TemplateArgument *TemplateArgs,
480 unsigned NumTemplateArgs);
481 void mangleUnqualifiedName(const NamedDecl *ND,
482 const AbiTagList *AdditionalAbiTags) {
483 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
484 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000485 }
486 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000487 unsigned KnownArity,
488 const AbiTagList *AdditionalAbiTags);
489 void mangleUnscopedName(const NamedDecl *ND,
490 const AbiTagList *AdditionalAbiTags);
491 void mangleUnscopedTemplateName(const TemplateDecl *ND,
492 const AbiTagList *AdditionalAbiTags);
493 void mangleUnscopedTemplateName(TemplateName,
494 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000495 void mangleSourceName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000496 void mangleSourceNameWithAbiTags(
497 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
498 void mangleLocalName(const Decl *D,
499 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000500 void mangleBlockForPrefix(const BlockDecl *Block);
501 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000502 void mangleLambda(const CXXRecordDecl *Lambda);
503 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000504 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000505 bool NoFunction=false);
506 void mangleNestedName(const TemplateDecl *TD,
507 const TemplateArgument *TemplateArgs,
508 unsigned NumTemplateArgs);
509 void manglePrefix(NestedNameSpecifier *qualifier);
510 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
511 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000512 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000513 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000514 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
515 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000516 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000518 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000519 void mangleQualifiers(Qualifiers Quals);
520 void mangleRefQualifier(RefQualifierKind RefQualifier);
521
522 void mangleObjCMethodName(const ObjCMethodDecl *MD);
523
524 // Declare manglers for every type class.
525#define ABSTRACT_TYPE(CLASS, PARENT)
526#define NON_CANONICAL_TYPE(CLASS, PARENT)
527#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
528#include "clang/AST/TypeNodes.def"
529
530 void mangleType(const TagType*);
531 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000532 static StringRef getCallingConvQualifierName(CallingConv CC);
533 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
534 void mangleExtFunctionInfo(const FunctionType *T);
535 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000536 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000538 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000539
540 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000541 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000542 void mangleMemberExpr(const Expr *base, bool isArrow,
543 NestedNameSpecifier *qualifier,
544 NamedDecl *firstQualifierLookup,
545 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000546 const TemplateArgumentLoc *TemplateArgs,
547 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000549 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000550 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000551 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000552 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000553 void mangleCXXDtorType(CXXDtorType T);
554
James Y Knight04ec5bf2015-12-24 02:59:37 +0000555 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
556 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
558 unsigned NumTemplateArgs);
559 void mangleTemplateArgs(const TemplateArgumentList &AL);
560 void mangleTemplateArg(TemplateArgument A);
561
562 void mangleTemplateParameter(unsigned Index);
563
564 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000565
566 void writeAbiTags(const NamedDecl *ND,
567 const AbiTagList *AdditionalAbiTags);
568
569 // Returns sorted unique list of ABI tags.
570 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
571 // Returns sorted unique list of ABI tags.
572 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000573};
574
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000575}
Guy Benyei11169dd2012-12-18 14:30:41 +0000576
Rafael Espindola002667c2013-10-16 01:40:34 +0000577bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000579 if (FD) {
580 LanguageLinkage L = FD->getLanguageLinkage();
581 // Overloadable functions need mangling.
582 if (FD->hasAttr<OverloadableAttr>())
583 return true;
584
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000585 // "main" is not mangled.
586 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000587 return false;
588
589 // C++ functions and those whose names are not a simple identifier need
590 // mangling.
591 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
592 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000593
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000594 // C functions are not mangled.
595 if (L == CLanguageLinkage)
596 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000597 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000598
599 // Otherwise, no mangling is done outside C++ mode.
600 if (!getASTContext().getLangOpts().CPlusPlus)
601 return false;
602
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000603 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000604 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000605 // C variables are not mangled.
606 if (VD->isExternC())
607 return false;
608
609 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 const DeclContext *DC = getEffectiveDeclContext(D);
611 // Check for extern variable declared locally.
612 if (DC->isFunctionOrMethod() && D->hasLinkage())
613 while (!DC->isNamespace() && !DC->isTranslationUnit())
614 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000615 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000616 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000617 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000618 return false;
619 }
620
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 return true;
622}
623
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000624void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
625 const AbiTagList *AdditionalAbiTags) {
626 assert(AbiTags && "require AbiTagState");
627 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
628}
629
630void CXXNameMangler::mangleSourceNameWithAbiTags(
631 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
632 mangleSourceName(ND->getIdentifier());
633 writeAbiTags(ND, AdditionalAbiTags);
634}
635
David Majnemer7ff7eb72015-02-18 07:47:09 +0000636void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 // <mangled-name> ::= _Z <encoding>
638 // ::= <data name>
639 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000640 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
642 mangleFunctionEncoding(FD);
643 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
644 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000645 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
646 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 else
648 mangleName(cast<FieldDecl>(D));
649}
650
651void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
652 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000653
654 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000655 if (!Context.shouldMangleDeclName(FD)) {
656 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000658 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000659
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000660 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
661 if (ReturnTypeAbiTags.empty()) {
662 // There are no tags for return type, the simplest case.
663 mangleName(FD);
664 mangleFunctionEncodingBareType(FD);
665 return;
666 }
667
668 // Mangle function name and encoding to temporary buffer.
669 // We have to output name and encoding to the same mangler to get the same
670 // substitution as it will be in final mangling.
671 SmallString<256> FunctionEncodingBuf;
672 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
673 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
674 // Output name of the function.
675 FunctionEncodingMangler.disableDerivedAbiTags();
676 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
677
678 // Remember length of the function name in the buffer.
679 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
680 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
681
682 // Get tags from return type that are not present in function name or
683 // encoding.
684 const AbiTagList &UsedAbiTags =
685 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
686 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
687 AdditionalAbiTags.erase(
688 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
689 UsedAbiTags.begin(), UsedAbiTags.end(),
690 AdditionalAbiTags.begin()),
691 AdditionalAbiTags.end());
692
693 // Output name with implicit tags and function encoding from temporary buffer.
694 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
695 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000696
697 // Function encoding could create new substitutions so we have to add
698 // temp mangled substitutions to main mangler.
699 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000700}
701
702void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000703 if (FD->hasAttr<EnableIfAttr>()) {
704 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
705 Out << "Ua9enable_ifI";
706 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
707 // it here.
708 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
709 E = FD->getAttrs().rend();
710 I != E; ++I) {
711 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
712 if (!EIA)
713 continue;
714 Out << 'X';
715 mangleExpression(EIA->getCond());
716 Out << 'E';
717 }
718 Out << 'E';
719 FunctionTypeDepth.pop(Saved);
720 }
721
Richard Smith5179eb72016-06-28 19:03:57 +0000722 // When mangling an inheriting constructor, the bare function type used is
723 // that of the inherited constructor.
724 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
725 if (auto Inherited = CD->getInheritedConstructor())
726 FD = Inherited.getConstructor();
727
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 // Whether the mangling of a function type includes the return type depends on
729 // the context and the nature of the function. The rules for deciding whether
730 // the return type is included are:
731 //
732 // 1. Template functions (names or types) have return types encoded, with
733 // the exceptions listed below.
734 // 2. Function types not appearing as part of a function name mangling,
735 // e.g. parameters, pointer types, etc., have return type encoded, with the
736 // exceptions listed below.
737 // 3. Non-template function names do not have return types encoded.
738 //
739 // The exceptions mentioned in (1) and (2) above, for which the return type is
740 // never included, are
741 // 1. Constructors.
742 // 2. Destructors.
743 // 3. Conversion operator functions, e.g. operator int.
744 bool MangleReturnType = false;
745 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
746 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
747 isa<CXXConversionDecl>(FD)))
748 MangleReturnType = true;
749
750 // Mangle the type of the primary template.
751 FD = PrimaryTemplate->getTemplatedDecl();
752 }
753
John McCall07daf722016-03-01 22:18:03 +0000754 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000755 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000756}
757
758static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
759 while (isa<LinkageSpecDecl>(DC)) {
760 DC = getEffectiveParentContext(DC);
761 }
762
763 return DC;
764}
765
Justin Bognere8d762e2015-05-22 06:48:13 +0000766/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000767static bool isStd(const NamespaceDecl *NS) {
768 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
769 ->isTranslationUnit())
770 return false;
771
772 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
773 return II && II->isStr("std");
774}
775
776// isStdNamespace - Return whether a given decl context is a toplevel 'std'
777// namespace.
778static bool isStdNamespace(const DeclContext *DC) {
779 if (!DC->isNamespace())
780 return false;
781
782 return isStd(cast<NamespaceDecl>(DC));
783}
784
785static const TemplateDecl *
786isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
787 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000788 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
790 TemplateArgs = FD->getTemplateSpecializationArgs();
791 return TD;
792 }
793 }
794
795 // Check if we have a class template.
796 if (const ClassTemplateSpecializationDecl *Spec =
797 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
798 TemplateArgs = &Spec->getTemplateArgs();
799 return Spec->getSpecializedTemplate();
800 }
801
Larisse Voufo39a1e502013-08-06 01:03:05 +0000802 // Check if we have a variable template.
803 if (const VarTemplateSpecializationDecl *Spec =
804 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
805 TemplateArgs = &Spec->getTemplateArgs();
806 return Spec->getSpecializedTemplate();
807 }
808
Craig Topper36250ad2014-05-12 05:36:57 +0000809 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000810}
811
Guy Benyei11169dd2012-12-18 14:30:41 +0000812void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000813 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
814 // Variables should have implicit tags from its type.
815 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
816 if (VariableTypeAbiTags.empty()) {
817 // Simple case no variable type tags.
818 mangleNameWithAbiTags(VD, nullptr);
819 return;
820 }
821
822 // Mangle variable name to null stream to collect tags.
823 llvm::raw_null_ostream NullOutStream;
824 CXXNameMangler VariableNameMangler(*this, NullOutStream);
825 VariableNameMangler.disableDerivedAbiTags();
826 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
827
828 // Get tags from variable type that are not present in its name.
829 const AbiTagList &UsedAbiTags =
830 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
831 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
832 AdditionalAbiTags.erase(
833 std::set_difference(VariableTypeAbiTags.begin(),
834 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
835 UsedAbiTags.end(), AdditionalAbiTags.begin()),
836 AdditionalAbiTags.end());
837
838 // Output name with implicit tags.
839 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
840 } else {
841 mangleNameWithAbiTags(ND, nullptr);
842 }
843}
844
845void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
846 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 // <name> ::= <nested-name>
848 // ::= <unscoped-name>
849 // ::= <unscoped-template-name> <template-args>
850 // ::= <local-name>
851 //
852 const DeclContext *DC = getEffectiveDeclContext(ND);
853
854 // If this is an extern variable declared locally, the relevant DeclContext
855 // is that of the containing namespace, or the translation unit.
856 // FIXME: This is a hack; extern variables declared locally should have
857 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000858 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 while (!DC->isNamespace() && !DC->isTranslationUnit())
860 DC = getEffectiveParentContext(DC);
861 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000862 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 return;
864 }
865
866 DC = IgnoreLinkageSpecDecls(DC);
867
868 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
869 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000870 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000872 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000873 mangleTemplateArgs(*TemplateArgs);
874 return;
875 }
876
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000877 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 return;
879 }
880
Eli Friedman95f50122013-07-02 17:52:28 +0000881 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000882 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 return;
884 }
885
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000886 mangleNestedName(ND, DC, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000887}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000888
889void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
890 const TemplateArgument *TemplateArgs,
891 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
893
894 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000895 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
897 } else {
898 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
899 }
900}
901
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000902void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
903 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 // <unscoped-name> ::= <unqualified-name>
905 // ::= St <unqualified-name> # ::std::
906
907 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
908 Out << "St";
909
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000910 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000911}
912
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000913void CXXNameMangler::mangleUnscopedTemplateName(
914 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000915 // <unscoped-template-name> ::= <unscoped-name>
916 // ::= <substitution>
917 if (mangleSubstitution(ND))
918 return;
919
920 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000921 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
922 assert(!AdditionalAbiTags &&
923 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000925 } else if (isa<BuiltinTemplateDecl>(ND)) {
926 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000927 } else {
928 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
929 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000930
Guy Benyei11169dd2012-12-18 14:30:41 +0000931 addSubstitution(ND);
932}
933
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000934void CXXNameMangler::mangleUnscopedTemplateName(
935 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000936 // <unscoped-template-name> ::= <unscoped-name>
937 // ::= <substitution>
938 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000939 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000940
941 if (mangleSubstitution(Template))
942 return;
943
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000944 assert(!AdditionalAbiTags &&
945 "dependent template name cannot have abi tags");
946
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
948 assert(Dependent && "Not a dependent template name?");
949 if (const IdentifierInfo *Id = Dependent->getIdentifier())
950 mangleSourceName(Id);
951 else
952 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000953
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 addSubstitution(Template);
955}
956
957void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
958 // ABI:
959 // Floating-point literals are encoded using a fixed-length
960 // lowercase hexadecimal string corresponding to the internal
961 // representation (IEEE on Itanium), high-order bytes first,
962 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
963 // on Itanium.
964 // The 'without leading zeroes' thing seems to be an editorial
965 // mistake; see the discussion on cxx-abi-dev beginning on
966 // 2012-01-16.
967
968 // Our requirements here are just barely weird enough to justify
969 // using a custom algorithm instead of post-processing APInt::toString().
970
971 llvm::APInt valueBits = f.bitcastToAPInt();
972 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
973 assert(numCharacters != 0);
974
975 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000976 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977
978 // Fill the buffer left-to-right.
979 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
980 // The bit-index of the next hex digit.
981 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
982
983 // Project out 4 bits starting at 'digitIndex'.
984 llvm::integerPart hexDigit
985 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
986 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
987 hexDigit &= 0xF;
988
989 // Map that over to a lowercase hex digit.
990 static const char charForHex[16] = {
991 '0', '1', '2', '3', '4', '5', '6', '7',
992 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
993 };
994 buffer[stringIndex] = charForHex[hexDigit];
995 }
996
997 Out.write(buffer.data(), numCharacters);
998}
999
1000void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1001 if (Value.isSigned() && Value.isNegative()) {
1002 Out << 'n';
1003 Value.abs().print(Out, /*signed*/ false);
1004 } else {
1005 Value.print(Out, /*signed*/ false);
1006 }
1007}
1008
1009void CXXNameMangler::mangleNumber(int64_t Number) {
1010 // <number> ::= [n] <non-negative decimal integer>
1011 if (Number < 0) {
1012 Out << 'n';
1013 Number = -Number;
1014 }
1015
1016 Out << Number;
1017}
1018
1019void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1020 // <call-offset> ::= h <nv-offset> _
1021 // ::= v <v-offset> _
1022 // <nv-offset> ::= <offset number> # non-virtual base override
1023 // <v-offset> ::= <offset number> _ <virtual offset number>
1024 // # virtual base override, with vcall offset
1025 if (!Virtual) {
1026 Out << 'h';
1027 mangleNumber(NonVirtual);
1028 Out << '_';
1029 return;
1030 }
1031
1032 Out << 'v';
1033 mangleNumber(NonVirtual);
1034 Out << '_';
1035 mangleNumber(Virtual);
1036 Out << '_';
1037}
1038
1039void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001040 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 if (!mangleSubstitution(QualType(TST, 0))) {
1042 mangleTemplatePrefix(TST->getTemplateName());
1043
1044 // FIXME: GCC does not appear to mangle the template arguments when
1045 // the template in question is a dependent template name. Should we
1046 // emulate that badness?
1047 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1048 addSubstitution(QualType(TST, 0));
1049 }
David Majnemera88b3592015-02-18 02:28:01 +00001050 } else if (const auto *DTST =
1051 type->getAs<DependentTemplateSpecializationType>()) {
1052 if (!mangleSubstitution(QualType(DTST, 0))) {
1053 TemplateName Template = getASTContext().getDependentTemplateName(
1054 DTST->getQualifier(), DTST->getIdentifier());
1055 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001056
David Majnemera88b3592015-02-18 02:28:01 +00001057 // FIXME: GCC does not appear to mangle the template arguments when
1058 // the template in question is a dependent template name. Should we
1059 // emulate that badness?
1060 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1061 addSubstitution(QualType(DTST, 0));
1062 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 } else {
1064 // We use the QualType mangle type variant here because it handles
1065 // substitutions.
1066 mangleType(type);
1067 }
1068}
1069
1070/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1071///
Guy Benyei11169dd2012-12-18 14:30:41 +00001072/// \param recursive - true if this is being called recursively,
1073/// i.e. if there is more prefix "to the right".
1074void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 bool recursive) {
1076
1077 // x, ::x
1078 // <unresolved-name> ::= [gs] <base-unresolved-name>
1079
1080 // T::x / decltype(p)::x
1081 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1082
1083 // T::N::x /decltype(p)::N::x
1084 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1085 // <base-unresolved-name>
1086
1087 // A::x, N::y, A<T>::z; "gs" means leading "::"
1088 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1089 // <base-unresolved-name>
1090
1091 switch (qualifier->getKind()) {
1092 case NestedNameSpecifier::Global:
1093 Out << "gs";
1094
1095 // We want an 'sr' unless this is the entire NNS.
1096 if (recursive)
1097 Out << "sr";
1098
1099 // We never want an 'E' here.
1100 return;
1101
Nikola Smiljanic67860242014-09-26 00:28:20 +00001102 case NestedNameSpecifier::Super:
1103 llvm_unreachable("Can't mangle __super specifier");
1104
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 case NestedNameSpecifier::Namespace:
1106 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001107 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 /*recursive*/ true);
1109 else
1110 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001111 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 break;
1113 case NestedNameSpecifier::NamespaceAlias:
1114 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001115 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 /*recursive*/ true);
1117 else
1118 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001119 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 break;
1121
1122 case NestedNameSpecifier::TypeSpec:
1123 case NestedNameSpecifier::TypeSpecWithTemplate: {
1124 const Type *type = qualifier->getAsType();
1125
1126 // We only want to use an unresolved-type encoding if this is one of:
1127 // - a decltype
1128 // - a template type parameter
1129 // - a template template parameter with arguments
1130 // In all of these cases, we should have no prefix.
1131 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001132 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 /*recursive*/ true);
1134 } else {
1135 // Otherwise, all the cases want this.
1136 Out << "sr";
1137 }
1138
David Majnemerb8014dd2015-02-19 02:16:16 +00001139 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 return;
1141
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 break;
1143 }
1144
1145 case NestedNameSpecifier::Identifier:
1146 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001147 if (qualifier->getPrefix())
1148 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001150 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001151 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001152
1153 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001154 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 break;
1156 }
1157
1158 // If this was the innermost part of the NNS, and we fell out to
1159 // here, append an 'E'.
1160 if (!recursive)
1161 Out << 'E';
1162}
1163
1164/// Mangle an unresolved-name, which is generally used for names which
1165/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001166void CXXNameMangler::mangleUnresolvedName(
1167 NestedNameSpecifier *qualifier, DeclarationName name,
1168 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1169 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001170 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001171 switch (name.getNameKind()) {
1172 // <base-unresolved-name> ::= <simple-id>
1173 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001174 mangleSourceName(name.getAsIdentifierInfo());
1175 break;
1176 // <base-unresolved-name> ::= dn <destructor-name>
1177 case DeclarationName::CXXDestructorName:
1178 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001179 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001180 break;
1181 // <base-unresolved-name> ::= on <operator-name>
1182 case DeclarationName::CXXConversionFunctionName:
1183 case DeclarationName::CXXLiteralOperatorName:
1184 case DeclarationName::CXXOperatorName:
1185 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001186 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001187 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001188 case DeclarationName::CXXConstructorName:
1189 llvm_unreachable("Can't mangle a constructor name!");
1190 case DeclarationName::CXXUsingDirective:
1191 llvm_unreachable("Can't mangle a using directive name!");
1192 case DeclarationName::ObjCMultiArgSelector:
1193 case DeclarationName::ObjCOneArgSelector:
1194 case DeclarationName::ObjCZeroArgSelector:
1195 llvm_unreachable("Can't mangle Objective-C selector names here!");
1196 }
Richard Smithafecd832016-10-24 20:47:04 +00001197
1198 // The <simple-id> and on <operator-name> productions end in an optional
1199 // <template-args>.
1200 if (TemplateArgs)
1201 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001202}
1203
Guy Benyei11169dd2012-12-18 14:30:41 +00001204void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1205 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001206 unsigned KnownArity,
1207 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001208 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 // <unqualified-name> ::= <operator-name>
1210 // ::= <ctor-dtor-name>
1211 // ::= <source-name>
1212 switch (Name.getNameKind()) {
1213 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001214 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1215
Richard Smithda383632016-08-15 01:33:41 +00001216 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001217 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001218 // FIXME: Non-standard mangling for decomposition declarations:
1219 //
1220 // <unqualified-name> ::= DC <source-name>* E
1221 //
1222 // These can never be referenced across translation units, so we do
1223 // not need a cross-vendor mangling for anything other than demanglers.
1224 // Proposed on cxx-abi-dev on 2016-08-12
1225 Out << "DC";
1226 for (auto *BD : DD->bindings())
1227 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1228 Out << 'E';
1229 writeAbiTags(ND, AdditionalAbiTags);
1230 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001231 }
1232
1233 if (II) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 // We must avoid conflicts between internally- and externally-
1235 // linked variable and function declaration names in the same TU:
1236 // void test() { extern void foo(); }
1237 // static void foo();
1238 // This naming convention is the same as that followed by GCC,
1239 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001240 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 getEffectiveDeclContext(ND)->isFileContext())
1242 Out << 'L';
1243
1244 mangleSourceName(II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001245 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246 break;
1247 }
1248
1249 // Otherwise, an anonymous entity. We must have a declaration.
1250 assert(ND && "mangling empty name without declaration");
1251
1252 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1253 if (NS->isAnonymousNamespace()) {
1254 // This is how gcc mangles these names.
1255 Out << "12_GLOBAL__N_1";
1256 break;
1257 }
1258 }
1259
1260 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1261 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001262 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001264
Guy Benyei11169dd2012-12-18 14:30:41 +00001265 // Itanium C++ ABI 5.1.2:
1266 //
1267 // For the purposes of mangling, the name of an anonymous union is
1268 // considered to be the name of the first named data member found by a
1269 // pre-order, depth-first, declaration-order walk of the data members of
1270 // the anonymous union. If there is no such data member (i.e., if all of
1271 // the data members in the union are unnamed), then there is no way for
1272 // a program to refer to the anonymous union, and there is therefore no
1273 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001274 assert(RD->isAnonymousStructOrUnion()
1275 && "Expected anonymous struct or union!");
1276 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001277
1278 // It's actually possible for various reasons for us to get here
1279 // with an empty anonymous struct / union. Fortunately, it
1280 // doesn't really matter what name we generate.
1281 if (!FD) break;
1282 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001283
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001285 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 break;
1287 }
John McCall924046f2013-04-10 06:08:21 +00001288
1289 // Class extensions have no name as a category, and it's possible
1290 // for them to be the semantic parent of certain declarations
1291 // (primarily, tag decls defined within declarations). Such
1292 // declarations will always have internal linkage, so the name
1293 // doesn't really matter, but we shouldn't crash on them. For
1294 // safety, just handle all ObjC containers here.
1295 if (isa<ObjCContainerDecl>(ND))
1296 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001297
1298 // We must have an anonymous struct.
1299 const TagDecl *TD = cast<TagDecl>(ND);
1300 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1301 assert(TD->getDeclContext() == D->getDeclContext() &&
1302 "Typedef should not be in another decl context!");
1303 assert(D->getDeclName().getAsIdentifierInfo() &&
1304 "Typedef was not named!");
1305 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001306 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1307 // Explicit abi tags are still possible; take from underlying type, not
1308 // from typedef.
1309 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 break;
1311 }
1312
1313 // <unnamed-type-name> ::= <closure-type-name>
1314 //
1315 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1316 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1317 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1318 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001319 assert(!AdditionalAbiTags &&
1320 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 mangleLambda(Record);
1322 break;
1323 }
1324 }
1325
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001326 if (TD->isExternallyVisible()) {
1327 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001329 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001330 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001331 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001332 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 break;
1334 }
1335
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001336 // Get a unique id for the anonymous struct. If it is not a real output
1337 // ID doesn't matter so use fake one.
1338 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001339
1340 // Mangle it as a source name in the form
1341 // [n] $_<id>
1342 // where n is the length of the string.
1343 SmallString<8> Str;
1344 Str += "$_";
1345 Str += llvm::utostr(AnonStructId);
1346
1347 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001348 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001349 break;
1350 }
1351
1352 case DeclarationName::ObjCZeroArgSelector:
1353 case DeclarationName::ObjCOneArgSelector:
1354 case DeclarationName::ObjCMultiArgSelector:
1355 llvm_unreachable("Can't mangle Objective-C selector names here!");
1356
Richard Smith5179eb72016-06-28 19:03:57 +00001357 case DeclarationName::CXXConstructorName: {
1358 const CXXRecordDecl *InheritedFrom = nullptr;
1359 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1360 if (auto Inherited =
1361 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1362 InheritedFrom = Inherited.getConstructor()->getParent();
1363 InheritedTemplateArgs =
1364 Inherited.getConstructor()->getTemplateSpecializationArgs();
1365 }
1366
Guy Benyei11169dd2012-12-18 14:30:41 +00001367 if (ND == Structor)
1368 // If the named decl is the C++ constructor we're mangling, use the type
1369 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001370 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 else
1372 // Otherwise, use the complete constructor name. This is relevant if a
1373 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001374 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1375
1376 // FIXME: The template arguments are part of the enclosing prefix or
1377 // nested-name, but it's more convenient to mangle them here.
1378 if (InheritedTemplateArgs)
1379 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001380
1381 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001384
1385 case DeclarationName::CXXDestructorName:
1386 if (ND == Structor)
1387 // If the named decl is the C++ destructor we're mangling, use the type we
1388 // were given.
1389 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1390 else
1391 // Otherwise, use the complete destructor name. This is relevant if a
1392 // class with a destructor is declared within a destructor.
1393 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001394 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 break;
1396
David Majnemera88b3592015-02-18 02:28:01 +00001397 case DeclarationName::CXXOperatorName:
1398 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 Arity = cast<FunctionDecl>(ND)->getNumParams();
1400
David Majnemera88b3592015-02-18 02:28:01 +00001401 // If we have a member function, we need to include the 'this' pointer.
1402 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1403 if (!MD->isStatic())
1404 Arity++;
1405 }
1406 // FALLTHROUGH
1407 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001409 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001410 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 break;
1412
1413 case DeclarationName::CXXUsingDirective:
1414 llvm_unreachable("Can't mangle a using directive name!");
1415 }
1416}
1417
1418void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1419 // <source-name> ::= <positive length number> <identifier>
1420 // <number> ::= [n] <non-negative decimal integer>
1421 // <identifier> ::= <unqualified source code identifier>
1422 Out << II->getLength() << II->getName();
1423}
1424
1425void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1426 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001427 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 bool NoFunction) {
1429 // <nested-name>
1430 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1431 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1432 // <template-args> E
1433
1434 Out << 'N';
1435 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001436 Qualifiers MethodQuals =
1437 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1438 // We do not consider restrict a distinguishing attribute for overloading
1439 // purposes so we must not mangle it.
1440 MethodQuals.removeRestrict();
1441 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 mangleRefQualifier(Method->getRefQualifier());
1443 }
1444
1445 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001446 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001448 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 mangleTemplateArgs(*TemplateArgs);
1450 }
1451 else {
1452 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001453 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 }
1455
1456 Out << 'E';
1457}
1458void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1459 const TemplateArgument *TemplateArgs,
1460 unsigned NumTemplateArgs) {
1461 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1462
1463 Out << 'N';
1464
1465 mangleTemplatePrefix(TD);
1466 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1467
1468 Out << 'E';
1469}
1470
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001471void CXXNameMangler::mangleLocalName(const Decl *D,
1472 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1474 // := Z <function encoding> E s [<discriminator>]
1475 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1476 // _ <entity name>
1477 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001478 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001479 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001480 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
1482 Out << 'Z';
1483
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001484 {
1485 AbiTagState LocalAbiTags(AbiTags);
1486
1487 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1488 mangleObjCMethodName(MD);
1489 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1490 mangleBlockForPrefix(BD);
1491 else
1492 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1493
1494 // Implicit ABI tags (from namespace) are not available in the following
1495 // entity; reset to actually emitted tags, which are available.
1496 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1497 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001498
Eli Friedman92821742013-07-02 02:01:18 +00001499 Out << 'E';
1500
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001501 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1502 // be a bug that is fixed in trunk.
1503
Eli Friedman92821742013-07-02 02:01:18 +00001504 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 // The parameter number is omitted for the last parameter, 0 for the
1506 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1507 // <entity name> will of course contain a <closure-type-name>: Its
1508 // numbering will be local to the particular argument in which it appears
1509 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001510 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001511 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001513 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 if (const FunctionDecl *Func
1515 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1516 Out << 'd';
1517 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1518 if (Num > 1)
1519 mangleNumber(Num - 2);
1520 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 }
1522 }
1523 }
1524
1525 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001526 // equality ok because RD derived from ND above
1527 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001528 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001529 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1530 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001531 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001532 mangleUnqualifiedBlock(BD);
1533 } else {
1534 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001535 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1536 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001537 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001538 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1539 // Mangle a block in a default parameter; see above explanation for
1540 // lambdas.
1541 if (const ParmVarDecl *Parm
1542 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1543 if (const FunctionDecl *Func
1544 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1545 Out << 'd';
1546 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1547 if (Num > 1)
1548 mangleNumber(Num - 2);
1549 Out << '_';
1550 }
1551 }
1552
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001553 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001554 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001555 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001556 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001558
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001559 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1560 unsigned disc;
1561 if (Context.getNextDiscriminator(ND, disc)) {
1562 if (disc < 10)
1563 Out << '_' << disc;
1564 else
1565 Out << "__" << disc << '_';
1566 }
1567 }
Eli Friedman95f50122013-07-02 17:52:28 +00001568}
1569
1570void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1571 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001572 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001573 return;
1574 }
1575 const DeclContext *DC = getEffectiveDeclContext(Block);
1576 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001577 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001578 return;
1579 }
1580 manglePrefix(getEffectiveDeclContext(Block));
1581 mangleUnqualifiedBlock(Block);
1582}
1583
1584void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1585 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1586 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1587 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001588 const auto *ND = cast<NamedDecl>(Context);
1589 if (ND->getIdentifier()) {
1590 mangleSourceNameWithAbiTags(ND);
1591 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001592 }
1593 }
1594 }
1595
1596 // If we have a block mangling number, use it.
1597 unsigned Number = Block->getBlockManglingNumber();
1598 // Otherwise, just make up a number. It doesn't matter what it is because
1599 // the symbol in question isn't externally visible.
1600 if (!Number)
1601 Number = Context.getBlockId(Block, false);
1602 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001603 if (Number > 0)
1604 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001605 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001606}
1607
1608void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1609 // If the context of a closure type is an initializer for a class member
1610 // (static or nonstatic), it is encoded in a qualified name with a final
1611 // <prefix> of the form:
1612 //
1613 // <data-member-prefix> := <member source-name> M
1614 //
1615 // Technically, the data-member-prefix is part of the <prefix>. However,
1616 // since a closure type will always be mangled with a prefix, it's easier
1617 // to emit that last part of the prefix here.
1618 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1619 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1620 Context->getDeclContext()->isRecord()) {
1621 if (const IdentifierInfo *Name
1622 = cast<NamedDecl>(Context)->getIdentifier()) {
1623 mangleSourceName(Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001624 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 }
1626 }
1627 }
1628
1629 Out << "Ul";
1630 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1631 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001632 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1633 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 Out << "E";
1635
1636 // The number is omitted for the first closure type with a given
1637 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1638 // (in lexical order) with that same <lambda-sig> and context.
1639 //
1640 // The AST keeps track of the number for us.
1641 unsigned Number = Lambda->getLambdaManglingNumber();
1642 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1643 if (Number > 1)
1644 mangleNumber(Number - 2);
1645 Out << '_';
1646}
1647
1648void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1649 switch (qualifier->getKind()) {
1650 case NestedNameSpecifier::Global:
1651 // nothing
1652 return;
1653
Nikola Smiljanic67860242014-09-26 00:28:20 +00001654 case NestedNameSpecifier::Super:
1655 llvm_unreachable("Can't mangle __super specifier");
1656
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 case NestedNameSpecifier::Namespace:
1658 mangleName(qualifier->getAsNamespace());
1659 return;
1660
1661 case NestedNameSpecifier::NamespaceAlias:
1662 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1663 return;
1664
1665 case NestedNameSpecifier::TypeSpec:
1666 case NestedNameSpecifier::TypeSpecWithTemplate:
1667 manglePrefix(QualType(qualifier->getAsType(), 0));
1668 return;
1669
1670 case NestedNameSpecifier::Identifier:
1671 // Member expressions can have these without prefixes, but that
1672 // should end up in mangleUnresolvedPrefix instead.
1673 assert(qualifier->getPrefix());
1674 manglePrefix(qualifier->getPrefix());
1675
1676 mangleSourceName(qualifier->getAsIdentifier());
1677 return;
1678 }
1679
1680 llvm_unreachable("unexpected nested name specifier");
1681}
1682
1683void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1684 // <prefix> ::= <prefix> <unqualified-name>
1685 // ::= <template-prefix> <template-args>
1686 // ::= <template-param>
1687 // ::= # empty
1688 // ::= <substitution>
1689
1690 DC = IgnoreLinkageSpecDecls(DC);
1691
1692 if (DC->isTranslationUnit())
1693 return;
1694
Eli Friedman95f50122013-07-02 17:52:28 +00001695 if (NoFunction && isLocalContainerContext(DC))
1696 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001697
Eli Friedman95f50122013-07-02 17:52:28 +00001698 assert(!isLocalContainerContext(DC));
1699
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 const NamedDecl *ND = cast<NamedDecl>(DC);
1701 if (mangleSubstitution(ND))
1702 return;
1703
1704 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001705 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1707 mangleTemplatePrefix(TD);
1708 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001709 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001710 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001711 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 }
1713
1714 addSubstitution(ND);
1715}
1716
1717void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1718 // <template-prefix> ::= <prefix> <template unqualified-name>
1719 // ::= <template-param>
1720 // ::= <substitution>
1721 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1722 return mangleTemplatePrefix(TD);
1723
1724 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1725 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001726
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 if (OverloadedTemplateStorage *Overloaded
1728 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001729 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001730 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001731 return;
1732 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001733
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1735 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001736 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1737 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001738 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001739}
1740
Eli Friedman86af13f02013-07-05 18:41:30 +00001741void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1742 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 // <template-prefix> ::= <prefix> <template unqualified-name>
1744 // ::= <template-param>
1745 // ::= <substitution>
1746 // <template-template-param> ::= <template-param>
1747 // <substitution>
1748
1749 if (mangleSubstitution(ND))
1750 return;
1751
1752 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001753 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001755 } else {
1756 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001757 if (isa<BuiltinTemplateDecl>(ND))
1758 mangleUnqualifiedName(ND, nullptr);
1759 else
1760 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001761 }
1762
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 addSubstitution(ND);
1764}
1765
1766/// Mangles a template name under the production <type>. Required for
1767/// template template arguments.
1768/// <type> ::= <class-enum-type>
1769/// ::= <template-param>
1770/// ::= <substitution>
1771void CXXNameMangler::mangleType(TemplateName TN) {
1772 if (mangleSubstitution(TN))
1773 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001774
1775 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001776
1777 switch (TN.getKind()) {
1778 case TemplateName::QualifiedTemplate:
1779 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1780 goto HaveDecl;
1781
1782 case TemplateName::Template:
1783 TD = TN.getAsTemplateDecl();
1784 goto HaveDecl;
1785
1786 HaveDecl:
1787 if (isa<TemplateTemplateParmDecl>(TD))
1788 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1789 else
1790 mangleName(TD);
1791 break;
1792
1793 case TemplateName::OverloadedTemplate:
1794 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1795
1796 case TemplateName::DependentTemplate: {
1797 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1798 assert(Dependent->isIdentifier());
1799
1800 // <class-enum-type> ::= <name>
1801 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001802 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001803 mangleSourceName(Dependent->getIdentifier());
1804 break;
1805 }
1806
1807 case TemplateName::SubstTemplateTemplateParm: {
1808 // Substituted template parameters are mangled as the substituted
1809 // template. This will check for the substitution twice, which is
1810 // fine, but we have to return early so that we don't try to *add*
1811 // the substitution twice.
1812 SubstTemplateTemplateParmStorage *subst
1813 = TN.getAsSubstTemplateTemplateParm();
1814 mangleType(subst->getReplacement());
1815 return;
1816 }
1817
1818 case TemplateName::SubstTemplateTemplateParmPack: {
1819 // FIXME: not clear how to mangle this!
1820 // template <template <class> class T...> class A {
1821 // template <template <class> class U...> void foo(B<T,U> x...);
1822 // };
1823 Out << "_SUBSTPACK_";
1824 break;
1825 }
1826 }
1827
1828 addSubstitution(TN);
1829}
1830
David Majnemerb8014dd2015-02-19 02:16:16 +00001831bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1832 StringRef Prefix) {
1833 // Only certain other types are valid as prefixes; enumerate them.
1834 switch (Ty->getTypeClass()) {
1835 case Type::Builtin:
1836 case Type::Complex:
1837 case Type::Adjusted:
1838 case Type::Decayed:
1839 case Type::Pointer:
1840 case Type::BlockPointer:
1841 case Type::LValueReference:
1842 case Type::RValueReference:
1843 case Type::MemberPointer:
1844 case Type::ConstantArray:
1845 case Type::IncompleteArray:
1846 case Type::VariableArray:
1847 case Type::DependentSizedArray:
1848 case Type::DependentSizedExtVector:
1849 case Type::Vector:
1850 case Type::ExtVector:
1851 case Type::FunctionProto:
1852 case Type::FunctionNoProto:
1853 case Type::Paren:
1854 case Type::Attributed:
1855 case Type::Auto:
1856 case Type::PackExpansion:
1857 case Type::ObjCObject:
1858 case Type::ObjCInterface:
1859 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001860 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001861 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001862 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001863 llvm_unreachable("type is illegal as a nested name specifier");
1864
1865 case Type::SubstTemplateTypeParmPack:
1866 // FIXME: not clear how to mangle this!
1867 // template <class T...> class A {
1868 // template <class U...> void foo(decltype(T::foo(U())) x...);
1869 // };
1870 Out << "_SUBSTPACK_";
1871 break;
1872
1873 // <unresolved-type> ::= <template-param>
1874 // ::= <decltype>
1875 // ::= <template-template-param> <template-args>
1876 // (this last is not official yet)
1877 case Type::TypeOfExpr:
1878 case Type::TypeOf:
1879 case Type::Decltype:
1880 case Type::TemplateTypeParm:
1881 case Type::UnaryTransform:
1882 case Type::SubstTemplateTypeParm:
1883 unresolvedType:
1884 // Some callers want a prefix before the mangled type.
1885 Out << Prefix;
1886
1887 // This seems to do everything we want. It's not really
1888 // sanctioned for a substituted template parameter, though.
1889 mangleType(Ty);
1890
1891 // We never want to print 'E' directly after an unresolved-type,
1892 // so we return directly.
1893 return true;
1894
1895 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001896 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001897 break;
1898
1899 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001900 mangleSourceNameWithAbiTags(
1901 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001902 break;
1903
1904 case Type::Enum:
1905 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001906 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001907 break;
1908
1909 case Type::TemplateSpecialization: {
1910 const TemplateSpecializationType *TST =
1911 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001912 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001913 switch (TN.getKind()) {
1914 case TemplateName::Template:
1915 case TemplateName::QualifiedTemplate: {
1916 TemplateDecl *TD = TN.getAsTemplateDecl();
1917
1918 // If the base is a template template parameter, this is an
1919 // unresolved type.
1920 assert(TD && "no template for template specialization type");
1921 if (isa<TemplateTemplateParmDecl>(TD))
1922 goto unresolvedType;
1923
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001924 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00001925 break;
David Majnemera88b3592015-02-18 02:28:01 +00001926 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001927
1928 case TemplateName::OverloadedTemplate:
1929 case TemplateName::DependentTemplate:
1930 llvm_unreachable("invalid base for a template specialization type");
1931
1932 case TemplateName::SubstTemplateTemplateParm: {
1933 SubstTemplateTemplateParmStorage *subst =
1934 TN.getAsSubstTemplateTemplateParm();
1935 mangleExistingSubstitution(subst->getReplacement());
1936 break;
1937 }
1938
1939 case TemplateName::SubstTemplateTemplateParmPack: {
1940 // FIXME: not clear how to mangle this!
1941 // template <template <class U> class T...> class A {
1942 // template <class U...> void foo(decltype(T<U>::foo) x...);
1943 // };
1944 Out << "_SUBSTPACK_";
1945 break;
1946 }
1947 }
1948
David Majnemera88b3592015-02-18 02:28:01 +00001949 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001950 break;
David Majnemera88b3592015-02-18 02:28:01 +00001951 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001952
1953 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001954 mangleSourceNameWithAbiTags(
1955 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001956 break;
1957
1958 case Type::DependentName:
1959 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1960 break;
1961
1962 case Type::DependentTemplateSpecialization: {
1963 const DependentTemplateSpecializationType *DTST =
1964 cast<DependentTemplateSpecializationType>(Ty);
1965 mangleSourceName(DTST->getIdentifier());
1966 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1967 break;
1968 }
1969
1970 case Type::Elaborated:
1971 return mangleUnresolvedTypeOrSimpleId(
1972 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1973 }
1974
1975 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001976}
1977
1978void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1979 switch (Name.getNameKind()) {
1980 case DeclarationName::CXXConstructorName:
1981 case DeclarationName::CXXDestructorName:
1982 case DeclarationName::CXXUsingDirective:
1983 case DeclarationName::Identifier:
1984 case DeclarationName::ObjCMultiArgSelector:
1985 case DeclarationName::ObjCOneArgSelector:
1986 case DeclarationName::ObjCZeroArgSelector:
1987 llvm_unreachable("Not an operator name");
1988
1989 case DeclarationName::CXXConversionFunctionName:
1990 // <operator-name> ::= cv <type> # (cast)
1991 Out << "cv";
1992 mangleType(Name.getCXXNameType());
1993 break;
1994
1995 case DeclarationName::CXXLiteralOperatorName:
1996 Out << "li";
1997 mangleSourceName(Name.getCXXLiteralIdentifier());
1998 return;
1999
2000 case DeclarationName::CXXOperatorName:
2001 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2002 break;
2003 }
2004}
2005
Guy Benyei11169dd2012-12-18 14:30:41 +00002006void
2007CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2008 switch (OO) {
2009 // <operator-name> ::= nw # new
2010 case OO_New: Out << "nw"; break;
2011 // ::= na # new[]
2012 case OO_Array_New: Out << "na"; break;
2013 // ::= dl # delete
2014 case OO_Delete: Out << "dl"; break;
2015 // ::= da # delete[]
2016 case OO_Array_Delete: Out << "da"; break;
2017 // ::= ps # + (unary)
2018 // ::= pl # + (binary or unknown)
2019 case OO_Plus:
2020 Out << (Arity == 1? "ps" : "pl"); break;
2021 // ::= ng # - (unary)
2022 // ::= mi # - (binary or unknown)
2023 case OO_Minus:
2024 Out << (Arity == 1? "ng" : "mi"); break;
2025 // ::= ad # & (unary)
2026 // ::= an # & (binary or unknown)
2027 case OO_Amp:
2028 Out << (Arity == 1? "ad" : "an"); break;
2029 // ::= de # * (unary)
2030 // ::= ml # * (binary or unknown)
2031 case OO_Star:
2032 // Use binary when unknown.
2033 Out << (Arity == 1? "de" : "ml"); break;
2034 // ::= co # ~
2035 case OO_Tilde: Out << "co"; break;
2036 // ::= dv # /
2037 case OO_Slash: Out << "dv"; break;
2038 // ::= rm # %
2039 case OO_Percent: Out << "rm"; break;
2040 // ::= or # |
2041 case OO_Pipe: Out << "or"; break;
2042 // ::= eo # ^
2043 case OO_Caret: Out << "eo"; break;
2044 // ::= aS # =
2045 case OO_Equal: Out << "aS"; break;
2046 // ::= pL # +=
2047 case OO_PlusEqual: Out << "pL"; break;
2048 // ::= mI # -=
2049 case OO_MinusEqual: Out << "mI"; break;
2050 // ::= mL # *=
2051 case OO_StarEqual: Out << "mL"; break;
2052 // ::= dV # /=
2053 case OO_SlashEqual: Out << "dV"; break;
2054 // ::= rM # %=
2055 case OO_PercentEqual: Out << "rM"; break;
2056 // ::= aN # &=
2057 case OO_AmpEqual: Out << "aN"; break;
2058 // ::= oR # |=
2059 case OO_PipeEqual: Out << "oR"; break;
2060 // ::= eO # ^=
2061 case OO_CaretEqual: Out << "eO"; break;
2062 // ::= ls # <<
2063 case OO_LessLess: Out << "ls"; break;
2064 // ::= rs # >>
2065 case OO_GreaterGreater: Out << "rs"; break;
2066 // ::= lS # <<=
2067 case OO_LessLessEqual: Out << "lS"; break;
2068 // ::= rS # >>=
2069 case OO_GreaterGreaterEqual: Out << "rS"; break;
2070 // ::= eq # ==
2071 case OO_EqualEqual: Out << "eq"; break;
2072 // ::= ne # !=
2073 case OO_ExclaimEqual: Out << "ne"; break;
2074 // ::= lt # <
2075 case OO_Less: Out << "lt"; break;
2076 // ::= gt # >
2077 case OO_Greater: Out << "gt"; break;
2078 // ::= le # <=
2079 case OO_LessEqual: Out << "le"; break;
2080 // ::= ge # >=
2081 case OO_GreaterEqual: Out << "ge"; break;
2082 // ::= nt # !
2083 case OO_Exclaim: Out << "nt"; break;
2084 // ::= aa # &&
2085 case OO_AmpAmp: Out << "aa"; break;
2086 // ::= oo # ||
2087 case OO_PipePipe: Out << "oo"; break;
2088 // ::= pp # ++
2089 case OO_PlusPlus: Out << "pp"; break;
2090 // ::= mm # --
2091 case OO_MinusMinus: Out << "mm"; break;
2092 // ::= cm # ,
2093 case OO_Comma: Out << "cm"; break;
2094 // ::= pm # ->*
2095 case OO_ArrowStar: Out << "pm"; break;
2096 // ::= pt # ->
2097 case OO_Arrow: Out << "pt"; break;
2098 // ::= cl # ()
2099 case OO_Call: Out << "cl"; break;
2100 // ::= ix # []
2101 case OO_Subscript: Out << "ix"; break;
2102
2103 // ::= qu # ?
2104 // The conditional operator can't be overloaded, but we still handle it when
2105 // mangling expressions.
2106 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002107 // Proposal on cxx-abi-dev, 2015-10-21.
2108 // ::= aw # co_await
2109 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002110
2111 case OO_None:
2112 case NUM_OVERLOADED_OPERATORS:
2113 llvm_unreachable("Not an overloaded operator");
2114 }
2115}
2116
2117void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
John McCall07daf722016-03-01 22:18:03 +00002118 // Vendor qualifiers come first.
Guy Benyei11169dd2012-12-18 14:30:41 +00002119
John McCall07daf722016-03-01 22:18:03 +00002120 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002122 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 //
David Tweed31d09b02013-09-13 12:04:22 +00002124 // <type> ::= U <target-addrspace>
2125 // <type> ::= U <OpenCL-addrspace>
2126 // <type> ::= U <CUDA-addrspace>
2127
Guy Benyei11169dd2012-12-18 14:30:41 +00002128 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00002129 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002130
2131 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2132 // <target-addrspace> ::= "AS" <address-space-number>
2133 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00002134 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002135 } else {
2136 switch (AS) {
2137 default: llvm_unreachable("Not a language specific address space");
2138 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
2139 case LangAS::opencl_global: ASString = "CLglobal"; break;
2140 case LangAS::opencl_local: ASString = "CLlocal"; break;
2141 case LangAS::opencl_constant: ASString = "CLconstant"; break;
2142 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2143 case LangAS::cuda_device: ASString = "CUdevice"; break;
2144 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2145 case LangAS::cuda_shared: ASString = "CUshared"; break;
2146 }
2147 }
John McCall07daf722016-03-01 22:18:03 +00002148 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002149 }
John McCall07daf722016-03-01 22:18:03 +00002150
2151 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 switch (Quals.getObjCLifetime()) {
2153 // Objective-C ARC Extension:
2154 //
2155 // <type> ::= U "__strong"
2156 // <type> ::= U "__weak"
2157 // <type> ::= U "__autoreleasing"
2158 case Qualifiers::OCL_None:
2159 break;
2160
2161 case Qualifiers::OCL_Weak:
John McCall07daf722016-03-01 22:18:03 +00002162 mangleVendorQualifier("__weak");
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 break;
2164
2165 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002166 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002167 break;
2168
2169 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002170 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 break;
2172
2173 case Qualifiers::OCL_ExplicitNone:
2174 // The __unsafe_unretained qualifier is *not* mangled, so that
2175 // __unsafe_unretained types in ARC produce the same manglings as the
2176 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2177 // better ABI compatibility.
2178 //
2179 // It's safe to do this because unqualified 'id' won't show up
2180 // in any type signatures that need to be mangled.
2181 break;
2182 }
John McCall07daf722016-03-01 22:18:03 +00002183
2184 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2185 if (Quals.hasRestrict())
2186 Out << 'r';
2187 if (Quals.hasVolatile())
2188 Out << 'V';
2189 if (Quals.hasConst())
2190 Out << 'K';
2191}
2192
2193void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2194 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002195}
2196
2197void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2198 // <ref-qualifier> ::= R # lvalue reference
2199 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 switch (RefQualifier) {
2201 case RQ_None:
2202 break;
2203
2204 case RQ_LValue:
2205 Out << 'R';
2206 break;
2207
2208 case RQ_RValue:
2209 Out << 'O';
2210 break;
2211 }
2212}
2213
2214void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2215 Context.mangleObjCMethodName(MD, Out);
2216}
2217
David Majnemereea02ee2014-11-28 22:22:46 +00002218static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2219 if (Quals)
2220 return true;
2221 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2222 return true;
2223 if (Ty->isOpenCLSpecificType())
2224 return true;
2225 if (Ty->isBuiltinType())
2226 return false;
2227
2228 return true;
2229}
2230
Guy Benyei11169dd2012-12-18 14:30:41 +00002231void CXXNameMangler::mangleType(QualType T) {
2232 // If our type is instantiation-dependent but not dependent, we mangle
2233 // it as it was written in the source, removing any top-level sugar.
2234 // Otherwise, use the canonical type.
2235 //
2236 // FIXME: This is an approximation of the instantiation-dependent name
2237 // mangling rules, since we should really be using the type as written and
2238 // augmented via semantic analysis (i.e., with implicit conversions and
2239 // default template arguments) for any instantiation-dependent type.
2240 // Unfortunately, that requires several changes to our AST:
2241 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2242 // uniqued, so that we can handle substitutions properly
2243 // - Default template arguments will need to be represented in the
2244 // TemplateSpecializationType, since they need to be mangled even though
2245 // they aren't written.
2246 // - Conversions on non-type template arguments need to be expressed, since
2247 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002248 //
2249 // FIXME: This is wrong when mapping to the canonical type for a dependent
2250 // type discards instantiation-dependent portions of the type, such as for:
2251 //
2252 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2253 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2254 //
2255 // It's also wrong in the opposite direction when instantiation-dependent,
2256 // canonically-equivalent types differ in some irrelevant portion of inner
2257 // type sugar. In such cases, we fail to form correct substitutions, eg:
2258 //
2259 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2260 //
2261 // We should instead canonicalize the non-instantiation-dependent parts,
2262 // regardless of whether the type as a whole is dependent or instantiation
2263 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 if (!T->isInstantiationDependentType() || T->isDependentType())
2265 T = T.getCanonicalType();
2266 else {
2267 // Desugar any types that are purely sugar.
2268 do {
2269 // Don't desugar through template specialization types that aren't
2270 // type aliases. We need to mangle the template arguments as written.
2271 if (const TemplateSpecializationType *TST
2272 = dyn_cast<TemplateSpecializationType>(T))
2273 if (!TST->isTypeAlias())
2274 break;
2275
2276 QualType Desugared
2277 = T.getSingleStepDesugaredType(Context.getASTContext());
2278 if (Desugared == T)
2279 break;
2280
2281 T = Desugared;
2282 } while (true);
2283 }
2284 SplitQualType split = T.split();
2285 Qualifiers quals = split.Quals;
2286 const Type *ty = split.Ty;
2287
David Majnemereea02ee2014-11-28 22:22:46 +00002288 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 if (isSubstitutable && mangleSubstitution(T))
2290 return;
2291
2292 // If we're mangling a qualified array type, push the qualifiers to
2293 // the element type.
2294 if (quals && isa<ArrayType>(T)) {
2295 ty = Context.getASTContext().getAsArrayType(T);
2296 quals = Qualifiers();
2297
2298 // Note that we don't update T: we want to add the
2299 // substitution at the original type.
2300 }
2301
2302 if (quals) {
2303 mangleQualifiers(quals);
2304 // Recurse: even if the qualified type isn't yet substitutable,
2305 // the unqualified type might be.
2306 mangleType(QualType(ty, 0));
2307 } else {
2308 switch (ty->getTypeClass()) {
2309#define ABSTRACT_TYPE(CLASS, PARENT)
2310#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2311 case Type::CLASS: \
2312 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2313 return;
2314#define TYPE(CLASS, PARENT) \
2315 case Type::CLASS: \
2316 mangleType(static_cast<const CLASS##Type*>(ty)); \
2317 break;
2318#include "clang/AST/TypeNodes.def"
2319 }
2320 }
2321
2322 // Add the substitution.
2323 if (isSubstitutable)
2324 addSubstitution(T);
2325}
2326
2327void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2328 if (!mangleStandardSubstitution(ND))
2329 mangleName(ND);
2330}
2331
2332void CXXNameMangler::mangleType(const BuiltinType *T) {
2333 // <type> ::= <builtin-type>
2334 // <builtin-type> ::= v # void
2335 // ::= w # wchar_t
2336 // ::= b # bool
2337 // ::= c # char
2338 // ::= a # signed char
2339 // ::= h # unsigned char
2340 // ::= s # short
2341 // ::= t # unsigned short
2342 // ::= i # int
2343 // ::= j # unsigned int
2344 // ::= l # long
2345 // ::= m # unsigned long
2346 // ::= x # long long, __int64
2347 // ::= y # unsigned long long, __int64
2348 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002349 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 // ::= f # float
2351 // ::= d # double
2352 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002353 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2355 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2356 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2357 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2358 // ::= Di # char32_t
2359 // ::= Ds # char16_t
2360 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2361 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002362 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002364 case BuiltinType::Void:
2365 Out << 'v';
2366 break;
2367 case BuiltinType::Bool:
2368 Out << 'b';
2369 break;
2370 case BuiltinType::Char_U:
2371 case BuiltinType::Char_S:
2372 Out << 'c';
2373 break;
2374 case BuiltinType::UChar:
2375 Out << 'h';
2376 break;
2377 case BuiltinType::UShort:
2378 Out << 't';
2379 break;
2380 case BuiltinType::UInt:
2381 Out << 'j';
2382 break;
2383 case BuiltinType::ULong:
2384 Out << 'm';
2385 break;
2386 case BuiltinType::ULongLong:
2387 Out << 'y';
2388 break;
2389 case BuiltinType::UInt128:
2390 Out << 'o';
2391 break;
2392 case BuiltinType::SChar:
2393 Out << 'a';
2394 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002396 case BuiltinType::WChar_U:
2397 Out << 'w';
2398 break;
2399 case BuiltinType::Char16:
2400 Out << "Ds";
2401 break;
2402 case BuiltinType::Char32:
2403 Out << "Di";
2404 break;
2405 case BuiltinType::Short:
2406 Out << 's';
2407 break;
2408 case BuiltinType::Int:
2409 Out << 'i';
2410 break;
2411 case BuiltinType::Long:
2412 Out << 'l';
2413 break;
2414 case BuiltinType::LongLong:
2415 Out << 'x';
2416 break;
2417 case BuiltinType::Int128:
2418 Out << 'n';
2419 break;
2420 case BuiltinType::Half:
2421 Out << "Dh";
2422 break;
2423 case BuiltinType::Float:
2424 Out << 'f';
2425 break;
2426 case BuiltinType::Double:
2427 Out << 'd';
2428 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002429 case BuiltinType::LongDouble:
2430 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2431 ? 'g'
2432 : 'e');
2433 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002434 case BuiltinType::Float128:
2435 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2436 Out << "U10__float128"; // Match the GCC mangling
2437 else
2438 Out << 'g';
2439 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002440 case BuiltinType::NullPtr:
2441 Out << "Dn";
2442 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002443
2444#define BUILTIN_TYPE(Id, SingletonId)
2445#define PLACEHOLDER_TYPE(Id, SingletonId) \
2446 case BuiltinType::Id:
2447#include "clang/AST/BuiltinTypes.def"
2448 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002449 if (!NullOut)
2450 llvm_unreachable("mangling a placeholder type");
2451 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002452 case BuiltinType::ObjCId:
2453 Out << "11objc_object";
2454 break;
2455 case BuiltinType::ObjCClass:
2456 Out << "10objc_class";
2457 break;
2458 case BuiltinType::ObjCSel:
2459 Out << "13objc_selector";
2460 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002461#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2462 case BuiltinType::Id: \
2463 type_name = "ocl_" #ImgType "_" #Suffix; \
2464 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002465 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002466#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002467 case BuiltinType::OCLSampler:
2468 Out << "11ocl_sampler";
2469 break;
2470 case BuiltinType::OCLEvent:
2471 Out << "9ocl_event";
2472 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002473 case BuiltinType::OCLClkEvent:
2474 Out << "12ocl_clkevent";
2475 break;
2476 case BuiltinType::OCLQueue:
2477 Out << "9ocl_queue";
2478 break;
2479 case BuiltinType::OCLNDRange:
2480 Out << "11ocl_ndrange";
2481 break;
2482 case BuiltinType::OCLReserveID:
2483 Out << "13ocl_reserveid";
2484 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 }
2486}
2487
John McCall07daf722016-03-01 22:18:03 +00002488StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2489 switch (CC) {
2490 case CC_C:
2491 return "";
2492
2493 case CC_X86StdCall:
2494 case CC_X86FastCall:
2495 case CC_X86ThisCall:
2496 case CC_X86VectorCall:
2497 case CC_X86Pascal:
2498 case CC_X86_64Win64:
2499 case CC_X86_64SysV:
2500 case CC_AAPCS:
2501 case CC_AAPCS_VFP:
2502 case CC_IntelOclBicc:
2503 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002504 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002505 case CC_PreserveMost:
2506 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002507 // FIXME: we should be mangling all of the above.
2508 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002509
2510 case CC_Swift:
2511 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002512 }
2513 llvm_unreachable("bad calling convention");
2514}
2515
2516void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2517 // Fast path.
2518 if (T->getExtInfo() == FunctionType::ExtInfo())
2519 return;
2520
2521 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2522 // This will get more complicated in the future if we mangle other
2523 // things here; but for now, since we mangle ns_returns_retained as
2524 // a qualifier on the result type, we can get away with this:
2525 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2526 if (!CCQualifier.empty())
2527 mangleVendorQualifier(CCQualifier);
2528
2529 // FIXME: regparm
2530 // FIXME: noreturn
2531}
2532
2533void
2534CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2535 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2536
2537 // Note that these are *not* substitution candidates. Demanglers might
2538 // have trouble with this if the parameter type is fully substituted.
2539
John McCall477f2bb2016-03-03 06:39:32 +00002540 switch (PI.getABI()) {
2541 case ParameterABI::Ordinary:
2542 break;
2543
2544 // All of these start with "swift", so they come before "ns_consumed".
2545 case ParameterABI::SwiftContext:
2546 case ParameterABI::SwiftErrorResult:
2547 case ParameterABI::SwiftIndirectResult:
2548 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2549 break;
2550 }
2551
John McCall07daf722016-03-01 22:18:03 +00002552 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002553 mangleVendorQualifier("ns_consumed");
John McCall07daf722016-03-01 22:18:03 +00002554}
2555
Guy Benyei11169dd2012-12-18 14:30:41 +00002556// <type> ::= <function-type>
2557// <function-type> ::= [<CV-qualifiers>] F [Y]
2558// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002559void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002560 mangleExtFunctionInfo(T);
2561
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2563 // e.g. "const" in "int (A::*)() const".
2564 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2565
Richard Smithfda59e52016-10-26 01:05:54 +00002566 // Mangle instantiation-dependent exception-specification, if present,
2567 // per cxx-abi-dev proposal on 2016-10-11.
2568 if (T->hasInstantiationDependentExceptionSpec()) {
2569 if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
2570 Out << "nX";
2571 mangleExpression(T->getNoexceptExpr());
2572 Out << "E";
2573 } else {
2574 assert(T->getExceptionSpecType() == EST_Dynamic);
2575 Out << "tw";
2576 for (auto ExceptTy : T->exceptions())
2577 mangleType(ExceptTy);
2578 Out << "E";
2579 }
2580 } else if (T->isNothrow(getASTContext())) {
2581 Out << "nx";
2582 }
2583
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 Out << 'F';
2585
2586 // FIXME: We don't have enough information in the AST to produce the 'Y'
2587 // encoding for extern "C" function types.
2588 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2589
2590 // Mangle the ref-qualifier, if present.
2591 mangleRefQualifier(T->getRefQualifier());
2592
2593 Out << 'E';
2594}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002597 // Function types without prototypes can arise when mangling a function type
2598 // within an overloadable function in C. We mangle these as the absence of any
2599 // parameter types (not even an empty parameter list).
2600 Out << 'F';
2601
2602 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2603
2604 FunctionTypeDepth.enterResultType();
2605 mangleType(T->getReturnType());
2606 FunctionTypeDepth.leaveResultType();
2607
2608 FunctionTypeDepth.pop(saved);
2609 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002610}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002611
John McCall07daf722016-03-01 22:18:03 +00002612void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002613 bool MangleReturnType,
2614 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 // Record that we're in a function type. See mangleFunctionParam
2616 // for details on what we're trying to achieve here.
2617 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2618
2619 // <bare-function-type> ::= <signature type>+
2620 if (MangleReturnType) {
2621 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002622
2623 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002624 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002625 mangleVendorQualifier("ns_returns_retained");
2626
2627 // Mangle the return type without any direct ARC ownership qualifiers.
2628 QualType ReturnTy = Proto->getReturnType();
2629 if (ReturnTy.getObjCLifetime()) {
2630 auto SplitReturnTy = ReturnTy.split();
2631 SplitReturnTy.Quals.removeObjCLifetime();
2632 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2633 }
2634 mangleType(ReturnTy);
2635
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 FunctionTypeDepth.leaveResultType();
2637 }
2638
Alp Toker9cacbab2014-01-20 20:26:09 +00002639 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 // <builtin-type> ::= v # void
2641 Out << 'v';
2642
2643 FunctionTypeDepth.pop(saved);
2644 return;
2645 }
2646
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002647 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2648 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002649 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002650 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002651 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2652 }
2653
2654 // Mangle the type.
2655 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002656 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2657
2658 if (FD) {
2659 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2660 // Attr can only take 1 character, so we can hardcode the length below.
2661 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2662 Out << "U17pass_object_size" << Attr->getType();
2663 }
2664 }
2665 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002666
2667 FunctionTypeDepth.pop(saved);
2668
2669 // <builtin-type> ::= z # ellipsis
2670 if (Proto->isVariadic())
2671 Out << 'z';
2672}
2673
2674// <type> ::= <class-enum-type>
2675// <class-enum-type> ::= <name>
2676void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2677 mangleName(T->getDecl());
2678}
2679
2680// <type> ::= <class-enum-type>
2681// <class-enum-type> ::= <name>
2682void CXXNameMangler::mangleType(const EnumType *T) {
2683 mangleType(static_cast<const TagType*>(T));
2684}
2685void CXXNameMangler::mangleType(const RecordType *T) {
2686 mangleType(static_cast<const TagType*>(T));
2687}
2688void CXXNameMangler::mangleType(const TagType *T) {
2689 mangleName(T->getDecl());
2690}
2691
2692// <type> ::= <array-type>
2693// <array-type> ::= A <positive dimension number> _ <element type>
2694// ::= A [<dimension expression>] _ <element type>
2695void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2696 Out << 'A' << T->getSize() << '_';
2697 mangleType(T->getElementType());
2698}
2699void CXXNameMangler::mangleType(const VariableArrayType *T) {
2700 Out << 'A';
2701 // decayed vla types (size 0) will just be skipped.
2702 if (T->getSizeExpr())
2703 mangleExpression(T->getSizeExpr());
2704 Out << '_';
2705 mangleType(T->getElementType());
2706}
2707void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2708 Out << 'A';
2709 mangleExpression(T->getSizeExpr());
2710 Out << '_';
2711 mangleType(T->getElementType());
2712}
2713void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2714 Out << "A_";
2715 mangleType(T->getElementType());
2716}
2717
2718// <type> ::= <pointer-to-member-type>
2719// <pointer-to-member-type> ::= M <class type> <member type>
2720void CXXNameMangler::mangleType(const MemberPointerType *T) {
2721 Out << 'M';
2722 mangleType(QualType(T->getClass(), 0));
2723 QualType PointeeType = T->getPointeeType();
2724 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2725 mangleType(FPT);
2726
2727 // Itanium C++ ABI 5.1.8:
2728 //
2729 // The type of a non-static member function is considered to be different,
2730 // for the purposes of substitution, from the type of a namespace-scope or
2731 // static member function whose type appears similar. The types of two
2732 // non-static member functions are considered to be different, for the
2733 // purposes of substitution, if the functions are members of different
2734 // classes. In other words, for the purposes of substitution, the class of
2735 // which the function is a member is considered part of the type of
2736 // function.
2737
2738 // Given that we already substitute member function pointers as a
2739 // whole, the net effect of this rule is just to unconditionally
2740 // suppress substitution on the function type in a member pointer.
2741 // We increment the SeqID here to emulate adding an entry to the
2742 // substitution table.
2743 ++SeqID;
2744 } else
2745 mangleType(PointeeType);
2746}
2747
2748// <type> ::= <template-param>
2749void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2750 mangleTemplateParameter(T->getIndex());
2751}
2752
2753// <type> ::= <template-param>
2754void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2755 // FIXME: not clear how to mangle this!
2756 // template <class T...> class A {
2757 // template <class U...> void foo(T(*)(U) x...);
2758 // };
2759 Out << "_SUBSTPACK_";
2760}
2761
2762// <type> ::= P <type> # pointer-to
2763void CXXNameMangler::mangleType(const PointerType *T) {
2764 Out << 'P';
2765 mangleType(T->getPointeeType());
2766}
2767void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2768 Out << 'P';
2769 mangleType(T->getPointeeType());
2770}
2771
2772// <type> ::= R <type> # reference-to
2773void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2774 Out << 'R';
2775 mangleType(T->getPointeeType());
2776}
2777
2778// <type> ::= O <type> # rvalue reference-to (C++0x)
2779void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2780 Out << 'O';
2781 mangleType(T->getPointeeType());
2782}
2783
2784// <type> ::= C <type> # complex pair (C 2000)
2785void CXXNameMangler::mangleType(const ComplexType *T) {
2786 Out << 'C';
2787 mangleType(T->getElementType());
2788}
2789
2790// ARM's ABI for Neon vector types specifies that they should be mangled as
2791// if they are structs (to match ARM's initial implementation). The
2792// vector type must be one of the special types predefined by ARM.
2793void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2794 QualType EltType = T->getElementType();
2795 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002796 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2798 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002799 case BuiltinType::SChar:
2800 case BuiltinType::UChar:
2801 EltName = "poly8_t";
2802 break;
2803 case BuiltinType::Short:
2804 case BuiltinType::UShort:
2805 EltName = "poly16_t";
2806 break;
2807 case BuiltinType::ULongLong:
2808 EltName = "poly64_t";
2809 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2811 }
2812 } else {
2813 switch (cast<BuiltinType>(EltType)->getKind()) {
2814 case BuiltinType::SChar: EltName = "int8_t"; break;
2815 case BuiltinType::UChar: EltName = "uint8_t"; break;
2816 case BuiltinType::Short: EltName = "int16_t"; break;
2817 case BuiltinType::UShort: EltName = "uint16_t"; break;
2818 case BuiltinType::Int: EltName = "int32_t"; break;
2819 case BuiltinType::UInt: EltName = "uint32_t"; break;
2820 case BuiltinType::LongLong: EltName = "int64_t"; break;
2821 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002822 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002824 case BuiltinType::Half: EltName = "float16_t";break;
2825 default:
2826 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 }
2828 }
Craig Topper36250ad2014-05-12 05:36:57 +00002829 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 unsigned BitSize = (T->getNumElements() *
2831 getASTContext().getTypeSize(EltType));
2832 if (BitSize == 64)
2833 BaseName = "__simd64_";
2834 else {
2835 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2836 BaseName = "__simd128_";
2837 }
2838 Out << strlen(BaseName) + strlen(EltName);
2839 Out << BaseName << EltName;
2840}
2841
Tim Northover2fe823a2013-08-01 09:23:19 +00002842static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2843 switch (EltType->getKind()) {
2844 case BuiltinType::SChar:
2845 return "Int8";
2846 case BuiltinType::Short:
2847 return "Int16";
2848 case BuiltinType::Int:
2849 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002850 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002851 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002852 return "Int64";
2853 case BuiltinType::UChar:
2854 return "Uint8";
2855 case BuiltinType::UShort:
2856 return "Uint16";
2857 case BuiltinType::UInt:
2858 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002859 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002860 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002861 return "Uint64";
2862 case BuiltinType::Half:
2863 return "Float16";
2864 case BuiltinType::Float:
2865 return "Float32";
2866 case BuiltinType::Double:
2867 return "Float64";
2868 default:
2869 llvm_unreachable("Unexpected vector element base type");
2870 }
2871}
2872
2873// AArch64's ABI for Neon vector types specifies that they should be mangled as
2874// the equivalent internal name. The vector type must be one of the special
2875// types predefined by ARM.
2876void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2877 QualType EltType = T->getElementType();
2878 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2879 unsigned BitSize =
2880 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002881 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002882
2883 assert((BitSize == 64 || BitSize == 128) &&
2884 "Neon vector type not 64 or 128 bits");
2885
Tim Northover2fe823a2013-08-01 09:23:19 +00002886 StringRef EltName;
2887 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2888 switch (cast<BuiltinType>(EltType)->getKind()) {
2889 case BuiltinType::UChar:
2890 EltName = "Poly8";
2891 break;
2892 case BuiltinType::UShort:
2893 EltName = "Poly16";
2894 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002895 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002896 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002897 EltName = "Poly64";
2898 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002899 default:
2900 llvm_unreachable("unexpected Neon polynomial vector element type");
2901 }
2902 } else
2903 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2904
2905 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00002906 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00002907 Out << TypeName.length() << TypeName;
2908}
2909
Guy Benyei11169dd2012-12-18 14:30:41 +00002910// GNU extension: vector types
2911// <type> ::= <vector-type>
2912// <vector-type> ::= Dv <positive dimension number> _
2913// <extended element type>
2914// ::= Dv [<dimension expression>] _ <element type>
2915// <extended element type> ::= <element type>
2916// ::= p # AltiVec vector pixel
2917// ::= b # Altivec vector bool
2918void CXXNameMangler::mangleType(const VectorType *T) {
2919 if ((T->getVectorKind() == VectorType::NeonVector ||
2920 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002921 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002922 llvm::Triple::ArchType Arch =
2923 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002924 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002925 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002926 mangleAArch64NeonVectorType(T);
2927 else
2928 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 return;
2930 }
2931 Out << "Dv" << T->getNumElements() << '_';
2932 if (T->getVectorKind() == VectorType::AltiVecPixel)
2933 Out << 'p';
2934 else if (T->getVectorKind() == VectorType::AltiVecBool)
2935 Out << 'b';
2936 else
2937 mangleType(T->getElementType());
2938}
2939void CXXNameMangler::mangleType(const ExtVectorType *T) {
2940 mangleType(static_cast<const VectorType*>(T));
2941}
2942void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2943 Out << "Dv";
2944 mangleExpression(T->getSizeExpr());
2945 Out << '_';
2946 mangleType(T->getElementType());
2947}
2948
2949void CXXNameMangler::mangleType(const PackExpansionType *T) {
2950 // <type> ::= Dp <type> # pack expansion (C++0x)
2951 Out << "Dp";
2952 mangleType(T->getPattern());
2953}
2954
2955void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2956 mangleSourceName(T->getDecl()->getIdentifier());
2957}
2958
2959void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002960 // Treat __kindof as a vendor extended type qualifier.
2961 if (T->isKindOfType())
2962 Out << "U8__kindof";
2963
Eli Friedman5f508952013-06-18 22:41:37 +00002964 if (!T->qual_empty()) {
2965 // Mangle protocol qualifiers.
2966 SmallString<64> QualStr;
2967 llvm::raw_svector_ostream QualOS(QualStr);
2968 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002969 for (const auto *I : T->quals()) {
2970 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002971 QualOS << name.size() << name;
2972 }
Eli Friedman5f508952013-06-18 22:41:37 +00002973 Out << 'U' << QualStr.size() << QualStr;
2974 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002975
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002977
2978 if (T->isSpecialized()) {
2979 // Mangle type arguments as I <type>+ E
2980 Out << 'I';
2981 for (auto typeArg : T->getTypeArgs())
2982 mangleType(typeArg);
2983 Out << 'E';
2984 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002985}
2986
2987void CXXNameMangler::mangleType(const BlockPointerType *T) {
2988 Out << "U13block_pointer";
2989 mangleType(T->getPointeeType());
2990}
2991
2992void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2993 // Mangle injected class name types as if the user had written the
2994 // specialization out fully. It may not actually be possible to see
2995 // this mangling, though.
2996 mangleType(T->getInjectedSpecializationType());
2997}
2998
2999void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3000 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003001 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 } else {
3003 if (mangleSubstitution(QualType(T, 0)))
3004 return;
3005
3006 mangleTemplatePrefix(T->getTemplateName());
3007
3008 // FIXME: GCC does not appear to mangle the template arguments when
3009 // the template in question is a dependent template name. Should we
3010 // emulate that badness?
3011 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3012 addSubstitution(QualType(T, 0));
3013 }
3014}
3015
3016void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003017 // Proposal by cxx-abi-dev, 2014-03-26
3018 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3019 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003020 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003021 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003022 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003023 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003024 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003025 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003026 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003027 switch (T->getKeyword()) {
3028 case ETK_Typename:
3029 break;
3030 case ETK_Struct:
3031 case ETK_Class:
3032 case ETK_Interface:
3033 Out << "Ts";
3034 break;
3035 case ETK_Union:
3036 Out << "Tu";
3037 break;
3038 case ETK_Enum:
3039 Out << "Te";
3040 break;
3041 default:
3042 llvm_unreachable("unexpected keyword for dependent type name");
3043 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003044 // Typename types are always nested
3045 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003047 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 Out << 'E';
3049}
3050
3051void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3052 // Dependently-scoped template types are nested if they have a prefix.
3053 Out << 'N';
3054
3055 // TODO: avoid making this TemplateName.
3056 TemplateName Prefix =
3057 getASTContext().getDependentTemplateName(T->getQualifier(),
3058 T->getIdentifier());
3059 mangleTemplatePrefix(Prefix);
3060
3061 // FIXME: GCC does not appear to mangle the template arguments when
3062 // the template in question is a dependent template name. Should we
3063 // emulate that badness?
3064 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3065 Out << 'E';
3066}
3067
3068void CXXNameMangler::mangleType(const TypeOfType *T) {
3069 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3070 // "extension with parameters" mangling.
3071 Out << "u6typeof";
3072}
3073
3074void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3075 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3076 // "extension with parameters" mangling.
3077 Out << "u6typeof";
3078}
3079
3080void CXXNameMangler::mangleType(const DecltypeType *T) {
3081 Expr *E = T->getUnderlyingExpr();
3082
3083 // type ::= Dt <expression> E # decltype of an id-expression
3084 // # or class member access
3085 // ::= DT <expression> E # decltype of an expression
3086
3087 // This purports to be an exhaustive list of id-expressions and
3088 // class member accesses. Note that we do not ignore parentheses;
3089 // parentheses change the semantics of decltype for these
3090 // expressions (and cause the mangler to use the other form).
3091 if (isa<DeclRefExpr>(E) ||
3092 isa<MemberExpr>(E) ||
3093 isa<UnresolvedLookupExpr>(E) ||
3094 isa<DependentScopeDeclRefExpr>(E) ||
3095 isa<CXXDependentScopeMemberExpr>(E) ||
3096 isa<UnresolvedMemberExpr>(E))
3097 Out << "Dt";
3098 else
3099 Out << "DT";
3100 mangleExpression(E);
3101 Out << 'E';
3102}
3103
3104void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3105 // If this is dependent, we need to record that. If not, we simply
3106 // mangle it as the underlying type since they are equivalent.
3107 if (T->isDependentType()) {
3108 Out << 'U';
3109
3110 switch (T->getUTTKind()) {
3111 case UnaryTransformType::EnumUnderlyingType:
3112 Out << "3eut";
3113 break;
3114 }
3115 }
3116
David Majnemer140065a2016-06-08 00:34:15 +00003117 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003118}
3119
3120void CXXNameMangler::mangleType(const AutoType *T) {
3121 QualType D = T->getDeducedType();
3122 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00003123 if (D.isNull()) {
3124 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3125 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00003126 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00003127 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 mangleType(D);
3129}
3130
3131void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003132 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 // (Until there's a standardized mangling...)
3134 Out << "U7_Atomic";
3135 mangleType(T->getValueType());
3136}
3137
Xiuli Pan9c14e282016-01-09 12:53:17 +00003138void CXXNameMangler::mangleType(const PipeType *T) {
3139 // Pipe type mangling rules are described in SPIR 2.0 specification
3140 // A.1 Data types and A.3 Summary of changes
3141 // <type> ::= 8ocl_pipe
3142 Out << "8ocl_pipe";
3143}
3144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145void CXXNameMangler::mangleIntegerLiteral(QualType T,
3146 const llvm::APSInt &Value) {
3147 // <expr-primary> ::= L <type> <value number> E # integer literal
3148 Out << 'L';
3149
3150 mangleType(T);
3151 if (T->isBooleanType()) {
3152 // Boolean values are encoded as 0/1.
3153 Out << (Value.getBoolValue() ? '1' : '0');
3154 } else {
3155 mangleNumber(Value);
3156 }
3157 Out << 'E';
3158
3159}
3160
David Majnemer1dabfdc2015-02-14 13:23:54 +00003161void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3162 // Ignore member expressions involving anonymous unions.
3163 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3164 if (!RT->getDecl()->isAnonymousStructOrUnion())
3165 break;
3166 const auto *ME = dyn_cast<MemberExpr>(Base);
3167 if (!ME)
3168 break;
3169 Base = ME->getBase();
3170 IsArrow = ME->isArrow();
3171 }
3172
3173 if (Base->isImplicitCXXThis()) {
3174 // Note: GCC mangles member expressions to the implicit 'this' as
3175 // *this., whereas we represent them as this->. The Itanium C++ ABI
3176 // does not specify anything here, so we follow GCC.
3177 Out << "dtdefpT";
3178 } else {
3179 Out << (IsArrow ? "pt" : "dt");
3180 mangleExpression(Base);
3181 }
3182}
3183
Guy Benyei11169dd2012-12-18 14:30:41 +00003184/// Mangles a member expression.
3185void CXXNameMangler::mangleMemberExpr(const Expr *base,
3186 bool isArrow,
3187 NestedNameSpecifier *qualifier,
3188 NamedDecl *firstQualifierLookup,
3189 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003190 const TemplateArgumentLoc *TemplateArgs,
3191 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 unsigned arity) {
3193 // <expression> ::= dt <expression> <unresolved-name>
3194 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003195 if (base)
3196 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003197 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003198}
3199
3200/// Look at the callee of the given call expression and determine if
3201/// it's a parenthesized id-expression which would have triggered ADL
3202/// otherwise.
3203static bool isParenthesizedADLCallee(const CallExpr *call) {
3204 const Expr *callee = call->getCallee();
3205 const Expr *fn = callee->IgnoreParens();
3206
3207 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3208 // too, but for those to appear in the callee, it would have to be
3209 // parenthesized.
3210 if (callee == fn) return false;
3211
3212 // Must be an unresolved lookup.
3213 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3214 if (!lookup) return false;
3215
3216 assert(!lookup->requiresADL());
3217
3218 // Must be an unqualified lookup.
3219 if (lookup->getQualifier()) return false;
3220
3221 // Must not have found a class member. Note that if one is a class
3222 // member, they're all class members.
3223 if (lookup->getNumDecls() > 0 &&
3224 (*lookup->decls_begin())->isCXXClassMember())
3225 return false;
3226
3227 // Otherwise, ADL would have been triggered.
3228 return true;
3229}
3230
David Majnemer9c775c72014-09-23 04:27:55 +00003231void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3232 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3233 Out << CastEncoding;
3234 mangleType(ECE->getType());
3235 mangleExpression(ECE->getSubExpr());
3236}
3237
Richard Smith520449d2015-02-05 06:15:50 +00003238void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3239 if (auto *Syntactic = InitList->getSyntacticForm())
3240 InitList = Syntactic;
3241 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3242 mangleExpression(InitList->getInit(i));
3243}
3244
Guy Benyei11169dd2012-12-18 14:30:41 +00003245void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3246 // <expression> ::= <unary operator-name> <expression>
3247 // ::= <binary operator-name> <expression> <expression>
3248 // ::= <trinary operator-name> <expression> <expression> <expression>
3249 // ::= cv <type> expression # conversion with one argument
3250 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003251 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3252 // ::= sc <type> <expression> # static_cast<type> (expression)
3253 // ::= cc <type> <expression> # const_cast<type> (expression)
3254 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 // ::= st <type> # sizeof (a type)
3256 // ::= at <type> # alignof (a type)
3257 // ::= <template-param>
3258 // ::= <function-param>
3259 // ::= sr <type> <unqualified-name> # dependent name
3260 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3261 // ::= ds <expression> <expression> # expr.*expr
3262 // ::= sZ <template-param> # size of a parameter pack
3263 // ::= sZ <function-param> # size of a function parameter pack
3264 // ::= <expr-primary>
3265 // <expr-primary> ::= L <type> <value number> E # integer literal
3266 // ::= L <type <value float> E # floating literal
3267 // ::= L <mangled-name> E # external name
3268 // ::= fpT # 'this' expression
3269 QualType ImplicitlyConvertedToType;
3270
3271recurse:
3272 switch (E->getStmtClass()) {
3273 case Expr::NoStmtClass:
3274#define ABSTRACT_STMT(Type)
3275#define EXPR(Type, Base)
3276#define STMT(Type, Base) \
3277 case Expr::Type##Class:
3278#include "clang/AST/StmtNodes.inc"
3279 // fallthrough
3280
3281 // These all can only appear in local or variable-initialization
3282 // contexts and so should never appear in a mangling.
3283 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003284 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003286 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 case Expr::ParenListExprClass:
3288 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003289 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003290 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003291 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003292 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003293 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 llvm_unreachable("unexpected statement kind");
3295
3296 // FIXME: invent manglings for all these.
3297 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003298 case Expr::ChooseExprClass:
3299 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00003300 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 case Expr::ExtVectorElementExprClass:
3302 case Expr::GenericSelectionExprClass:
3303 case Expr::ObjCEncodeExprClass:
3304 case Expr::ObjCIsaExprClass:
3305 case Expr::ObjCIvarRefExprClass:
3306 case Expr::ObjCMessageExprClass:
3307 case Expr::ObjCPropertyRefExprClass:
3308 case Expr::ObjCProtocolExprClass:
3309 case Expr::ObjCSelectorExprClass:
3310 case Expr::ObjCStringLiteralClass:
3311 case Expr::ObjCBoxedExprClass:
3312 case Expr::ObjCArrayLiteralClass:
3313 case Expr::ObjCDictionaryLiteralClass:
3314 case Expr::ObjCSubscriptRefExprClass:
3315 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003316 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 case Expr::OffsetOfExprClass:
3318 case Expr::PredefinedExprClass:
3319 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003320 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003322 case Expr::TypeTraitExprClass:
3323 case Expr::ArrayTypeTraitExprClass:
3324 case Expr::ExpressionTraitExprClass:
3325 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 case Expr::CUDAKernelCallExprClass:
3327 case Expr::AsTypeExprClass:
3328 case Expr::PseudoObjectExprClass:
3329 case Expr::AtomicExprClass:
3330 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003331 if (!NullOut) {
3332 // As bad as this diagnostic is, it's better than crashing.
3333 DiagnosticsEngine &Diags = Context.getDiags();
3334 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3335 "cannot yet mangle expression type %0");
3336 Diags.Report(E->getExprLoc(), DiagID)
3337 << E->getStmtClassName() << E->getSourceRange();
3338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 break;
3340 }
3341
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003342 case Expr::CXXUuidofExprClass: {
3343 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3344 if (UE->isTypeOperand()) {
3345 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3346 Out << "u8__uuidoft";
3347 mangleType(UuidT);
3348 } else {
3349 Expr *UuidExp = UE->getExprOperand();
3350 Out << "u8__uuidofz";
3351 mangleExpression(UuidExp, Arity);
3352 }
3353 break;
3354 }
3355
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 // Even gcc-4.5 doesn't mangle this.
3357 case Expr::BinaryConditionalOperatorClass: {
3358 DiagnosticsEngine &Diags = Context.getDiags();
3359 unsigned DiagID =
3360 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3361 "?: operator with omitted middle operand cannot be mangled");
3362 Diags.Report(E->getExprLoc(), DiagID)
3363 << E->getStmtClassName() << E->getSourceRange();
3364 break;
3365 }
3366
3367 // These are used for internal purposes and cannot be meaningfully mangled.
3368 case Expr::OpaqueValueExprClass:
3369 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3370
3371 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003372 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003373 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003374 Out << "E";
3375 break;
3376 }
3377
3378 case Expr::CXXDefaultArgExprClass:
3379 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3380 break;
3381
Richard Smith852c9db2013-04-20 22:23:05 +00003382 case Expr::CXXDefaultInitExprClass:
3383 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3384 break;
3385
Richard Smithcc1b96d2013-06-12 22:31:48 +00003386 case Expr::CXXStdInitializerListExprClass:
3387 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3388 break;
3389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 case Expr::SubstNonTypeTemplateParmExprClass:
3391 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3392 Arity);
3393 break;
3394
3395 case Expr::UserDefinedLiteralClass:
3396 // We follow g++'s approach of mangling a UDL as a call to the literal
3397 // operator.
3398 case Expr::CXXMemberCallExprClass: // fallthrough
3399 case Expr::CallExprClass: {
3400 const CallExpr *CE = cast<CallExpr>(E);
3401
3402 // <expression> ::= cp <simple-id> <expression>* E
3403 // We use this mangling only when the call would use ADL except
3404 // for being parenthesized. Per discussion with David
3405 // Vandervoorde, 2011.04.25.
3406 if (isParenthesizedADLCallee(CE)) {
3407 Out << "cp";
3408 // The callee here is a parenthesized UnresolvedLookupExpr with
3409 // no qualifier and should always get mangled as a <simple-id>
3410 // anyway.
3411
3412 // <expression> ::= cl <expression>* E
3413 } else {
3414 Out << "cl";
3415 }
3416
David Majnemer67a8ec62015-02-19 21:41:48 +00003417 unsigned CallArity = CE->getNumArgs();
3418 for (const Expr *Arg : CE->arguments())
3419 if (isa<PackExpansionExpr>(Arg))
3420 CallArity = UnknownArity;
3421
3422 mangleExpression(CE->getCallee(), CallArity);
3423 for (const Expr *Arg : CE->arguments())
3424 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003425 Out << 'E';
3426 break;
3427 }
3428
3429 case Expr::CXXNewExprClass: {
3430 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3431 if (New->isGlobalNew()) Out << "gs";
3432 Out << (New->isArray() ? "na" : "nw");
3433 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3434 E = New->placement_arg_end(); I != E; ++I)
3435 mangleExpression(*I);
3436 Out << '_';
3437 mangleType(New->getAllocatedType());
3438 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3440 Out << "il";
3441 else
3442 Out << "pi";
3443 const Expr *Init = New->getInitializer();
3444 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3445 // Directly inline the initializers.
3446 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3447 E = CCE->arg_end();
3448 I != E; ++I)
3449 mangleExpression(*I);
3450 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3451 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3452 mangleExpression(PLE->getExpr(i));
3453 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3454 isa<InitListExpr>(Init)) {
3455 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003456 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 } else
3458 mangleExpression(Init);
3459 }
3460 Out << 'E';
3461 break;
3462 }
3463
David Majnemer1dabfdc2015-02-14 13:23:54 +00003464 case Expr::CXXPseudoDestructorExprClass: {
3465 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3466 if (const Expr *Base = PDE->getBase())
3467 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003468 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3469 QualType ScopeType;
3470 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3471 if (Qualifier) {
3472 mangleUnresolvedPrefix(Qualifier,
3473 /*Recursive=*/true);
3474 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3475 Out << 'E';
3476 } else {
3477 Out << "sr";
3478 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3479 Out << 'E';
3480 }
3481 } else if (Qualifier) {
3482 mangleUnresolvedPrefix(Qualifier);
3483 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003484 // <base-unresolved-name> ::= dn <destructor-name>
3485 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003486 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003487 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003488 break;
3489 }
3490
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 case Expr::MemberExprClass: {
3492 const MemberExpr *ME = cast<MemberExpr>(E);
3493 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003494 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003495 ME->getMemberDecl()->getDeclName(),
3496 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3497 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 break;
3499 }
3500
3501 case Expr::UnresolvedMemberExprClass: {
3502 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003503 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3504 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003505 ME->getMemberName(),
3506 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3507 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 break;
3509 }
3510
3511 case Expr::CXXDependentScopeMemberExprClass: {
3512 const CXXDependentScopeMemberExpr *ME
3513 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003514 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3515 ME->isArrow(), ME->getQualifier(),
3516 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003517 ME->getMember(),
3518 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3519 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 break;
3521 }
3522
3523 case Expr::UnresolvedLookupExprClass: {
3524 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003525 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3526 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3527 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 break;
3529 }
3530
3531 case Expr::CXXUnresolvedConstructExprClass: {
3532 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3533 unsigned N = CE->arg_size();
3534
3535 Out << "cv";
3536 mangleType(CE->getType());
3537 if (N != 1) Out << '_';
3538 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3539 if (N != 1) Out << 'E';
3540 break;
3541 }
3542
Guy Benyei11169dd2012-12-18 14:30:41 +00003543 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003544 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003545 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003546 assert(
3547 CE->getNumArgs() >= 1 &&
3548 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3549 "implicit CXXConstructExpr must have one argument");
3550 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3551 }
3552 Out << "il";
3553 for (auto *E : CE->arguments())
3554 mangleExpression(E);
3555 Out << "E";
3556 break;
3557 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003558
Richard Smith520449d2015-02-05 06:15:50 +00003559 case Expr::CXXTemporaryObjectExprClass: {
3560 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3561 unsigned N = CE->getNumArgs();
3562 bool List = CE->isListInitialization();
3563
3564 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 Out << "tl";
3566 else
3567 Out << "cv";
3568 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003569 if (!List && N != 1)
3570 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003571 if (CE->isStdInitListInitialization()) {
3572 // We implicitly created a std::initializer_list<T> for the first argument
3573 // of a constructor of type U in an expression of the form U{a, b, c}.
3574 // Strip all the semantic gunk off the initializer list.
3575 auto *SILE =
3576 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3577 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3578 mangleInitListElements(ILE);
3579 } else {
3580 for (auto *E : CE->arguments())
3581 mangleExpression(E);
3582 }
Richard Smith520449d2015-02-05 06:15:50 +00003583 if (List || N != 1)
3584 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 break;
3586 }
3587
3588 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003589 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003591 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 break;
3593
3594 case Expr::CXXNoexceptExprClass:
3595 Out << "nx";
3596 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3597 break;
3598
3599 case Expr::UnaryExprOrTypeTraitExprClass: {
3600 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3601
3602 if (!SAE->isInstantiationDependent()) {
3603 // Itanium C++ ABI:
3604 // If the operand of a sizeof or alignof operator is not
3605 // instantiation-dependent it is encoded as an integer literal
3606 // reflecting the result of the operator.
3607 //
3608 // If the result of the operator is implicitly converted to a known
3609 // integer type, that type is used for the literal; otherwise, the type
3610 // of std::size_t or std::ptrdiff_t is used.
3611 QualType T = (ImplicitlyConvertedToType.isNull() ||
3612 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3613 : ImplicitlyConvertedToType;
3614 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3615 mangleIntegerLiteral(T, V);
3616 break;
3617 }
3618
3619 switch(SAE->getKind()) {
3620 case UETT_SizeOf:
3621 Out << 's';
3622 break;
3623 case UETT_AlignOf:
3624 Out << 'a';
3625 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003626 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 DiagnosticsEngine &Diags = Context.getDiags();
3628 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3629 "cannot yet mangle vec_step expression");
3630 Diags.Report(DiagID);
3631 return;
3632 }
Alexey Bataev00396512015-07-02 03:40:19 +00003633 case UETT_OpenMPRequiredSimdAlign:
3634 DiagnosticsEngine &Diags = Context.getDiags();
3635 unsigned DiagID = Diags.getCustomDiagID(
3636 DiagnosticsEngine::Error,
3637 "cannot yet mangle __builtin_omp_required_simd_align expression");
3638 Diags.Report(DiagID);
3639 return;
3640 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 if (SAE->isArgumentType()) {
3642 Out << 't';
3643 mangleType(SAE->getArgumentType());
3644 } else {
3645 Out << 'z';
3646 mangleExpression(SAE->getArgumentExpr());
3647 }
3648 break;
3649 }
3650
3651 case Expr::CXXThrowExprClass: {
3652 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003653 // <expression> ::= tw <expression> # throw expression
3654 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 if (TE->getSubExpr()) {
3656 Out << "tw";
3657 mangleExpression(TE->getSubExpr());
3658 } else {
3659 Out << "tr";
3660 }
3661 break;
3662 }
3663
3664 case Expr::CXXTypeidExprClass: {
3665 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003666 // <expression> ::= ti <type> # typeid (type)
3667 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 if (TIE->isTypeOperand()) {
3669 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003670 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 } else {
3672 Out << "te";
3673 mangleExpression(TIE->getExprOperand());
3674 }
3675 break;
3676 }
3677
3678 case Expr::CXXDeleteExprClass: {
3679 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003680 // <expression> ::= [gs] dl <expression> # [::] delete expr
3681 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 if (DE->isGlobalDelete()) Out << "gs";
3683 Out << (DE->isArrayForm() ? "da" : "dl");
3684 mangleExpression(DE->getArgument());
3685 break;
3686 }
3687
3688 case Expr::UnaryOperatorClass: {
3689 const UnaryOperator *UO = cast<UnaryOperator>(E);
3690 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3691 /*Arity=*/1);
3692 mangleExpression(UO->getSubExpr());
3693 break;
3694 }
3695
3696 case Expr::ArraySubscriptExprClass: {
3697 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3698
3699 // Array subscript is treated as a syntactically weird form of
3700 // binary operator.
3701 Out << "ix";
3702 mangleExpression(AE->getLHS());
3703 mangleExpression(AE->getRHS());
3704 break;
3705 }
3706
3707 case Expr::CompoundAssignOperatorClass: // fallthrough
3708 case Expr::BinaryOperatorClass: {
3709 const BinaryOperator *BO = cast<BinaryOperator>(E);
3710 if (BO->getOpcode() == BO_PtrMemD)
3711 Out << "ds";
3712 else
3713 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3714 /*Arity=*/2);
3715 mangleExpression(BO->getLHS());
3716 mangleExpression(BO->getRHS());
3717 break;
3718 }
3719
3720 case Expr::ConditionalOperatorClass: {
3721 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3722 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3723 mangleExpression(CO->getCond());
3724 mangleExpression(CO->getLHS(), Arity);
3725 mangleExpression(CO->getRHS(), Arity);
3726 break;
3727 }
3728
3729 case Expr::ImplicitCastExprClass: {
3730 ImplicitlyConvertedToType = E->getType();
3731 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3732 goto recurse;
3733 }
3734
3735 case Expr::ObjCBridgedCastExprClass: {
3736 // Mangle ownership casts as a vendor extended operator __bridge,
3737 // __bridge_transfer, or __bridge_retain.
3738 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3739 Out << "v1U" << Kind.size() << Kind;
3740 }
3741 // Fall through to mangle the cast itself.
3742
3743 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003744 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003746
Richard Smith520449d2015-02-05 06:15:50 +00003747 case Expr::CXXFunctionalCastExprClass: {
3748 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3749 // FIXME: Add isImplicit to CXXConstructExpr.
3750 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3751 if (CCE->getParenOrBraceRange().isInvalid())
3752 Sub = CCE->getArg(0)->IgnoreImplicit();
3753 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3754 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3755 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3756 Out << "tl";
3757 mangleType(E->getType());
3758 mangleInitListElements(IL);
3759 Out << "E";
3760 } else {
3761 mangleCastExpression(E, "cv");
3762 }
3763 break;
3764 }
3765
David Majnemer9c775c72014-09-23 04:27:55 +00003766 case Expr::CXXStaticCastExprClass:
3767 mangleCastExpression(E, "sc");
3768 break;
3769 case Expr::CXXDynamicCastExprClass:
3770 mangleCastExpression(E, "dc");
3771 break;
3772 case Expr::CXXReinterpretCastExprClass:
3773 mangleCastExpression(E, "rc");
3774 break;
3775 case Expr::CXXConstCastExprClass:
3776 mangleCastExpression(E, "cc");
3777 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
3779 case Expr::CXXOperatorCallExprClass: {
3780 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3781 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00003782 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
3783 // (the enclosing MemberExpr covers the syntactic portion).
3784 if (CE->getOperator() != OO_Arrow)
3785 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 // Mangle the arguments.
3787 for (unsigned i = 0; i != NumArgs; ++i)
3788 mangleExpression(CE->getArg(i));
3789 break;
3790 }
3791
3792 case Expr::ParenExprClass:
3793 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3794 break;
3795
3796 case Expr::DeclRefExprClass: {
3797 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3798
3799 switch (D->getKind()) {
3800 default:
3801 // <expr-primary> ::= L <mangled-name> E # external name
3802 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003803 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 Out << 'E';
3805 break;
3806
3807 case Decl::ParmVar:
3808 mangleFunctionParam(cast<ParmVarDecl>(D));
3809 break;
3810
3811 case Decl::EnumConstant: {
3812 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3813 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3814 break;
3815 }
3816
3817 case Decl::NonTypeTemplateParm: {
3818 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3819 mangleTemplateParameter(PD->getIndex());
3820 break;
3821 }
3822
3823 }
3824
3825 break;
3826 }
3827
3828 case Expr::SubstNonTypeTemplateParmPackExprClass:
3829 // FIXME: not clear how to mangle this!
3830 // template <unsigned N...> class A {
3831 // template <class U...> void foo(U (&x)[N]...);
3832 // };
3833 Out << "_SUBSTPACK_";
3834 break;
3835
3836 case Expr::FunctionParmPackExprClass: {
3837 // FIXME: not clear how to mangle this!
3838 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3839 Out << "v110_SUBSTPACK";
3840 mangleFunctionParam(FPPE->getParameterPack());
3841 break;
3842 }
3843
3844 case Expr::DependentScopeDeclRefExprClass: {
3845 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003846 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
3847 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
3848 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 break;
3850 }
3851
3852 case Expr::CXXBindTemporaryExprClass:
3853 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3854 break;
3855
3856 case Expr::ExprWithCleanupsClass:
3857 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3858 break;
3859
3860 case Expr::FloatingLiteralClass: {
3861 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3862 Out << 'L';
3863 mangleType(FL->getType());
3864 mangleFloat(FL->getValue());
3865 Out << 'E';
3866 break;
3867 }
3868
3869 case Expr::CharacterLiteralClass:
3870 Out << 'L';
3871 mangleType(E->getType());
3872 Out << cast<CharacterLiteral>(E)->getValue();
3873 Out << 'E';
3874 break;
3875
3876 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3877 case Expr::ObjCBoolLiteralExprClass:
3878 Out << "Lb";
3879 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3880 Out << 'E';
3881 break;
3882
3883 case Expr::CXXBoolLiteralExprClass:
3884 Out << "Lb";
3885 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3886 Out << 'E';
3887 break;
3888
3889 case Expr::IntegerLiteralClass: {
3890 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3891 if (E->getType()->isSignedIntegerType())
3892 Value.setIsSigned(true);
3893 mangleIntegerLiteral(E->getType(), Value);
3894 break;
3895 }
3896
3897 case Expr::ImaginaryLiteralClass: {
3898 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3899 // Mangle as if a complex literal.
3900 // Proposal from David Vandevoorde, 2010.06.30.
3901 Out << 'L';
3902 mangleType(E->getType());
3903 if (const FloatingLiteral *Imag =
3904 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3905 // Mangle a floating-point zero of the appropriate type.
3906 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3907 Out << '_';
3908 mangleFloat(Imag->getValue());
3909 } else {
3910 Out << "0_";
3911 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3912 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3913 Value.setIsSigned(true);
3914 mangleNumber(Value);
3915 }
3916 Out << 'E';
3917 break;
3918 }
3919
3920 case Expr::StringLiteralClass: {
3921 // Revised proposal from David Vandervoorde, 2010.07.15.
3922 Out << 'L';
3923 assert(isa<ConstantArrayType>(E->getType()));
3924 mangleType(E->getType());
3925 Out << 'E';
3926 break;
3927 }
3928
3929 case Expr::GNUNullExprClass:
3930 // FIXME: should this really be mangled the same as nullptr?
3931 // fallthrough
3932
3933 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 Out << "LDnE";
3935 break;
3936 }
3937
3938 case Expr::PackExpansionExprClass:
3939 Out << "sp";
3940 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3941 break;
3942
3943 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003944 auto *SPE = cast<SizeOfPackExpr>(E);
3945 if (SPE->isPartiallySubstituted()) {
3946 Out << "sP";
3947 for (const auto &A : SPE->getPartialArguments())
3948 mangleTemplateArg(A);
3949 Out << "E";
3950 break;
3951 }
3952
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003954 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3956 mangleTemplateParameter(TTP->getIndex());
3957 else if (const NonTypeTemplateParmDecl *NTTP
3958 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3959 mangleTemplateParameter(NTTP->getIndex());
3960 else if (const TemplateTemplateParmDecl *TempTP
3961 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3962 mangleTemplateParameter(TempTP->getIndex());
3963 else
3964 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3965 break;
3966 }
Richard Smith0f0af192014-11-08 05:07:16 +00003967
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 case Expr::MaterializeTemporaryExprClass: {
3969 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3970 break;
3971 }
Richard Smith0f0af192014-11-08 05:07:16 +00003972
3973 case Expr::CXXFoldExprClass: {
3974 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003975 if (FE->isLeftFold())
3976 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003977 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003978 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003979
3980 if (FE->getOperator() == BO_PtrMemD)
3981 Out << "ds";
3982 else
3983 mangleOperatorName(
3984 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3985 /*Arity=*/2);
3986
3987 if (FE->getLHS())
3988 mangleExpression(FE->getLHS());
3989 if (FE->getRHS())
3990 mangleExpression(FE->getRHS());
3991 break;
3992 }
3993
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 case Expr::CXXThisExprClass:
3995 Out << "fpT";
3996 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00003997
3998 case Expr::CoawaitExprClass:
3999 // FIXME: Propose a non-vendor mangling.
4000 Out << "v18co_await";
4001 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4002 break;
4003
4004 case Expr::CoyieldExprClass:
4005 // FIXME: Propose a non-vendor mangling.
4006 Out << "v18co_yield";
4007 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4008 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 }
4010}
4011
4012/// Mangle an expression which refers to a parameter variable.
4013///
4014/// <expression> ::= <function-param>
4015/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4016/// <function-param> ::= fp <top-level CV-qualifiers>
4017/// <parameter-2 non-negative number> _ # L == 0, I > 0
4018/// <function-param> ::= fL <L-1 non-negative number>
4019/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4020/// <function-param> ::= fL <L-1 non-negative number>
4021/// p <top-level CV-qualifiers>
4022/// <I-1 non-negative number> _ # L > 0, I > 0
4023///
4024/// L is the nesting depth of the parameter, defined as 1 if the
4025/// parameter comes from the innermost function prototype scope
4026/// enclosing the current context, 2 if from the next enclosing
4027/// function prototype scope, and so on, with one special case: if
4028/// we've processed the full parameter clause for the innermost
4029/// function type, then L is one less. This definition conveniently
4030/// makes it irrelevant whether a function's result type was written
4031/// trailing or leading, but is otherwise overly complicated; the
4032/// numbering was first designed without considering references to
4033/// parameter in locations other than return types, and then the
4034/// mangling had to be generalized without changing the existing
4035/// manglings.
4036///
4037/// I is the zero-based index of the parameter within its parameter
4038/// declaration clause. Note that the original ABI document describes
4039/// this using 1-based ordinals.
4040void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4041 unsigned parmDepth = parm->getFunctionScopeDepth();
4042 unsigned parmIndex = parm->getFunctionScopeIndex();
4043
4044 // Compute 'L'.
4045 // parmDepth does not include the declaring function prototype.
4046 // FunctionTypeDepth does account for that.
4047 assert(parmDepth < FunctionTypeDepth.getDepth());
4048 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4049 if (FunctionTypeDepth.isInResultType())
4050 nestingDepth--;
4051
4052 if (nestingDepth == 0) {
4053 Out << "fp";
4054 } else {
4055 Out << "fL" << (nestingDepth - 1) << 'p';
4056 }
4057
4058 // Top-level qualifiers. We don't have to worry about arrays here,
4059 // because parameters declared as arrays should already have been
4060 // transformed to have pointer type. FIXME: apparently these don't
4061 // get mangled if used as an rvalue of a known non-class type?
4062 assert(!parm->getType()->isArrayType()
4063 && "parameter's type is still an array type?");
4064 mangleQualifiers(parm->getType().getQualifiers());
4065
4066 // Parameter index.
4067 if (parmIndex != 0) {
4068 Out << (parmIndex - 1);
4069 }
4070 Out << '_';
4071}
4072
Richard Smith5179eb72016-06-28 19:03:57 +00004073void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4074 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 // <ctor-dtor-name> ::= C1 # complete object constructor
4076 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004077 // ::= CI1 <type> # complete inheriting constructor
4078 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004079 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004080 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004081 Out << 'C';
4082 if (InheritedFrom)
4083 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 switch (T) {
4085 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004086 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 break;
4088 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004089 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004091 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004092 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004094 case Ctor_DefaultClosure:
4095 case Ctor_CopyingClosure:
4096 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 }
Richard Smith5179eb72016-06-28 19:03:57 +00004098 if (InheritedFrom)
4099 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004100}
4101
4102void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4103 // <ctor-dtor-name> ::= D0 # deleting destructor
4104 // ::= D1 # complete object destructor
4105 // ::= D2 # base object destructor
4106 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004107 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 switch (T) {
4109 case Dtor_Deleting:
4110 Out << "D0";
4111 break;
4112 case Dtor_Complete:
4113 Out << "D1";
4114 break;
4115 case Dtor_Base:
4116 Out << "D2";
4117 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004118 case Dtor_Comdat:
4119 Out << "D5";
4120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 }
4122}
4123
James Y Knight04ec5bf2015-12-24 02:59:37 +00004124void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4125 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 // <template-args> ::= I <template-arg>+ E
4127 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004128 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4129 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 Out << 'E';
4131}
4132
4133void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4134 // <template-args> ::= I <template-arg>+ E
4135 Out << 'I';
4136 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4137 mangleTemplateArg(AL[i]);
4138 Out << 'E';
4139}
4140
4141void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4142 unsigned NumTemplateArgs) {
4143 // <template-args> ::= I <template-arg>+ E
4144 Out << 'I';
4145 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4146 mangleTemplateArg(TemplateArgs[i]);
4147 Out << 'E';
4148}
4149
4150void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4151 // <template-arg> ::= <type> # type or template
4152 // ::= X <expression> E # expression
4153 // ::= <expr-primary> # simple expressions
4154 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 if (!A.isInstantiationDependent() || A.isDependent())
4156 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4157
4158 switch (A.getKind()) {
4159 case TemplateArgument::Null:
4160 llvm_unreachable("Cannot mangle NULL template argument");
4161
4162 case TemplateArgument::Type:
4163 mangleType(A.getAsType());
4164 break;
4165 case TemplateArgument::Template:
4166 // This is mangled as <type>.
4167 mangleType(A.getAsTemplate());
4168 break;
4169 case TemplateArgument::TemplateExpansion:
4170 // <type> ::= Dp <type> # pack expansion (C++0x)
4171 Out << "Dp";
4172 mangleType(A.getAsTemplateOrTemplatePattern());
4173 break;
4174 case TemplateArgument::Expression: {
4175 // It's possible to end up with a DeclRefExpr here in certain
4176 // dependent cases, in which case we should mangle as a
4177 // declaration.
4178 const Expr *E = A.getAsExpr()->IgnoreParens();
4179 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4180 const ValueDecl *D = DRE->getDecl();
4181 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004182 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004183 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 Out << 'E';
4185 break;
4186 }
4187 }
4188
4189 Out << 'X';
4190 mangleExpression(E);
4191 Out << 'E';
4192 break;
4193 }
4194 case TemplateArgument::Integral:
4195 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4196 break;
4197 case TemplateArgument::Declaration: {
4198 // <expr-primary> ::= L <mangled-name> E # external name
4199 // Clang produces AST's where pointer-to-member-function expressions
4200 // and pointer-to-function expressions are represented as a declaration not
4201 // an expression. We compensate for it here to produce the correct mangling.
4202 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004203 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 if (compensateMangling) {
4205 Out << 'X';
4206 mangleOperatorName(OO_Amp, 1);
4207 }
4208
4209 Out << 'L';
4210 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004211 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004212 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 Out << 'E';
4214
4215 if (compensateMangling)
4216 Out << 'E';
4217
4218 break;
4219 }
4220 case TemplateArgument::NullPtr: {
4221 // <expr-primary> ::= L <type> 0 E
4222 Out << 'L';
4223 mangleType(A.getNullPtrType());
4224 Out << "0E";
4225 break;
4226 }
4227 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004228 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004230 for (const auto &P : A.pack_elements())
4231 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 Out << 'E';
4233 }
4234 }
4235}
4236
4237void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4238 // <template-param> ::= T_ # first template parameter
4239 // ::= T <parameter-2 non-negative number> _
4240 if (Index == 0)
4241 Out << "T_";
4242 else
4243 Out << 'T' << (Index - 1) << '_';
4244}
4245
David Majnemer3b3bdb52014-05-06 22:49:16 +00004246void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4247 if (SeqID == 1)
4248 Out << '0';
4249 else if (SeqID > 1) {
4250 SeqID--;
4251
4252 // <seq-id> is encoded in base-36, using digits and upper case letters.
4253 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004254 MutableArrayRef<char> BufferRef(Buffer);
4255 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004256
4257 for (; SeqID != 0; SeqID /= 36) {
4258 unsigned C = SeqID % 36;
4259 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4260 }
4261
4262 Out.write(I.base(), I - BufferRef.rbegin());
4263 }
4264 Out << '_';
4265}
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4268 bool result = mangleSubstitution(tname);
4269 assert(result && "no existing substitution for template name");
4270 (void) result;
4271}
4272
4273// <substitution> ::= S <seq-id> _
4274// ::= S_
4275bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4276 // Try one of the standard substitutions first.
4277 if (mangleStandardSubstitution(ND))
4278 return true;
4279
4280 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4281 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4282}
4283
Justin Bognere8d762e2015-05-22 06:48:13 +00004284/// Determine whether the given type has any qualifiers that are relevant for
4285/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004286static bool hasMangledSubstitutionQualifiers(QualType T) {
4287 Qualifiers Qs = T.getQualifiers();
4288 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4289}
4290
4291bool CXXNameMangler::mangleSubstitution(QualType T) {
4292 if (!hasMangledSubstitutionQualifiers(T)) {
4293 if (const RecordType *RT = T->getAs<RecordType>())
4294 return mangleSubstitution(RT->getDecl());
4295 }
4296
4297 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4298
4299 return mangleSubstitution(TypePtr);
4300}
4301
4302bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4303 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4304 return mangleSubstitution(TD);
4305
4306 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4307 return mangleSubstitution(
4308 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4309}
4310
4311bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4312 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4313 if (I == Substitutions.end())
4314 return false;
4315
4316 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004317 Out << 'S';
4318 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004319
4320 return true;
4321}
4322
4323static bool isCharType(QualType T) {
4324 if (T.isNull())
4325 return false;
4326
4327 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4328 T->isSpecificBuiltinType(BuiltinType::Char_U);
4329}
4330
Justin Bognere8d762e2015-05-22 06:48:13 +00004331/// Returns whether a given type is a template specialization of a given name
4332/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004333static bool isCharSpecialization(QualType T, const char *Name) {
4334 if (T.isNull())
4335 return false;
4336
4337 const RecordType *RT = T->getAs<RecordType>();
4338 if (!RT)
4339 return false;
4340
4341 const ClassTemplateSpecializationDecl *SD =
4342 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4343 if (!SD)
4344 return false;
4345
4346 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4347 return false;
4348
4349 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4350 if (TemplateArgs.size() != 1)
4351 return false;
4352
4353 if (!isCharType(TemplateArgs[0].getAsType()))
4354 return false;
4355
4356 return SD->getIdentifier()->getName() == Name;
4357}
4358
4359template <std::size_t StrLen>
4360static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4361 const char (&Str)[StrLen]) {
4362 if (!SD->getIdentifier()->isStr(Str))
4363 return false;
4364
4365 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4366 if (TemplateArgs.size() != 2)
4367 return false;
4368
4369 if (!isCharType(TemplateArgs[0].getAsType()))
4370 return false;
4371
4372 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4373 return false;
4374
4375 return true;
4376}
4377
4378bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4379 // <substitution> ::= St # ::std::
4380 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4381 if (isStd(NS)) {
4382 Out << "St";
4383 return true;
4384 }
4385 }
4386
4387 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4388 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4389 return false;
4390
4391 // <substitution> ::= Sa # ::std::allocator
4392 if (TD->getIdentifier()->isStr("allocator")) {
4393 Out << "Sa";
4394 return true;
4395 }
4396
4397 // <<substitution> ::= Sb # ::std::basic_string
4398 if (TD->getIdentifier()->isStr("basic_string")) {
4399 Out << "Sb";
4400 return true;
4401 }
4402 }
4403
4404 if (const ClassTemplateSpecializationDecl *SD =
4405 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4406 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4407 return false;
4408
4409 // <substitution> ::= Ss # ::std::basic_string<char,
4410 // ::std::char_traits<char>,
4411 // ::std::allocator<char> >
4412 if (SD->getIdentifier()->isStr("basic_string")) {
4413 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4414
4415 if (TemplateArgs.size() != 3)
4416 return false;
4417
4418 if (!isCharType(TemplateArgs[0].getAsType()))
4419 return false;
4420
4421 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4422 return false;
4423
4424 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4425 return false;
4426
4427 Out << "Ss";
4428 return true;
4429 }
4430
4431 // <substitution> ::= Si # ::std::basic_istream<char,
4432 // ::std::char_traits<char> >
4433 if (isStreamCharSpecialization(SD, "basic_istream")) {
4434 Out << "Si";
4435 return true;
4436 }
4437
4438 // <substitution> ::= So # ::std::basic_ostream<char,
4439 // ::std::char_traits<char> >
4440 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4441 Out << "So";
4442 return true;
4443 }
4444
4445 // <substitution> ::= Sd # ::std::basic_iostream<char,
4446 // ::std::char_traits<char> >
4447 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4448 Out << "Sd";
4449 return true;
4450 }
4451 }
4452 return false;
4453}
4454
4455void CXXNameMangler::addSubstitution(QualType T) {
4456 if (!hasMangledSubstitutionQualifiers(T)) {
4457 if (const RecordType *RT = T->getAs<RecordType>()) {
4458 addSubstitution(RT->getDecl());
4459 return;
4460 }
4461 }
4462
4463 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4464 addSubstitution(TypePtr);
4465}
4466
4467void CXXNameMangler::addSubstitution(TemplateName Template) {
4468 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4469 return addSubstitution(TD);
4470
4471 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4472 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4473}
4474
4475void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4476 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4477 Substitutions[Ptr] = SeqID++;
4478}
4479
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004480void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4481 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4482 if (Other->SeqID > SeqID) {
4483 Substitutions.swap(Other->Substitutions);
4484 SeqID = Other->SeqID;
4485 }
4486}
4487
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004488CXXNameMangler::AbiTagList
4489CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4490 // When derived abi tags are disabled there is no need to make any list.
4491 if (DisableDerivedAbiTags)
4492 return AbiTagList();
4493
4494 llvm::raw_null_ostream NullOutStream;
4495 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4496 TrackReturnTypeTags.disableDerivedAbiTags();
4497
4498 const FunctionProtoType *Proto =
4499 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4500 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4501 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4502 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4503
4504 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4505}
4506
4507CXXNameMangler::AbiTagList
4508CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4509 // When derived abi tags are disabled there is no need to make any list.
4510 if (DisableDerivedAbiTags)
4511 return AbiTagList();
4512
4513 llvm::raw_null_ostream NullOutStream;
4514 CXXNameMangler TrackVariableType(*this, NullOutStream);
4515 TrackVariableType.disableDerivedAbiTags();
4516
4517 TrackVariableType.mangleType(VD->getType());
4518
4519 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4520}
4521
4522bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4523 const VarDecl *VD) {
4524 llvm::raw_null_ostream NullOutStream;
4525 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4526 TrackAbiTags.mangle(VD);
4527 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4528}
4529
Guy Benyei11169dd2012-12-18 14:30:41 +00004530//
4531
Justin Bognere8d762e2015-05-22 06:48:13 +00004532/// Mangles the name of the declaration D and emits that name to the given
4533/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004534///
4535/// If the declaration D requires a mangled name, this routine will emit that
4536/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4537/// and this routine will return false. In this case, the caller should just
4538/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4539/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004540void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4541 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4543 "Invalid mangleName() call, argument is not a variable or function!");
4544 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4545 "Invalid mangleName() call on 'structor decl!");
4546
4547 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4548 getASTContext().getSourceManager(),
4549 "Mangling declaration");
4550
4551 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004552 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004553}
4554
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004555void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4556 CXXCtorType Type,
4557 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 CXXNameMangler Mangler(*this, Out, D, Type);
4559 Mangler.mangle(D);
4560}
4561
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004562void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4563 CXXDtorType Type,
4564 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 CXXNameMangler Mangler(*this, Out, D, Type);
4566 Mangler.mangle(D);
4567}
4568
Rafael Espindola1e4df922014-09-16 15:18:21 +00004569void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4570 raw_ostream &Out) {
4571 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4572 Mangler.mangle(D);
4573}
4574
4575void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4576 raw_ostream &Out) {
4577 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4578 Mangler.mangle(D);
4579}
4580
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004581void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4582 const ThunkInfo &Thunk,
4583 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 // <special-name> ::= T <call-offset> <base encoding>
4585 // # base is the nominal target function of thunk
4586 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4587 // # base is the nominal target function of thunk
4588 // # first call-offset is 'this' adjustment
4589 // # second call-offset is result adjustment
4590
4591 assert(!isa<CXXDestructorDecl>(MD) &&
4592 "Use mangleCXXDtor for destructor decls!");
4593 CXXNameMangler Mangler(*this, Out);
4594 Mangler.getStream() << "_ZT";
4595 if (!Thunk.Return.isEmpty())
4596 Mangler.getStream() << 'c';
4597
4598 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004599 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4600 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4601
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 // Mangle the return pointer adjustment if there is one.
4603 if (!Thunk.Return.isEmpty())
4604 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004605 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4606
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 Mangler.mangleFunctionEncoding(MD);
4608}
4609
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004610void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4611 const CXXDestructorDecl *DD, CXXDtorType Type,
4612 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 // <special-name> ::= T <call-offset> <base encoding>
4614 // # base is the nominal target function of thunk
4615 CXXNameMangler Mangler(*this, Out, DD, Type);
4616 Mangler.getStream() << "_ZT";
4617
4618 // Mangle the 'this' pointer adjustment.
4619 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004620 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621
4622 Mangler.mangleFunctionEncoding(DD);
4623}
4624
Justin Bognere8d762e2015-05-22 06:48:13 +00004625/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004626void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4627 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 // <special-name> ::= GV <object name> # Guard variable for one-time
4629 // # initialization
4630 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004631 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4632 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 Mangler.getStream() << "_ZGV";
4634 Mangler.mangleName(D);
4635}
4636
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004637void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4638 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004639 // These symbols are internal in the Itanium ABI, so the names don't matter.
4640 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4641 // avoid duplicate symbols.
4642 Out << "__cxx_global_var_init";
4643}
4644
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004645void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4646 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004647 // Prefix the mangling of D with __dtor_.
4648 CXXNameMangler Mangler(*this, Out);
4649 Mangler.getStream() << "__dtor_";
4650 if (shouldMangleDeclName(D))
4651 Mangler.mangle(D);
4652 else
4653 Mangler.getStream() << D->getName();
4654}
4655
Reid Kleckner1d59f992015-01-22 01:36:17 +00004656void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4657 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4658 CXXNameMangler Mangler(*this, Out);
4659 Mangler.getStream() << "__filt_";
4660 if (shouldMangleDeclName(EnclosingDecl))
4661 Mangler.mangle(EnclosingDecl);
4662 else
4663 Mangler.getStream() << EnclosingDecl->getName();
4664}
4665
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004666void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4667 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4668 CXXNameMangler Mangler(*this, Out);
4669 Mangler.getStream() << "__fin_";
4670 if (shouldMangleDeclName(EnclosingDecl))
4671 Mangler.mangle(EnclosingDecl);
4672 else
4673 Mangler.getStream() << EnclosingDecl->getName();
4674}
4675
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004676void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4677 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004678 // <special-name> ::= TH <object name>
4679 CXXNameMangler Mangler(*this, Out);
4680 Mangler.getStream() << "_ZTH";
4681 Mangler.mangleName(D);
4682}
4683
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004684void
4685ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4686 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004687 // <special-name> ::= TW <object name>
4688 CXXNameMangler Mangler(*this, Out);
4689 Mangler.getStream() << "_ZTW";
4690 Mangler.mangleName(D);
4691}
4692
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004693void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004694 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004695 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 // We match the GCC mangling here.
4697 // <special-name> ::= GR <object name>
4698 CXXNameMangler Mangler(*this, Out);
4699 Mangler.getStream() << "_ZGR";
4700 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004701 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004702 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703}
4704
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004705void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4706 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 // <special-name> ::= TV <type> # virtual table
4708 CXXNameMangler Mangler(*this, Out);
4709 Mangler.getStream() << "_ZTV";
4710 Mangler.mangleNameOrStandardSubstitution(RD);
4711}
4712
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004713void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4714 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 // <special-name> ::= TT <type> # VTT structure
4716 CXXNameMangler Mangler(*this, Out);
4717 Mangler.getStream() << "_ZTT";
4718 Mangler.mangleNameOrStandardSubstitution(RD);
4719}
4720
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004721void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4722 int64_t Offset,
4723 const CXXRecordDecl *Type,
4724 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004725 // <special-name> ::= TC <type> <offset number> _ <base type>
4726 CXXNameMangler Mangler(*this, Out);
4727 Mangler.getStream() << "_ZTC";
4728 Mangler.mangleNameOrStandardSubstitution(RD);
4729 Mangler.getStream() << Offset;
4730 Mangler.getStream() << '_';
4731 Mangler.mangleNameOrStandardSubstitution(Type);
4732}
4733
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004734void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 // <special-name> ::= TI <type> # typeinfo structure
4736 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4737 CXXNameMangler Mangler(*this, Out);
4738 Mangler.getStream() << "_ZTI";
4739 Mangler.mangleType(Ty);
4740}
4741
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004742void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4743 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4745 CXXNameMangler Mangler(*this, Out);
4746 Mangler.getStream() << "_ZTS";
4747 Mangler.mangleType(Ty);
4748}
4749
Reid Klecknercc99e262013-11-19 23:23:00 +00004750void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4751 mangleCXXRTTIName(Ty, Out);
4752}
4753
David Majnemer58e5bee2014-03-24 21:43:36 +00004754void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4755 llvm_unreachable("Can't mangle string literals");
4756}
4757
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004758ItaniumMangleContext *
4759ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4760 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004761}