blob: 5ce521715621fa037ae154b0b135fb2f9e5b55a1 [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//
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +000014// http://itanium-cxx-abi.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;
Richard Smithdd8b5332017-09-04 05:37:53 +0000384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000385
386 ASTContext &getASTContext() const { return Context.getASTContext(); }
387
388public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000389 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000390 const NamedDecl *D = nullptr, bool NullOut_ = false)
391 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
392 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 // These can't be mangled without a ctor type or dtor type.
394 assert(!D || (!isa<CXXDestructorDecl>(D) &&
395 !isa<CXXConstructorDecl>(D)));
396 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000397 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 const CXXConstructorDecl *D, CXXCtorType Type)
399 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000400 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000401 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 const CXXDestructorDecl *D, CXXDtorType Type)
403 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000404 SeqID(0), AbiTagsRoot(AbiTags) { }
405
406 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(false),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000411
412 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
413 : Context(Outer.Context), Out(Out_), NullOut(true),
414 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000415 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
416 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
418#if MANGLE_CHECKER
419 ~CXXNameMangler() {
420 if (Out.str()[0] == '\01')
421 return;
422
423 int status = 0;
424 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
425 assert(status == 0 && "Could not demangle mangled name!");
426 free(result);
427 }
428#endif
429 raw_ostream &getStream() { return Out; }
430
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000431 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
432 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
433
David Majnemer7ff7eb72015-02-18 07:47:09 +0000434 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
436 void mangleNumber(const llvm::APSInt &I);
437 void mangleNumber(int64_t Number);
438 void mangleFloat(const llvm::APFloat &F);
439 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000440 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 void mangleName(const NamedDecl *ND);
442 void mangleType(QualType T);
443 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
444
445private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000446
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 bool mangleSubstitution(const NamedDecl *ND);
448 bool mangleSubstitution(QualType T);
449 bool mangleSubstitution(TemplateName Template);
450 bool mangleSubstitution(uintptr_t Ptr);
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 void mangleExistingSubstitution(TemplateName name);
453
454 bool mangleStandardSubstitution(const NamedDecl *ND);
455
456 void addSubstitution(const NamedDecl *ND) {
457 ND = cast<NamedDecl>(ND->getCanonicalDecl());
458
459 addSubstitution(reinterpret_cast<uintptr_t>(ND));
460 }
461 void addSubstitution(QualType T);
462 void addSubstitution(TemplateName Template);
463 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000464 // Destructive copy substitutions from other mangler.
465 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000466
467 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 bool recursive = false);
469 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000471 const TemplateArgumentLoc *TemplateArgs,
472 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000473 unsigned KnownArity = UnknownArity);
474
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000475 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
476
477 void mangleNameWithAbiTags(const NamedDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000479 void mangleModuleName(const Module *M);
480 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000481 void mangleTemplateName(const TemplateDecl *TD,
482 const TemplateArgument *TemplateArgs,
483 unsigned NumTemplateArgs);
484 void mangleUnqualifiedName(const NamedDecl *ND,
485 const AbiTagList *AdditionalAbiTags) {
486 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
487 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 }
489 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000490 unsigned KnownArity,
491 const AbiTagList *AdditionalAbiTags);
492 void mangleUnscopedName(const NamedDecl *ND,
493 const AbiTagList *AdditionalAbiTags);
494 void mangleUnscopedTemplateName(const TemplateDecl *ND,
495 const AbiTagList *AdditionalAbiTags);
496 void mangleUnscopedTemplateName(TemplateName,
497 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000499 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000500 void mangleSourceNameWithAbiTags(
501 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
502 void mangleLocalName(const Decl *D,
503 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000504 void mangleBlockForPrefix(const BlockDecl *Block);
505 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 void mangleLambda(const CXXRecordDecl *Lambda);
507 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000508 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 bool NoFunction=false);
510 void mangleNestedName(const TemplateDecl *TD,
511 const TemplateArgument *TemplateArgs,
512 unsigned NumTemplateArgs);
513 void manglePrefix(NestedNameSpecifier *qualifier);
514 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
515 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000516 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000518 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
519 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000520 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000522 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523 void mangleQualifiers(Qualifiers Quals);
524 void mangleRefQualifier(RefQualifierKind RefQualifier);
525
526 void mangleObjCMethodName(const ObjCMethodDecl *MD);
527
528 // Declare manglers for every type class.
529#define ABSTRACT_TYPE(CLASS, PARENT)
530#define NON_CANONICAL_TYPE(CLASS, PARENT)
531#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
532#include "clang/AST/TypeNodes.def"
533
534 void mangleType(const TagType*);
535 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000536 static StringRef getCallingConvQualifierName(CallingConv CC);
537 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
538 void mangleExtFunctionInfo(const FunctionType *T);
539 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000540 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000542 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000543
544 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000545 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000546 void mangleMemberExpr(const Expr *base, bool isArrow,
547 NestedNameSpecifier *qualifier,
548 NamedDecl *firstQualifierLookup,
549 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000550 const TemplateArgumentLoc *TemplateArgs,
551 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000553 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000554 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000556 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleCXXDtorType(CXXDtorType T);
558
James Y Knight04ec5bf2015-12-24 02:59:37 +0000559 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
560 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
562 unsigned NumTemplateArgs);
563 void mangleTemplateArgs(const TemplateArgumentList &AL);
564 void mangleTemplateArg(TemplateArgument A);
565
566 void mangleTemplateParameter(unsigned Index);
567
568 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000569
570 void writeAbiTags(const NamedDecl *ND,
571 const AbiTagList *AdditionalAbiTags);
572
573 // Returns sorted unique list of ABI tags.
574 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
575 // Returns sorted unique list of ABI tags.
576 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000577};
578
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000579}
Guy Benyei11169dd2012-12-18 14:30:41 +0000580
Rafael Espindola002667c2013-10-16 01:40:34 +0000581bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000583 if (FD) {
584 LanguageLinkage L = FD->getLanguageLinkage();
585 // Overloadable functions need mangling.
586 if (FD->hasAttr<OverloadableAttr>())
587 return true;
588
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000589 // "main" is not mangled.
590 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000591 return false;
592
593 // C++ functions and those whose names are not a simple identifier need
594 // mangling.
595 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
596 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000597
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000598 // C functions are not mangled.
599 if (L == CLanguageLinkage)
600 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000601 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 // Otherwise, no mangling is done outside C++ mode.
604 if (!getASTContext().getLangOpts().CPlusPlus)
605 return false;
606
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000607 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000608 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000609 // C variables are not mangled.
610 if (VD->isExternC())
611 return false;
612
613 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000614 const DeclContext *DC = getEffectiveDeclContext(D);
615 // Check for extern variable declared locally.
616 if (DC->isFunctionOrMethod() && D->hasLinkage())
617 while (!DC->isNamespace() && !DC->isTranslationUnit())
618 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000619 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000620 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000621 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 return false;
623 }
624
Guy Benyei11169dd2012-12-18 14:30:41 +0000625 return true;
626}
627
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000628void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
629 const AbiTagList *AdditionalAbiTags) {
630 assert(AbiTags && "require AbiTagState");
631 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
632}
633
634void CXXNameMangler::mangleSourceNameWithAbiTags(
635 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
636 mangleSourceName(ND->getIdentifier());
637 writeAbiTags(ND, AdditionalAbiTags);
638}
639
David Majnemer7ff7eb72015-02-18 07:47:09 +0000640void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 // <mangled-name> ::= _Z <encoding>
642 // ::= <data name>
643 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000644 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
646 mangleFunctionEncoding(FD);
647 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
648 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000649 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
650 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 else
652 mangleName(cast<FieldDecl>(D));
653}
654
655void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
656 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000657
658 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000659 if (!Context.shouldMangleDeclName(FD)) {
660 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000662 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000663
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000664 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
665 if (ReturnTypeAbiTags.empty()) {
666 // There are no tags for return type, the simplest case.
667 mangleName(FD);
668 mangleFunctionEncodingBareType(FD);
669 return;
670 }
671
672 // Mangle function name and encoding to temporary buffer.
673 // We have to output name and encoding to the same mangler to get the same
674 // substitution as it will be in final mangling.
675 SmallString<256> FunctionEncodingBuf;
676 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
677 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
678 // Output name of the function.
679 FunctionEncodingMangler.disableDerivedAbiTags();
680 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
681
682 // Remember length of the function name in the buffer.
683 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
684 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
685
686 // Get tags from return type that are not present in function name or
687 // encoding.
688 const AbiTagList &UsedAbiTags =
689 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
690 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
691 AdditionalAbiTags.erase(
692 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
693 UsedAbiTags.begin(), UsedAbiTags.end(),
694 AdditionalAbiTags.begin()),
695 AdditionalAbiTags.end());
696
697 // Output name with implicit tags and function encoding from temporary buffer.
698 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
699 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000700
701 // Function encoding could create new substitutions so we have to add
702 // temp mangled substitutions to main mangler.
703 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000704}
705
706void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000707 if (FD->hasAttr<EnableIfAttr>()) {
708 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
709 Out << "Ua9enable_ifI";
710 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
711 // it here.
712 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
713 E = FD->getAttrs().rend();
714 I != E; ++I) {
715 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
716 if (!EIA)
717 continue;
718 Out << 'X';
719 mangleExpression(EIA->getCond());
720 Out << 'E';
721 }
722 Out << 'E';
723 FunctionTypeDepth.pop(Saved);
724 }
725
Richard Smith5179eb72016-06-28 19:03:57 +0000726 // When mangling an inheriting constructor, the bare function type used is
727 // that of the inherited constructor.
728 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
729 if (auto Inherited = CD->getInheritedConstructor())
730 FD = Inherited.getConstructor();
731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 // Whether the mangling of a function type includes the return type depends on
733 // the context and the nature of the function. The rules for deciding whether
734 // the return type is included are:
735 //
736 // 1. Template functions (names or types) have return types encoded, with
737 // the exceptions listed below.
738 // 2. Function types not appearing as part of a function name mangling,
739 // e.g. parameters, pointer types, etc., have return type encoded, with the
740 // exceptions listed below.
741 // 3. Non-template function names do not have return types encoded.
742 //
743 // The exceptions mentioned in (1) and (2) above, for which the return type is
744 // never included, are
745 // 1. Constructors.
746 // 2. Destructors.
747 // 3. Conversion operator functions, e.g. operator int.
748 bool MangleReturnType = false;
749 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
750 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
751 isa<CXXConversionDecl>(FD)))
752 MangleReturnType = true;
753
754 // Mangle the type of the primary template.
755 FD = PrimaryTemplate->getTemplatedDecl();
756 }
757
John McCall07daf722016-03-01 22:18:03 +0000758 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000759 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000760}
761
762static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
763 while (isa<LinkageSpecDecl>(DC)) {
764 DC = getEffectiveParentContext(DC);
765 }
766
767 return DC;
768}
769
Justin Bognere8d762e2015-05-22 06:48:13 +0000770/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000771static bool isStd(const NamespaceDecl *NS) {
772 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
773 ->isTranslationUnit())
774 return false;
775
776 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
777 return II && II->isStr("std");
778}
779
780// isStdNamespace - Return whether a given decl context is a toplevel 'std'
781// namespace.
782static bool isStdNamespace(const DeclContext *DC) {
783 if (!DC->isNamespace())
784 return false;
785
786 return isStd(cast<NamespaceDecl>(DC));
787}
788
789static const TemplateDecl *
790isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
791 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000792 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
794 TemplateArgs = FD->getTemplateSpecializationArgs();
795 return TD;
796 }
797 }
798
799 // Check if we have a class template.
800 if (const ClassTemplateSpecializationDecl *Spec =
801 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
802 TemplateArgs = &Spec->getTemplateArgs();
803 return Spec->getSpecializedTemplate();
804 }
805
Larisse Voufo39a1e502013-08-06 01:03:05 +0000806 // Check if we have a variable template.
807 if (const VarTemplateSpecializationDecl *Spec =
808 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
809 TemplateArgs = &Spec->getTemplateArgs();
810 return Spec->getSpecializedTemplate();
811 }
812
Craig Topper36250ad2014-05-12 05:36:57 +0000813 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000814}
815
Guy Benyei11169dd2012-12-18 14:30:41 +0000816void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000817 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
818 // Variables should have implicit tags from its type.
819 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
820 if (VariableTypeAbiTags.empty()) {
821 // Simple case no variable type tags.
822 mangleNameWithAbiTags(VD, nullptr);
823 return;
824 }
825
826 // Mangle variable name to null stream to collect tags.
827 llvm::raw_null_ostream NullOutStream;
828 CXXNameMangler VariableNameMangler(*this, NullOutStream);
829 VariableNameMangler.disableDerivedAbiTags();
830 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
831
832 // Get tags from variable type that are not present in its name.
833 const AbiTagList &UsedAbiTags =
834 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
835 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
836 AdditionalAbiTags.erase(
837 std::set_difference(VariableTypeAbiTags.begin(),
838 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
839 UsedAbiTags.end(), AdditionalAbiTags.begin()),
840 AdditionalAbiTags.end());
841
842 // Output name with implicit tags.
843 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
844 } else {
845 mangleNameWithAbiTags(ND, nullptr);
846 }
847}
848
849void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
850 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000851 // <name> ::= [<module-name>] <nested-name>
852 // ::= [<module-name>] <unscoped-name>
853 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 // ::= <local-name>
855 //
856 const DeclContext *DC = getEffectiveDeclContext(ND);
857
858 // If this is an extern variable declared locally, the relevant DeclContext
859 // is that of the containing namespace, or the translation unit.
860 // FIXME: This is a hack; extern variables declared locally should have
861 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000862 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 while (!DC->isNamespace() && !DC->isTranslationUnit())
864 DC = getEffectiveParentContext(DC);
865 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000866 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 return;
868 }
869
870 DC = IgnoreLinkageSpecDecls(DC);
871
Richard Smithdd8b5332017-09-04 05:37:53 +0000872 if (isLocalContainerContext(DC)) {
873 mangleLocalName(ND, AdditionalAbiTags);
874 return;
875 }
876
877 // Do not mangle the owning module for an external linkage declaration.
878 // This enables backwards-compatibility with non-modular code, and is
879 // a valid choice since conflicts are not permitted by C++ Modules TS
880 // [basic.def.odr]/6.2.
881 if (!ND->hasExternalFormalLinkage())
882 if (Module *M = ND->getOwningModuleForLinkage())
883 mangleModuleName(M);
884
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
886 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000887 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000888 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000889 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 mangleTemplateArgs(*TemplateArgs);
891 return;
892 }
893
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000894 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000895 return;
896 }
897
Richard Smithdd8b5332017-09-04 05:37:53 +0000898 mangleNestedName(ND, DC, AdditionalAbiTags);
899}
900
901void CXXNameMangler::mangleModuleName(const Module *M) {
902 // Implement the C++ Modules TS name mangling proposal; see
903 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
904 //
905 // <module-name> ::= W <unscoped-name>+ E
906 // ::= W <module-subst> <unscoped-name>* E
907 Out << 'W';
908 mangleModuleNamePrefix(M->Name);
909 Out << 'E';
910}
911
912void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
913 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
914 // ::= W <seq-id - 10> _ # otherwise
915 auto It = ModuleSubstitutions.find(Name);
916 if (It != ModuleSubstitutions.end()) {
917 if (It->second < 10)
918 Out << '_' << static_cast<char>('0' + It->second);
919 else
920 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000921 return;
922 }
923
Richard Smithdd8b5332017-09-04 05:37:53 +0000924 // FIXME: Preserve hierarchy in module names rather than flattening
925 // them to strings; use Module*s as substitution keys.
926 auto Parts = Name.rsplit('.');
927 if (Parts.second.empty())
928 Parts.second = Parts.first;
929 else
930 mangleModuleNamePrefix(Parts.first);
931
932 Out << Parts.second.size() << Parts.second;
933 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000934}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000935
936void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
937 const TemplateArgument *TemplateArgs,
938 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
940
941 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000942 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
944 } else {
945 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
946 }
947}
948
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000949void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
950 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 // <unscoped-name> ::= <unqualified-name>
952 // ::= St <unqualified-name> # ::std::
953
954 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
955 Out << "St";
956
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000957 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000958}
959
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000960void CXXNameMangler::mangleUnscopedTemplateName(
961 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 // <unscoped-template-name> ::= <unscoped-name>
963 // ::= <substitution>
964 if (mangleSubstitution(ND))
965 return;
966
967 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000968 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
969 assert(!AdditionalAbiTags &&
970 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000972 } else if (isa<BuiltinTemplateDecl>(ND)) {
973 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000974 } else {
975 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
976 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 addSubstitution(ND);
979}
980
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000981void CXXNameMangler::mangleUnscopedTemplateName(
982 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 // <unscoped-template-name> ::= <unscoped-name>
984 // ::= <substitution>
985 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000986 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000987
988 if (mangleSubstitution(Template))
989 return;
990
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000991 assert(!AdditionalAbiTags &&
992 "dependent template name cannot have abi tags");
993
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
995 assert(Dependent && "Not a dependent template name?");
996 if (const IdentifierInfo *Id = Dependent->getIdentifier())
997 mangleSourceName(Id);
998 else
999 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001000
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 addSubstitution(Template);
1002}
1003
1004void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1005 // ABI:
1006 // Floating-point literals are encoded using a fixed-length
1007 // lowercase hexadecimal string corresponding to the internal
1008 // representation (IEEE on Itanium), high-order bytes first,
1009 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1010 // on Itanium.
1011 // The 'without leading zeroes' thing seems to be an editorial
1012 // mistake; see the discussion on cxx-abi-dev beginning on
1013 // 2012-01-16.
1014
1015 // Our requirements here are just barely weird enough to justify
1016 // using a custom algorithm instead of post-processing APInt::toString().
1017
1018 llvm::APInt valueBits = f.bitcastToAPInt();
1019 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1020 assert(numCharacters != 0);
1021
1022 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001023 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Fill the buffer left-to-right.
1026 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1027 // The bit-index of the next hex digit.
1028 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1029
1030 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001031 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1032 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 hexDigit &= 0xF;
1034
1035 // Map that over to a lowercase hex digit.
1036 static const char charForHex[16] = {
1037 '0', '1', '2', '3', '4', '5', '6', '7',
1038 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1039 };
1040 buffer[stringIndex] = charForHex[hexDigit];
1041 }
1042
1043 Out.write(buffer.data(), numCharacters);
1044}
1045
1046void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1047 if (Value.isSigned() && Value.isNegative()) {
1048 Out << 'n';
1049 Value.abs().print(Out, /*signed*/ false);
1050 } else {
1051 Value.print(Out, /*signed*/ false);
1052 }
1053}
1054
1055void CXXNameMangler::mangleNumber(int64_t Number) {
1056 // <number> ::= [n] <non-negative decimal integer>
1057 if (Number < 0) {
1058 Out << 'n';
1059 Number = -Number;
1060 }
1061
1062 Out << Number;
1063}
1064
1065void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1066 // <call-offset> ::= h <nv-offset> _
1067 // ::= v <v-offset> _
1068 // <nv-offset> ::= <offset number> # non-virtual base override
1069 // <v-offset> ::= <offset number> _ <virtual offset number>
1070 // # virtual base override, with vcall offset
1071 if (!Virtual) {
1072 Out << 'h';
1073 mangleNumber(NonVirtual);
1074 Out << '_';
1075 return;
1076 }
1077
1078 Out << 'v';
1079 mangleNumber(NonVirtual);
1080 Out << '_';
1081 mangleNumber(Virtual);
1082 Out << '_';
1083}
1084
1085void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001086 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 if (!mangleSubstitution(QualType(TST, 0))) {
1088 mangleTemplatePrefix(TST->getTemplateName());
1089
1090 // FIXME: GCC does not appear to mangle the template arguments when
1091 // the template in question is a dependent template name. Should we
1092 // emulate that badness?
1093 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1094 addSubstitution(QualType(TST, 0));
1095 }
David Majnemera88b3592015-02-18 02:28:01 +00001096 } else if (const auto *DTST =
1097 type->getAs<DependentTemplateSpecializationType>()) {
1098 if (!mangleSubstitution(QualType(DTST, 0))) {
1099 TemplateName Template = getASTContext().getDependentTemplateName(
1100 DTST->getQualifier(), DTST->getIdentifier());
1101 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
David Majnemera88b3592015-02-18 02:28:01 +00001103 // FIXME: GCC does not appear to mangle the template arguments when
1104 // the template in question is a dependent template name. Should we
1105 // emulate that badness?
1106 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1107 addSubstitution(QualType(DTST, 0));
1108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 } else {
1110 // We use the QualType mangle type variant here because it handles
1111 // substitutions.
1112 mangleType(type);
1113 }
1114}
1115
1116/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1117///
Guy Benyei11169dd2012-12-18 14:30:41 +00001118/// \param recursive - true if this is being called recursively,
1119/// i.e. if there is more prefix "to the right".
1120void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 bool recursive) {
1122
1123 // x, ::x
1124 // <unresolved-name> ::= [gs] <base-unresolved-name>
1125
1126 // T::x / decltype(p)::x
1127 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1128
1129 // T::N::x /decltype(p)::N::x
1130 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1131 // <base-unresolved-name>
1132
1133 // A::x, N::y, A<T>::z; "gs" means leading "::"
1134 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1135 // <base-unresolved-name>
1136
1137 switch (qualifier->getKind()) {
1138 case NestedNameSpecifier::Global:
1139 Out << "gs";
1140
1141 // We want an 'sr' unless this is the entire NNS.
1142 if (recursive)
1143 Out << "sr";
1144
1145 // We never want an 'E' here.
1146 return;
1147
Nikola Smiljanic67860242014-09-26 00:28:20 +00001148 case NestedNameSpecifier::Super:
1149 llvm_unreachable("Can't mangle __super specifier");
1150
Guy Benyei11169dd2012-12-18 14:30:41 +00001151 case NestedNameSpecifier::Namespace:
1152 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001153 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 /*recursive*/ true);
1155 else
1156 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001157 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 break;
1159 case NestedNameSpecifier::NamespaceAlias:
1160 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001161 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 /*recursive*/ true);
1163 else
1164 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001165 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 break;
1167
1168 case NestedNameSpecifier::TypeSpec:
1169 case NestedNameSpecifier::TypeSpecWithTemplate: {
1170 const Type *type = qualifier->getAsType();
1171
1172 // We only want to use an unresolved-type encoding if this is one of:
1173 // - a decltype
1174 // - a template type parameter
1175 // - a template template parameter with arguments
1176 // In all of these cases, we should have no prefix.
1177 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001178 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 /*recursive*/ true);
1180 } else {
1181 // Otherwise, all the cases want this.
1182 Out << "sr";
1183 }
1184
David Majnemerb8014dd2015-02-19 02:16:16 +00001185 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 return;
1187
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 break;
1189 }
1190
1191 case NestedNameSpecifier::Identifier:
1192 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001193 if (qualifier->getPrefix())
1194 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001196 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001198
1199 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001200 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 break;
1202 }
1203
1204 // If this was the innermost part of the NNS, and we fell out to
1205 // here, append an 'E'.
1206 if (!recursive)
1207 Out << 'E';
1208}
1209
1210/// Mangle an unresolved-name, which is generally used for names which
1211/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001212void CXXNameMangler::mangleUnresolvedName(
1213 NestedNameSpecifier *qualifier, DeclarationName name,
1214 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1215 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001216 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001217 switch (name.getNameKind()) {
1218 // <base-unresolved-name> ::= <simple-id>
1219 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001220 mangleSourceName(name.getAsIdentifierInfo());
1221 break;
1222 // <base-unresolved-name> ::= dn <destructor-name>
1223 case DeclarationName::CXXDestructorName:
1224 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001225 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001226 break;
1227 // <base-unresolved-name> ::= on <operator-name>
1228 case DeclarationName::CXXConversionFunctionName:
1229 case DeclarationName::CXXLiteralOperatorName:
1230 case DeclarationName::CXXOperatorName:
1231 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001232 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001233 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001234 case DeclarationName::CXXConstructorName:
1235 llvm_unreachable("Can't mangle a constructor name!");
1236 case DeclarationName::CXXUsingDirective:
1237 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001238 case DeclarationName::CXXDeductionGuideName:
1239 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001240 case DeclarationName::ObjCMultiArgSelector:
1241 case DeclarationName::ObjCOneArgSelector:
1242 case DeclarationName::ObjCZeroArgSelector:
1243 llvm_unreachable("Can't mangle Objective-C selector names here!");
1244 }
Richard Smithafecd832016-10-24 20:47:04 +00001245
1246 // The <simple-id> and on <operator-name> productions end in an optional
1247 // <template-args>.
1248 if (TemplateArgs)
1249 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250}
1251
Guy Benyei11169dd2012-12-18 14:30:41 +00001252void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1253 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001254 unsigned KnownArity,
1255 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001256 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001257 // <unqualified-name> ::= <operator-name>
1258 // ::= <ctor-dtor-name>
1259 // ::= <source-name>
1260 switch (Name.getNameKind()) {
1261 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001262 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1263
Richard Smithda383632016-08-15 01:33:41 +00001264 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001265 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001266 // FIXME: Non-standard mangling for decomposition declarations:
1267 //
1268 // <unqualified-name> ::= DC <source-name>* E
1269 //
1270 // These can never be referenced across translation units, so we do
1271 // not need a cross-vendor mangling for anything other than demanglers.
1272 // Proposed on cxx-abi-dev on 2016-08-12
1273 Out << "DC";
1274 for (auto *BD : DD->bindings())
1275 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1276 Out << 'E';
1277 writeAbiTags(ND, AdditionalAbiTags);
1278 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001279 }
1280
1281 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001282 // Match GCC's naming convention for internal linkage symbols, for
1283 // symbols that are not actually visible outside of this TU. GCC
1284 // distinguishes between internal and external linkage symbols in
1285 // its mangling, to support cases like this that were valid C++ prior
1286 // to DR426:
1287 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 // void test() { extern void foo(); }
1289 // static void foo();
Rafael Espindola3ae00052013-05-13 00:12:11 +00001290 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001291 !ND->isExternallyVisible() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001292 getEffectiveDeclContext(ND)->isFileContext())
1293 Out << 'L';
1294
Erich Keane757d3172016-11-02 18:29:35 +00001295 auto *FD = dyn_cast<FunctionDecl>(ND);
1296 bool IsRegCall = FD &&
1297 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1298 clang::CC_X86RegCall;
1299 if (IsRegCall)
1300 mangleRegCallName(II);
1301 else
1302 mangleSourceName(II);
1303
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001304 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 break;
1306 }
1307
1308 // Otherwise, an anonymous entity. We must have a declaration.
1309 assert(ND && "mangling empty name without declaration");
1310
1311 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1312 if (NS->isAnonymousNamespace()) {
1313 // This is how gcc mangles these names.
1314 Out << "12_GLOBAL__N_1";
1315 break;
1316 }
1317 }
1318
1319 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1320 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001321 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001323
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 // Itanium C++ ABI 5.1.2:
1325 //
1326 // For the purposes of mangling, the name of an anonymous union is
1327 // considered to be the name of the first named data member found by a
1328 // pre-order, depth-first, declaration-order walk of the data members of
1329 // the anonymous union. If there is no such data member (i.e., if all of
1330 // the data members in the union are unnamed), then there is no way for
1331 // a program to refer to the anonymous union, and there is therefore no
1332 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001333 assert(RD->isAnonymousStructOrUnion()
1334 && "Expected anonymous struct or union!");
1335 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001336
1337 // It's actually possible for various reasons for us to get here
1338 // with an empty anonymous struct / union. Fortunately, it
1339 // doesn't really matter what name we generate.
1340 if (!FD) break;
1341 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001342
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001344 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 break;
1346 }
John McCall924046f2013-04-10 06:08:21 +00001347
1348 // Class extensions have no name as a category, and it's possible
1349 // for them to be the semantic parent of certain declarations
1350 // (primarily, tag decls defined within declarations). Such
1351 // declarations will always have internal linkage, so the name
1352 // doesn't really matter, but we shouldn't crash on them. For
1353 // safety, just handle all ObjC containers here.
1354 if (isa<ObjCContainerDecl>(ND))
1355 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001356
1357 // We must have an anonymous struct.
1358 const TagDecl *TD = cast<TagDecl>(ND);
1359 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1360 assert(TD->getDeclContext() == D->getDeclContext() &&
1361 "Typedef should not be in another decl context!");
1362 assert(D->getDeclName().getAsIdentifierInfo() &&
1363 "Typedef was not named!");
1364 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001365 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1366 // Explicit abi tags are still possible; take from underlying type, not
1367 // from typedef.
1368 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 break;
1370 }
1371
1372 // <unnamed-type-name> ::= <closure-type-name>
1373 //
1374 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1375 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1376 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1377 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001378 assert(!AdditionalAbiTags &&
1379 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 mangleLambda(Record);
1381 break;
1382 }
1383 }
1384
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001385 if (TD->isExternallyVisible()) {
1386 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001387 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001388 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001389 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001391 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 break;
1393 }
1394
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001395 // Get a unique id for the anonymous struct. If it is not a real output
1396 // ID doesn't matter so use fake one.
1397 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001398
1399 // Mangle it as a source name in the form
1400 // [n] $_<id>
1401 // where n is the length of the string.
1402 SmallString<8> Str;
1403 Str += "$_";
1404 Str += llvm::utostr(AnonStructId);
1405
1406 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001407 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 break;
1409 }
1410
1411 case DeclarationName::ObjCZeroArgSelector:
1412 case DeclarationName::ObjCOneArgSelector:
1413 case DeclarationName::ObjCMultiArgSelector:
1414 llvm_unreachable("Can't mangle Objective-C selector names here!");
1415
Richard Smith5179eb72016-06-28 19:03:57 +00001416 case DeclarationName::CXXConstructorName: {
1417 const CXXRecordDecl *InheritedFrom = nullptr;
1418 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1419 if (auto Inherited =
1420 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1421 InheritedFrom = Inherited.getConstructor()->getParent();
1422 InheritedTemplateArgs =
1423 Inherited.getConstructor()->getTemplateSpecializationArgs();
1424 }
1425
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 if (ND == Structor)
1427 // If the named decl is the C++ constructor we're mangling, use the type
1428 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001429 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 else
1431 // Otherwise, use the complete constructor name. This is relevant if a
1432 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001433 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1434
1435 // FIXME: The template arguments are part of the enclosing prefix or
1436 // nested-name, but it's more convenient to mangle them here.
1437 if (InheritedTemplateArgs)
1438 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001439
1440 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001442 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001443
1444 case DeclarationName::CXXDestructorName:
1445 if (ND == Structor)
1446 // If the named decl is the C++ destructor we're mangling, use the type we
1447 // were given.
1448 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1449 else
1450 // Otherwise, use the complete destructor name. This is relevant if a
1451 // class with a destructor is declared within a destructor.
1452 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001453 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 break;
1455
David Majnemera88b3592015-02-18 02:28:01 +00001456 case DeclarationName::CXXOperatorName:
1457 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 Arity = cast<FunctionDecl>(ND)->getNumParams();
1459
David Majnemera88b3592015-02-18 02:28:01 +00001460 // If we have a member function, we need to include the 'this' pointer.
1461 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1462 if (!MD->isStatic())
1463 Arity++;
1464 }
1465 // FALLTHROUGH
1466 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001468 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001469 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001470 break;
1471
Richard Smith35845152017-02-07 01:37:30 +00001472 case DeclarationName::CXXDeductionGuideName:
1473 llvm_unreachable("Can't mangle a deduction guide name!");
1474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 case DeclarationName::CXXUsingDirective:
1476 llvm_unreachable("Can't mangle a using directive name!");
1477 }
1478}
1479
Erich Keane757d3172016-11-02 18:29:35 +00001480void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1481 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1482 // <number> ::= [n] <non-negative decimal integer>
1483 // <identifier> ::= <unqualified source code identifier>
1484 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1485 << II->getName();
1486}
1487
Guy Benyei11169dd2012-12-18 14:30:41 +00001488void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1489 // <source-name> ::= <positive length number> <identifier>
1490 // <number> ::= [n] <non-negative decimal integer>
1491 // <identifier> ::= <unqualified source code identifier>
1492 Out << II->getLength() << II->getName();
1493}
1494
1495void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1496 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001497 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001498 bool NoFunction) {
1499 // <nested-name>
1500 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1501 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1502 // <template-args> E
1503
1504 Out << 'N';
1505 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001506 Qualifiers MethodQuals =
Roger Ferrer Ibanezcb895132017-04-19 12:23:28 +00001507 Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
David Majnemer42350df2013-11-03 23:51:28 +00001508 // We do not consider restrict a distinguishing attribute for overloading
1509 // purposes so we must not mangle it.
1510 MethodQuals.removeRestrict();
1511 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 mangleRefQualifier(Method->getRefQualifier());
1513 }
1514
1515 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001516 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001518 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 mangleTemplateArgs(*TemplateArgs);
1520 }
1521 else {
1522 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001523 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 }
1525
1526 Out << 'E';
1527}
1528void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1529 const TemplateArgument *TemplateArgs,
1530 unsigned NumTemplateArgs) {
1531 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1532
1533 Out << 'N';
1534
1535 mangleTemplatePrefix(TD);
1536 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1537
1538 Out << 'E';
1539}
1540
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001541void CXXNameMangler::mangleLocalName(const Decl *D,
1542 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1544 // := Z <function encoding> E s [<discriminator>]
1545 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1546 // _ <entity name>
1547 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001548 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001549 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001550 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001551
1552 Out << 'Z';
1553
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001554 {
1555 AbiTagState LocalAbiTags(AbiTags);
1556
1557 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1558 mangleObjCMethodName(MD);
1559 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1560 mangleBlockForPrefix(BD);
1561 else
1562 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1563
1564 // Implicit ABI tags (from namespace) are not available in the following
1565 // entity; reset to actually emitted tags, which are available.
1566 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1567 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001568
Eli Friedman92821742013-07-02 02:01:18 +00001569 Out << 'E';
1570
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001571 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1572 // be a bug that is fixed in trunk.
1573
Eli Friedman92821742013-07-02 02:01:18 +00001574 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 // The parameter number is omitted for the last parameter, 0 for the
1576 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1577 // <entity name> will of course contain a <closure-type-name>: Its
1578 // numbering will be local to the particular argument in which it appears
1579 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001580 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001581 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001583 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 if (const FunctionDecl *Func
1585 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1586 Out << 'd';
1587 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1588 if (Num > 1)
1589 mangleNumber(Num - 2);
1590 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 }
1592 }
1593 }
1594
1595 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001596 // equality ok because RD derived from ND above
1597 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001598 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001599 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1600 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001601 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001602 mangleUnqualifiedBlock(BD);
1603 } else {
1604 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001605 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1606 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001607 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001608 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1609 // Mangle a block in a default parameter; see above explanation for
1610 // lambdas.
1611 if (const ParmVarDecl *Parm
1612 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1613 if (const FunctionDecl *Func
1614 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1615 Out << 'd';
1616 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1617 if (Num > 1)
1618 mangleNumber(Num - 2);
1619 Out << '_';
1620 }
1621 }
1622
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001623 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001624 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001625 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001626 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001627 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001628
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001629 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1630 unsigned disc;
1631 if (Context.getNextDiscriminator(ND, disc)) {
1632 if (disc < 10)
1633 Out << '_' << disc;
1634 else
1635 Out << "__" << disc << '_';
1636 }
1637 }
Eli Friedman95f50122013-07-02 17:52:28 +00001638}
1639
1640void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1641 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001642 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001643 return;
1644 }
1645 const DeclContext *DC = getEffectiveDeclContext(Block);
1646 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001647 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001648 return;
1649 }
1650 manglePrefix(getEffectiveDeclContext(Block));
1651 mangleUnqualifiedBlock(Block);
1652}
1653
1654void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1655 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1656 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1657 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001658 const auto *ND = cast<NamedDecl>(Context);
1659 if (ND->getIdentifier()) {
1660 mangleSourceNameWithAbiTags(ND);
1661 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001662 }
1663 }
1664 }
1665
1666 // If we have a block mangling number, use it.
1667 unsigned Number = Block->getBlockManglingNumber();
1668 // Otherwise, just make up a number. It doesn't matter what it is because
1669 // the symbol in question isn't externally visible.
1670 if (!Number)
1671 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001672 else {
1673 // Stored mangling numbers are 1-based.
1674 --Number;
1675 }
Eli Friedman95f50122013-07-02 17:52:28 +00001676 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001677 if (Number > 0)
1678 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001679 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001680}
1681
1682void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1683 // If the context of a closure type is an initializer for a class member
1684 // (static or nonstatic), it is encoded in a qualified name with a final
1685 // <prefix> of the form:
1686 //
1687 // <data-member-prefix> := <member source-name> M
1688 //
1689 // Technically, the data-member-prefix is part of the <prefix>. However,
1690 // since a closure type will always be mangled with a prefix, it's easier
1691 // to emit that last part of the prefix here.
1692 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1693 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001694 !isa<ParmVarDecl>(Context)) {
1695 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1696 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 if (const IdentifierInfo *Name
1698 = cast<NamedDecl>(Context)->getIdentifier()) {
1699 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001700 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001701 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001702 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001703 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 }
1705 }
1706 }
1707
1708 Out << "Ul";
1709 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1710 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001711 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1712 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 Out << "E";
1714
1715 // The number is omitted for the first closure type with a given
1716 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1717 // (in lexical order) with that same <lambda-sig> and context.
1718 //
1719 // The AST keeps track of the number for us.
1720 unsigned Number = Lambda->getLambdaManglingNumber();
1721 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1722 if (Number > 1)
1723 mangleNumber(Number - 2);
1724 Out << '_';
1725}
1726
1727void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1728 switch (qualifier->getKind()) {
1729 case NestedNameSpecifier::Global:
1730 // nothing
1731 return;
1732
Nikola Smiljanic67860242014-09-26 00:28:20 +00001733 case NestedNameSpecifier::Super:
1734 llvm_unreachable("Can't mangle __super specifier");
1735
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 case NestedNameSpecifier::Namespace:
1737 mangleName(qualifier->getAsNamespace());
1738 return;
1739
1740 case NestedNameSpecifier::NamespaceAlias:
1741 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1742 return;
1743
1744 case NestedNameSpecifier::TypeSpec:
1745 case NestedNameSpecifier::TypeSpecWithTemplate:
1746 manglePrefix(QualType(qualifier->getAsType(), 0));
1747 return;
1748
1749 case NestedNameSpecifier::Identifier:
1750 // Member expressions can have these without prefixes, but that
1751 // should end up in mangleUnresolvedPrefix instead.
1752 assert(qualifier->getPrefix());
1753 manglePrefix(qualifier->getPrefix());
1754
1755 mangleSourceName(qualifier->getAsIdentifier());
1756 return;
1757 }
1758
1759 llvm_unreachable("unexpected nested name specifier");
1760}
1761
1762void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1763 // <prefix> ::= <prefix> <unqualified-name>
1764 // ::= <template-prefix> <template-args>
1765 // ::= <template-param>
1766 // ::= # empty
1767 // ::= <substitution>
1768
1769 DC = IgnoreLinkageSpecDecls(DC);
1770
1771 if (DC->isTranslationUnit())
1772 return;
1773
Eli Friedman95f50122013-07-02 17:52:28 +00001774 if (NoFunction && isLocalContainerContext(DC))
1775 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001776
Eli Friedman95f50122013-07-02 17:52:28 +00001777 assert(!isLocalContainerContext(DC));
1778
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 const NamedDecl *ND = cast<NamedDecl>(DC);
1780 if (mangleSubstitution(ND))
1781 return;
1782
1783 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001784 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001785 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1786 mangleTemplatePrefix(TD);
1787 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001788 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001790 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 }
1792
1793 addSubstitution(ND);
1794}
1795
1796void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1797 // <template-prefix> ::= <prefix> <template unqualified-name>
1798 // ::= <template-param>
1799 // ::= <substitution>
1800 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1801 return mangleTemplatePrefix(TD);
1802
1803 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1804 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001805
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 if (OverloadedTemplateStorage *Overloaded
1807 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001808 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001809 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 return;
1811 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001812
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1814 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001815 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1816 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001817 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001818}
1819
Eli Friedman86af13f02013-07-05 18:41:30 +00001820void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1821 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 // <template-prefix> ::= <prefix> <template unqualified-name>
1823 // ::= <template-param>
1824 // ::= <substitution>
1825 // <template-template-param> ::= <template-param>
1826 // <substitution>
1827
1828 if (mangleSubstitution(ND))
1829 return;
1830
1831 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001832 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001834 } else {
1835 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001836 if (isa<BuiltinTemplateDecl>(ND))
1837 mangleUnqualifiedName(ND, nullptr);
1838 else
1839 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 }
1841
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 addSubstitution(ND);
1843}
1844
1845/// Mangles a template name under the production <type>. Required for
1846/// template template arguments.
1847/// <type> ::= <class-enum-type>
1848/// ::= <template-param>
1849/// ::= <substitution>
1850void CXXNameMangler::mangleType(TemplateName TN) {
1851 if (mangleSubstitution(TN))
1852 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001853
1854 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001855
1856 switch (TN.getKind()) {
1857 case TemplateName::QualifiedTemplate:
1858 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1859 goto HaveDecl;
1860
1861 case TemplateName::Template:
1862 TD = TN.getAsTemplateDecl();
1863 goto HaveDecl;
1864
1865 HaveDecl:
1866 if (isa<TemplateTemplateParmDecl>(TD))
1867 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1868 else
1869 mangleName(TD);
1870 break;
1871
1872 case TemplateName::OverloadedTemplate:
1873 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1874
1875 case TemplateName::DependentTemplate: {
1876 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1877 assert(Dependent->isIdentifier());
1878
1879 // <class-enum-type> ::= <name>
1880 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001881 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 mangleSourceName(Dependent->getIdentifier());
1883 break;
1884 }
1885
1886 case TemplateName::SubstTemplateTemplateParm: {
1887 // Substituted template parameters are mangled as the substituted
1888 // template. This will check for the substitution twice, which is
1889 // fine, but we have to return early so that we don't try to *add*
1890 // the substitution twice.
1891 SubstTemplateTemplateParmStorage *subst
1892 = TN.getAsSubstTemplateTemplateParm();
1893 mangleType(subst->getReplacement());
1894 return;
1895 }
1896
1897 case TemplateName::SubstTemplateTemplateParmPack: {
1898 // FIXME: not clear how to mangle this!
1899 // template <template <class> class T...> class A {
1900 // template <template <class> class U...> void foo(B<T,U> x...);
1901 // };
1902 Out << "_SUBSTPACK_";
1903 break;
1904 }
1905 }
1906
1907 addSubstitution(TN);
1908}
1909
David Majnemerb8014dd2015-02-19 02:16:16 +00001910bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1911 StringRef Prefix) {
1912 // Only certain other types are valid as prefixes; enumerate them.
1913 switch (Ty->getTypeClass()) {
1914 case Type::Builtin:
1915 case Type::Complex:
1916 case Type::Adjusted:
1917 case Type::Decayed:
1918 case Type::Pointer:
1919 case Type::BlockPointer:
1920 case Type::LValueReference:
1921 case Type::RValueReference:
1922 case Type::MemberPointer:
1923 case Type::ConstantArray:
1924 case Type::IncompleteArray:
1925 case Type::VariableArray:
1926 case Type::DependentSizedArray:
1927 case Type::DependentSizedExtVector:
1928 case Type::Vector:
1929 case Type::ExtVector:
1930 case Type::FunctionProto:
1931 case Type::FunctionNoProto:
1932 case Type::Paren:
1933 case Type::Attributed:
1934 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001935 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001936 case Type::PackExpansion:
1937 case Type::ObjCObject:
1938 case Type::ObjCInterface:
1939 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001940 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001941 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001942 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001943 llvm_unreachable("type is illegal as a nested name specifier");
1944
1945 case Type::SubstTemplateTypeParmPack:
1946 // FIXME: not clear how to mangle this!
1947 // template <class T...> class A {
1948 // template <class U...> void foo(decltype(T::foo(U())) x...);
1949 // };
1950 Out << "_SUBSTPACK_";
1951 break;
1952
1953 // <unresolved-type> ::= <template-param>
1954 // ::= <decltype>
1955 // ::= <template-template-param> <template-args>
1956 // (this last is not official yet)
1957 case Type::TypeOfExpr:
1958 case Type::TypeOf:
1959 case Type::Decltype:
1960 case Type::TemplateTypeParm:
1961 case Type::UnaryTransform:
1962 case Type::SubstTemplateTypeParm:
1963 unresolvedType:
1964 // Some callers want a prefix before the mangled type.
1965 Out << Prefix;
1966
1967 // This seems to do everything we want. It's not really
1968 // sanctioned for a substituted template parameter, though.
1969 mangleType(Ty);
1970
1971 // We never want to print 'E' directly after an unresolved-type,
1972 // so we return directly.
1973 return true;
1974
1975 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001976 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001977 break;
1978
1979 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001980 mangleSourceNameWithAbiTags(
1981 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001982 break;
1983
1984 case Type::Enum:
1985 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001986 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001987 break;
1988
1989 case Type::TemplateSpecialization: {
1990 const TemplateSpecializationType *TST =
1991 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001992 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001993 switch (TN.getKind()) {
1994 case TemplateName::Template:
1995 case TemplateName::QualifiedTemplate: {
1996 TemplateDecl *TD = TN.getAsTemplateDecl();
1997
1998 // If the base is a template template parameter, this is an
1999 // unresolved type.
2000 assert(TD && "no template for template specialization type");
2001 if (isa<TemplateTemplateParmDecl>(TD))
2002 goto unresolvedType;
2003
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002004 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002005 break;
David Majnemera88b3592015-02-18 02:28:01 +00002006 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002007
2008 case TemplateName::OverloadedTemplate:
2009 case TemplateName::DependentTemplate:
2010 llvm_unreachable("invalid base for a template specialization type");
2011
2012 case TemplateName::SubstTemplateTemplateParm: {
2013 SubstTemplateTemplateParmStorage *subst =
2014 TN.getAsSubstTemplateTemplateParm();
2015 mangleExistingSubstitution(subst->getReplacement());
2016 break;
2017 }
2018
2019 case TemplateName::SubstTemplateTemplateParmPack: {
2020 // FIXME: not clear how to mangle this!
2021 // template <template <class U> class T...> class A {
2022 // template <class U...> void foo(decltype(T<U>::foo) x...);
2023 // };
2024 Out << "_SUBSTPACK_";
2025 break;
2026 }
2027 }
2028
David Majnemera88b3592015-02-18 02:28:01 +00002029 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002030 break;
David Majnemera88b3592015-02-18 02:28:01 +00002031 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002032
2033 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002034 mangleSourceNameWithAbiTags(
2035 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002036 break;
2037
2038 case Type::DependentName:
2039 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2040 break;
2041
2042 case Type::DependentTemplateSpecialization: {
2043 const DependentTemplateSpecializationType *DTST =
2044 cast<DependentTemplateSpecializationType>(Ty);
2045 mangleSourceName(DTST->getIdentifier());
2046 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2047 break;
2048 }
2049
2050 case Type::Elaborated:
2051 return mangleUnresolvedTypeOrSimpleId(
2052 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2053 }
2054
2055 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002056}
2057
2058void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2059 switch (Name.getNameKind()) {
2060 case DeclarationName::CXXConstructorName:
2061 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002062 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002063 case DeclarationName::CXXUsingDirective:
2064 case DeclarationName::Identifier:
2065 case DeclarationName::ObjCMultiArgSelector:
2066 case DeclarationName::ObjCOneArgSelector:
2067 case DeclarationName::ObjCZeroArgSelector:
2068 llvm_unreachable("Not an operator name");
2069
2070 case DeclarationName::CXXConversionFunctionName:
2071 // <operator-name> ::= cv <type> # (cast)
2072 Out << "cv";
2073 mangleType(Name.getCXXNameType());
2074 break;
2075
2076 case DeclarationName::CXXLiteralOperatorName:
2077 Out << "li";
2078 mangleSourceName(Name.getCXXLiteralIdentifier());
2079 return;
2080
2081 case DeclarationName::CXXOperatorName:
2082 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2083 break;
2084 }
2085}
2086
Guy Benyei11169dd2012-12-18 14:30:41 +00002087void
2088CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2089 switch (OO) {
2090 // <operator-name> ::= nw # new
2091 case OO_New: Out << "nw"; break;
2092 // ::= na # new[]
2093 case OO_Array_New: Out << "na"; break;
2094 // ::= dl # delete
2095 case OO_Delete: Out << "dl"; break;
2096 // ::= da # delete[]
2097 case OO_Array_Delete: Out << "da"; break;
2098 // ::= ps # + (unary)
2099 // ::= pl # + (binary or unknown)
2100 case OO_Plus:
2101 Out << (Arity == 1? "ps" : "pl"); break;
2102 // ::= ng # - (unary)
2103 // ::= mi # - (binary or unknown)
2104 case OO_Minus:
2105 Out << (Arity == 1? "ng" : "mi"); break;
2106 // ::= ad # & (unary)
2107 // ::= an # & (binary or unknown)
2108 case OO_Amp:
2109 Out << (Arity == 1? "ad" : "an"); break;
2110 // ::= de # * (unary)
2111 // ::= ml # * (binary or unknown)
2112 case OO_Star:
2113 // Use binary when unknown.
2114 Out << (Arity == 1? "de" : "ml"); break;
2115 // ::= co # ~
2116 case OO_Tilde: Out << "co"; break;
2117 // ::= dv # /
2118 case OO_Slash: Out << "dv"; break;
2119 // ::= rm # %
2120 case OO_Percent: Out << "rm"; break;
2121 // ::= or # |
2122 case OO_Pipe: Out << "or"; break;
2123 // ::= eo # ^
2124 case OO_Caret: Out << "eo"; break;
2125 // ::= aS # =
2126 case OO_Equal: Out << "aS"; break;
2127 // ::= pL # +=
2128 case OO_PlusEqual: Out << "pL"; break;
2129 // ::= mI # -=
2130 case OO_MinusEqual: Out << "mI"; break;
2131 // ::= mL # *=
2132 case OO_StarEqual: Out << "mL"; break;
2133 // ::= dV # /=
2134 case OO_SlashEqual: Out << "dV"; break;
2135 // ::= rM # %=
2136 case OO_PercentEqual: Out << "rM"; break;
2137 // ::= aN # &=
2138 case OO_AmpEqual: Out << "aN"; break;
2139 // ::= oR # |=
2140 case OO_PipeEqual: Out << "oR"; break;
2141 // ::= eO # ^=
2142 case OO_CaretEqual: Out << "eO"; break;
2143 // ::= ls # <<
2144 case OO_LessLess: Out << "ls"; break;
2145 // ::= rs # >>
2146 case OO_GreaterGreater: Out << "rs"; break;
2147 // ::= lS # <<=
2148 case OO_LessLessEqual: Out << "lS"; break;
2149 // ::= rS # >>=
2150 case OO_GreaterGreaterEqual: Out << "rS"; break;
2151 // ::= eq # ==
2152 case OO_EqualEqual: Out << "eq"; break;
2153 // ::= ne # !=
2154 case OO_ExclaimEqual: Out << "ne"; break;
2155 // ::= lt # <
2156 case OO_Less: Out << "lt"; break;
2157 // ::= gt # >
2158 case OO_Greater: Out << "gt"; break;
2159 // ::= le # <=
2160 case OO_LessEqual: Out << "le"; break;
2161 // ::= ge # >=
2162 case OO_GreaterEqual: Out << "ge"; break;
2163 // ::= nt # !
2164 case OO_Exclaim: Out << "nt"; break;
2165 // ::= aa # &&
2166 case OO_AmpAmp: Out << "aa"; break;
2167 // ::= oo # ||
2168 case OO_PipePipe: Out << "oo"; break;
2169 // ::= pp # ++
2170 case OO_PlusPlus: Out << "pp"; break;
2171 // ::= mm # --
2172 case OO_MinusMinus: Out << "mm"; break;
2173 // ::= cm # ,
2174 case OO_Comma: Out << "cm"; break;
2175 // ::= pm # ->*
2176 case OO_ArrowStar: Out << "pm"; break;
2177 // ::= pt # ->
2178 case OO_Arrow: Out << "pt"; break;
2179 // ::= cl # ()
2180 case OO_Call: Out << "cl"; break;
2181 // ::= ix # []
2182 case OO_Subscript: Out << "ix"; break;
2183
2184 // ::= qu # ?
2185 // The conditional operator can't be overloaded, but we still handle it when
2186 // mangling expressions.
2187 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002188 // Proposal on cxx-abi-dev, 2015-10-21.
2189 // ::= aw # co_await
2190 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002191
2192 case OO_None:
2193 case NUM_OVERLOADED_OPERATORS:
2194 llvm_unreachable("Not an overloaded operator");
2195 }
2196}
2197
2198void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002199 // Vendor qualifiers come first and if they are order-insensitive they must
2200 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002201
John McCall07daf722016-03-01 22:18:03 +00002202 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002203 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002204 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002205 //
David Tweed31d09b02013-09-13 12:04:22 +00002206 // <type> ::= U <target-addrspace>
2207 // <type> ::= U <OpenCL-addrspace>
2208 // <type> ::= U <CUDA-addrspace>
2209
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00002211 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002212
2213 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2214 // <target-addrspace> ::= "AS" <address-space-number>
2215 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00002216 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002217 } else {
2218 switch (AS) {
2219 default: llvm_unreachable("Not a language specific address space");
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002220 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant |
2221 // "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002222 case LangAS::opencl_global: ASString = "CLglobal"; break;
2223 case LangAS::opencl_local: ASString = "CLlocal"; break;
2224 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002225 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002226 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2227 case LangAS::cuda_device: ASString = "CUdevice"; break;
2228 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2229 case LangAS::cuda_shared: ASString = "CUshared"; break;
2230 }
2231 }
John McCall07daf722016-03-01 22:18:03 +00002232 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 }
John McCall07daf722016-03-01 22:18:03 +00002234
2235 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 // Objective-C ARC Extension:
2237 //
2238 // <type> ::= U "__strong"
2239 // <type> ::= U "__weak"
2240 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002241 //
2242 // Note: we emit __weak first to preserve the order as
2243 // required by the Itanium ABI.
2244 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2245 mangleVendorQualifier("__weak");
2246
2247 // __unaligned (from -fms-extensions)
2248 if (Quals.hasUnaligned())
2249 mangleVendorQualifier("__unaligned");
2250
2251 // Remaining ARC ownership qualifiers.
2252 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 case Qualifiers::OCL_None:
2254 break;
2255
2256 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002257 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 break;
2259
2260 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002261 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 break;
2263
2264 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002265 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 break;
2267
2268 case Qualifiers::OCL_ExplicitNone:
2269 // The __unsafe_unretained qualifier is *not* mangled, so that
2270 // __unsafe_unretained types in ARC produce the same manglings as the
2271 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2272 // better ABI compatibility.
2273 //
2274 // It's safe to do this because unqualified 'id' won't show up
2275 // in any type signatures that need to be mangled.
2276 break;
2277 }
John McCall07daf722016-03-01 22:18:03 +00002278
2279 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2280 if (Quals.hasRestrict())
2281 Out << 'r';
2282 if (Quals.hasVolatile())
2283 Out << 'V';
2284 if (Quals.hasConst())
2285 Out << 'K';
2286}
2287
2288void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2289 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002290}
2291
2292void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2293 // <ref-qualifier> ::= R # lvalue reference
2294 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 switch (RefQualifier) {
2296 case RQ_None:
2297 break;
2298
2299 case RQ_LValue:
2300 Out << 'R';
2301 break;
2302
2303 case RQ_RValue:
2304 Out << 'O';
2305 break;
2306 }
2307}
2308
2309void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2310 Context.mangleObjCMethodName(MD, Out);
2311}
2312
David Majnemereea02ee2014-11-28 22:22:46 +00002313static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2314 if (Quals)
2315 return true;
2316 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2317 return true;
2318 if (Ty->isOpenCLSpecificType())
2319 return true;
2320 if (Ty->isBuiltinType())
2321 return false;
2322
2323 return true;
2324}
2325
Guy Benyei11169dd2012-12-18 14:30:41 +00002326void CXXNameMangler::mangleType(QualType T) {
2327 // If our type is instantiation-dependent but not dependent, we mangle
2328 // it as it was written in the source, removing any top-level sugar.
2329 // Otherwise, use the canonical type.
2330 //
2331 // FIXME: This is an approximation of the instantiation-dependent name
2332 // mangling rules, since we should really be using the type as written and
2333 // augmented via semantic analysis (i.e., with implicit conversions and
2334 // default template arguments) for any instantiation-dependent type.
2335 // Unfortunately, that requires several changes to our AST:
2336 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2337 // uniqued, so that we can handle substitutions properly
2338 // - Default template arguments will need to be represented in the
2339 // TemplateSpecializationType, since they need to be mangled even though
2340 // they aren't written.
2341 // - Conversions on non-type template arguments need to be expressed, since
2342 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002343 //
2344 // FIXME: This is wrong when mapping to the canonical type for a dependent
2345 // type discards instantiation-dependent portions of the type, such as for:
2346 //
2347 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2348 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2349 //
2350 // It's also wrong in the opposite direction when instantiation-dependent,
2351 // canonically-equivalent types differ in some irrelevant portion of inner
2352 // type sugar. In such cases, we fail to form correct substitutions, eg:
2353 //
2354 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2355 //
2356 // We should instead canonicalize the non-instantiation-dependent parts,
2357 // regardless of whether the type as a whole is dependent or instantiation
2358 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 if (!T->isInstantiationDependentType() || T->isDependentType())
2360 T = T.getCanonicalType();
2361 else {
2362 // Desugar any types that are purely sugar.
2363 do {
2364 // Don't desugar through template specialization types that aren't
2365 // type aliases. We need to mangle the template arguments as written.
2366 if (const TemplateSpecializationType *TST
2367 = dyn_cast<TemplateSpecializationType>(T))
2368 if (!TST->isTypeAlias())
2369 break;
2370
2371 QualType Desugared
2372 = T.getSingleStepDesugaredType(Context.getASTContext());
2373 if (Desugared == T)
2374 break;
2375
2376 T = Desugared;
2377 } while (true);
2378 }
2379 SplitQualType split = T.split();
2380 Qualifiers quals = split.Quals;
2381 const Type *ty = split.Ty;
2382
David Majnemereea02ee2014-11-28 22:22:46 +00002383 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 if (isSubstitutable && mangleSubstitution(T))
2385 return;
2386
2387 // If we're mangling a qualified array type, push the qualifiers to
2388 // the element type.
2389 if (quals && isa<ArrayType>(T)) {
2390 ty = Context.getASTContext().getAsArrayType(T);
2391 quals = Qualifiers();
2392
2393 // Note that we don't update T: we want to add the
2394 // substitution at the original type.
2395 }
2396
2397 if (quals) {
2398 mangleQualifiers(quals);
2399 // Recurse: even if the qualified type isn't yet substitutable,
2400 // the unqualified type might be.
2401 mangleType(QualType(ty, 0));
2402 } else {
2403 switch (ty->getTypeClass()) {
2404#define ABSTRACT_TYPE(CLASS, PARENT)
2405#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2406 case Type::CLASS: \
2407 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2408 return;
2409#define TYPE(CLASS, PARENT) \
2410 case Type::CLASS: \
2411 mangleType(static_cast<const CLASS##Type*>(ty)); \
2412 break;
2413#include "clang/AST/TypeNodes.def"
2414 }
2415 }
2416
2417 // Add the substitution.
2418 if (isSubstitutable)
2419 addSubstitution(T);
2420}
2421
2422void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2423 if (!mangleStandardSubstitution(ND))
2424 mangleName(ND);
2425}
2426
2427void CXXNameMangler::mangleType(const BuiltinType *T) {
2428 // <type> ::= <builtin-type>
2429 // <builtin-type> ::= v # void
2430 // ::= w # wchar_t
2431 // ::= b # bool
2432 // ::= c # char
2433 // ::= a # signed char
2434 // ::= h # unsigned char
2435 // ::= s # short
2436 // ::= t # unsigned short
2437 // ::= i # int
2438 // ::= j # unsigned int
2439 // ::= l # long
2440 // ::= m # unsigned long
2441 // ::= x # long long, __int64
2442 // ::= y # unsigned long long, __int64
2443 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002444 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 // ::= f # float
2446 // ::= d # double
2447 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002448 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2450 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2451 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2452 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002453 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 // ::= Di # char32_t
2455 // ::= Ds # char16_t
2456 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2457 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002458 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002460 case BuiltinType::Void:
2461 Out << 'v';
2462 break;
2463 case BuiltinType::Bool:
2464 Out << 'b';
2465 break;
2466 case BuiltinType::Char_U:
2467 case BuiltinType::Char_S:
2468 Out << 'c';
2469 break;
2470 case BuiltinType::UChar:
2471 Out << 'h';
2472 break;
2473 case BuiltinType::UShort:
2474 Out << 't';
2475 break;
2476 case BuiltinType::UInt:
2477 Out << 'j';
2478 break;
2479 case BuiltinType::ULong:
2480 Out << 'm';
2481 break;
2482 case BuiltinType::ULongLong:
2483 Out << 'y';
2484 break;
2485 case BuiltinType::UInt128:
2486 Out << 'o';
2487 break;
2488 case BuiltinType::SChar:
2489 Out << 'a';
2490 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002492 case BuiltinType::WChar_U:
2493 Out << 'w';
2494 break;
2495 case BuiltinType::Char16:
2496 Out << "Ds";
2497 break;
2498 case BuiltinType::Char32:
2499 Out << "Di";
2500 break;
2501 case BuiltinType::Short:
2502 Out << 's';
2503 break;
2504 case BuiltinType::Int:
2505 Out << 'i';
2506 break;
2507 case BuiltinType::Long:
2508 Out << 'l';
2509 break;
2510 case BuiltinType::LongLong:
2511 Out << 'x';
2512 break;
2513 case BuiltinType::Int128:
2514 Out << 'n';
2515 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002516 case BuiltinType::Float16:
2517 Out << "DF16_";
2518 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002519 case BuiltinType::Half:
2520 Out << "Dh";
2521 break;
2522 case BuiltinType::Float:
2523 Out << 'f';
2524 break;
2525 case BuiltinType::Double:
2526 Out << 'd';
2527 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002528 case BuiltinType::LongDouble:
2529 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2530 ? 'g'
2531 : 'e');
2532 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002533 case BuiltinType::Float128:
2534 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2535 Out << "U10__float128"; // Match the GCC mangling
2536 else
2537 Out << 'g';
2538 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002539 case BuiltinType::NullPtr:
2540 Out << "Dn";
2541 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002542
2543#define BUILTIN_TYPE(Id, SingletonId)
2544#define PLACEHOLDER_TYPE(Id, SingletonId) \
2545 case BuiltinType::Id:
2546#include "clang/AST/BuiltinTypes.def"
2547 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002548 if (!NullOut)
2549 llvm_unreachable("mangling a placeholder type");
2550 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002551 case BuiltinType::ObjCId:
2552 Out << "11objc_object";
2553 break;
2554 case BuiltinType::ObjCClass:
2555 Out << "10objc_class";
2556 break;
2557 case BuiltinType::ObjCSel:
2558 Out << "13objc_selector";
2559 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002560#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2561 case BuiltinType::Id: \
2562 type_name = "ocl_" #ImgType "_" #Suffix; \
2563 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002564 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002565#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002566 case BuiltinType::OCLSampler:
2567 Out << "11ocl_sampler";
2568 break;
2569 case BuiltinType::OCLEvent:
2570 Out << "9ocl_event";
2571 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002572 case BuiltinType::OCLClkEvent:
2573 Out << "12ocl_clkevent";
2574 break;
2575 case BuiltinType::OCLQueue:
2576 Out << "9ocl_queue";
2577 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002578 case BuiltinType::OCLReserveID:
2579 Out << "13ocl_reserveid";
2580 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 }
2582}
2583
John McCall07daf722016-03-01 22:18:03 +00002584StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2585 switch (CC) {
2586 case CC_C:
2587 return "";
2588
2589 case CC_X86StdCall:
2590 case CC_X86FastCall:
2591 case CC_X86ThisCall:
2592 case CC_X86VectorCall:
2593 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002594 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002595 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002596 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002597 case CC_AAPCS:
2598 case CC_AAPCS_VFP:
2599 case CC_IntelOclBicc:
2600 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002601 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002602 case CC_PreserveMost:
2603 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002604 // FIXME: we should be mangling all of the above.
2605 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002606
2607 case CC_Swift:
2608 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002609 }
2610 llvm_unreachable("bad calling convention");
2611}
2612
2613void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2614 // Fast path.
2615 if (T->getExtInfo() == FunctionType::ExtInfo())
2616 return;
2617
2618 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2619 // This will get more complicated in the future if we mangle other
2620 // things here; but for now, since we mangle ns_returns_retained as
2621 // a qualifier on the result type, we can get away with this:
2622 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2623 if (!CCQualifier.empty())
2624 mangleVendorQualifier(CCQualifier);
2625
2626 // FIXME: regparm
2627 // FIXME: noreturn
2628}
2629
2630void
2631CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2632 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2633
2634 // Note that these are *not* substitution candidates. Demanglers might
2635 // have trouble with this if the parameter type is fully substituted.
2636
John McCall477f2bb2016-03-03 06:39:32 +00002637 switch (PI.getABI()) {
2638 case ParameterABI::Ordinary:
2639 break;
2640
2641 // All of these start with "swift", so they come before "ns_consumed".
2642 case ParameterABI::SwiftContext:
2643 case ParameterABI::SwiftErrorResult:
2644 case ParameterABI::SwiftIndirectResult:
2645 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2646 break;
2647 }
2648
John McCall07daf722016-03-01 22:18:03 +00002649 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002650 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002651
2652 if (PI.isNoEscape())
2653 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002654}
2655
Guy Benyei11169dd2012-12-18 14:30:41 +00002656// <type> ::= <function-type>
2657// <function-type> ::= [<CV-qualifiers>] F [Y]
2658// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002659void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002660 mangleExtFunctionInfo(T);
2661
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2663 // e.g. "const" in "int (A::*)() const".
2664 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2665
Richard Smithfda59e52016-10-26 01:05:54 +00002666 // Mangle instantiation-dependent exception-specification, if present,
2667 // per cxx-abi-dev proposal on 2016-10-11.
2668 if (T->hasInstantiationDependentExceptionSpec()) {
2669 if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smithef09aa92016-11-03 00:27:54 +00002670 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002671 mangleExpression(T->getNoexceptExpr());
2672 Out << "E";
2673 } else {
2674 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002675 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002676 for (auto ExceptTy : T->exceptions())
2677 mangleType(ExceptTy);
2678 Out << "E";
2679 }
2680 } else if (T->isNothrow(getASTContext())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002681 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002682 }
2683
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 Out << 'F';
2685
2686 // FIXME: We don't have enough information in the AST to produce the 'Y'
2687 // encoding for extern "C" function types.
2688 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2689
2690 // Mangle the ref-qualifier, if present.
2691 mangleRefQualifier(T->getRefQualifier());
2692
2693 Out << 'E';
2694}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002697 // Function types without prototypes can arise when mangling a function type
2698 // within an overloadable function in C. We mangle these as the absence of any
2699 // parameter types (not even an empty parameter list).
2700 Out << 'F';
2701
2702 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2703
2704 FunctionTypeDepth.enterResultType();
2705 mangleType(T->getReturnType());
2706 FunctionTypeDepth.leaveResultType();
2707
2708 FunctionTypeDepth.pop(saved);
2709 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002710}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002711
John McCall07daf722016-03-01 22:18:03 +00002712void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002713 bool MangleReturnType,
2714 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 // Record that we're in a function type. See mangleFunctionParam
2716 // for details on what we're trying to achieve here.
2717 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2718
2719 // <bare-function-type> ::= <signature type>+
2720 if (MangleReturnType) {
2721 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002722
2723 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002724 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002725 mangleVendorQualifier("ns_returns_retained");
2726
2727 // Mangle the return type without any direct ARC ownership qualifiers.
2728 QualType ReturnTy = Proto->getReturnType();
2729 if (ReturnTy.getObjCLifetime()) {
2730 auto SplitReturnTy = ReturnTy.split();
2731 SplitReturnTy.Quals.removeObjCLifetime();
2732 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2733 }
2734 mangleType(ReturnTy);
2735
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 FunctionTypeDepth.leaveResultType();
2737 }
2738
Alp Toker9cacbab2014-01-20 20:26:09 +00002739 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // <builtin-type> ::= v # void
2741 Out << 'v';
2742
2743 FunctionTypeDepth.pop(saved);
2744 return;
2745 }
2746
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002747 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2748 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002749 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002750 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002751 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2752 }
2753
2754 // Mangle the type.
2755 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002756 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2757
2758 if (FD) {
2759 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2760 // Attr can only take 1 character, so we can hardcode the length below.
2761 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2762 Out << "U17pass_object_size" << Attr->getType();
2763 }
2764 }
2765 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002766
2767 FunctionTypeDepth.pop(saved);
2768
2769 // <builtin-type> ::= z # ellipsis
2770 if (Proto->isVariadic())
2771 Out << 'z';
2772}
2773
2774// <type> ::= <class-enum-type>
2775// <class-enum-type> ::= <name>
2776void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2777 mangleName(T->getDecl());
2778}
2779
2780// <type> ::= <class-enum-type>
2781// <class-enum-type> ::= <name>
2782void CXXNameMangler::mangleType(const EnumType *T) {
2783 mangleType(static_cast<const TagType*>(T));
2784}
2785void CXXNameMangler::mangleType(const RecordType *T) {
2786 mangleType(static_cast<const TagType*>(T));
2787}
2788void CXXNameMangler::mangleType(const TagType *T) {
2789 mangleName(T->getDecl());
2790}
2791
2792// <type> ::= <array-type>
2793// <array-type> ::= A <positive dimension number> _ <element type>
2794// ::= A [<dimension expression>] _ <element type>
2795void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2796 Out << 'A' << T->getSize() << '_';
2797 mangleType(T->getElementType());
2798}
2799void CXXNameMangler::mangleType(const VariableArrayType *T) {
2800 Out << 'A';
2801 // decayed vla types (size 0) will just be skipped.
2802 if (T->getSizeExpr())
2803 mangleExpression(T->getSizeExpr());
2804 Out << '_';
2805 mangleType(T->getElementType());
2806}
2807void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2808 Out << 'A';
2809 mangleExpression(T->getSizeExpr());
2810 Out << '_';
2811 mangleType(T->getElementType());
2812}
2813void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2814 Out << "A_";
2815 mangleType(T->getElementType());
2816}
2817
2818// <type> ::= <pointer-to-member-type>
2819// <pointer-to-member-type> ::= M <class type> <member type>
2820void CXXNameMangler::mangleType(const MemberPointerType *T) {
2821 Out << 'M';
2822 mangleType(QualType(T->getClass(), 0));
2823 QualType PointeeType = T->getPointeeType();
2824 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2825 mangleType(FPT);
2826
2827 // Itanium C++ ABI 5.1.8:
2828 //
2829 // The type of a non-static member function is considered to be different,
2830 // for the purposes of substitution, from the type of a namespace-scope or
2831 // static member function whose type appears similar. The types of two
2832 // non-static member functions are considered to be different, for the
2833 // purposes of substitution, if the functions are members of different
2834 // classes. In other words, for the purposes of substitution, the class of
2835 // which the function is a member is considered part of the type of
2836 // function.
2837
2838 // Given that we already substitute member function pointers as a
2839 // whole, the net effect of this rule is just to unconditionally
2840 // suppress substitution on the function type in a member pointer.
2841 // We increment the SeqID here to emulate adding an entry to the
2842 // substitution table.
2843 ++SeqID;
2844 } else
2845 mangleType(PointeeType);
2846}
2847
2848// <type> ::= <template-param>
2849void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2850 mangleTemplateParameter(T->getIndex());
2851}
2852
2853// <type> ::= <template-param>
2854void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2855 // FIXME: not clear how to mangle this!
2856 // template <class T...> class A {
2857 // template <class U...> void foo(T(*)(U) x...);
2858 // };
2859 Out << "_SUBSTPACK_";
2860}
2861
2862// <type> ::= P <type> # pointer-to
2863void CXXNameMangler::mangleType(const PointerType *T) {
2864 Out << 'P';
2865 mangleType(T->getPointeeType());
2866}
2867void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2868 Out << 'P';
2869 mangleType(T->getPointeeType());
2870}
2871
2872// <type> ::= R <type> # reference-to
2873void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2874 Out << 'R';
2875 mangleType(T->getPointeeType());
2876}
2877
2878// <type> ::= O <type> # rvalue reference-to (C++0x)
2879void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2880 Out << 'O';
2881 mangleType(T->getPointeeType());
2882}
2883
2884// <type> ::= C <type> # complex pair (C 2000)
2885void CXXNameMangler::mangleType(const ComplexType *T) {
2886 Out << 'C';
2887 mangleType(T->getElementType());
2888}
2889
2890// ARM's ABI for Neon vector types specifies that they should be mangled as
2891// if they are structs (to match ARM's initial implementation). The
2892// vector type must be one of the special types predefined by ARM.
2893void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2894 QualType EltType = T->getElementType();
2895 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002896 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2898 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002899 case BuiltinType::SChar:
2900 case BuiltinType::UChar:
2901 EltName = "poly8_t";
2902 break;
2903 case BuiltinType::Short:
2904 case BuiltinType::UShort:
2905 EltName = "poly16_t";
2906 break;
2907 case BuiltinType::ULongLong:
2908 EltName = "poly64_t";
2909 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2911 }
2912 } else {
2913 switch (cast<BuiltinType>(EltType)->getKind()) {
2914 case BuiltinType::SChar: EltName = "int8_t"; break;
2915 case BuiltinType::UChar: EltName = "uint8_t"; break;
2916 case BuiltinType::Short: EltName = "int16_t"; break;
2917 case BuiltinType::UShort: EltName = "uint16_t"; break;
2918 case BuiltinType::Int: EltName = "int32_t"; break;
2919 case BuiltinType::UInt: EltName = "uint32_t"; break;
2920 case BuiltinType::LongLong: EltName = "int64_t"; break;
2921 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002922 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002924 case BuiltinType::Half: EltName = "float16_t";break;
2925 default:
2926 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 }
2928 }
Craig Topper36250ad2014-05-12 05:36:57 +00002929 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 unsigned BitSize = (T->getNumElements() *
2931 getASTContext().getTypeSize(EltType));
2932 if (BitSize == 64)
2933 BaseName = "__simd64_";
2934 else {
2935 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2936 BaseName = "__simd128_";
2937 }
2938 Out << strlen(BaseName) + strlen(EltName);
2939 Out << BaseName << EltName;
2940}
2941
Tim Northover2fe823a2013-08-01 09:23:19 +00002942static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2943 switch (EltType->getKind()) {
2944 case BuiltinType::SChar:
2945 return "Int8";
2946 case BuiltinType::Short:
2947 return "Int16";
2948 case BuiltinType::Int:
2949 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002950 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002951 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002952 return "Int64";
2953 case BuiltinType::UChar:
2954 return "Uint8";
2955 case BuiltinType::UShort:
2956 return "Uint16";
2957 case BuiltinType::UInt:
2958 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002959 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002960 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002961 return "Uint64";
2962 case BuiltinType::Half:
2963 return "Float16";
2964 case BuiltinType::Float:
2965 return "Float32";
2966 case BuiltinType::Double:
2967 return "Float64";
2968 default:
2969 llvm_unreachable("Unexpected vector element base type");
2970 }
2971}
2972
2973// AArch64's ABI for Neon vector types specifies that they should be mangled as
2974// the equivalent internal name. The vector type must be one of the special
2975// types predefined by ARM.
2976void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2977 QualType EltType = T->getElementType();
2978 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2979 unsigned BitSize =
2980 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002981 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002982
2983 assert((BitSize == 64 || BitSize == 128) &&
2984 "Neon vector type not 64 or 128 bits");
2985
Tim Northover2fe823a2013-08-01 09:23:19 +00002986 StringRef EltName;
2987 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2988 switch (cast<BuiltinType>(EltType)->getKind()) {
2989 case BuiltinType::UChar:
2990 EltName = "Poly8";
2991 break;
2992 case BuiltinType::UShort:
2993 EltName = "Poly16";
2994 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002995 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002996 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002997 EltName = "Poly64";
2998 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002999 default:
3000 llvm_unreachable("unexpected Neon polynomial vector element type");
3001 }
3002 } else
3003 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3004
3005 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003006 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003007 Out << TypeName.length() << TypeName;
3008}
3009
Guy Benyei11169dd2012-12-18 14:30:41 +00003010// GNU extension: vector types
3011// <type> ::= <vector-type>
3012// <vector-type> ::= Dv <positive dimension number> _
3013// <extended element type>
3014// ::= Dv [<dimension expression>] _ <element type>
3015// <extended element type> ::= <element type>
3016// ::= p # AltiVec vector pixel
3017// ::= b # Altivec vector bool
3018void CXXNameMangler::mangleType(const VectorType *T) {
3019 if ((T->getVectorKind() == VectorType::NeonVector ||
3020 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003021 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003022 llvm::Triple::ArchType Arch =
3023 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003024 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003025 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003026 mangleAArch64NeonVectorType(T);
3027 else
3028 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 return;
3030 }
3031 Out << "Dv" << T->getNumElements() << '_';
3032 if (T->getVectorKind() == VectorType::AltiVecPixel)
3033 Out << 'p';
3034 else if (T->getVectorKind() == VectorType::AltiVecBool)
3035 Out << 'b';
3036 else
3037 mangleType(T->getElementType());
3038}
3039void CXXNameMangler::mangleType(const ExtVectorType *T) {
3040 mangleType(static_cast<const VectorType*>(T));
3041}
3042void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3043 Out << "Dv";
3044 mangleExpression(T->getSizeExpr());
3045 Out << '_';
3046 mangleType(T->getElementType());
3047}
3048
3049void CXXNameMangler::mangleType(const PackExpansionType *T) {
3050 // <type> ::= Dp <type> # pack expansion (C++0x)
3051 Out << "Dp";
3052 mangleType(T->getPattern());
3053}
3054
3055void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3056 mangleSourceName(T->getDecl()->getIdentifier());
3057}
3058
3059void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003060 // Treat __kindof as a vendor extended type qualifier.
3061 if (T->isKindOfType())
3062 Out << "U8__kindof";
3063
Eli Friedman5f508952013-06-18 22:41:37 +00003064 if (!T->qual_empty()) {
3065 // Mangle protocol qualifiers.
3066 SmallString<64> QualStr;
3067 llvm::raw_svector_ostream QualOS(QualStr);
3068 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003069 for (const auto *I : T->quals()) {
3070 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003071 QualOS << name.size() << name;
3072 }
Eli Friedman5f508952013-06-18 22:41:37 +00003073 Out << 'U' << QualStr.size() << QualStr;
3074 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003075
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003077
3078 if (T->isSpecialized()) {
3079 // Mangle type arguments as I <type>+ E
3080 Out << 'I';
3081 for (auto typeArg : T->getTypeArgs())
3082 mangleType(typeArg);
3083 Out << 'E';
3084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003085}
3086
3087void CXXNameMangler::mangleType(const BlockPointerType *T) {
3088 Out << "U13block_pointer";
3089 mangleType(T->getPointeeType());
3090}
3091
3092void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3093 // Mangle injected class name types as if the user had written the
3094 // specialization out fully. It may not actually be possible to see
3095 // this mangling, though.
3096 mangleType(T->getInjectedSpecializationType());
3097}
3098
3099void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3100 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003101 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 } else {
3103 if (mangleSubstitution(QualType(T, 0)))
3104 return;
3105
3106 mangleTemplatePrefix(T->getTemplateName());
3107
3108 // FIXME: GCC does not appear to mangle the template arguments when
3109 // the template in question is a dependent template name. Should we
3110 // emulate that badness?
3111 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3112 addSubstitution(QualType(T, 0));
3113 }
3114}
3115
3116void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003117 // Proposal by cxx-abi-dev, 2014-03-26
3118 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3119 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003120 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003121 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003122 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003123 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003124 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003125 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003126 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003127 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003128 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003129 case ETK_Typename:
3130 break;
3131 case ETK_Struct:
3132 case ETK_Class:
3133 case ETK_Interface:
3134 Out << "Ts";
3135 break;
3136 case ETK_Union:
3137 Out << "Tu";
3138 break;
3139 case ETK_Enum:
3140 Out << "Te";
3141 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003142 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003143 // Typename types are always nested
3144 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003146 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 Out << 'E';
3148}
3149
3150void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3151 // Dependently-scoped template types are nested if they have a prefix.
3152 Out << 'N';
3153
3154 // TODO: avoid making this TemplateName.
3155 TemplateName Prefix =
3156 getASTContext().getDependentTemplateName(T->getQualifier(),
3157 T->getIdentifier());
3158 mangleTemplatePrefix(Prefix);
3159
3160 // FIXME: GCC does not appear to mangle the template arguments when
3161 // the template in question is a dependent template name. Should we
3162 // emulate that badness?
3163 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3164 Out << 'E';
3165}
3166
3167void CXXNameMangler::mangleType(const TypeOfType *T) {
3168 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3169 // "extension with parameters" mangling.
3170 Out << "u6typeof";
3171}
3172
3173void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3174 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3175 // "extension with parameters" mangling.
3176 Out << "u6typeof";
3177}
3178
3179void CXXNameMangler::mangleType(const DecltypeType *T) {
3180 Expr *E = T->getUnderlyingExpr();
3181
3182 // type ::= Dt <expression> E # decltype of an id-expression
3183 // # or class member access
3184 // ::= DT <expression> E # decltype of an expression
3185
3186 // This purports to be an exhaustive list of id-expressions and
3187 // class member accesses. Note that we do not ignore parentheses;
3188 // parentheses change the semantics of decltype for these
3189 // expressions (and cause the mangler to use the other form).
3190 if (isa<DeclRefExpr>(E) ||
3191 isa<MemberExpr>(E) ||
3192 isa<UnresolvedLookupExpr>(E) ||
3193 isa<DependentScopeDeclRefExpr>(E) ||
3194 isa<CXXDependentScopeMemberExpr>(E) ||
3195 isa<UnresolvedMemberExpr>(E))
3196 Out << "Dt";
3197 else
3198 Out << "DT";
3199 mangleExpression(E);
3200 Out << 'E';
3201}
3202
3203void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3204 // If this is dependent, we need to record that. If not, we simply
3205 // mangle it as the underlying type since they are equivalent.
3206 if (T->isDependentType()) {
3207 Out << 'U';
3208
3209 switch (T->getUTTKind()) {
3210 case UnaryTransformType::EnumUnderlyingType:
3211 Out << "3eut";
3212 break;
3213 }
3214 }
3215
David Majnemer140065a2016-06-08 00:34:15 +00003216 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003217}
3218
3219void CXXNameMangler::mangleType(const AutoType *T) {
3220 QualType D = T->getDeducedType();
3221 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00003222 if (D.isNull()) {
3223 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3224 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00003225 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00003226 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 mangleType(D);
3228}
3229
Richard Smith600b5262017-01-26 20:40:47 +00003230void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3231 // FIXME: This is not the right mangling. We also need to include a scope
3232 // here in some cases.
3233 QualType D = T->getDeducedType();
3234 if (D.isNull())
3235 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3236 else
3237 mangleType(D);
3238}
3239
Guy Benyei11169dd2012-12-18 14:30:41 +00003240void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003241 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 // (Until there's a standardized mangling...)
3243 Out << "U7_Atomic";
3244 mangleType(T->getValueType());
3245}
3246
Xiuli Pan9c14e282016-01-09 12:53:17 +00003247void CXXNameMangler::mangleType(const PipeType *T) {
3248 // Pipe type mangling rules are described in SPIR 2.0 specification
3249 // A.1 Data types and A.3 Summary of changes
3250 // <type> ::= 8ocl_pipe
3251 Out << "8ocl_pipe";
3252}
3253
Guy Benyei11169dd2012-12-18 14:30:41 +00003254void CXXNameMangler::mangleIntegerLiteral(QualType T,
3255 const llvm::APSInt &Value) {
3256 // <expr-primary> ::= L <type> <value number> E # integer literal
3257 Out << 'L';
3258
3259 mangleType(T);
3260 if (T->isBooleanType()) {
3261 // Boolean values are encoded as 0/1.
3262 Out << (Value.getBoolValue() ? '1' : '0');
3263 } else {
3264 mangleNumber(Value);
3265 }
3266 Out << 'E';
3267
3268}
3269
David Majnemer1dabfdc2015-02-14 13:23:54 +00003270void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3271 // Ignore member expressions involving anonymous unions.
3272 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3273 if (!RT->getDecl()->isAnonymousStructOrUnion())
3274 break;
3275 const auto *ME = dyn_cast<MemberExpr>(Base);
3276 if (!ME)
3277 break;
3278 Base = ME->getBase();
3279 IsArrow = ME->isArrow();
3280 }
3281
3282 if (Base->isImplicitCXXThis()) {
3283 // Note: GCC mangles member expressions to the implicit 'this' as
3284 // *this., whereas we represent them as this->. The Itanium C++ ABI
3285 // does not specify anything here, so we follow GCC.
3286 Out << "dtdefpT";
3287 } else {
3288 Out << (IsArrow ? "pt" : "dt");
3289 mangleExpression(Base);
3290 }
3291}
3292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293/// Mangles a member expression.
3294void CXXNameMangler::mangleMemberExpr(const Expr *base,
3295 bool isArrow,
3296 NestedNameSpecifier *qualifier,
3297 NamedDecl *firstQualifierLookup,
3298 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003299 const TemplateArgumentLoc *TemplateArgs,
3300 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 unsigned arity) {
3302 // <expression> ::= dt <expression> <unresolved-name>
3303 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003304 if (base)
3305 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003306 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003307}
3308
3309/// Look at the callee of the given call expression and determine if
3310/// it's a parenthesized id-expression which would have triggered ADL
3311/// otherwise.
3312static bool isParenthesizedADLCallee(const CallExpr *call) {
3313 const Expr *callee = call->getCallee();
3314 const Expr *fn = callee->IgnoreParens();
3315
3316 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3317 // too, but for those to appear in the callee, it would have to be
3318 // parenthesized.
3319 if (callee == fn) return false;
3320
3321 // Must be an unresolved lookup.
3322 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3323 if (!lookup) return false;
3324
3325 assert(!lookup->requiresADL());
3326
3327 // Must be an unqualified lookup.
3328 if (lookup->getQualifier()) return false;
3329
3330 // Must not have found a class member. Note that if one is a class
3331 // member, they're all class members.
3332 if (lookup->getNumDecls() > 0 &&
3333 (*lookup->decls_begin())->isCXXClassMember())
3334 return false;
3335
3336 // Otherwise, ADL would have been triggered.
3337 return true;
3338}
3339
David Majnemer9c775c72014-09-23 04:27:55 +00003340void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3341 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3342 Out << CastEncoding;
3343 mangleType(ECE->getType());
3344 mangleExpression(ECE->getSubExpr());
3345}
3346
Richard Smith520449d2015-02-05 06:15:50 +00003347void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3348 if (auto *Syntactic = InitList->getSyntacticForm())
3349 InitList = Syntactic;
3350 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3351 mangleExpression(InitList->getInit(i));
3352}
3353
Guy Benyei11169dd2012-12-18 14:30:41 +00003354void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3355 // <expression> ::= <unary operator-name> <expression>
3356 // ::= <binary operator-name> <expression> <expression>
3357 // ::= <trinary operator-name> <expression> <expression> <expression>
3358 // ::= cv <type> expression # conversion with one argument
3359 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003360 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3361 // ::= sc <type> <expression> # static_cast<type> (expression)
3362 // ::= cc <type> <expression> # const_cast<type> (expression)
3363 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 // ::= st <type> # sizeof (a type)
3365 // ::= at <type> # alignof (a type)
3366 // ::= <template-param>
3367 // ::= <function-param>
3368 // ::= sr <type> <unqualified-name> # dependent name
3369 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3370 // ::= ds <expression> <expression> # expr.*expr
3371 // ::= sZ <template-param> # size of a parameter pack
3372 // ::= sZ <function-param> # size of a function parameter pack
3373 // ::= <expr-primary>
3374 // <expr-primary> ::= L <type> <value number> E # integer literal
3375 // ::= L <type <value float> E # floating literal
3376 // ::= L <mangled-name> E # external name
3377 // ::= fpT # 'this' expression
3378 QualType ImplicitlyConvertedToType;
3379
3380recurse:
3381 switch (E->getStmtClass()) {
3382 case Expr::NoStmtClass:
3383#define ABSTRACT_STMT(Type)
3384#define EXPR(Type, Base)
3385#define STMT(Type, Base) \
3386 case Expr::Type##Class:
3387#include "clang/AST/StmtNodes.inc"
3388 // fallthrough
3389
3390 // These all can only appear in local or variable-initialization
3391 // contexts and so should never appear in a mangling.
3392 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003393 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003395 case Expr::ArrayInitLoopExprClass:
3396 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003397 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 case Expr::ParenListExprClass:
3399 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003400 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003401 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003402 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003403 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003404 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 llvm_unreachable("unexpected statement kind");
3406
3407 // FIXME: invent manglings for all these.
3408 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 case Expr::ChooseExprClass:
3410 case Expr::CompoundLiteralExprClass:
3411 case Expr::ExtVectorElementExprClass:
3412 case Expr::GenericSelectionExprClass:
3413 case Expr::ObjCEncodeExprClass:
3414 case Expr::ObjCIsaExprClass:
3415 case Expr::ObjCIvarRefExprClass:
3416 case Expr::ObjCMessageExprClass:
3417 case Expr::ObjCPropertyRefExprClass:
3418 case Expr::ObjCProtocolExprClass:
3419 case Expr::ObjCSelectorExprClass:
3420 case Expr::ObjCStringLiteralClass:
3421 case Expr::ObjCBoxedExprClass:
3422 case Expr::ObjCArrayLiteralClass:
3423 case Expr::ObjCDictionaryLiteralClass:
3424 case Expr::ObjCSubscriptRefExprClass:
3425 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003426 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 case Expr::OffsetOfExprClass:
3428 case Expr::PredefinedExprClass:
3429 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003430 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 case Expr::TypeTraitExprClass:
3433 case Expr::ArrayTypeTraitExprClass:
3434 case Expr::ExpressionTraitExprClass:
3435 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 case Expr::CUDAKernelCallExprClass:
3437 case Expr::AsTypeExprClass:
3438 case Expr::PseudoObjectExprClass:
3439 case Expr::AtomicExprClass:
3440 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003441 if (!NullOut) {
3442 // As bad as this diagnostic is, it's better than crashing.
3443 DiagnosticsEngine &Diags = Context.getDiags();
3444 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3445 "cannot yet mangle expression type %0");
3446 Diags.Report(E->getExprLoc(), DiagID)
3447 << E->getStmtClassName() << E->getSourceRange();
3448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 break;
3450 }
3451
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003452 case Expr::CXXUuidofExprClass: {
3453 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3454 if (UE->isTypeOperand()) {
3455 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3456 Out << "u8__uuidoft";
3457 mangleType(UuidT);
3458 } else {
3459 Expr *UuidExp = UE->getExprOperand();
3460 Out << "u8__uuidofz";
3461 mangleExpression(UuidExp, Arity);
3462 }
3463 break;
3464 }
3465
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 // Even gcc-4.5 doesn't mangle this.
3467 case Expr::BinaryConditionalOperatorClass: {
3468 DiagnosticsEngine &Diags = Context.getDiags();
3469 unsigned DiagID =
3470 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3471 "?: operator with omitted middle operand cannot be mangled");
3472 Diags.Report(E->getExprLoc(), DiagID)
3473 << E->getStmtClassName() << E->getSourceRange();
3474 break;
3475 }
3476
3477 // These are used for internal purposes and cannot be meaningfully mangled.
3478 case Expr::OpaqueValueExprClass:
3479 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3480
3481 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003483 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 Out << "E";
3485 break;
3486 }
3487
Richard Smith39eca9b2017-08-23 22:12:08 +00003488 case Expr::DesignatedInitExprClass: {
3489 auto *DIE = cast<DesignatedInitExpr>(E);
3490 for (const auto &Designator : DIE->designators()) {
3491 if (Designator.isFieldDesignator()) {
3492 Out << "di";
3493 mangleSourceName(Designator.getFieldName());
3494 } else if (Designator.isArrayDesignator()) {
3495 Out << "dx";
3496 mangleExpression(DIE->getArrayIndex(Designator));
3497 } else {
3498 assert(Designator.isArrayRangeDesignator() &&
3499 "unknown designator kind");
3500 Out << "dX";
3501 mangleExpression(DIE->getArrayRangeStart(Designator));
3502 mangleExpression(DIE->getArrayRangeEnd(Designator));
3503 }
3504 }
3505 mangleExpression(DIE->getInit());
3506 break;
3507 }
3508
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 case Expr::CXXDefaultArgExprClass:
3510 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3511 break;
3512
Richard Smith852c9db2013-04-20 22:23:05 +00003513 case Expr::CXXDefaultInitExprClass:
3514 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3515 break;
3516
Richard Smithcc1b96d2013-06-12 22:31:48 +00003517 case Expr::CXXStdInitializerListExprClass:
3518 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3519 break;
3520
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 case Expr::SubstNonTypeTemplateParmExprClass:
3522 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3523 Arity);
3524 break;
3525
3526 case Expr::UserDefinedLiteralClass:
3527 // We follow g++'s approach of mangling a UDL as a call to the literal
3528 // operator.
3529 case Expr::CXXMemberCallExprClass: // fallthrough
3530 case Expr::CallExprClass: {
3531 const CallExpr *CE = cast<CallExpr>(E);
3532
3533 // <expression> ::= cp <simple-id> <expression>* E
3534 // We use this mangling only when the call would use ADL except
3535 // for being parenthesized. Per discussion with David
3536 // Vandervoorde, 2011.04.25.
3537 if (isParenthesizedADLCallee(CE)) {
3538 Out << "cp";
3539 // The callee here is a parenthesized UnresolvedLookupExpr with
3540 // no qualifier and should always get mangled as a <simple-id>
3541 // anyway.
3542
3543 // <expression> ::= cl <expression>* E
3544 } else {
3545 Out << "cl";
3546 }
3547
David Majnemer67a8ec62015-02-19 21:41:48 +00003548 unsigned CallArity = CE->getNumArgs();
3549 for (const Expr *Arg : CE->arguments())
3550 if (isa<PackExpansionExpr>(Arg))
3551 CallArity = UnknownArity;
3552
3553 mangleExpression(CE->getCallee(), CallArity);
3554 for (const Expr *Arg : CE->arguments())
3555 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 Out << 'E';
3557 break;
3558 }
3559
3560 case Expr::CXXNewExprClass: {
3561 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3562 if (New->isGlobalNew()) Out << "gs";
3563 Out << (New->isArray() ? "na" : "nw");
3564 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3565 E = New->placement_arg_end(); I != E; ++I)
3566 mangleExpression(*I);
3567 Out << '_';
3568 mangleType(New->getAllocatedType());
3569 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003570 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3571 Out << "il";
3572 else
3573 Out << "pi";
3574 const Expr *Init = New->getInitializer();
3575 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3576 // Directly inline the initializers.
3577 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3578 E = CCE->arg_end();
3579 I != E; ++I)
3580 mangleExpression(*I);
3581 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3582 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3583 mangleExpression(PLE->getExpr(i));
3584 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3585 isa<InitListExpr>(Init)) {
3586 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003587 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 } else
3589 mangleExpression(Init);
3590 }
3591 Out << 'E';
3592 break;
3593 }
3594
David Majnemer1dabfdc2015-02-14 13:23:54 +00003595 case Expr::CXXPseudoDestructorExprClass: {
3596 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3597 if (const Expr *Base = PDE->getBase())
3598 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003599 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3600 QualType ScopeType;
3601 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3602 if (Qualifier) {
3603 mangleUnresolvedPrefix(Qualifier,
3604 /*Recursive=*/true);
3605 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3606 Out << 'E';
3607 } else {
3608 Out << "sr";
3609 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3610 Out << 'E';
3611 }
3612 } else if (Qualifier) {
3613 mangleUnresolvedPrefix(Qualifier);
3614 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003615 // <base-unresolved-name> ::= dn <destructor-name>
3616 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003617 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003618 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003619 break;
3620 }
3621
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 case Expr::MemberExprClass: {
3623 const MemberExpr *ME = cast<MemberExpr>(E);
3624 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003625 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003626 ME->getMemberDecl()->getDeclName(),
3627 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3628 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 break;
3630 }
3631
3632 case Expr::UnresolvedMemberExprClass: {
3633 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003634 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3635 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003636 ME->getMemberName(),
3637 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3638 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 break;
3640 }
3641
3642 case Expr::CXXDependentScopeMemberExprClass: {
3643 const CXXDependentScopeMemberExpr *ME
3644 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003645 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3646 ME->isArrow(), ME->getQualifier(),
3647 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003648 ME->getMember(),
3649 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3650 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 break;
3652 }
3653
3654 case Expr::UnresolvedLookupExprClass: {
3655 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003656 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3657 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3658 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 break;
3660 }
3661
3662 case Expr::CXXUnresolvedConstructExprClass: {
3663 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3664 unsigned N = CE->arg_size();
3665
Richard Smith39eca9b2017-08-23 22:12:08 +00003666 if (CE->isListInitialization()) {
3667 assert(N == 1 && "unexpected form for list initialization");
3668 auto *IL = cast<InitListExpr>(CE->getArg(0));
3669 Out << "tl";
3670 mangleType(CE->getType());
3671 mangleInitListElements(IL);
3672 Out << "E";
3673 return;
3674 }
3675
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 Out << "cv";
3677 mangleType(CE->getType());
3678 if (N != 1) Out << '_';
3679 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3680 if (N != 1) Out << 'E';
3681 break;
3682 }
3683
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003685 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003686 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003687 assert(
3688 CE->getNumArgs() >= 1 &&
3689 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3690 "implicit CXXConstructExpr must have one argument");
3691 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3692 }
3693 Out << "il";
3694 for (auto *E : CE->arguments())
3695 mangleExpression(E);
3696 Out << "E";
3697 break;
3698 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003699
Richard Smith520449d2015-02-05 06:15:50 +00003700 case Expr::CXXTemporaryObjectExprClass: {
3701 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3702 unsigned N = CE->getNumArgs();
3703 bool List = CE->isListInitialization();
3704
3705 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 Out << "tl";
3707 else
3708 Out << "cv";
3709 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003710 if (!List && N != 1)
3711 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003712 if (CE->isStdInitListInitialization()) {
3713 // We implicitly created a std::initializer_list<T> for the first argument
3714 // of a constructor of type U in an expression of the form U{a, b, c}.
3715 // Strip all the semantic gunk off the initializer list.
3716 auto *SILE =
3717 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3718 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3719 mangleInitListElements(ILE);
3720 } else {
3721 for (auto *E : CE->arguments())
3722 mangleExpression(E);
3723 }
Richard Smith520449d2015-02-05 06:15:50 +00003724 if (List || N != 1)
3725 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 break;
3727 }
3728
3729 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003730 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003732 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 break;
3734
3735 case Expr::CXXNoexceptExprClass:
3736 Out << "nx";
3737 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3738 break;
3739
3740 case Expr::UnaryExprOrTypeTraitExprClass: {
3741 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3742
3743 if (!SAE->isInstantiationDependent()) {
3744 // Itanium C++ ABI:
3745 // If the operand of a sizeof or alignof operator is not
3746 // instantiation-dependent it is encoded as an integer literal
3747 // reflecting the result of the operator.
3748 //
3749 // If the result of the operator is implicitly converted to a known
3750 // integer type, that type is used for the literal; otherwise, the type
3751 // of std::size_t or std::ptrdiff_t is used.
3752 QualType T = (ImplicitlyConvertedToType.isNull() ||
3753 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3754 : ImplicitlyConvertedToType;
3755 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3756 mangleIntegerLiteral(T, V);
3757 break;
3758 }
3759
3760 switch(SAE->getKind()) {
3761 case UETT_SizeOf:
3762 Out << 's';
3763 break;
3764 case UETT_AlignOf:
3765 Out << 'a';
3766 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003767 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 DiagnosticsEngine &Diags = Context.getDiags();
3769 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3770 "cannot yet mangle vec_step expression");
3771 Diags.Report(DiagID);
3772 return;
3773 }
Alexey Bataev00396512015-07-02 03:40:19 +00003774 case UETT_OpenMPRequiredSimdAlign:
3775 DiagnosticsEngine &Diags = Context.getDiags();
3776 unsigned DiagID = Diags.getCustomDiagID(
3777 DiagnosticsEngine::Error,
3778 "cannot yet mangle __builtin_omp_required_simd_align expression");
3779 Diags.Report(DiagID);
3780 return;
3781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 if (SAE->isArgumentType()) {
3783 Out << 't';
3784 mangleType(SAE->getArgumentType());
3785 } else {
3786 Out << 'z';
3787 mangleExpression(SAE->getArgumentExpr());
3788 }
3789 break;
3790 }
3791
3792 case Expr::CXXThrowExprClass: {
3793 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003794 // <expression> ::= tw <expression> # throw expression
3795 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003796 if (TE->getSubExpr()) {
3797 Out << "tw";
3798 mangleExpression(TE->getSubExpr());
3799 } else {
3800 Out << "tr";
3801 }
3802 break;
3803 }
3804
3805 case Expr::CXXTypeidExprClass: {
3806 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003807 // <expression> ::= ti <type> # typeid (type)
3808 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 if (TIE->isTypeOperand()) {
3810 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003811 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 } else {
3813 Out << "te";
3814 mangleExpression(TIE->getExprOperand());
3815 }
3816 break;
3817 }
3818
3819 case Expr::CXXDeleteExprClass: {
3820 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003821 // <expression> ::= [gs] dl <expression> # [::] delete expr
3822 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003823 if (DE->isGlobalDelete()) Out << "gs";
3824 Out << (DE->isArrayForm() ? "da" : "dl");
3825 mangleExpression(DE->getArgument());
3826 break;
3827 }
3828
3829 case Expr::UnaryOperatorClass: {
3830 const UnaryOperator *UO = cast<UnaryOperator>(E);
3831 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3832 /*Arity=*/1);
3833 mangleExpression(UO->getSubExpr());
3834 break;
3835 }
3836
3837 case Expr::ArraySubscriptExprClass: {
3838 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3839
3840 // Array subscript is treated as a syntactically weird form of
3841 // binary operator.
3842 Out << "ix";
3843 mangleExpression(AE->getLHS());
3844 mangleExpression(AE->getRHS());
3845 break;
3846 }
3847
3848 case Expr::CompoundAssignOperatorClass: // fallthrough
3849 case Expr::BinaryOperatorClass: {
3850 const BinaryOperator *BO = cast<BinaryOperator>(E);
3851 if (BO->getOpcode() == BO_PtrMemD)
3852 Out << "ds";
3853 else
3854 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3855 /*Arity=*/2);
3856 mangleExpression(BO->getLHS());
3857 mangleExpression(BO->getRHS());
3858 break;
3859 }
3860
3861 case Expr::ConditionalOperatorClass: {
3862 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3863 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3864 mangleExpression(CO->getCond());
3865 mangleExpression(CO->getLHS(), Arity);
3866 mangleExpression(CO->getRHS(), Arity);
3867 break;
3868 }
3869
3870 case Expr::ImplicitCastExprClass: {
3871 ImplicitlyConvertedToType = E->getType();
3872 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3873 goto recurse;
3874 }
3875
3876 case Expr::ObjCBridgedCastExprClass: {
3877 // Mangle ownership casts as a vendor extended operator __bridge,
3878 // __bridge_transfer, or __bridge_retain.
3879 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3880 Out << "v1U" << Kind.size() << Kind;
3881 }
3882 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00003883 LLVM_FALLTHROUGH;
Guy Benyei11169dd2012-12-18 14:30:41 +00003884
3885 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003886 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003888
Richard Smith520449d2015-02-05 06:15:50 +00003889 case Expr::CXXFunctionalCastExprClass: {
3890 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3891 // FIXME: Add isImplicit to CXXConstructExpr.
3892 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3893 if (CCE->getParenOrBraceRange().isInvalid())
3894 Sub = CCE->getArg(0)->IgnoreImplicit();
3895 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3896 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3897 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3898 Out << "tl";
3899 mangleType(E->getType());
3900 mangleInitListElements(IL);
3901 Out << "E";
3902 } else {
3903 mangleCastExpression(E, "cv");
3904 }
3905 break;
3906 }
3907
David Majnemer9c775c72014-09-23 04:27:55 +00003908 case Expr::CXXStaticCastExprClass:
3909 mangleCastExpression(E, "sc");
3910 break;
3911 case Expr::CXXDynamicCastExprClass:
3912 mangleCastExpression(E, "dc");
3913 break;
3914 case Expr::CXXReinterpretCastExprClass:
3915 mangleCastExpression(E, "rc");
3916 break;
3917 case Expr::CXXConstCastExprClass:
3918 mangleCastExpression(E, "cc");
3919 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003920
3921 case Expr::CXXOperatorCallExprClass: {
3922 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3923 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00003924 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
3925 // (the enclosing MemberExpr covers the syntactic portion).
3926 if (CE->getOperator() != OO_Arrow)
3927 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 // Mangle the arguments.
3929 for (unsigned i = 0; i != NumArgs; ++i)
3930 mangleExpression(CE->getArg(i));
3931 break;
3932 }
3933
3934 case Expr::ParenExprClass:
3935 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3936 break;
3937
3938 case Expr::DeclRefExprClass: {
3939 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3940
3941 switch (D->getKind()) {
3942 default:
3943 // <expr-primary> ::= L <mangled-name> E # external name
3944 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003945 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 Out << 'E';
3947 break;
3948
3949 case Decl::ParmVar:
3950 mangleFunctionParam(cast<ParmVarDecl>(D));
3951 break;
3952
3953 case Decl::EnumConstant: {
3954 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3955 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3956 break;
3957 }
3958
3959 case Decl::NonTypeTemplateParm: {
3960 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3961 mangleTemplateParameter(PD->getIndex());
3962 break;
3963 }
3964
3965 }
3966
3967 break;
3968 }
3969
3970 case Expr::SubstNonTypeTemplateParmPackExprClass:
3971 // FIXME: not clear how to mangle this!
3972 // template <unsigned N...> class A {
3973 // template <class U...> void foo(U (&x)[N]...);
3974 // };
3975 Out << "_SUBSTPACK_";
3976 break;
3977
3978 case Expr::FunctionParmPackExprClass: {
3979 // FIXME: not clear how to mangle this!
3980 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3981 Out << "v110_SUBSTPACK";
3982 mangleFunctionParam(FPPE->getParameterPack());
3983 break;
3984 }
3985
3986 case Expr::DependentScopeDeclRefExprClass: {
3987 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003988 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
3989 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
3990 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 break;
3992 }
3993
3994 case Expr::CXXBindTemporaryExprClass:
3995 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3996 break;
3997
3998 case Expr::ExprWithCleanupsClass:
3999 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4000 break;
4001
4002 case Expr::FloatingLiteralClass: {
4003 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4004 Out << 'L';
4005 mangleType(FL->getType());
4006 mangleFloat(FL->getValue());
4007 Out << 'E';
4008 break;
4009 }
4010
4011 case Expr::CharacterLiteralClass:
4012 Out << 'L';
4013 mangleType(E->getType());
4014 Out << cast<CharacterLiteral>(E)->getValue();
4015 Out << 'E';
4016 break;
4017
4018 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4019 case Expr::ObjCBoolLiteralExprClass:
4020 Out << "Lb";
4021 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4022 Out << 'E';
4023 break;
4024
4025 case Expr::CXXBoolLiteralExprClass:
4026 Out << "Lb";
4027 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4028 Out << 'E';
4029 break;
4030
4031 case Expr::IntegerLiteralClass: {
4032 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4033 if (E->getType()->isSignedIntegerType())
4034 Value.setIsSigned(true);
4035 mangleIntegerLiteral(E->getType(), Value);
4036 break;
4037 }
4038
4039 case Expr::ImaginaryLiteralClass: {
4040 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4041 // Mangle as if a complex literal.
4042 // Proposal from David Vandevoorde, 2010.06.30.
4043 Out << 'L';
4044 mangleType(E->getType());
4045 if (const FloatingLiteral *Imag =
4046 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4047 // Mangle a floating-point zero of the appropriate type.
4048 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4049 Out << '_';
4050 mangleFloat(Imag->getValue());
4051 } else {
4052 Out << "0_";
4053 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4054 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4055 Value.setIsSigned(true);
4056 mangleNumber(Value);
4057 }
4058 Out << 'E';
4059 break;
4060 }
4061
4062 case Expr::StringLiteralClass: {
4063 // Revised proposal from David Vandervoorde, 2010.07.15.
4064 Out << 'L';
4065 assert(isa<ConstantArrayType>(E->getType()));
4066 mangleType(E->getType());
4067 Out << 'E';
4068 break;
4069 }
4070
4071 case Expr::GNUNullExprClass:
4072 // FIXME: should this really be mangled the same as nullptr?
4073 // fallthrough
4074
4075 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 Out << "LDnE";
4077 break;
4078 }
4079
4080 case Expr::PackExpansionExprClass:
4081 Out << "sp";
4082 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4083 break;
4084
4085 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004086 auto *SPE = cast<SizeOfPackExpr>(E);
4087 if (SPE->isPartiallySubstituted()) {
4088 Out << "sP";
4089 for (const auto &A : SPE->getPartialArguments())
4090 mangleTemplateArg(A);
4091 Out << "E";
4092 break;
4093 }
4094
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004096 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4098 mangleTemplateParameter(TTP->getIndex());
4099 else if (const NonTypeTemplateParmDecl *NTTP
4100 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4101 mangleTemplateParameter(NTTP->getIndex());
4102 else if (const TemplateTemplateParmDecl *TempTP
4103 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4104 mangleTemplateParameter(TempTP->getIndex());
4105 else
4106 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4107 break;
4108 }
Richard Smith0f0af192014-11-08 05:07:16 +00004109
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 case Expr::MaterializeTemporaryExprClass: {
4111 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4112 break;
4113 }
Richard Smith0f0af192014-11-08 05:07:16 +00004114
4115 case Expr::CXXFoldExprClass: {
4116 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004117 if (FE->isLeftFold())
4118 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004119 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004120 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004121
4122 if (FE->getOperator() == BO_PtrMemD)
4123 Out << "ds";
4124 else
4125 mangleOperatorName(
4126 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4127 /*Arity=*/2);
4128
4129 if (FE->getLHS())
4130 mangleExpression(FE->getLHS());
4131 if (FE->getRHS())
4132 mangleExpression(FE->getRHS());
4133 break;
4134 }
4135
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 case Expr::CXXThisExprClass:
4137 Out << "fpT";
4138 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004139
4140 case Expr::CoawaitExprClass:
4141 // FIXME: Propose a non-vendor mangling.
4142 Out << "v18co_await";
4143 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4144 break;
4145
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004146 case Expr::DependentCoawaitExprClass:
4147 // FIXME: Propose a non-vendor mangling.
4148 Out << "v18co_await";
4149 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4150 break;
4151
Richard Smith9f690bd2015-10-27 06:02:45 +00004152 case Expr::CoyieldExprClass:
4153 // FIXME: Propose a non-vendor mangling.
4154 Out << "v18co_yield";
4155 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
4158}
4159
4160/// Mangle an expression which refers to a parameter variable.
4161///
4162/// <expression> ::= <function-param>
4163/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4164/// <function-param> ::= fp <top-level CV-qualifiers>
4165/// <parameter-2 non-negative number> _ # L == 0, I > 0
4166/// <function-param> ::= fL <L-1 non-negative number>
4167/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4168/// <function-param> ::= fL <L-1 non-negative number>
4169/// p <top-level CV-qualifiers>
4170/// <I-1 non-negative number> _ # L > 0, I > 0
4171///
4172/// L is the nesting depth of the parameter, defined as 1 if the
4173/// parameter comes from the innermost function prototype scope
4174/// enclosing the current context, 2 if from the next enclosing
4175/// function prototype scope, and so on, with one special case: if
4176/// we've processed the full parameter clause for the innermost
4177/// function type, then L is one less. This definition conveniently
4178/// makes it irrelevant whether a function's result type was written
4179/// trailing or leading, but is otherwise overly complicated; the
4180/// numbering was first designed without considering references to
4181/// parameter in locations other than return types, and then the
4182/// mangling had to be generalized without changing the existing
4183/// manglings.
4184///
4185/// I is the zero-based index of the parameter within its parameter
4186/// declaration clause. Note that the original ABI document describes
4187/// this using 1-based ordinals.
4188void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4189 unsigned parmDepth = parm->getFunctionScopeDepth();
4190 unsigned parmIndex = parm->getFunctionScopeIndex();
4191
4192 // Compute 'L'.
4193 // parmDepth does not include the declaring function prototype.
4194 // FunctionTypeDepth does account for that.
4195 assert(parmDepth < FunctionTypeDepth.getDepth());
4196 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4197 if (FunctionTypeDepth.isInResultType())
4198 nestingDepth--;
4199
4200 if (nestingDepth == 0) {
4201 Out << "fp";
4202 } else {
4203 Out << "fL" << (nestingDepth - 1) << 'p';
4204 }
4205
4206 // Top-level qualifiers. We don't have to worry about arrays here,
4207 // because parameters declared as arrays should already have been
4208 // transformed to have pointer type. FIXME: apparently these don't
4209 // get mangled if used as an rvalue of a known non-class type?
4210 assert(!parm->getType()->isArrayType()
4211 && "parameter's type is still an array type?");
4212 mangleQualifiers(parm->getType().getQualifiers());
4213
4214 // Parameter index.
4215 if (parmIndex != 0) {
4216 Out << (parmIndex - 1);
4217 }
4218 Out << '_';
4219}
4220
Richard Smith5179eb72016-06-28 19:03:57 +00004221void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4222 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 // <ctor-dtor-name> ::= C1 # complete object constructor
4224 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004225 // ::= CI1 <type> # complete inheriting constructor
4226 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004228 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004229 Out << 'C';
4230 if (InheritedFrom)
4231 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 switch (T) {
4233 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004234 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 break;
4236 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004237 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004239 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004240 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004242 case Ctor_DefaultClosure:
4243 case Ctor_CopyingClosure:
4244 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 }
Richard Smith5179eb72016-06-28 19:03:57 +00004246 if (InheritedFrom)
4247 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004248}
4249
4250void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4251 // <ctor-dtor-name> ::= D0 # deleting destructor
4252 // ::= D1 # complete object destructor
4253 // ::= D2 # base object destructor
4254 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004255 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 switch (T) {
4257 case Dtor_Deleting:
4258 Out << "D0";
4259 break;
4260 case Dtor_Complete:
4261 Out << "D1";
4262 break;
4263 case Dtor_Base:
4264 Out << "D2";
4265 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004266 case Dtor_Comdat:
4267 Out << "D5";
4268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 }
4270}
4271
James Y Knight04ec5bf2015-12-24 02:59:37 +00004272void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4273 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 // <template-args> ::= I <template-arg>+ E
4275 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004276 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4277 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 Out << 'E';
4279}
4280
4281void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4282 // <template-args> ::= I <template-arg>+ E
4283 Out << 'I';
4284 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4285 mangleTemplateArg(AL[i]);
4286 Out << 'E';
4287}
4288
4289void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4290 unsigned NumTemplateArgs) {
4291 // <template-args> ::= I <template-arg>+ E
4292 Out << 'I';
4293 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4294 mangleTemplateArg(TemplateArgs[i]);
4295 Out << 'E';
4296}
4297
4298void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4299 // <template-arg> ::= <type> # type or template
4300 // ::= X <expression> E # expression
4301 // ::= <expr-primary> # simple expressions
4302 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 if (!A.isInstantiationDependent() || A.isDependent())
4304 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4305
4306 switch (A.getKind()) {
4307 case TemplateArgument::Null:
4308 llvm_unreachable("Cannot mangle NULL template argument");
4309
4310 case TemplateArgument::Type:
4311 mangleType(A.getAsType());
4312 break;
4313 case TemplateArgument::Template:
4314 // This is mangled as <type>.
4315 mangleType(A.getAsTemplate());
4316 break;
4317 case TemplateArgument::TemplateExpansion:
4318 // <type> ::= Dp <type> # pack expansion (C++0x)
4319 Out << "Dp";
4320 mangleType(A.getAsTemplateOrTemplatePattern());
4321 break;
4322 case TemplateArgument::Expression: {
4323 // It's possible to end up with a DeclRefExpr here in certain
4324 // dependent cases, in which case we should mangle as a
4325 // declaration.
4326 const Expr *E = A.getAsExpr()->IgnoreParens();
4327 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4328 const ValueDecl *D = DRE->getDecl();
4329 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004330 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004331 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 Out << 'E';
4333 break;
4334 }
4335 }
4336
4337 Out << 'X';
4338 mangleExpression(E);
4339 Out << 'E';
4340 break;
4341 }
4342 case TemplateArgument::Integral:
4343 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4344 break;
4345 case TemplateArgument::Declaration: {
4346 // <expr-primary> ::= L <mangled-name> E # external name
4347 // Clang produces AST's where pointer-to-member-function expressions
4348 // and pointer-to-function expressions are represented as a declaration not
4349 // an expression. We compensate for it here to produce the correct mangling.
4350 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004351 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 if (compensateMangling) {
4353 Out << 'X';
4354 mangleOperatorName(OO_Amp, 1);
4355 }
4356
4357 Out << 'L';
4358 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004359 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004360 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 Out << 'E';
4362
4363 if (compensateMangling)
4364 Out << 'E';
4365
4366 break;
4367 }
4368 case TemplateArgument::NullPtr: {
4369 // <expr-primary> ::= L <type> 0 E
4370 Out << 'L';
4371 mangleType(A.getNullPtrType());
4372 Out << "0E";
4373 break;
4374 }
4375 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004376 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004378 for (const auto &P : A.pack_elements())
4379 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 Out << 'E';
4381 }
4382 }
4383}
4384
4385void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4386 // <template-param> ::= T_ # first template parameter
4387 // ::= T <parameter-2 non-negative number> _
4388 if (Index == 0)
4389 Out << "T_";
4390 else
4391 Out << 'T' << (Index - 1) << '_';
4392}
4393
David Majnemer3b3bdb52014-05-06 22:49:16 +00004394void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4395 if (SeqID == 1)
4396 Out << '0';
4397 else if (SeqID > 1) {
4398 SeqID--;
4399
4400 // <seq-id> is encoded in base-36, using digits and upper case letters.
4401 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004402 MutableArrayRef<char> BufferRef(Buffer);
4403 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004404
4405 for (; SeqID != 0; SeqID /= 36) {
4406 unsigned C = SeqID % 36;
4407 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4408 }
4409
4410 Out.write(I.base(), I - BufferRef.rbegin());
4411 }
4412 Out << '_';
4413}
4414
Guy Benyei11169dd2012-12-18 14:30:41 +00004415void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4416 bool result = mangleSubstitution(tname);
4417 assert(result && "no existing substitution for template name");
4418 (void) result;
4419}
4420
4421// <substitution> ::= S <seq-id> _
4422// ::= S_
4423bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4424 // Try one of the standard substitutions first.
4425 if (mangleStandardSubstitution(ND))
4426 return true;
4427
4428 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4429 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4430}
4431
Justin Bognere8d762e2015-05-22 06:48:13 +00004432/// Determine whether the given type has any qualifiers that are relevant for
4433/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004434static bool hasMangledSubstitutionQualifiers(QualType T) {
4435 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004436 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004437}
4438
4439bool CXXNameMangler::mangleSubstitution(QualType T) {
4440 if (!hasMangledSubstitutionQualifiers(T)) {
4441 if (const RecordType *RT = T->getAs<RecordType>())
4442 return mangleSubstitution(RT->getDecl());
4443 }
4444
4445 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4446
4447 return mangleSubstitution(TypePtr);
4448}
4449
4450bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4451 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4452 return mangleSubstitution(TD);
4453
4454 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4455 return mangleSubstitution(
4456 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4457}
4458
4459bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4460 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4461 if (I == Substitutions.end())
4462 return false;
4463
4464 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004465 Out << 'S';
4466 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004467
4468 return true;
4469}
4470
4471static bool isCharType(QualType T) {
4472 if (T.isNull())
4473 return false;
4474
4475 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4476 T->isSpecificBuiltinType(BuiltinType::Char_U);
4477}
4478
Justin Bognere8d762e2015-05-22 06:48:13 +00004479/// Returns whether a given type is a template specialization of a given name
4480/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004481static bool isCharSpecialization(QualType T, const char *Name) {
4482 if (T.isNull())
4483 return false;
4484
4485 const RecordType *RT = T->getAs<RecordType>();
4486 if (!RT)
4487 return false;
4488
4489 const ClassTemplateSpecializationDecl *SD =
4490 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4491 if (!SD)
4492 return false;
4493
4494 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4495 return false;
4496
4497 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4498 if (TemplateArgs.size() != 1)
4499 return false;
4500
4501 if (!isCharType(TemplateArgs[0].getAsType()))
4502 return false;
4503
4504 return SD->getIdentifier()->getName() == Name;
4505}
4506
4507template <std::size_t StrLen>
4508static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4509 const char (&Str)[StrLen]) {
4510 if (!SD->getIdentifier()->isStr(Str))
4511 return false;
4512
4513 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4514 if (TemplateArgs.size() != 2)
4515 return false;
4516
4517 if (!isCharType(TemplateArgs[0].getAsType()))
4518 return false;
4519
4520 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4521 return false;
4522
4523 return true;
4524}
4525
4526bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4527 // <substitution> ::= St # ::std::
4528 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4529 if (isStd(NS)) {
4530 Out << "St";
4531 return true;
4532 }
4533 }
4534
4535 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4536 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4537 return false;
4538
4539 // <substitution> ::= Sa # ::std::allocator
4540 if (TD->getIdentifier()->isStr("allocator")) {
4541 Out << "Sa";
4542 return true;
4543 }
4544
4545 // <<substitution> ::= Sb # ::std::basic_string
4546 if (TD->getIdentifier()->isStr("basic_string")) {
4547 Out << "Sb";
4548 return true;
4549 }
4550 }
4551
4552 if (const ClassTemplateSpecializationDecl *SD =
4553 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4554 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4555 return false;
4556
4557 // <substitution> ::= Ss # ::std::basic_string<char,
4558 // ::std::char_traits<char>,
4559 // ::std::allocator<char> >
4560 if (SD->getIdentifier()->isStr("basic_string")) {
4561 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4562
4563 if (TemplateArgs.size() != 3)
4564 return false;
4565
4566 if (!isCharType(TemplateArgs[0].getAsType()))
4567 return false;
4568
4569 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4570 return false;
4571
4572 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4573 return false;
4574
4575 Out << "Ss";
4576 return true;
4577 }
4578
4579 // <substitution> ::= Si # ::std::basic_istream<char,
4580 // ::std::char_traits<char> >
4581 if (isStreamCharSpecialization(SD, "basic_istream")) {
4582 Out << "Si";
4583 return true;
4584 }
4585
4586 // <substitution> ::= So # ::std::basic_ostream<char,
4587 // ::std::char_traits<char> >
4588 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4589 Out << "So";
4590 return true;
4591 }
4592
4593 // <substitution> ::= Sd # ::std::basic_iostream<char,
4594 // ::std::char_traits<char> >
4595 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4596 Out << "Sd";
4597 return true;
4598 }
4599 }
4600 return false;
4601}
4602
4603void CXXNameMangler::addSubstitution(QualType T) {
4604 if (!hasMangledSubstitutionQualifiers(T)) {
4605 if (const RecordType *RT = T->getAs<RecordType>()) {
4606 addSubstitution(RT->getDecl());
4607 return;
4608 }
4609 }
4610
4611 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4612 addSubstitution(TypePtr);
4613}
4614
4615void CXXNameMangler::addSubstitution(TemplateName Template) {
4616 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4617 return addSubstitution(TD);
4618
4619 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4620 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4621}
4622
4623void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4624 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4625 Substitutions[Ptr] = SeqID++;
4626}
4627
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004628void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4629 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4630 if (Other->SeqID > SeqID) {
4631 Substitutions.swap(Other->Substitutions);
4632 SeqID = Other->SeqID;
4633 }
4634}
4635
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004636CXXNameMangler::AbiTagList
4637CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4638 // When derived abi tags are disabled there is no need to make any list.
4639 if (DisableDerivedAbiTags)
4640 return AbiTagList();
4641
4642 llvm::raw_null_ostream NullOutStream;
4643 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4644 TrackReturnTypeTags.disableDerivedAbiTags();
4645
4646 const FunctionProtoType *Proto =
4647 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004648 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004649 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4650 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4651 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004652 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004653
4654 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4655}
4656
4657CXXNameMangler::AbiTagList
4658CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4659 // When derived abi tags are disabled there is no need to make any list.
4660 if (DisableDerivedAbiTags)
4661 return AbiTagList();
4662
4663 llvm::raw_null_ostream NullOutStream;
4664 CXXNameMangler TrackVariableType(*this, NullOutStream);
4665 TrackVariableType.disableDerivedAbiTags();
4666
4667 TrackVariableType.mangleType(VD->getType());
4668
4669 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4670}
4671
4672bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4673 const VarDecl *VD) {
4674 llvm::raw_null_ostream NullOutStream;
4675 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4676 TrackAbiTags.mangle(VD);
4677 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4678}
4679
Guy Benyei11169dd2012-12-18 14:30:41 +00004680//
4681
Justin Bognere8d762e2015-05-22 06:48:13 +00004682/// Mangles the name of the declaration D and emits that name to the given
4683/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004684///
4685/// If the declaration D requires a mangled name, this routine will emit that
4686/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4687/// and this routine will return false. In this case, the caller should just
4688/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4689/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004690void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4691 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4693 "Invalid mangleName() call, argument is not a variable or function!");
4694 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4695 "Invalid mangleName() call on 'structor decl!");
4696
4697 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4698 getASTContext().getSourceManager(),
4699 "Mangling declaration");
4700
4701 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004702 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004703}
4704
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004705void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4706 CXXCtorType Type,
4707 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004708 CXXNameMangler Mangler(*this, Out, D, Type);
4709 Mangler.mangle(D);
4710}
4711
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004712void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4713 CXXDtorType Type,
4714 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 CXXNameMangler Mangler(*this, Out, D, Type);
4716 Mangler.mangle(D);
4717}
4718
Rafael Espindola1e4df922014-09-16 15:18:21 +00004719void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4720 raw_ostream &Out) {
4721 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4722 Mangler.mangle(D);
4723}
4724
4725void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4726 raw_ostream &Out) {
4727 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4728 Mangler.mangle(D);
4729}
4730
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004731void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4732 const ThunkInfo &Thunk,
4733 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 // <special-name> ::= T <call-offset> <base encoding>
4735 // # base is the nominal target function of thunk
4736 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4737 // # base is the nominal target function of thunk
4738 // # first call-offset is 'this' adjustment
4739 // # second call-offset is result adjustment
4740
4741 assert(!isa<CXXDestructorDecl>(MD) &&
4742 "Use mangleCXXDtor for destructor decls!");
4743 CXXNameMangler Mangler(*this, Out);
4744 Mangler.getStream() << "_ZT";
4745 if (!Thunk.Return.isEmpty())
4746 Mangler.getStream() << 'c';
4747
4748 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004749 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4750 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4751
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 // Mangle the return pointer adjustment if there is one.
4753 if (!Thunk.Return.isEmpty())
4754 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004755 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4756
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 Mangler.mangleFunctionEncoding(MD);
4758}
4759
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004760void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4761 const CXXDestructorDecl *DD, CXXDtorType Type,
4762 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 // <special-name> ::= T <call-offset> <base encoding>
4764 // # base is the nominal target function of thunk
4765 CXXNameMangler Mangler(*this, Out, DD, Type);
4766 Mangler.getStream() << "_ZT";
4767
4768 // Mangle the 'this' pointer adjustment.
4769 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004770 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004771
4772 Mangler.mangleFunctionEncoding(DD);
4773}
4774
Justin Bognere8d762e2015-05-22 06:48:13 +00004775/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004776void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4777 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 // <special-name> ::= GV <object name> # Guard variable for one-time
4779 // # initialization
4780 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004781 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4782 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 Mangler.getStream() << "_ZGV";
4784 Mangler.mangleName(D);
4785}
4786
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004787void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4788 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004789 // These symbols are internal in the Itanium ABI, so the names don't matter.
4790 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4791 // avoid duplicate symbols.
4792 Out << "__cxx_global_var_init";
4793}
4794
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004795void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4796 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004797 // Prefix the mangling of D with __dtor_.
4798 CXXNameMangler Mangler(*this, Out);
4799 Mangler.getStream() << "__dtor_";
4800 if (shouldMangleDeclName(D))
4801 Mangler.mangle(D);
4802 else
4803 Mangler.getStream() << D->getName();
4804}
4805
Reid Kleckner1d59f992015-01-22 01:36:17 +00004806void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4807 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4808 CXXNameMangler Mangler(*this, Out);
4809 Mangler.getStream() << "__filt_";
4810 if (shouldMangleDeclName(EnclosingDecl))
4811 Mangler.mangle(EnclosingDecl);
4812 else
4813 Mangler.getStream() << EnclosingDecl->getName();
4814}
4815
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004816void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4817 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4818 CXXNameMangler Mangler(*this, Out);
4819 Mangler.getStream() << "__fin_";
4820 if (shouldMangleDeclName(EnclosingDecl))
4821 Mangler.mangle(EnclosingDecl);
4822 else
4823 Mangler.getStream() << EnclosingDecl->getName();
4824}
4825
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004826void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4827 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004828 // <special-name> ::= TH <object name>
4829 CXXNameMangler Mangler(*this, Out);
4830 Mangler.getStream() << "_ZTH";
4831 Mangler.mangleName(D);
4832}
4833
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004834void
4835ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4836 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004837 // <special-name> ::= TW <object name>
4838 CXXNameMangler Mangler(*this, Out);
4839 Mangler.getStream() << "_ZTW";
4840 Mangler.mangleName(D);
4841}
4842
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004843void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004844 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004845 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 // We match the GCC mangling here.
4847 // <special-name> ::= GR <object name>
4848 CXXNameMangler Mangler(*this, Out);
4849 Mangler.getStream() << "_ZGR";
4850 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004851 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004852 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004853}
4854
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004855void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4856 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 // <special-name> ::= TV <type> # virtual table
4858 CXXNameMangler Mangler(*this, Out);
4859 Mangler.getStream() << "_ZTV";
4860 Mangler.mangleNameOrStandardSubstitution(RD);
4861}
4862
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004863void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4864 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 // <special-name> ::= TT <type> # VTT structure
4866 CXXNameMangler Mangler(*this, Out);
4867 Mangler.getStream() << "_ZTT";
4868 Mangler.mangleNameOrStandardSubstitution(RD);
4869}
4870
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004871void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4872 int64_t Offset,
4873 const CXXRecordDecl *Type,
4874 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 // <special-name> ::= TC <type> <offset number> _ <base type>
4876 CXXNameMangler Mangler(*this, Out);
4877 Mangler.getStream() << "_ZTC";
4878 Mangler.mangleNameOrStandardSubstitution(RD);
4879 Mangler.getStream() << Offset;
4880 Mangler.getStream() << '_';
4881 Mangler.mangleNameOrStandardSubstitution(Type);
4882}
4883
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004884void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 // <special-name> ::= TI <type> # typeinfo structure
4886 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4887 CXXNameMangler Mangler(*this, Out);
4888 Mangler.getStream() << "_ZTI";
4889 Mangler.mangleType(Ty);
4890}
4891
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004892void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4893 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4895 CXXNameMangler Mangler(*this, Out);
4896 Mangler.getStream() << "_ZTS";
4897 Mangler.mangleType(Ty);
4898}
4899
Reid Klecknercc99e262013-11-19 23:23:00 +00004900void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4901 mangleCXXRTTIName(Ty, Out);
4902}
4903
David Majnemer58e5bee2014-03-24 21:43:36 +00004904void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4905 llvm_unreachable("Can't mangle string literals");
4906}
4907
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004908ItaniumMangleContext *
4909ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4910 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004911}