blob: 83682a48b98e2c1070f0fdfaf9b4f9ed58819799 [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
Guy Benyei11169dd2012-12-18 14:30:41 +000036using namespace clang;
37
38namespace {
39
Justin Bognere8d762e2015-05-22 06:48:13 +000040/// Retrieve the declaration context that should be used when mangling the given
41/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000042static const DeclContext *getEffectiveDeclContext(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +000043 // The ABI assumes that lambda closure types that occur within
Guy Benyei11169dd2012-12-18 14:30:41 +000044 // default arguments live in the context of the function. However, due to
45 // the way in which Clang parses and creates function declarations, this is
Fangrui Song6907ce22018-07-30 19:24:48 +000046 // not the case: the lambda closure type ends up living in the context
Guy Benyei11169dd2012-12-18 14:30:41 +000047 // where the function itself resides, because the function declaration itself
48 // had not yet been created. Fix the context here.
49 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
50 if (RD->isLambda())
51 if (ParmVarDecl *ContextParam
52 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
53 return ContextParam->getDeclContext();
54 }
Eli Friedman0cd23352013-07-10 01:33:19 +000055
56 // Perform the same check for block literals.
57 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
58 if (ParmVarDecl *ContextParam
59 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
60 return ContextParam->getDeclContext();
61 }
Fangrui Song6907ce22018-07-30 19:24:48 +000062
Eli Friedman95f50122013-07-02 17:52:28 +000063 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000064 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
65 return getEffectiveDeclContext(cast<Decl>(DC));
66 }
Eli Friedman95f50122013-07-02 17:52:28 +000067
David Majnemerf8c02e62015-02-18 19:08:11 +000068 if (const auto *VD = dyn_cast<VarDecl>(D))
69 if (VD->isExternC())
70 return VD->getASTContext().getTranslationUnitDecl();
71
72 if (const auto *FD = dyn_cast<FunctionDecl>(D))
73 if (FD->isExternC())
74 return FD->getASTContext().getTranslationUnitDecl();
75
Richard Smithec24bbe2016-04-29 01:23:20 +000076 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000077}
78
79static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
80 return getEffectiveDeclContext(cast<Decl>(DC));
81}
Eli Friedman95f50122013-07-02 17:52:28 +000082
83static bool isLocalContainerContext(const DeclContext *DC) {
84 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
85}
86
Eli Friedmaneecc09a2013-07-05 20:27:40 +000087static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000088 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000089 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000090 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000091 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000092 D = cast<Decl>(DC);
93 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000094 }
Craig Topper36250ad2014-05-12 05:36:57 +000095 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000096}
97
98static const FunctionDecl *getStructor(const FunctionDecl *fn) {
99 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
100 return ftd->getTemplatedDecl();
101
102 return fn;
103}
104
105static const NamedDecl *getStructor(const NamedDecl *decl) {
106 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
107 return (fn ? getStructor(fn) : decl);
108}
David Majnemer2206bf52014-03-05 08:57:59 +0000109
110static bool isLambda(const NamedDecl *ND) {
111 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
112 if (!Record)
113 return false;
114
115 return Record->isLambda();
116}
117
Guy Benyei11169dd2012-12-18 14:30:41 +0000118static const unsigned UnknownArity = ~0U;
119
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000120class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000121 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
122 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000123 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000124
Guy Benyei11169dd2012-12-18 14:30:41 +0000125public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126 explicit ItaniumMangleContextImpl(ASTContext &Context,
127 DiagnosticsEngine &Diags)
128 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000129
Guy Benyei11169dd2012-12-18 14:30:41 +0000130 /// @name Mangler Entry Points
131 /// @{
132
Craig Toppercbce6e92014-03-11 06:22:39 +0000133 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000134 bool shouldMangleStringLiteral(const StringLiteral *) override {
135 return false;
136 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000137 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
138 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
139 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000140 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
141 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000142 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000143 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
144 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000145 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
146 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000147 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 const CXXRecordDecl *Type, raw_ostream &) override;
149 void mangleCXXRTTI(QualType T, raw_ostream &) override;
150 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
151 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000152 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000153 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000154 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000155 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
Rafael Espindola1e4df922014-09-16 15:18:21 +0000157 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
158 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
160 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
161 void mangleDynamicAtExitDestructor(const VarDecl *D,
162 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000163 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000165 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000167 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000170
David Majnemer58e5bee2014-03-24 21:43:36 +0000171 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
172
Guy Benyei11169dd2012-12-18 14:30:41 +0000173 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000174 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000175 if (isLambda(ND))
176 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000177
178 // Anonymous tags are already numbered.
179 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
180 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
181 return false;
182 }
183
184 // Use the canonical number for externally visible decls.
185 if (ND->isExternallyVisible()) {
186 unsigned discriminator = getASTContext().getManglingNumber(ND);
187 if (discriminator == 1)
188 return false;
189 disc = discriminator - 2;
190 return true;
191 }
192
193 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000194 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000195 if (!discriminator) {
196 const DeclContext *DC = getEffectiveDeclContext(ND);
197 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
198 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000199 if (discriminator == 1)
200 return false;
201 disc = discriminator-2;
202 return true;
203 }
204 /// @}
205};
206
Justin Bognere8d762e2015-05-22 06:48:13 +0000207/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000208class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000209 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000210 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000211 bool NullOut = false;
212 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
213 /// This mode is used when mangler creates another mangler recursively to
214 /// calculate ABI tags for the function return value or the variable type.
215 /// Also it is required to avoid infinite recursion in some cases.
216 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000217
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
223
Justin Bognere8d762e2015-05-22 06:48:13 +0000224 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225 unsigned SeqID;
226
227 class FunctionTypeDepthState {
228 unsigned Bits;
229
230 enum { InResultTypeMask = 1 };
231
232 public:
233 FunctionTypeDepthState() : Bits(0) {}
234
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
237 return Bits >> 1;
238 }
239
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
243 }
244
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
248 return tmp;
249 }
250
251 void enterResultType() {
252 Bits |= InResultTypeMask;
253 }
254
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
257 }
258
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
261 Bits = saved.Bits;
262 }
263
264 } FunctionTypeDepth;
265
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000266 // abi_tag is a gcc attribute, taking one or more strings called "tags".
267 // The goal is to annotate against which version of a library an object was
268 // built and to be able to provide backwards compatibility ("dual abi").
269 // For more information see docs/ItaniumMangleAbiTags.rst.
270 typedef SmallVector<StringRef, 4> AbiTagList;
271
272 // State to gather all implicit and explicit tags used in a mangled name.
273 // Must always have an instance of this while emitting any name to keep
274 // track.
275 class AbiTagState final {
276 public:
277 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
278 Parent = LinkHead;
279 LinkHead = this;
280 }
281
282 // No copy, no move.
283 AbiTagState(const AbiTagState &) = delete;
284 AbiTagState &operator=(const AbiTagState &) = delete;
285
286 ~AbiTagState() { pop(); }
287
288 void write(raw_ostream &Out, const NamedDecl *ND,
289 const AbiTagList *AdditionalAbiTags) {
290 ND = cast<NamedDecl>(ND->getCanonicalDecl());
291 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
292 assert(
293 !AdditionalAbiTags &&
294 "only function and variables need a list of additional abi tags");
295 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
296 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
297 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
298 AbiTag->tags().end());
299 }
300 // Don't emit abi tags for namespaces.
301 return;
302 }
303 }
304
305 AbiTagList TagList;
306 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
307 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
308 AbiTag->tags().end());
309 TagList.insert(TagList.end(), AbiTag->tags().begin(),
310 AbiTag->tags().end());
311 }
312
313 if (AdditionalAbiTags) {
314 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
315 AdditionalAbiTags->end());
316 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
317 AdditionalAbiTags->end());
318 }
319
Fangrui Song55fab262018-09-26 22:16:28 +0000320 llvm::sort(TagList);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000321 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
322
323 writeSortedUniqueAbiTags(Out, TagList);
324 }
325
326 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
327 void setUsedAbiTags(const AbiTagList &AbiTags) {
328 UsedAbiTags = AbiTags;
329 }
330
331 const AbiTagList &getEmittedAbiTags() const {
332 return EmittedAbiTags;
333 }
334
335 const AbiTagList &getSortedUniqueUsedAbiTags() {
Fangrui Song55fab262018-09-26 22:16:28 +0000336 llvm::sort(UsedAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000337 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
338 UsedAbiTags.end());
339 return UsedAbiTags;
340 }
341
342 private:
343 //! All abi tags used implicitly or explicitly.
344 AbiTagList UsedAbiTags;
345 //! All explicit abi tags (i.e. not from namespace).
346 AbiTagList EmittedAbiTags;
347
348 AbiTagState *&LinkHead;
349 AbiTagState *Parent = nullptr;
350
351 void pop() {
352 assert(LinkHead == this &&
353 "abi tag link head must point to us on destruction");
354 if (Parent) {
355 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
356 UsedAbiTags.begin(), UsedAbiTags.end());
357 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
358 EmittedAbiTags.begin(),
359 EmittedAbiTags.end());
360 }
361 LinkHead = Parent;
362 }
363
364 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
365 for (const auto &Tag : AbiTags) {
366 EmittedAbiTags.push_back(Tag);
367 Out << "B";
368 Out << Tag.size();
369 Out << Tag;
370 }
371 }
372 };
373
374 AbiTagState *AbiTags = nullptr;
375 AbiTagState AbiTagsRoot;
376
Guy Benyei11169dd2012-12-18 14:30:41 +0000377 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000378 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000379
380 ASTContext &getASTContext() const { return Context.getASTContext(); }
381
382public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000383 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000384 const NamedDecl *D = nullptr, bool NullOut_ = false)
385 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
386 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 // These can't be mangled without a ctor type or dtor type.
388 assert(!D || (!isa<CXXDestructorDecl>(D) &&
389 !isa<CXXConstructorDecl>(D)));
390 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000391 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 const CXXConstructorDecl *D, CXXCtorType Type)
393 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000394 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000395 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000396 const CXXDestructorDecl *D, CXXDtorType Type)
397 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000398 SeqID(0), AbiTagsRoot(AbiTags) { }
399
400 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
401 : Context(Outer.Context), Out(Out_), NullOut(false),
402 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000403 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
404 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000405
406 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(true),
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) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Guy Benyei11169dd2012-12-18 14:30:41 +0000412 raw_ostream &getStream() { return Out; }
413
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000414 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
415 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
416
David Majnemer7ff7eb72015-02-18 07:47:09 +0000417 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
419 void mangleNumber(const llvm::APSInt &I);
420 void mangleNumber(int64_t Number);
421 void mangleFloat(const llvm::APFloat &F);
422 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000423 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 void mangleName(const NamedDecl *ND);
425 void mangleType(QualType T);
426 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
Fangrui Song6907ce22018-07-30 19:24:48 +0000427
Guy Benyei11169dd2012-12-18 14:30:41 +0000428private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 bool mangleSubstitution(const NamedDecl *ND);
431 bool mangleSubstitution(QualType T);
432 bool mangleSubstitution(TemplateName Template);
433 bool mangleSubstitution(uintptr_t Ptr);
434
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleExistingSubstitution(TemplateName name);
436
437 bool mangleStandardSubstitution(const NamedDecl *ND);
438
439 void addSubstitution(const NamedDecl *ND) {
440 ND = cast<NamedDecl>(ND->getCanonicalDecl());
441
442 addSubstitution(reinterpret_cast<uintptr_t>(ND));
443 }
444 void addSubstitution(QualType T);
445 void addSubstitution(TemplateName Template);
446 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000447 // Destructive copy substitutions from other mangler.
448 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000449
450 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 bool recursive = false);
452 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000454 const TemplateArgumentLoc *TemplateArgs,
455 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000456 unsigned KnownArity = UnknownArity);
457
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000458 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
459
460 void mangleNameWithAbiTags(const NamedDecl *ND,
461 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000462 void mangleModuleName(const Module *M);
463 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000464 void mangleTemplateName(const TemplateDecl *TD,
465 const TemplateArgument *TemplateArgs,
466 unsigned NumTemplateArgs);
467 void mangleUnqualifiedName(const NamedDecl *ND,
468 const AbiTagList *AdditionalAbiTags) {
469 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
470 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000471 }
472 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000473 unsigned KnownArity,
474 const AbiTagList *AdditionalAbiTags);
475 void mangleUnscopedName(const NamedDecl *ND,
476 const AbiTagList *AdditionalAbiTags);
477 void mangleUnscopedTemplateName(const TemplateDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
479 void mangleUnscopedTemplateName(TemplateName,
480 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000482 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000483 void mangleSourceNameWithAbiTags(
484 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
485 void mangleLocalName(const Decl *D,
486 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000487 void mangleBlockForPrefix(const BlockDecl *Block);
488 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000489 void mangleLambda(const CXXRecordDecl *Lambda);
490 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000491 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000492 bool NoFunction=false);
493 void mangleNestedName(const TemplateDecl *TD,
494 const TemplateArgument *TemplateArgs,
495 unsigned NumTemplateArgs);
496 void manglePrefix(NestedNameSpecifier *qualifier);
497 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
498 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000499 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000500 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000501 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
502 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000503 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000504 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000505 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000506 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000507 void mangleRefQualifier(RefQualifierKind RefQualifier);
508
509 void mangleObjCMethodName(const ObjCMethodDecl *MD);
510
511 // Declare manglers for every type class.
512#define ABSTRACT_TYPE(CLASS, PARENT)
513#define NON_CANONICAL_TYPE(CLASS, PARENT)
514#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
515#include "clang/AST/TypeNodes.def"
516
517 void mangleType(const TagType*);
518 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000519 static StringRef getCallingConvQualifierName(CallingConv CC);
520 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
521 void mangleExtFunctionInfo(const FunctionType *T);
522 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000523 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000525 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000526 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000527 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000528
529 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000530 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000531 void mangleMemberExpr(const Expr *base, bool isArrow,
532 NestedNameSpecifier *qualifier,
533 NamedDecl *firstQualifierLookup,
534 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000535 const TemplateArgumentLoc *TemplateArgs,
536 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000538 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000539 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000540 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000541 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000542 void mangleCXXDtorType(CXXDtorType T);
543
James Y Knight04ec5bf2015-12-24 02:59:37 +0000544 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
545 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000546 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
547 unsigned NumTemplateArgs);
548 void mangleTemplateArgs(const TemplateArgumentList &AL);
549 void mangleTemplateArg(TemplateArgument A);
550
551 void mangleTemplateParameter(unsigned Index);
552
553 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000554
555 void writeAbiTags(const NamedDecl *ND,
556 const AbiTagList *AdditionalAbiTags);
557
558 // Returns sorted unique list of ABI tags.
559 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
560 // Returns sorted unique list of ABI tags.
561 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000562};
563
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000564}
Guy Benyei11169dd2012-12-18 14:30:41 +0000565
Rafael Espindola002667c2013-10-16 01:40:34 +0000566bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000568 if (FD) {
569 LanguageLinkage L = FD->getLanguageLinkage();
570 // Overloadable functions need mangling.
571 if (FD->hasAttr<OverloadableAttr>())
572 return true;
573
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000574 // "main" is not mangled.
575 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000576 return false;
577
Martin Storsjo92e26612018-07-16 05:42:25 +0000578 // The Windows ABI expects that we would never mangle "typical"
579 // user-defined entry points regardless of visibility or freestanding-ness.
580 //
581 // N.B. This is distinct from asking about "main". "main" has a lot of
582 // special rules associated with it in the standard while these
583 // user-defined entry points are outside of the purview of the standard.
584 // For example, there can be only one definition for "main" in a standards
585 // compliant program; however nothing forbids the existence of wmain and
586 // WinMain in the same translation unit.
587 if (FD->isMSVCRTEntryPoint())
588 return false;
589
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000590 // C++ functions and those whose names are not a simple identifier need
591 // mangling.
592 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
593 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000594
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000595 // C functions are not mangled.
596 if (L == CLanguageLinkage)
597 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000598 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000599
600 // Otherwise, no mangling is done outside C++ mode.
601 if (!getASTContext().getLangOpts().CPlusPlus)
602 return false;
603
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000604 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000605 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000606 // C variables are not mangled.
607 if (VD->isExternC())
608 return false;
609
610 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 const DeclContext *DC = getEffectiveDeclContext(D);
612 // Check for extern variable declared locally.
613 if (DC->isFunctionOrMethod() && D->hasLinkage())
614 while (!DC->isNamespace() && !DC->isTranslationUnit())
615 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000616 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000617 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000618 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000619 return false;
620 }
621
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 return true;
623}
624
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000625void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
626 const AbiTagList *AdditionalAbiTags) {
627 assert(AbiTags && "require AbiTagState");
628 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
629}
630
631void CXXNameMangler::mangleSourceNameWithAbiTags(
632 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
633 mangleSourceName(ND->getIdentifier());
634 writeAbiTags(ND, AdditionalAbiTags);
635}
636
David Majnemer7ff7eb72015-02-18 07:47:09 +0000637void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // <mangled-name> ::= _Z <encoding>
639 // ::= <data name>
640 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000641 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
643 mangleFunctionEncoding(FD);
644 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
645 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000646 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
647 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 else
649 mangleName(cast<FieldDecl>(D));
650}
651
652void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
653 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000654
655 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000656 if (!Context.shouldMangleDeclName(FD)) {
657 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000659 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000660
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000661 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
662 if (ReturnTypeAbiTags.empty()) {
663 // There are no tags for return type, the simplest case.
664 mangleName(FD);
665 mangleFunctionEncodingBareType(FD);
666 return;
667 }
668
669 // Mangle function name and encoding to temporary buffer.
670 // We have to output name and encoding to the same mangler to get the same
671 // substitution as it will be in final mangling.
672 SmallString<256> FunctionEncodingBuf;
673 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
674 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
675 // Output name of the function.
676 FunctionEncodingMangler.disableDerivedAbiTags();
677 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
678
679 // Remember length of the function name in the buffer.
680 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
681 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
682
683 // Get tags from return type that are not present in function name or
684 // encoding.
685 const AbiTagList &UsedAbiTags =
686 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
687 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
688 AdditionalAbiTags.erase(
689 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
690 UsedAbiTags.begin(), UsedAbiTags.end(),
691 AdditionalAbiTags.begin()),
692 AdditionalAbiTags.end());
693
694 // Output name with implicit tags and function encoding from temporary buffer.
695 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
696 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000697
698 // Function encoding could create new substitutions so we have to add
699 // temp mangled substitutions to main mangler.
700 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000701}
702
703void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000704 if (FD->hasAttr<EnableIfAttr>()) {
705 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
706 Out << "Ua9enable_ifI";
Michael Krusedc5ce722018-08-03 01:21:16 +0000707 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
708 E = FD->getAttrs().end();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000709 I != E; ++I) {
710 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
711 if (!EIA)
712 continue;
713 Out << 'X';
714 mangleExpression(EIA->getCond());
715 Out << 'E';
716 }
717 Out << 'E';
718 FunctionTypeDepth.pop(Saved);
719 }
720
Richard Smith5179eb72016-06-28 19:03:57 +0000721 // When mangling an inheriting constructor, the bare function type used is
722 // that of the inherited constructor.
723 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
724 if (auto Inherited = CD->getInheritedConstructor())
725 FD = Inherited.getConstructor();
726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 // Whether the mangling of a function type includes the return type depends on
728 // the context and the nature of the function. The rules for deciding whether
729 // the return type is included are:
730 //
731 // 1. Template functions (names or types) have return types encoded, with
732 // the exceptions listed below.
733 // 2. Function types not appearing as part of a function name mangling,
734 // e.g. parameters, pointer types, etc., have return type encoded, with the
735 // exceptions listed below.
736 // 3. Non-template function names do not have return types encoded.
737 //
738 // The exceptions mentioned in (1) and (2) above, for which the return type is
739 // never included, are
740 // 1. Constructors.
741 // 2. Destructors.
742 // 3. Conversion operator functions, e.g. operator int.
743 bool MangleReturnType = false;
744 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
745 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
746 isa<CXXConversionDecl>(FD)))
747 MangleReturnType = true;
748
749 // Mangle the type of the primary template.
750 FD = PrimaryTemplate->getTemplatedDecl();
751 }
752
John McCall07daf722016-03-01 22:18:03 +0000753 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000754 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000755}
756
757static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
758 while (isa<LinkageSpecDecl>(DC)) {
759 DC = getEffectiveParentContext(DC);
760 }
761
762 return DC;
763}
764
Justin Bognere8d762e2015-05-22 06:48:13 +0000765/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000766static bool isStd(const NamespaceDecl *NS) {
767 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
768 ->isTranslationUnit())
769 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000770
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
772 return II && II->isStr("std");
773}
774
775// isStdNamespace - Return whether a given decl context is a toplevel 'std'
776// namespace.
777static bool isStdNamespace(const DeclContext *DC) {
778 if (!DC->isNamespace())
779 return false;
780
781 return isStd(cast<NamespaceDecl>(DC));
782}
783
784static const TemplateDecl *
785isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
786 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000787 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
789 TemplateArgs = FD->getTemplateSpecializationArgs();
790 return TD;
791 }
792 }
793
794 // Check if we have a class template.
795 if (const ClassTemplateSpecializationDecl *Spec =
796 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
797 TemplateArgs = &Spec->getTemplateArgs();
798 return Spec->getSpecializedTemplate();
799 }
800
Larisse Voufo39a1e502013-08-06 01:03:05 +0000801 // Check if we have a variable template.
802 if (const VarTemplateSpecializationDecl *Spec =
803 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
804 TemplateArgs = &Spec->getTemplateArgs();
805 return Spec->getSpecializedTemplate();
806 }
807
Craig Topper36250ad2014-05-12 05:36:57 +0000808 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000809}
810
Guy Benyei11169dd2012-12-18 14:30:41 +0000811void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000812 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
813 // Variables should have implicit tags from its type.
814 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
815 if (VariableTypeAbiTags.empty()) {
816 // Simple case no variable type tags.
817 mangleNameWithAbiTags(VD, nullptr);
818 return;
819 }
820
821 // Mangle variable name to null stream to collect tags.
822 llvm::raw_null_ostream NullOutStream;
823 CXXNameMangler VariableNameMangler(*this, NullOutStream);
824 VariableNameMangler.disableDerivedAbiTags();
825 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
826
827 // Get tags from variable type that are not present in its name.
828 const AbiTagList &UsedAbiTags =
829 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
830 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
831 AdditionalAbiTags.erase(
832 std::set_difference(VariableTypeAbiTags.begin(),
833 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
834 UsedAbiTags.end(), AdditionalAbiTags.begin()),
835 AdditionalAbiTags.end());
836
837 // Output name with implicit tags.
838 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
839 } else {
840 mangleNameWithAbiTags(ND, nullptr);
841 }
842}
843
844void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
845 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000846 // <name> ::= [<module-name>] <nested-name>
847 // ::= [<module-name>] <unscoped-name>
848 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 // ::= <local-name>
850 //
851 const DeclContext *DC = getEffectiveDeclContext(ND);
852
853 // If this is an extern variable declared locally, the relevant DeclContext
854 // is that of the containing namespace, or the translation unit.
855 // FIXME: This is a hack; extern variables declared locally should have
856 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000857 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000858 while (!DC->isNamespace() && !DC->isTranslationUnit())
859 DC = getEffectiveParentContext(DC);
860 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000861 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000862 return;
863 }
864
865 DC = IgnoreLinkageSpecDecls(DC);
866
Richard Smithdd8b5332017-09-04 05:37:53 +0000867 if (isLocalContainerContext(DC)) {
868 mangleLocalName(ND, AdditionalAbiTags);
869 return;
870 }
871
872 // Do not mangle the owning module for an external linkage declaration.
873 // This enables backwards-compatibility with non-modular code, and is
874 // a valid choice since conflicts are not permitted by C++ Modules TS
875 // [basic.def.odr]/6.2.
876 if (!ND->hasExternalFormalLinkage())
877 if (Module *M = ND->getOwningModuleForLinkage())
878 mangleModuleName(M);
879
Guy Benyei11169dd2012-12-18 14:30:41 +0000880 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
881 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000882 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000884 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 mangleTemplateArgs(*TemplateArgs);
886 return;
887 }
888
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000889 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 return;
891 }
892
Richard Smithdd8b5332017-09-04 05:37:53 +0000893 mangleNestedName(ND, DC, AdditionalAbiTags);
894}
895
896void CXXNameMangler::mangleModuleName(const Module *M) {
897 // Implement the C++ Modules TS name mangling proposal; see
898 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
899 //
900 // <module-name> ::= W <unscoped-name>+ E
901 // ::= W <module-subst> <unscoped-name>* E
902 Out << 'W';
903 mangleModuleNamePrefix(M->Name);
904 Out << 'E';
905}
906
907void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
908 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
909 // ::= W <seq-id - 10> _ # otherwise
910 auto It = ModuleSubstitutions.find(Name);
911 if (It != ModuleSubstitutions.end()) {
912 if (It->second < 10)
913 Out << '_' << static_cast<char>('0' + It->second);
914 else
915 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000916 return;
917 }
918
Richard Smithdd8b5332017-09-04 05:37:53 +0000919 // FIXME: Preserve hierarchy in module names rather than flattening
920 // them to strings; use Module*s as substitution keys.
921 auto Parts = Name.rsplit('.');
922 if (Parts.second.empty())
923 Parts.second = Parts.first;
924 else
925 mangleModuleNamePrefix(Parts.first);
926
927 Out << Parts.second.size() << Parts.second;
928 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000929}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000930
931void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
932 const TemplateArgument *TemplateArgs,
933 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000934 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
935
936 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000937 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
939 } else {
940 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
941 }
942}
943
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000944void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
945 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 // <unscoped-name> ::= <unqualified-name>
947 // ::= St <unqualified-name> # ::std::
948
949 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
950 Out << "St";
951
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000952 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000953}
954
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000955void CXXNameMangler::mangleUnscopedTemplateName(
956 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 // <unscoped-template-name> ::= <unscoped-name>
958 // ::= <substitution>
959 if (mangleSubstitution(ND))
960 return;
961
962 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000963 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
964 assert(!AdditionalAbiTags &&
965 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000967 } else if (isa<BuiltinTemplateDecl>(ND)) {
968 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000969 } else {
970 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
971 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000972
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 addSubstitution(ND);
974}
975
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000976void CXXNameMangler::mangleUnscopedTemplateName(
977 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 // <unscoped-template-name> ::= <unscoped-name>
979 // ::= <substitution>
980 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000981 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +0000982
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 if (mangleSubstitution(Template))
984 return;
985
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000986 assert(!AdditionalAbiTags &&
987 "dependent template name cannot have abi tags");
988
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
990 assert(Dependent && "Not a dependent template name?");
991 if (const IdentifierInfo *Id = Dependent->getIdentifier())
992 mangleSourceName(Id);
993 else
994 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000995
Guy Benyei11169dd2012-12-18 14:30:41 +0000996 addSubstitution(Template);
997}
998
999void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1000 // ABI:
1001 // Floating-point literals are encoded using a fixed-length
1002 // lowercase hexadecimal string corresponding to the internal
1003 // representation (IEEE on Itanium), high-order bytes first,
1004 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1005 // on Itanium.
1006 // The 'without leading zeroes' thing seems to be an editorial
1007 // mistake; see the discussion on cxx-abi-dev beginning on
1008 // 2012-01-16.
1009
1010 // Our requirements here are just barely weird enough to justify
1011 // using a custom algorithm instead of post-processing APInt::toString().
1012
1013 llvm::APInt valueBits = f.bitcastToAPInt();
1014 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1015 assert(numCharacters != 0);
1016
1017 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001018 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001019
1020 // Fill the buffer left-to-right.
1021 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1022 // The bit-index of the next hex digit.
1023 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1024
1025 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001026 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1027 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 hexDigit &= 0xF;
1029
1030 // Map that over to a lowercase hex digit.
1031 static const char charForHex[16] = {
1032 '0', '1', '2', '3', '4', '5', '6', '7',
1033 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1034 };
1035 buffer[stringIndex] = charForHex[hexDigit];
1036 }
1037
1038 Out.write(buffer.data(), numCharacters);
1039}
1040
1041void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1042 if (Value.isSigned() && Value.isNegative()) {
1043 Out << 'n';
1044 Value.abs().print(Out, /*signed*/ false);
1045 } else {
1046 Value.print(Out, /*signed*/ false);
1047 }
1048}
1049
1050void CXXNameMangler::mangleNumber(int64_t Number) {
1051 // <number> ::= [n] <non-negative decimal integer>
1052 if (Number < 0) {
1053 Out << 'n';
1054 Number = -Number;
1055 }
1056
1057 Out << Number;
1058}
1059
1060void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1061 // <call-offset> ::= h <nv-offset> _
1062 // ::= v <v-offset> _
1063 // <nv-offset> ::= <offset number> # non-virtual base override
1064 // <v-offset> ::= <offset number> _ <virtual offset number>
1065 // # virtual base override, with vcall offset
1066 if (!Virtual) {
1067 Out << 'h';
1068 mangleNumber(NonVirtual);
1069 Out << '_';
1070 return;
1071 }
1072
1073 Out << 'v';
1074 mangleNumber(NonVirtual);
1075 Out << '_';
1076 mangleNumber(Virtual);
1077 Out << '_';
1078}
1079
1080void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001081 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001082 if (!mangleSubstitution(QualType(TST, 0))) {
1083 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001084
Guy Benyei11169dd2012-12-18 14:30:41 +00001085 // FIXME: GCC does not appear to mangle the template arguments when
1086 // the template in question is a dependent template name. Should we
1087 // emulate that badness?
1088 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1089 addSubstitution(QualType(TST, 0));
1090 }
David Majnemera88b3592015-02-18 02:28:01 +00001091 } else if (const auto *DTST =
1092 type->getAs<DependentTemplateSpecializationType>()) {
1093 if (!mangleSubstitution(QualType(DTST, 0))) {
1094 TemplateName Template = getASTContext().getDependentTemplateName(
1095 DTST->getQualifier(), DTST->getIdentifier());
1096 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001097
David Majnemera88b3592015-02-18 02:28:01 +00001098 // FIXME: GCC does not appear to mangle the template arguments when
1099 // the template in question is a dependent template name. Should we
1100 // emulate that badness?
1101 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1102 addSubstitution(QualType(DTST, 0));
1103 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 } else {
1105 // We use the QualType mangle type variant here because it handles
1106 // substitutions.
1107 mangleType(type);
1108 }
1109}
1110
1111/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1112///
Guy Benyei11169dd2012-12-18 14:30:41 +00001113/// \param recursive - true if this is being called recursively,
1114/// i.e. if there is more prefix "to the right".
1115void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 bool recursive) {
1117
1118 // x, ::x
1119 // <unresolved-name> ::= [gs] <base-unresolved-name>
1120
1121 // T::x / decltype(p)::x
1122 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1123
1124 // T::N::x /decltype(p)::N::x
1125 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1126 // <base-unresolved-name>
1127
1128 // A::x, N::y, A<T>::z; "gs" means leading "::"
1129 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1130 // <base-unresolved-name>
1131
1132 switch (qualifier->getKind()) {
1133 case NestedNameSpecifier::Global:
1134 Out << "gs";
1135
1136 // We want an 'sr' unless this is the entire NNS.
1137 if (recursive)
1138 Out << "sr";
1139
1140 // We never want an 'E' here.
1141 return;
1142
Nikola Smiljanic67860242014-09-26 00:28:20 +00001143 case NestedNameSpecifier::Super:
1144 llvm_unreachable("Can't mangle __super specifier");
1145
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 case NestedNameSpecifier::Namespace:
1147 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001148 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 /*recursive*/ true);
1150 else
1151 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001152 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 break;
1154 case NestedNameSpecifier::NamespaceAlias:
1155 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001156 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001157 /*recursive*/ true);
1158 else
1159 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001160 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001161 break;
1162
1163 case NestedNameSpecifier::TypeSpec:
1164 case NestedNameSpecifier::TypeSpecWithTemplate: {
1165 const Type *type = qualifier->getAsType();
1166
1167 // We only want to use an unresolved-type encoding if this is one of:
1168 // - a decltype
1169 // - a template type parameter
1170 // - a template template parameter with arguments
1171 // In all of these cases, we should have no prefix.
1172 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001173 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 /*recursive*/ true);
1175 } else {
1176 // Otherwise, all the cases want this.
1177 Out << "sr";
1178 }
1179
David Majnemerb8014dd2015-02-19 02:16:16 +00001180 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 return;
1182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 break;
1184 }
1185
1186 case NestedNameSpecifier::Identifier:
1187 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001188 if (qualifier->getPrefix())
1189 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001191 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
1194 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001195 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 break;
1197 }
1198
1199 // If this was the innermost part of the NNS, and we fell out to
1200 // here, append an 'E'.
1201 if (!recursive)
1202 Out << 'E';
1203}
1204
1205/// Mangle an unresolved-name, which is generally used for names which
1206/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001207void CXXNameMangler::mangleUnresolvedName(
1208 NestedNameSpecifier *qualifier, DeclarationName name,
1209 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1210 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001211 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001212 switch (name.getNameKind()) {
1213 // <base-unresolved-name> ::= <simple-id>
1214 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001215 mangleSourceName(name.getAsIdentifierInfo());
1216 break;
1217 // <base-unresolved-name> ::= dn <destructor-name>
1218 case DeclarationName::CXXDestructorName:
1219 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001220 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001221 break;
1222 // <base-unresolved-name> ::= on <operator-name>
1223 case DeclarationName::CXXConversionFunctionName:
1224 case DeclarationName::CXXLiteralOperatorName:
1225 case DeclarationName::CXXOperatorName:
1226 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001227 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001228 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001229 case DeclarationName::CXXConstructorName:
1230 llvm_unreachable("Can't mangle a constructor name!");
1231 case DeclarationName::CXXUsingDirective:
1232 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001233 case DeclarationName::CXXDeductionGuideName:
1234 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001235 case DeclarationName::ObjCMultiArgSelector:
1236 case DeclarationName::ObjCOneArgSelector:
1237 case DeclarationName::ObjCZeroArgSelector:
1238 llvm_unreachable("Can't mangle Objective-C selector names here!");
1239 }
Richard Smithafecd832016-10-24 20:47:04 +00001240
1241 // The <simple-id> and on <operator-name> productions end in an optional
1242 // <template-args>.
1243 if (TemplateArgs)
1244 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001245}
1246
Guy Benyei11169dd2012-12-18 14:30:41 +00001247void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1248 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001249 unsigned KnownArity,
1250 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001251 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001252 // <unqualified-name> ::= <operator-name>
1253 // ::= <ctor-dtor-name>
1254 // ::= <source-name>
1255 switch (Name.getNameKind()) {
1256 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001257 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1258
Richard Smithda383632016-08-15 01:33:41 +00001259 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001260 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001261 // FIXME: Non-standard mangling for decomposition declarations:
1262 //
1263 // <unqualified-name> ::= DC <source-name>* E
1264 //
1265 // These can never be referenced across translation units, so we do
1266 // not need a cross-vendor mangling for anything other than demanglers.
1267 // Proposed on cxx-abi-dev on 2016-08-12
1268 Out << "DC";
1269 for (auto *BD : DD->bindings())
1270 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1271 Out << 'E';
1272 writeAbiTags(ND, AdditionalAbiTags);
1273 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001274 }
1275
1276 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001277 // Match GCC's naming convention for internal linkage symbols, for
1278 // symbols that are not actually visible outside of this TU. GCC
1279 // distinguishes between internal and external linkage symbols in
1280 // its mangling, to support cases like this that were valid C++ prior
1281 // to DR426:
1282 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001283 // void test() { extern void foo(); }
1284 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001285 //
1286 // Don't bother with the L marker for names in anonymous namespaces; the
1287 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1288 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1289 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001290 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001291 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001292 getEffectiveDeclContext(ND)->isFileContext() &&
1293 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 Out << 'L';
1295
Erich Keane757d3172016-11-02 18:29:35 +00001296 auto *FD = dyn_cast<FunctionDecl>(ND);
1297 bool IsRegCall = FD &&
1298 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1299 clang::CC_X86RegCall;
1300 if (IsRegCall)
1301 mangleRegCallName(II);
1302 else
1303 mangleSourceName(II);
1304
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001305 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 break;
1307 }
1308
1309 // Otherwise, an anonymous entity. We must have a declaration.
1310 assert(ND && "mangling empty name without declaration");
1311
1312 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1313 if (NS->isAnonymousNamespace()) {
1314 // This is how gcc mangles these names.
1315 Out << "12_GLOBAL__N_1";
1316 break;
1317 }
1318 }
1319
1320 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1321 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001322 const RecordDecl *RD = 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;
Fangrui Song6907ce22018-07-30 19:24:48 +00001356
Guy Benyei11169dd2012-12-18 14:30:41 +00001357 // 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>
Fangrui Song6907ce22018-07-30 19:24:48 +00001373 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 // <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 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001465 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001466 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) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001499 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001501 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 // <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 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001514
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 // 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>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001545 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 // _ <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) {
Fangrui Song6907ce22018-07-30 19:24:48 +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
Guy Benyei11169dd2012-12-18 14:30:41 +00001578 // 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 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001594
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 // 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) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001683 // 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
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 // <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";
Fangrui Song6907ce22018-07-30 19:24:48 +00001714
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
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 // (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);
Fangrui Song6907ce22018-07-30 19:24:48 +00001724 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
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
Fangrui Song6907ce22018-07-30 19:24:48 +00001779 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001780 if (mangleSubstitution(ND))
1781 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001782
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 // 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:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001927 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001928 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001929 case Type::DependentSizedExtVector:
1930 case Type::Vector:
1931 case Type::ExtVector:
1932 case Type::FunctionProto:
1933 case Type::FunctionNoProto:
1934 case Type::Paren:
1935 case Type::Attributed:
1936 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001937 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001938 case Type::PackExpansion:
1939 case Type::ObjCObject:
1940 case Type::ObjCInterface:
1941 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001942 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001943 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001944 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001945 llvm_unreachable("type is illegal as a nested name specifier");
1946
1947 case Type::SubstTemplateTypeParmPack:
1948 // FIXME: not clear how to mangle this!
1949 // template <class T...> class A {
1950 // template <class U...> void foo(decltype(T::foo(U())) x...);
1951 // };
1952 Out << "_SUBSTPACK_";
1953 break;
1954
1955 // <unresolved-type> ::= <template-param>
1956 // ::= <decltype>
1957 // ::= <template-template-param> <template-args>
1958 // (this last is not official yet)
1959 case Type::TypeOfExpr:
1960 case Type::TypeOf:
1961 case Type::Decltype:
1962 case Type::TemplateTypeParm:
1963 case Type::UnaryTransform:
1964 case Type::SubstTemplateTypeParm:
1965 unresolvedType:
1966 // Some callers want a prefix before the mangled type.
1967 Out << Prefix;
1968
1969 // This seems to do everything we want. It's not really
1970 // sanctioned for a substituted template parameter, though.
1971 mangleType(Ty);
1972
1973 // We never want to print 'E' directly after an unresolved-type,
1974 // so we return directly.
1975 return true;
1976
1977 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001978 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001979 break;
1980
1981 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001982 mangleSourceNameWithAbiTags(
1983 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001984 break;
1985
1986 case Type::Enum:
1987 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001988 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001989 break;
1990
1991 case Type::TemplateSpecialization: {
1992 const TemplateSpecializationType *TST =
1993 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001994 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001995 switch (TN.getKind()) {
1996 case TemplateName::Template:
1997 case TemplateName::QualifiedTemplate: {
1998 TemplateDecl *TD = TN.getAsTemplateDecl();
1999
2000 // If the base is a template template parameter, this is an
2001 // unresolved type.
2002 assert(TD && "no template for template specialization type");
2003 if (isa<TemplateTemplateParmDecl>(TD))
2004 goto unresolvedType;
2005
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002006 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002007 break;
David Majnemera88b3592015-02-18 02:28:01 +00002008 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002009
2010 case TemplateName::OverloadedTemplate:
2011 case TemplateName::DependentTemplate:
2012 llvm_unreachable("invalid base for a template specialization type");
2013
2014 case TemplateName::SubstTemplateTemplateParm: {
2015 SubstTemplateTemplateParmStorage *subst =
2016 TN.getAsSubstTemplateTemplateParm();
2017 mangleExistingSubstitution(subst->getReplacement());
2018 break;
2019 }
2020
2021 case TemplateName::SubstTemplateTemplateParmPack: {
2022 // FIXME: not clear how to mangle this!
2023 // template <template <class U> class T...> class A {
2024 // template <class U...> void foo(decltype(T<U>::foo) x...);
2025 // };
2026 Out << "_SUBSTPACK_";
2027 break;
2028 }
2029 }
2030
David Majnemera88b3592015-02-18 02:28:01 +00002031 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002032 break;
David Majnemera88b3592015-02-18 02:28:01 +00002033 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002034
2035 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002036 mangleSourceNameWithAbiTags(
2037 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002038 break;
2039
2040 case Type::DependentName:
2041 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2042 break;
2043
2044 case Type::DependentTemplateSpecialization: {
2045 const DependentTemplateSpecializationType *DTST =
2046 cast<DependentTemplateSpecializationType>(Ty);
2047 mangleSourceName(DTST->getIdentifier());
2048 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2049 break;
2050 }
2051
2052 case Type::Elaborated:
2053 return mangleUnresolvedTypeOrSimpleId(
2054 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2055 }
2056
2057 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002058}
2059
2060void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2061 switch (Name.getNameKind()) {
2062 case DeclarationName::CXXConstructorName:
2063 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002064 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002065 case DeclarationName::CXXUsingDirective:
2066 case DeclarationName::Identifier:
2067 case DeclarationName::ObjCMultiArgSelector:
2068 case DeclarationName::ObjCOneArgSelector:
2069 case DeclarationName::ObjCZeroArgSelector:
2070 llvm_unreachable("Not an operator name");
2071
2072 case DeclarationName::CXXConversionFunctionName:
2073 // <operator-name> ::= cv <type> # (cast)
2074 Out << "cv";
2075 mangleType(Name.getCXXNameType());
2076 break;
2077
2078 case DeclarationName::CXXLiteralOperatorName:
2079 Out << "li";
2080 mangleSourceName(Name.getCXXLiteralIdentifier());
2081 return;
2082
2083 case DeclarationName::CXXOperatorName:
2084 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2085 break;
2086 }
2087}
2088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089void
2090CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2091 switch (OO) {
2092 // <operator-name> ::= nw # new
2093 case OO_New: Out << "nw"; break;
2094 // ::= na # new[]
2095 case OO_Array_New: Out << "na"; break;
2096 // ::= dl # delete
2097 case OO_Delete: Out << "dl"; break;
2098 // ::= da # delete[]
2099 case OO_Array_Delete: Out << "da"; break;
2100 // ::= ps # + (unary)
2101 // ::= pl # + (binary or unknown)
2102 case OO_Plus:
2103 Out << (Arity == 1? "ps" : "pl"); break;
2104 // ::= ng # - (unary)
2105 // ::= mi # - (binary or unknown)
2106 case OO_Minus:
2107 Out << (Arity == 1? "ng" : "mi"); break;
2108 // ::= ad # & (unary)
2109 // ::= an # & (binary or unknown)
2110 case OO_Amp:
2111 Out << (Arity == 1? "ad" : "an"); break;
2112 // ::= de # * (unary)
2113 // ::= ml # * (binary or unknown)
2114 case OO_Star:
2115 // Use binary when unknown.
2116 Out << (Arity == 1? "de" : "ml"); break;
2117 // ::= co # ~
2118 case OO_Tilde: Out << "co"; break;
2119 // ::= dv # /
2120 case OO_Slash: Out << "dv"; break;
2121 // ::= rm # %
2122 case OO_Percent: Out << "rm"; break;
2123 // ::= or # |
2124 case OO_Pipe: Out << "or"; break;
2125 // ::= eo # ^
2126 case OO_Caret: Out << "eo"; break;
2127 // ::= aS # =
2128 case OO_Equal: Out << "aS"; break;
2129 // ::= pL # +=
2130 case OO_PlusEqual: Out << "pL"; break;
2131 // ::= mI # -=
2132 case OO_MinusEqual: Out << "mI"; break;
2133 // ::= mL # *=
2134 case OO_StarEqual: Out << "mL"; break;
2135 // ::= dV # /=
2136 case OO_SlashEqual: Out << "dV"; break;
2137 // ::= rM # %=
2138 case OO_PercentEqual: Out << "rM"; break;
2139 // ::= aN # &=
2140 case OO_AmpEqual: Out << "aN"; break;
2141 // ::= oR # |=
2142 case OO_PipeEqual: Out << "oR"; break;
2143 // ::= eO # ^=
2144 case OO_CaretEqual: Out << "eO"; break;
2145 // ::= ls # <<
2146 case OO_LessLess: Out << "ls"; break;
2147 // ::= rs # >>
2148 case OO_GreaterGreater: Out << "rs"; break;
2149 // ::= lS # <<=
2150 case OO_LessLessEqual: Out << "lS"; break;
2151 // ::= rS # >>=
2152 case OO_GreaterGreaterEqual: Out << "rS"; break;
2153 // ::= eq # ==
2154 case OO_EqualEqual: Out << "eq"; break;
2155 // ::= ne # !=
2156 case OO_ExclaimEqual: Out << "ne"; break;
2157 // ::= lt # <
2158 case OO_Less: Out << "lt"; break;
2159 // ::= gt # >
2160 case OO_Greater: Out << "gt"; break;
2161 // ::= le # <=
2162 case OO_LessEqual: Out << "le"; break;
2163 // ::= ge # >=
2164 case OO_GreaterEqual: Out << "ge"; break;
2165 // ::= nt # !
2166 case OO_Exclaim: Out << "nt"; break;
2167 // ::= aa # &&
2168 case OO_AmpAmp: Out << "aa"; break;
2169 // ::= oo # ||
2170 case OO_PipePipe: Out << "oo"; break;
2171 // ::= pp # ++
2172 case OO_PlusPlus: Out << "pp"; break;
2173 // ::= mm # --
2174 case OO_MinusMinus: Out << "mm"; break;
2175 // ::= cm # ,
2176 case OO_Comma: Out << "cm"; break;
2177 // ::= pm # ->*
2178 case OO_ArrowStar: Out << "pm"; break;
2179 // ::= pt # ->
2180 case OO_Arrow: Out << "pt"; break;
2181 // ::= cl # ()
2182 case OO_Call: Out << "cl"; break;
2183 // ::= ix # []
2184 case OO_Subscript: Out << "ix"; break;
2185
2186 // ::= qu # ?
2187 // The conditional operator can't be overloaded, but we still handle it when
2188 // mangling expressions.
2189 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002190 // Proposal on cxx-abi-dev, 2015-10-21.
2191 // ::= aw # co_await
2192 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002193 // Proposed in cxx-abi github issue 43.
2194 // ::= ss # <=>
2195 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002196
2197 case OO_None:
2198 case NUM_OVERLOADED_OPERATORS:
2199 llvm_unreachable("Not an overloaded operator");
2200 }
2201}
2202
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002203void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002204 // Vendor qualifiers come first and if they are order-insensitive they must
2205 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002206
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002207 // <type> ::= U <addrspace-expr>
2208 if (DAST) {
2209 Out << "U2ASI";
2210 mangleExpression(DAST->getAddrSpaceExpr());
2211 Out << "E";
2212 }
2213
John McCall07daf722016-03-01 22:18:03 +00002214 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002216 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 //
David Tweed31d09b02013-09-13 12:04:22 +00002218 // <type> ::= U <target-addrspace>
2219 // <type> ::= U <OpenCL-addrspace>
2220 // <type> ::= U <CUDA-addrspace>
2221
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002223 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002224
2225 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2226 // <target-addrspace> ::= "AS" <address-space-number>
2227 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002228 if (TargetAS != 0)
2229 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002230 } else {
2231 switch (AS) {
2232 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002233 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2234 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002235 case LangAS::opencl_global: ASString = "CLglobal"; break;
2236 case LangAS::opencl_local: ASString = "CLlocal"; break;
2237 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002238 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002239 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002240 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2241 case LangAS::cuda_device: ASString = "CUdevice"; break;
2242 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2243 case LangAS::cuda_shared: ASString = "CUshared"; break;
2244 }
2245 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002246 if (!ASString.empty())
2247 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002248 }
John McCall07daf722016-03-01 22:18:03 +00002249
2250 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 // Objective-C ARC Extension:
2252 //
2253 // <type> ::= U "__strong"
2254 // <type> ::= U "__weak"
2255 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002256 //
2257 // Note: we emit __weak first to preserve the order as
2258 // required by the Itanium ABI.
2259 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2260 mangleVendorQualifier("__weak");
2261
2262 // __unaligned (from -fms-extensions)
2263 if (Quals.hasUnaligned())
2264 mangleVendorQualifier("__unaligned");
2265
2266 // Remaining ARC ownership qualifiers.
2267 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 case Qualifiers::OCL_None:
2269 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002270
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002272 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002274
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002276 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002278
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002280 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002282
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 case Qualifiers::OCL_ExplicitNone:
2284 // The __unsafe_unretained qualifier is *not* mangled, so that
2285 // __unsafe_unretained types in ARC produce the same manglings as the
2286 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2287 // better ABI compatibility.
2288 //
2289 // It's safe to do this because unqualified 'id' won't show up
2290 // in any type signatures that need to be mangled.
2291 break;
2292 }
John McCall07daf722016-03-01 22:18:03 +00002293
2294 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2295 if (Quals.hasRestrict())
2296 Out << 'r';
2297 if (Quals.hasVolatile())
2298 Out << 'V';
2299 if (Quals.hasConst())
2300 Out << 'K';
2301}
2302
2303void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2304 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002305}
2306
2307void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2308 // <ref-qualifier> ::= R # lvalue reference
2309 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 switch (RefQualifier) {
2311 case RQ_None:
2312 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002313
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 case RQ_LValue:
2315 Out << 'R';
2316 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 case RQ_RValue:
2319 Out << 'O';
2320 break;
2321 }
2322}
2323
2324void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2325 Context.mangleObjCMethodName(MD, Out);
2326}
2327
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002328static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2329 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002330 if (Quals)
2331 return true;
2332 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2333 return true;
2334 if (Ty->isOpenCLSpecificType())
2335 return true;
2336 if (Ty->isBuiltinType())
2337 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002338 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2339 // substitution candidates.
2340 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2341 isa<AutoType>(Ty))
2342 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002343 return true;
2344}
2345
Guy Benyei11169dd2012-12-18 14:30:41 +00002346void CXXNameMangler::mangleType(QualType T) {
2347 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002348 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 // Otherwise, use the canonical type.
2350 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002351 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 // mangling rules, since we should really be using the type as written and
2353 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002354 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002356 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 // uniqued, so that we can handle substitutions properly
2358 // - Default template arguments will need to be represented in the
2359 // TemplateSpecializationType, since they need to be mangled even though
2360 // they aren't written.
2361 // - Conversions on non-type template arguments need to be expressed, since
2362 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002363 //
2364 // FIXME: This is wrong when mapping to the canonical type for a dependent
2365 // type discards instantiation-dependent portions of the type, such as for:
2366 //
2367 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2368 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2369 //
2370 // It's also wrong in the opposite direction when instantiation-dependent,
2371 // canonically-equivalent types differ in some irrelevant portion of inner
2372 // type sugar. In such cases, we fail to form correct substitutions, eg:
2373 //
2374 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2375 //
2376 // We should instead canonicalize the non-instantiation-dependent parts,
2377 // regardless of whether the type as a whole is dependent or instantiation
2378 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 if (!T->isInstantiationDependentType() || T->isDependentType())
2380 T = T.getCanonicalType();
2381 else {
2382 // Desugar any types that are purely sugar.
2383 do {
2384 // Don't desugar through template specialization types that aren't
2385 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002386 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 = dyn_cast<TemplateSpecializationType>(T))
2388 if (!TST->isTypeAlias())
2389 break;
2390
Fangrui Song6907ce22018-07-30 19:24:48 +00002391 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 = T.getSingleStepDesugaredType(Context.getASTContext());
2393 if (Desugared == T)
2394 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 T = Desugared;
2397 } while (true);
2398 }
2399 SplitQualType split = T.split();
2400 Qualifiers quals = split.Quals;
2401 const Type *ty = split.Ty;
2402
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002403 bool isSubstitutable =
2404 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 if (isSubstitutable && mangleSubstitution(T))
2406 return;
2407
2408 // If we're mangling a qualified array type, push the qualifiers to
2409 // the element type.
2410 if (quals && isa<ArrayType>(T)) {
2411 ty = Context.getASTContext().getAsArrayType(T);
2412 quals = Qualifiers();
2413
2414 // Note that we don't update T: we want to add the
2415 // substitution at the original type.
2416 }
2417
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002418 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002419 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002420 dyn_cast<DependentAddressSpaceType>(ty)) {
2421 SplitQualType splitDAST = DAST->getPointeeType().split();
2422 mangleQualifiers(splitDAST.Quals, DAST);
2423 mangleType(QualType(splitDAST.Ty, 0));
2424 } else {
2425 mangleQualifiers(quals);
2426
2427 // Recurse: even if the qualified type isn't yet substitutable,
2428 // the unqualified type might be.
2429 mangleType(QualType(ty, 0));
2430 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 } else {
2432 switch (ty->getTypeClass()) {
2433#define ABSTRACT_TYPE(CLASS, PARENT)
2434#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2435 case Type::CLASS: \
2436 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2437 return;
2438#define TYPE(CLASS, PARENT) \
2439 case Type::CLASS: \
2440 mangleType(static_cast<const CLASS##Type*>(ty)); \
2441 break;
2442#include "clang/AST/TypeNodes.def"
2443 }
2444 }
2445
2446 // Add the substitution.
2447 if (isSubstitutable)
2448 addSubstitution(T);
2449}
2450
2451void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2452 if (!mangleStandardSubstitution(ND))
2453 mangleName(ND);
2454}
2455
2456void CXXNameMangler::mangleType(const BuiltinType *T) {
2457 // <type> ::= <builtin-type>
2458 // <builtin-type> ::= v # void
2459 // ::= w # wchar_t
2460 // ::= b # bool
2461 // ::= c # char
2462 // ::= a # signed char
2463 // ::= h # unsigned char
2464 // ::= s # short
2465 // ::= t # unsigned short
2466 // ::= i # int
2467 // ::= j # unsigned int
2468 // ::= l # long
2469 // ::= m # unsigned long
2470 // ::= x # long long, __int64
2471 // ::= y # unsigned long long, __int64
2472 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002473 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 // ::= f # float
2475 // ::= d # double
2476 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002477 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2479 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2480 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2481 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002482 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 // ::= Di # char32_t
2484 // ::= Ds # char16_t
2485 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2486 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002487 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002489 case BuiltinType::Void:
2490 Out << 'v';
2491 break;
2492 case BuiltinType::Bool:
2493 Out << 'b';
2494 break;
2495 case BuiltinType::Char_U:
2496 case BuiltinType::Char_S:
2497 Out << 'c';
2498 break;
2499 case BuiltinType::UChar:
2500 Out << 'h';
2501 break;
2502 case BuiltinType::UShort:
2503 Out << 't';
2504 break;
2505 case BuiltinType::UInt:
2506 Out << 'j';
2507 break;
2508 case BuiltinType::ULong:
2509 Out << 'm';
2510 break;
2511 case BuiltinType::ULongLong:
2512 Out << 'y';
2513 break;
2514 case BuiltinType::UInt128:
2515 Out << 'o';
2516 break;
2517 case BuiltinType::SChar:
2518 Out << 'a';
2519 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002521 case BuiltinType::WChar_U:
2522 Out << 'w';
2523 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002524 case BuiltinType::Char8:
2525 Out << "Du";
2526 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002527 case BuiltinType::Char16:
2528 Out << "Ds";
2529 break;
2530 case BuiltinType::Char32:
2531 Out << "Di";
2532 break;
2533 case BuiltinType::Short:
2534 Out << 's';
2535 break;
2536 case BuiltinType::Int:
2537 Out << 'i';
2538 break;
2539 case BuiltinType::Long:
2540 Out << 'l';
2541 break;
2542 case BuiltinType::LongLong:
2543 Out << 'x';
2544 break;
2545 case BuiltinType::Int128:
2546 Out << 'n';
2547 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002548 case BuiltinType::Float16:
2549 Out << "DF16_";
2550 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002551 case BuiltinType::ShortAccum:
2552 case BuiltinType::Accum:
2553 case BuiltinType::LongAccum:
2554 case BuiltinType::UShortAccum:
2555 case BuiltinType::UAccum:
2556 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002557 case BuiltinType::ShortFract:
2558 case BuiltinType::Fract:
2559 case BuiltinType::LongFract:
2560 case BuiltinType::UShortFract:
2561 case BuiltinType::UFract:
2562 case BuiltinType::ULongFract:
2563 case BuiltinType::SatShortAccum:
2564 case BuiltinType::SatAccum:
2565 case BuiltinType::SatLongAccum:
2566 case BuiltinType::SatUShortAccum:
2567 case BuiltinType::SatUAccum:
2568 case BuiltinType::SatULongAccum:
2569 case BuiltinType::SatShortFract:
2570 case BuiltinType::SatFract:
2571 case BuiltinType::SatLongFract:
2572 case BuiltinType::SatUShortFract:
2573 case BuiltinType::SatUFract:
2574 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002575 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002576 case BuiltinType::Half:
2577 Out << "Dh";
2578 break;
2579 case BuiltinType::Float:
2580 Out << 'f';
2581 break;
2582 case BuiltinType::Double:
2583 Out << 'd';
2584 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002585 case BuiltinType::LongDouble:
2586 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2587 ? 'g'
2588 : 'e');
2589 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002590 case BuiltinType::Float128:
2591 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2592 Out << "U10__float128"; // Match the GCC mangling
2593 else
2594 Out << 'g';
2595 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002596 case BuiltinType::NullPtr:
2597 Out << "Dn";
2598 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002599
2600#define BUILTIN_TYPE(Id, SingletonId)
2601#define PLACEHOLDER_TYPE(Id, SingletonId) \
2602 case BuiltinType::Id:
2603#include "clang/AST/BuiltinTypes.def"
2604 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002605 if (!NullOut)
2606 llvm_unreachable("mangling a placeholder type");
2607 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002608 case BuiltinType::ObjCId:
2609 Out << "11objc_object";
2610 break;
2611 case BuiltinType::ObjCClass:
2612 Out << "10objc_class";
2613 break;
2614 case BuiltinType::ObjCSel:
2615 Out << "13objc_selector";
2616 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002617#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2618 case BuiltinType::Id: \
2619 type_name = "ocl_" #ImgType "_" #Suffix; \
2620 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002621 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002622#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002623 case BuiltinType::OCLSampler:
2624 Out << "11ocl_sampler";
2625 break;
2626 case BuiltinType::OCLEvent:
2627 Out << "9ocl_event";
2628 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002629 case BuiltinType::OCLClkEvent:
2630 Out << "12ocl_clkevent";
2631 break;
2632 case BuiltinType::OCLQueue:
2633 Out << "9ocl_queue";
2634 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002635 case BuiltinType::OCLReserveID:
2636 Out << "13ocl_reserveid";
2637 break;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002638#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2639 case BuiltinType::Id: \
2640 type_name = "ocl_" #ExtType; \
2641 Out << type_name.size() << type_name; \
2642 break;
2643#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00002644 }
2645}
2646
John McCall07daf722016-03-01 22:18:03 +00002647StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2648 switch (CC) {
2649 case CC_C:
2650 return "";
2651
2652 case CC_X86StdCall:
2653 case CC_X86FastCall:
2654 case CC_X86ThisCall:
2655 case CC_X86VectorCall:
2656 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002657 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002658 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002659 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002660 case CC_AAPCS:
2661 case CC_AAPCS_VFP:
2662 case CC_IntelOclBicc:
2663 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002664 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002665 case CC_PreserveMost:
2666 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002667 // FIXME: we should be mangling all of the above.
2668 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002669
2670 case CC_Swift:
2671 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002672 }
2673 llvm_unreachable("bad calling convention");
2674}
2675
2676void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2677 // Fast path.
2678 if (T->getExtInfo() == FunctionType::ExtInfo())
2679 return;
2680
2681 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2682 // This will get more complicated in the future if we mangle other
2683 // things here; but for now, since we mangle ns_returns_retained as
2684 // a qualifier on the result type, we can get away with this:
2685 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2686 if (!CCQualifier.empty())
2687 mangleVendorQualifier(CCQualifier);
2688
2689 // FIXME: regparm
2690 // FIXME: noreturn
2691}
2692
2693void
2694CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2695 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2696
2697 // Note that these are *not* substitution candidates. Demanglers might
2698 // have trouble with this if the parameter type is fully substituted.
2699
John McCall477f2bb2016-03-03 06:39:32 +00002700 switch (PI.getABI()) {
2701 case ParameterABI::Ordinary:
2702 break;
2703
2704 // All of these start with "swift", so they come before "ns_consumed".
2705 case ParameterABI::SwiftContext:
2706 case ParameterABI::SwiftErrorResult:
2707 case ParameterABI::SwiftIndirectResult:
2708 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2709 break;
2710 }
2711
John McCall07daf722016-03-01 22:18:03 +00002712 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002713 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002714
2715 if (PI.isNoEscape())
2716 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002717}
2718
Guy Benyei11169dd2012-12-18 14:30:41 +00002719// <type> ::= <function-type>
2720// <function-type> ::= [<CV-qualifiers>] F [Y]
2721// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002722void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002723 mangleExtFunctionInfo(T);
2724
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2726 // e.g. "const" in "int (A::*)() const".
Reid Kleckner267589a2018-03-08 00:55:09 +00002727 mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002728
Richard Smithfda59e52016-10-26 01:05:54 +00002729 // Mangle instantiation-dependent exception-specification, if present,
2730 // per cxx-abi-dev proposal on 2016-10-11.
2731 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002732 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002733 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002734 mangleExpression(T->getNoexceptExpr());
2735 Out << "E";
2736 } else {
2737 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002738 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002739 for (auto ExceptTy : T->exceptions())
2740 mangleType(ExceptTy);
2741 Out << "E";
2742 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002743 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002744 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002745 }
2746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 Out << 'F';
2748
2749 // FIXME: We don't have enough information in the AST to produce the 'Y'
2750 // encoding for extern "C" function types.
2751 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2752
2753 // Mangle the ref-qualifier, if present.
2754 mangleRefQualifier(T->getRefQualifier());
2755
2756 Out << 'E';
2757}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002758
Guy Benyei11169dd2012-12-18 14:30:41 +00002759void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002760 // Function types without prototypes can arise when mangling a function type
2761 // within an overloadable function in C. We mangle these as the absence of any
2762 // parameter types (not even an empty parameter list).
2763 Out << 'F';
2764
2765 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2766
2767 FunctionTypeDepth.enterResultType();
2768 mangleType(T->getReturnType());
2769 FunctionTypeDepth.leaveResultType();
2770
2771 FunctionTypeDepth.pop(saved);
2772 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002773}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002774
John McCall07daf722016-03-01 22:18:03 +00002775void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002776 bool MangleReturnType,
2777 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 // Record that we're in a function type. See mangleFunctionParam
2779 // for details on what we're trying to achieve here.
2780 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2781
2782 // <bare-function-type> ::= <signature type>+
2783 if (MangleReturnType) {
2784 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002785
2786 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002787 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002788 mangleVendorQualifier("ns_returns_retained");
2789
2790 // Mangle the return type without any direct ARC ownership qualifiers.
2791 QualType ReturnTy = Proto->getReturnType();
2792 if (ReturnTy.getObjCLifetime()) {
2793 auto SplitReturnTy = ReturnTy.split();
2794 SplitReturnTy.Quals.removeObjCLifetime();
2795 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2796 }
2797 mangleType(ReturnTy);
2798
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 FunctionTypeDepth.leaveResultType();
2800 }
2801
Alp Toker9cacbab2014-01-20 20:26:09 +00002802 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 // <builtin-type> ::= v # void
2804 Out << 'v';
2805
2806 FunctionTypeDepth.pop(saved);
2807 return;
2808 }
2809
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002810 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2811 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002812 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002813 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002814 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2815 }
2816
2817 // Mangle the type.
2818 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002819 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2820
2821 if (FD) {
2822 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2823 // Attr can only take 1 character, so we can hardcode the length below.
2824 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2825 Out << "U17pass_object_size" << Attr->getType();
2826 }
2827 }
2828 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002829
2830 FunctionTypeDepth.pop(saved);
2831
2832 // <builtin-type> ::= z # ellipsis
2833 if (Proto->isVariadic())
2834 Out << 'z';
2835}
2836
2837// <type> ::= <class-enum-type>
2838// <class-enum-type> ::= <name>
2839void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2840 mangleName(T->getDecl());
2841}
2842
2843// <type> ::= <class-enum-type>
2844// <class-enum-type> ::= <name>
2845void CXXNameMangler::mangleType(const EnumType *T) {
2846 mangleType(static_cast<const TagType*>(T));
2847}
2848void CXXNameMangler::mangleType(const RecordType *T) {
2849 mangleType(static_cast<const TagType*>(T));
2850}
2851void CXXNameMangler::mangleType(const TagType *T) {
2852 mangleName(T->getDecl());
2853}
2854
2855// <type> ::= <array-type>
2856// <array-type> ::= A <positive dimension number> _ <element type>
2857// ::= A [<dimension expression>] _ <element type>
2858void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2859 Out << 'A' << T->getSize() << '_';
2860 mangleType(T->getElementType());
2861}
2862void CXXNameMangler::mangleType(const VariableArrayType *T) {
2863 Out << 'A';
2864 // decayed vla types (size 0) will just be skipped.
2865 if (T->getSizeExpr())
2866 mangleExpression(T->getSizeExpr());
2867 Out << '_';
2868 mangleType(T->getElementType());
2869}
2870void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2871 Out << 'A';
2872 mangleExpression(T->getSizeExpr());
2873 Out << '_';
2874 mangleType(T->getElementType());
2875}
2876void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2877 Out << "A_";
2878 mangleType(T->getElementType());
2879}
2880
2881// <type> ::= <pointer-to-member-type>
2882// <pointer-to-member-type> ::= M <class type> <member type>
2883void CXXNameMangler::mangleType(const MemberPointerType *T) {
2884 Out << 'M';
2885 mangleType(QualType(T->getClass(), 0));
2886 QualType PointeeType = T->getPointeeType();
2887 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2888 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002889
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 // Itanium C++ ABI 5.1.8:
2891 //
2892 // The type of a non-static member function is considered to be different,
2893 // for the purposes of substitution, from the type of a namespace-scope or
2894 // static member function whose type appears similar. The types of two
2895 // non-static member functions are considered to be different, for the
2896 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002897 // classes. In other words, for the purposes of substitution, the class of
2898 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 // function.
2900
2901 // Given that we already substitute member function pointers as a
2902 // whole, the net effect of this rule is just to unconditionally
2903 // suppress substitution on the function type in a member pointer.
2904 // We increment the SeqID here to emulate adding an entry to the
2905 // substitution table.
2906 ++SeqID;
2907 } else
2908 mangleType(PointeeType);
2909}
2910
2911// <type> ::= <template-param>
2912void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2913 mangleTemplateParameter(T->getIndex());
2914}
2915
2916// <type> ::= <template-param>
2917void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2918 // FIXME: not clear how to mangle this!
2919 // template <class T...> class A {
2920 // template <class U...> void foo(T(*)(U) x...);
2921 // };
2922 Out << "_SUBSTPACK_";
2923}
2924
2925// <type> ::= P <type> # pointer-to
2926void CXXNameMangler::mangleType(const PointerType *T) {
2927 Out << 'P';
2928 mangleType(T->getPointeeType());
2929}
2930void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2931 Out << 'P';
2932 mangleType(T->getPointeeType());
2933}
2934
2935// <type> ::= R <type> # reference-to
2936void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2937 Out << 'R';
2938 mangleType(T->getPointeeType());
2939}
2940
2941// <type> ::= O <type> # rvalue reference-to (C++0x)
2942void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2943 Out << 'O';
2944 mangleType(T->getPointeeType());
2945}
2946
2947// <type> ::= C <type> # complex pair (C 2000)
2948void CXXNameMangler::mangleType(const ComplexType *T) {
2949 Out << 'C';
2950 mangleType(T->getElementType());
2951}
2952
2953// ARM's ABI for Neon vector types specifies that they should be mangled as
2954// if they are structs (to match ARM's initial implementation). The
2955// vector type must be one of the special types predefined by ARM.
2956void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2957 QualType EltType = T->getElementType();
2958 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002959 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2961 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002962 case BuiltinType::SChar:
2963 case BuiltinType::UChar:
2964 EltName = "poly8_t";
2965 break;
2966 case BuiltinType::Short:
2967 case BuiltinType::UShort:
2968 EltName = "poly16_t";
2969 break;
2970 case BuiltinType::ULongLong:
2971 EltName = "poly64_t";
2972 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2974 }
2975 } else {
2976 switch (cast<BuiltinType>(EltType)->getKind()) {
2977 case BuiltinType::SChar: EltName = "int8_t"; break;
2978 case BuiltinType::UChar: EltName = "uint8_t"; break;
2979 case BuiltinType::Short: EltName = "int16_t"; break;
2980 case BuiltinType::UShort: EltName = "uint16_t"; break;
2981 case BuiltinType::Int: EltName = "int32_t"; break;
2982 case BuiltinType::UInt: EltName = "uint32_t"; break;
2983 case BuiltinType::LongLong: EltName = "int64_t"; break;
2984 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002985 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002987 case BuiltinType::Half: EltName = "float16_t";break;
2988 default:
2989 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 }
2991 }
Craig Topper36250ad2014-05-12 05:36:57 +00002992 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 unsigned BitSize = (T->getNumElements() *
2994 getASTContext().getTypeSize(EltType));
2995 if (BitSize == 64)
2996 BaseName = "__simd64_";
2997 else {
2998 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2999 BaseName = "__simd128_";
3000 }
3001 Out << strlen(BaseName) + strlen(EltName);
3002 Out << BaseName << EltName;
3003}
3004
Erich Keanef702b022018-07-13 19:46:04 +00003005void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3006 DiagnosticsEngine &Diags = Context.getDiags();
3007 unsigned DiagID = Diags.getCustomDiagID(
3008 DiagnosticsEngine::Error,
3009 "cannot mangle this dependent neon vector type yet");
3010 Diags.Report(T->getAttributeLoc(), DiagID);
3011}
3012
Tim Northover2fe823a2013-08-01 09:23:19 +00003013static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3014 switch (EltType->getKind()) {
3015 case BuiltinType::SChar:
3016 return "Int8";
3017 case BuiltinType::Short:
3018 return "Int16";
3019 case BuiltinType::Int:
3020 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003021 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003022 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003023 return "Int64";
3024 case BuiltinType::UChar:
3025 return "Uint8";
3026 case BuiltinType::UShort:
3027 return "Uint16";
3028 case BuiltinType::UInt:
3029 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003030 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003031 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003032 return "Uint64";
3033 case BuiltinType::Half:
3034 return "Float16";
3035 case BuiltinType::Float:
3036 return "Float32";
3037 case BuiltinType::Double:
3038 return "Float64";
3039 default:
3040 llvm_unreachable("Unexpected vector element base type");
3041 }
3042}
3043
3044// AArch64's ABI for Neon vector types specifies that they should be mangled as
3045// the equivalent internal name. The vector type must be one of the special
3046// types predefined by ARM.
3047void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3048 QualType EltType = T->getElementType();
3049 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3050 unsigned BitSize =
3051 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003052 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003053
3054 assert((BitSize == 64 || BitSize == 128) &&
3055 "Neon vector type not 64 or 128 bits");
3056
Tim Northover2fe823a2013-08-01 09:23:19 +00003057 StringRef EltName;
3058 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3059 switch (cast<BuiltinType>(EltType)->getKind()) {
3060 case BuiltinType::UChar:
3061 EltName = "Poly8";
3062 break;
3063 case BuiltinType::UShort:
3064 EltName = "Poly16";
3065 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003066 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003067 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003068 EltName = "Poly64";
3069 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003070 default:
3071 llvm_unreachable("unexpected Neon polynomial vector element type");
3072 }
3073 } else
3074 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3075
3076 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003077 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003078 Out << TypeName.length() << TypeName;
3079}
Erich Keanef702b022018-07-13 19:46:04 +00003080void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3081 DiagnosticsEngine &Diags = Context.getDiags();
3082 unsigned DiagID = Diags.getCustomDiagID(
3083 DiagnosticsEngine::Error,
3084 "cannot mangle this dependent neon vector type yet");
3085 Diags.Report(T->getAttributeLoc(), DiagID);
3086}
Tim Northover2fe823a2013-08-01 09:23:19 +00003087
Guy Benyei11169dd2012-12-18 14:30:41 +00003088// GNU extension: vector types
3089// <type> ::= <vector-type>
3090// <vector-type> ::= Dv <positive dimension number> _
3091// <extended element type>
3092// ::= Dv [<dimension expression>] _ <element type>
3093// <extended element type> ::= <element type>
3094// ::= p # AltiVec vector pixel
3095// ::= b # Altivec vector bool
3096void CXXNameMangler::mangleType(const VectorType *T) {
3097 if ((T->getVectorKind() == VectorType::NeonVector ||
3098 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003099 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003100 llvm::Triple::ArchType Arch =
3101 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003102 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003103 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003104 mangleAArch64NeonVectorType(T);
3105 else
3106 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 return;
3108 }
3109 Out << "Dv" << T->getNumElements() << '_';
3110 if (T->getVectorKind() == VectorType::AltiVecPixel)
3111 Out << 'p';
3112 else if (T->getVectorKind() == VectorType::AltiVecBool)
3113 Out << 'b';
3114 else
3115 mangleType(T->getElementType());
3116}
Erich Keanef702b022018-07-13 19:46:04 +00003117
3118void CXXNameMangler::mangleType(const DependentVectorType *T) {
3119 if ((T->getVectorKind() == VectorType::NeonVector ||
3120 T->getVectorKind() == VectorType::NeonPolyVector)) {
3121 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3122 llvm::Triple::ArchType Arch =
3123 getASTContext().getTargetInfo().getTriple().getArch();
3124 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3125 !Target.isOSDarwin())
3126 mangleAArch64NeonVectorType(T);
3127 else
3128 mangleNeonVectorType(T);
3129 return;
3130 }
3131
3132 Out << "Dv";
3133 mangleExpression(T->getSizeExpr());
3134 Out << '_';
3135 if (T->getVectorKind() == VectorType::AltiVecPixel)
3136 Out << 'p';
3137 else if (T->getVectorKind() == VectorType::AltiVecBool)
3138 Out << 'b';
3139 else
3140 mangleType(T->getElementType());
3141}
3142
Guy Benyei11169dd2012-12-18 14:30:41 +00003143void CXXNameMangler::mangleType(const ExtVectorType *T) {
3144 mangleType(static_cast<const VectorType*>(T));
3145}
3146void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3147 Out << "Dv";
3148 mangleExpression(T->getSizeExpr());
3149 Out << '_';
3150 mangleType(T->getElementType());
3151}
3152
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003153void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3154 SplitQualType split = T->getPointeeType().split();
3155 mangleQualifiers(split.Quals, T);
3156 mangleType(QualType(split.Ty, 0));
3157}
3158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159void CXXNameMangler::mangleType(const PackExpansionType *T) {
3160 // <type> ::= Dp <type> # pack expansion (C++0x)
3161 Out << "Dp";
3162 mangleType(T->getPattern());
3163}
3164
3165void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3166 mangleSourceName(T->getDecl()->getIdentifier());
3167}
3168
3169void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003170 // Treat __kindof as a vendor extended type qualifier.
3171 if (T->isKindOfType())
3172 Out << "U8__kindof";
3173
Eli Friedman5f508952013-06-18 22:41:37 +00003174 if (!T->qual_empty()) {
3175 // Mangle protocol qualifiers.
3176 SmallString<64> QualStr;
3177 llvm::raw_svector_ostream QualOS(QualStr);
3178 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003179 for (const auto *I : T->quals()) {
3180 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003181 QualOS << name.size() << name;
3182 }
Eli Friedman5f508952013-06-18 22:41:37 +00003183 Out << 'U' << QualStr.size() << QualStr;
3184 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003185
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003187
3188 if (T->isSpecialized()) {
3189 // Mangle type arguments as I <type>+ E
3190 Out << 'I';
3191 for (auto typeArg : T->getTypeArgs())
3192 mangleType(typeArg);
3193 Out << 'E';
3194 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003195}
3196
3197void CXXNameMangler::mangleType(const BlockPointerType *T) {
3198 Out << "U13block_pointer";
3199 mangleType(T->getPointeeType());
3200}
3201
3202void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3203 // Mangle injected class name types as if the user had written the
3204 // specialization out fully. It may not actually be possible to see
3205 // this mangling, though.
3206 mangleType(T->getInjectedSpecializationType());
3207}
3208
3209void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3210 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003211 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 } else {
3213 if (mangleSubstitution(QualType(T, 0)))
3214 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003215
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003217
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 // FIXME: GCC does not appear to mangle the template arguments when
3219 // the template in question is a dependent template name. Should we
3220 // emulate that badness?
3221 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3222 addSubstitution(QualType(T, 0));
3223 }
3224}
3225
3226void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003227 // Proposal by cxx-abi-dev, 2014-03-26
3228 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3229 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003230 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003231 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003232 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003233 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003234 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003235 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003236 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003237 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003238 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003239 case ETK_Typename:
3240 break;
3241 case ETK_Struct:
3242 case ETK_Class:
3243 case ETK_Interface:
3244 Out << "Ts";
3245 break;
3246 case ETK_Union:
3247 Out << "Tu";
3248 break;
3249 case ETK_Enum:
3250 Out << "Te";
3251 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003252 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003253 // Typename types are always nested
3254 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003256 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 Out << 'E';
3258}
3259
3260void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3261 // Dependently-scoped template types are nested if they have a prefix.
3262 Out << 'N';
3263
3264 // TODO: avoid making this TemplateName.
3265 TemplateName Prefix =
3266 getASTContext().getDependentTemplateName(T->getQualifier(),
3267 T->getIdentifier());
3268 mangleTemplatePrefix(Prefix);
3269
3270 // FIXME: GCC does not appear to mangle the template arguments when
3271 // the template in question is a dependent template name. Should we
3272 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003273 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 Out << 'E';
3275}
3276
3277void CXXNameMangler::mangleType(const TypeOfType *T) {
3278 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3279 // "extension with parameters" mangling.
3280 Out << "u6typeof";
3281}
3282
3283void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3284 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3285 // "extension with parameters" mangling.
3286 Out << "u6typeof";
3287}
3288
3289void CXXNameMangler::mangleType(const DecltypeType *T) {
3290 Expr *E = T->getUnderlyingExpr();
3291
3292 // type ::= Dt <expression> E # decltype of an id-expression
3293 // # or class member access
3294 // ::= DT <expression> E # decltype of an expression
3295
3296 // This purports to be an exhaustive list of id-expressions and
3297 // class member accesses. Note that we do not ignore parentheses;
3298 // parentheses change the semantics of decltype for these
3299 // expressions (and cause the mangler to use the other form).
3300 if (isa<DeclRefExpr>(E) ||
3301 isa<MemberExpr>(E) ||
3302 isa<UnresolvedLookupExpr>(E) ||
3303 isa<DependentScopeDeclRefExpr>(E) ||
3304 isa<CXXDependentScopeMemberExpr>(E) ||
3305 isa<UnresolvedMemberExpr>(E))
3306 Out << "Dt";
3307 else
3308 Out << "DT";
3309 mangleExpression(E);
3310 Out << 'E';
3311}
3312
3313void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3314 // If this is dependent, we need to record that. If not, we simply
3315 // mangle it as the underlying type since they are equivalent.
3316 if (T->isDependentType()) {
3317 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 switch (T->getUTTKind()) {
3320 case UnaryTransformType::EnumUnderlyingType:
3321 Out << "3eut";
3322 break;
3323 }
3324 }
3325
David Majnemer140065a2016-06-08 00:34:15 +00003326 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003327}
3328
3329void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003330 assert(T->getDeducedType().isNull() &&
3331 "Deduced AutoType shouldn't be handled here!");
3332 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3333 "shouldn't need to mangle __auto_type!");
3334 // <builtin-type> ::= Da # auto
3335 // ::= Dc # decltype(auto)
3336 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003337}
3338
Richard Smith600b5262017-01-26 20:40:47 +00003339void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3340 // FIXME: This is not the right mangling. We also need to include a scope
3341 // here in some cases.
3342 QualType D = T->getDeducedType();
3343 if (D.isNull())
3344 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3345 else
3346 mangleType(D);
3347}
3348
Guy Benyei11169dd2012-12-18 14:30:41 +00003349void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003350 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 // (Until there's a standardized mangling...)
3352 Out << "U7_Atomic";
3353 mangleType(T->getValueType());
3354}
3355
Xiuli Pan9c14e282016-01-09 12:53:17 +00003356void CXXNameMangler::mangleType(const PipeType *T) {
3357 // Pipe type mangling rules are described in SPIR 2.0 specification
3358 // A.1 Data types and A.3 Summary of changes
3359 // <type> ::= 8ocl_pipe
3360 Out << "8ocl_pipe";
3361}
3362
Guy Benyei11169dd2012-12-18 14:30:41 +00003363void CXXNameMangler::mangleIntegerLiteral(QualType T,
3364 const llvm::APSInt &Value) {
3365 // <expr-primary> ::= L <type> <value number> E # integer literal
3366 Out << 'L';
3367
3368 mangleType(T);
3369 if (T->isBooleanType()) {
3370 // Boolean values are encoded as 0/1.
3371 Out << (Value.getBoolValue() ? '1' : '0');
3372 } else {
3373 mangleNumber(Value);
3374 }
3375 Out << 'E';
3376
3377}
3378
David Majnemer1dabfdc2015-02-14 13:23:54 +00003379void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3380 // Ignore member expressions involving anonymous unions.
3381 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3382 if (!RT->getDecl()->isAnonymousStructOrUnion())
3383 break;
3384 const auto *ME = dyn_cast<MemberExpr>(Base);
3385 if (!ME)
3386 break;
3387 Base = ME->getBase();
3388 IsArrow = ME->isArrow();
3389 }
3390
3391 if (Base->isImplicitCXXThis()) {
3392 // Note: GCC mangles member expressions to the implicit 'this' as
3393 // *this., whereas we represent them as this->. The Itanium C++ ABI
3394 // does not specify anything here, so we follow GCC.
3395 Out << "dtdefpT";
3396 } else {
3397 Out << (IsArrow ? "pt" : "dt");
3398 mangleExpression(Base);
3399 }
3400}
3401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402/// Mangles a member expression.
3403void CXXNameMangler::mangleMemberExpr(const Expr *base,
3404 bool isArrow,
3405 NestedNameSpecifier *qualifier,
3406 NamedDecl *firstQualifierLookup,
3407 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003408 const TemplateArgumentLoc *TemplateArgs,
3409 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 unsigned arity) {
3411 // <expression> ::= dt <expression> <unresolved-name>
3412 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003413 if (base)
3414 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003415 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003416}
3417
3418/// Look at the callee of the given call expression and determine if
3419/// it's a parenthesized id-expression which would have triggered ADL
3420/// otherwise.
3421static bool isParenthesizedADLCallee(const CallExpr *call) {
3422 const Expr *callee = call->getCallee();
3423 const Expr *fn = callee->IgnoreParens();
3424
3425 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3426 // too, but for those to appear in the callee, it would have to be
3427 // parenthesized.
3428 if (callee == fn) return false;
3429
3430 // Must be an unresolved lookup.
3431 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3432 if (!lookup) return false;
3433
3434 assert(!lookup->requiresADL());
3435
3436 // Must be an unqualified lookup.
3437 if (lookup->getQualifier()) return false;
3438
3439 // Must not have found a class member. Note that if one is a class
3440 // member, they're all class members.
3441 if (lookup->getNumDecls() > 0 &&
3442 (*lookup->decls_begin())->isCXXClassMember())
3443 return false;
3444
3445 // Otherwise, ADL would have been triggered.
3446 return true;
3447}
3448
David Majnemer9c775c72014-09-23 04:27:55 +00003449void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3450 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3451 Out << CastEncoding;
3452 mangleType(ECE->getType());
3453 mangleExpression(ECE->getSubExpr());
3454}
3455
Richard Smith520449d2015-02-05 06:15:50 +00003456void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3457 if (auto *Syntactic = InitList->getSyntacticForm())
3458 InitList = Syntactic;
3459 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3460 mangleExpression(InitList->getInit(i));
3461}
3462
Guy Benyei11169dd2012-12-18 14:30:41 +00003463void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3464 // <expression> ::= <unary operator-name> <expression>
3465 // ::= <binary operator-name> <expression> <expression>
3466 // ::= <trinary operator-name> <expression> <expression> <expression>
3467 // ::= cv <type> expression # conversion with one argument
3468 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003469 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3470 // ::= sc <type> <expression> # static_cast<type> (expression)
3471 // ::= cc <type> <expression> # const_cast<type> (expression)
3472 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 // ::= st <type> # sizeof (a type)
3474 // ::= at <type> # alignof (a type)
3475 // ::= <template-param>
3476 // ::= <function-param>
3477 // ::= sr <type> <unqualified-name> # dependent name
3478 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3479 // ::= ds <expression> <expression> # expr.*expr
3480 // ::= sZ <template-param> # size of a parameter pack
3481 // ::= sZ <function-param> # size of a function parameter pack
3482 // ::= <expr-primary>
3483 // <expr-primary> ::= L <type> <value number> E # integer literal
3484 // ::= L <type <value float> E # floating literal
3485 // ::= L <mangled-name> E # external name
3486 // ::= fpT # 'this' expression
3487 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003488
Guy Benyei11169dd2012-12-18 14:30:41 +00003489recurse:
3490 switch (E->getStmtClass()) {
3491 case Expr::NoStmtClass:
3492#define ABSTRACT_STMT(Type)
3493#define EXPR(Type, Base)
3494#define STMT(Type, Base) \
3495 case Expr::Type##Class:
3496#include "clang/AST/StmtNodes.inc"
3497 // fallthrough
3498
3499 // These all can only appear in local or variable-initialization
3500 // contexts and so should never appear in a mangling.
3501 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003502 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003504 case Expr::ArrayInitLoopExprClass:
3505 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003506 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 case Expr::ParenListExprClass:
3508 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003509 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003510 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003511 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003512 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003513 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 llvm_unreachable("unexpected statement kind");
3515
Bill Wendling7c44da22018-10-31 03:48:47 +00003516 case Expr::ConstantExprClass:
3517 E = cast<ConstantExpr>(E)->getSubExpr();
3518 goto recurse;
3519
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 // FIXME: invent manglings for all these.
3521 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 case Expr::ChooseExprClass:
3523 case Expr::CompoundLiteralExprClass:
3524 case Expr::ExtVectorElementExprClass:
3525 case Expr::GenericSelectionExprClass:
3526 case Expr::ObjCEncodeExprClass:
3527 case Expr::ObjCIsaExprClass:
3528 case Expr::ObjCIvarRefExprClass:
3529 case Expr::ObjCMessageExprClass:
3530 case Expr::ObjCPropertyRefExprClass:
3531 case Expr::ObjCProtocolExprClass:
3532 case Expr::ObjCSelectorExprClass:
3533 case Expr::ObjCStringLiteralClass:
3534 case Expr::ObjCBoxedExprClass:
3535 case Expr::ObjCArrayLiteralClass:
3536 case Expr::ObjCDictionaryLiteralClass:
3537 case Expr::ObjCSubscriptRefExprClass:
3538 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003539 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 case Expr::OffsetOfExprClass:
3541 case Expr::PredefinedExprClass:
3542 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003543 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 case Expr::TypeTraitExprClass:
3546 case Expr::ArrayTypeTraitExprClass:
3547 case Expr::ExpressionTraitExprClass:
3548 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 case Expr::CUDAKernelCallExprClass:
3550 case Expr::AsTypeExprClass:
3551 case Expr::PseudoObjectExprClass:
3552 case Expr::AtomicExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003553 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003555 if (!NullOut) {
3556 // As bad as this diagnostic is, it's better than crashing.
3557 DiagnosticsEngine &Diags = Context.getDiags();
3558 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3559 "cannot yet mangle expression type %0");
3560 Diags.Report(E->getExprLoc(), DiagID)
3561 << E->getStmtClassName() << E->getSourceRange();
3562 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 break;
3564 }
3565
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003566 case Expr::CXXUuidofExprClass: {
3567 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3568 if (UE->isTypeOperand()) {
3569 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3570 Out << "u8__uuidoft";
3571 mangleType(UuidT);
3572 } else {
3573 Expr *UuidExp = UE->getExprOperand();
3574 Out << "u8__uuidofz";
3575 mangleExpression(UuidExp, Arity);
3576 }
3577 break;
3578 }
3579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 // Even gcc-4.5 doesn't mangle this.
3581 case Expr::BinaryConditionalOperatorClass: {
3582 DiagnosticsEngine &Diags = Context.getDiags();
3583 unsigned DiagID =
3584 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3585 "?: operator with omitted middle operand cannot be mangled");
3586 Diags.Report(E->getExprLoc(), DiagID)
3587 << E->getStmtClassName() << E->getSourceRange();
3588 break;
3589 }
3590
3591 // These are used for internal purposes and cannot be meaningfully mangled.
3592 case Expr::OpaqueValueExprClass:
3593 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3594
3595 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003596 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003597 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 Out << "E";
3599 break;
3600 }
3601
Richard Smith39eca9b2017-08-23 22:12:08 +00003602 case Expr::DesignatedInitExprClass: {
3603 auto *DIE = cast<DesignatedInitExpr>(E);
3604 for (const auto &Designator : DIE->designators()) {
3605 if (Designator.isFieldDesignator()) {
3606 Out << "di";
3607 mangleSourceName(Designator.getFieldName());
3608 } else if (Designator.isArrayDesignator()) {
3609 Out << "dx";
3610 mangleExpression(DIE->getArrayIndex(Designator));
3611 } else {
3612 assert(Designator.isArrayRangeDesignator() &&
3613 "unknown designator kind");
3614 Out << "dX";
3615 mangleExpression(DIE->getArrayRangeStart(Designator));
3616 mangleExpression(DIE->getArrayRangeEnd(Designator));
3617 }
3618 }
3619 mangleExpression(DIE->getInit());
3620 break;
3621 }
3622
Guy Benyei11169dd2012-12-18 14:30:41 +00003623 case Expr::CXXDefaultArgExprClass:
3624 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3625 break;
3626
Richard Smith852c9db2013-04-20 22:23:05 +00003627 case Expr::CXXDefaultInitExprClass:
3628 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3629 break;
3630
Richard Smithcc1b96d2013-06-12 22:31:48 +00003631 case Expr::CXXStdInitializerListExprClass:
3632 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3633 break;
3634
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 case Expr::SubstNonTypeTemplateParmExprClass:
3636 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3637 Arity);
3638 break;
3639
3640 case Expr::UserDefinedLiteralClass:
3641 // We follow g++'s approach of mangling a UDL as a call to the literal
3642 // operator.
3643 case Expr::CXXMemberCallExprClass: // fallthrough
3644 case Expr::CallExprClass: {
3645 const CallExpr *CE = cast<CallExpr>(E);
3646
3647 // <expression> ::= cp <simple-id> <expression>* E
3648 // We use this mangling only when the call would use ADL except
3649 // for being parenthesized. Per discussion with David
3650 // Vandervoorde, 2011.04.25.
3651 if (isParenthesizedADLCallee(CE)) {
3652 Out << "cp";
3653 // The callee here is a parenthesized UnresolvedLookupExpr with
3654 // no qualifier and should always get mangled as a <simple-id>
3655 // anyway.
3656
3657 // <expression> ::= cl <expression>* E
3658 } else {
3659 Out << "cl";
3660 }
3661
David Majnemer67a8ec62015-02-19 21:41:48 +00003662 unsigned CallArity = CE->getNumArgs();
3663 for (const Expr *Arg : CE->arguments())
3664 if (isa<PackExpansionExpr>(Arg))
3665 CallArity = UnknownArity;
3666
3667 mangleExpression(CE->getCallee(), CallArity);
3668 for (const Expr *Arg : CE->arguments())
3669 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 Out << 'E';
3671 break;
3672 }
3673
3674 case Expr::CXXNewExprClass: {
3675 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3676 if (New->isGlobalNew()) Out << "gs";
3677 Out << (New->isArray() ? "na" : "nw");
3678 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3679 E = New->placement_arg_end(); I != E; ++I)
3680 mangleExpression(*I);
3681 Out << '_';
3682 mangleType(New->getAllocatedType());
3683 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3685 Out << "il";
3686 else
3687 Out << "pi";
3688 const Expr *Init = New->getInitializer();
3689 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3690 // Directly inline the initializers.
3691 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3692 E = CCE->arg_end();
3693 I != E; ++I)
3694 mangleExpression(*I);
3695 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3696 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3697 mangleExpression(PLE->getExpr(i));
3698 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3699 isa<InitListExpr>(Init)) {
3700 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003701 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003702 } else
3703 mangleExpression(Init);
3704 }
3705 Out << 'E';
3706 break;
3707 }
3708
David Majnemer1dabfdc2015-02-14 13:23:54 +00003709 case Expr::CXXPseudoDestructorExprClass: {
3710 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3711 if (const Expr *Base = PDE->getBase())
3712 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003713 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003714 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3715 if (Qualifier) {
3716 mangleUnresolvedPrefix(Qualifier,
3717 /*Recursive=*/true);
3718 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3719 Out << 'E';
3720 } else {
3721 Out << "sr";
3722 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3723 Out << 'E';
3724 }
3725 } else if (Qualifier) {
3726 mangleUnresolvedPrefix(Qualifier);
3727 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003728 // <base-unresolved-name> ::= dn <destructor-name>
3729 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003730 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003731 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003732 break;
3733 }
3734
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 case Expr::MemberExprClass: {
3736 const MemberExpr *ME = cast<MemberExpr>(E);
3737 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003738 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003739 ME->getMemberDecl()->getDeclName(),
3740 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3741 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 break;
3743 }
3744
3745 case Expr::UnresolvedMemberExprClass: {
3746 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003747 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3748 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003749 ME->getMemberName(),
3750 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3751 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 break;
3753 }
3754
3755 case Expr::CXXDependentScopeMemberExprClass: {
3756 const CXXDependentScopeMemberExpr *ME
3757 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003758 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3759 ME->isArrow(), ME->getQualifier(),
3760 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003761 ME->getMember(),
3762 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3763 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 break;
3765 }
3766
3767 case Expr::UnresolvedLookupExprClass: {
3768 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003769 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3770 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3771 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003772 break;
3773 }
3774
3775 case Expr::CXXUnresolvedConstructExprClass: {
3776 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3777 unsigned N = CE->arg_size();
3778
Richard Smith39eca9b2017-08-23 22:12:08 +00003779 if (CE->isListInitialization()) {
3780 assert(N == 1 && "unexpected form for list initialization");
3781 auto *IL = cast<InitListExpr>(CE->getArg(0));
3782 Out << "tl";
3783 mangleType(CE->getType());
3784 mangleInitListElements(IL);
3785 Out << "E";
3786 return;
3787 }
3788
Guy Benyei11169dd2012-12-18 14:30:41 +00003789 Out << "cv";
3790 mangleType(CE->getType());
3791 if (N != 1) Out << '_';
3792 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3793 if (N != 1) Out << 'E';
3794 break;
3795 }
3796
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003798 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003799 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003800 assert(
3801 CE->getNumArgs() >= 1 &&
3802 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3803 "implicit CXXConstructExpr must have one argument");
3804 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3805 }
3806 Out << "il";
3807 for (auto *E : CE->arguments())
3808 mangleExpression(E);
3809 Out << "E";
3810 break;
3811 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003812
Richard Smith520449d2015-02-05 06:15:50 +00003813 case Expr::CXXTemporaryObjectExprClass: {
3814 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3815 unsigned N = CE->getNumArgs();
3816 bool List = CE->isListInitialization();
3817
3818 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 Out << "tl";
3820 else
3821 Out << "cv";
3822 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003823 if (!List && N != 1)
3824 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003825 if (CE->isStdInitListInitialization()) {
3826 // We implicitly created a std::initializer_list<T> for the first argument
3827 // of a constructor of type U in an expression of the form U{a, b, c}.
3828 // Strip all the semantic gunk off the initializer list.
3829 auto *SILE =
3830 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3831 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3832 mangleInitListElements(ILE);
3833 } else {
3834 for (auto *E : CE->arguments())
3835 mangleExpression(E);
3836 }
Richard Smith520449d2015-02-05 06:15:50 +00003837 if (List || N != 1)
3838 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 break;
3840 }
3841
3842 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003843 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003845 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 break;
3847
3848 case Expr::CXXNoexceptExprClass:
3849 Out << "nx";
3850 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3851 break;
3852
3853 case Expr::UnaryExprOrTypeTraitExprClass: {
3854 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003855
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 if (!SAE->isInstantiationDependent()) {
3857 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003858 // If the operand of a sizeof or alignof operator is not
3859 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003860 // reflecting the result of the operator.
3861 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003862 // If the result of the operator is implicitly converted to a known
3863 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003864 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003865 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3867 : ImplicitlyConvertedToType;
3868 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3869 mangleIntegerLiteral(T, V);
3870 break;
3871 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003872
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 switch(SAE->getKind()) {
3874 case UETT_SizeOf:
3875 Out << 's';
3876 break;
Richard Smith6822bd72018-10-26 19:26:45 +00003877 case UETT_PreferredAlignOf:
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 case UETT_AlignOf:
3879 Out << 'a';
3880 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003881 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 DiagnosticsEngine &Diags = Context.getDiags();
3883 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3884 "cannot yet mangle vec_step expression");
3885 Diags.Report(DiagID);
3886 return;
3887 }
Alexey Bataev00396512015-07-02 03:40:19 +00003888 case UETT_OpenMPRequiredSimdAlign:
3889 DiagnosticsEngine &Diags = Context.getDiags();
3890 unsigned DiagID = Diags.getCustomDiagID(
3891 DiagnosticsEngine::Error,
3892 "cannot yet mangle __builtin_omp_required_simd_align expression");
3893 Diags.Report(DiagID);
3894 return;
3895 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 if (SAE->isArgumentType()) {
3897 Out << 't';
3898 mangleType(SAE->getArgumentType());
3899 } else {
3900 Out << 'z';
3901 mangleExpression(SAE->getArgumentExpr());
3902 }
3903 break;
3904 }
3905
3906 case Expr::CXXThrowExprClass: {
3907 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003908 // <expression> ::= tw <expression> # throw expression
3909 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 if (TE->getSubExpr()) {
3911 Out << "tw";
3912 mangleExpression(TE->getSubExpr());
3913 } else {
3914 Out << "tr";
3915 }
3916 break;
3917 }
3918
3919 case Expr::CXXTypeidExprClass: {
3920 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003921 // <expression> ::= ti <type> # typeid (type)
3922 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 if (TIE->isTypeOperand()) {
3924 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003925 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 } else {
3927 Out << "te";
3928 mangleExpression(TIE->getExprOperand());
3929 }
3930 break;
3931 }
3932
3933 case Expr::CXXDeleteExprClass: {
3934 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003935 // <expression> ::= [gs] dl <expression> # [::] delete expr
3936 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 if (DE->isGlobalDelete()) Out << "gs";
3938 Out << (DE->isArrayForm() ? "da" : "dl");
3939 mangleExpression(DE->getArgument());
3940 break;
3941 }
3942
3943 case Expr::UnaryOperatorClass: {
3944 const UnaryOperator *UO = cast<UnaryOperator>(E);
3945 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3946 /*Arity=*/1);
3947 mangleExpression(UO->getSubExpr());
3948 break;
3949 }
3950
3951 case Expr::ArraySubscriptExprClass: {
3952 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3953
3954 // Array subscript is treated as a syntactically weird form of
3955 // binary operator.
3956 Out << "ix";
3957 mangleExpression(AE->getLHS());
3958 mangleExpression(AE->getRHS());
3959 break;
3960 }
3961
3962 case Expr::CompoundAssignOperatorClass: // fallthrough
3963 case Expr::BinaryOperatorClass: {
3964 const BinaryOperator *BO = cast<BinaryOperator>(E);
3965 if (BO->getOpcode() == BO_PtrMemD)
3966 Out << "ds";
3967 else
3968 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3969 /*Arity=*/2);
3970 mangleExpression(BO->getLHS());
3971 mangleExpression(BO->getRHS());
3972 break;
3973 }
3974
3975 case Expr::ConditionalOperatorClass: {
3976 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3977 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3978 mangleExpression(CO->getCond());
3979 mangleExpression(CO->getLHS(), Arity);
3980 mangleExpression(CO->getRHS(), Arity);
3981 break;
3982 }
3983
3984 case Expr::ImplicitCastExprClass: {
3985 ImplicitlyConvertedToType = E->getType();
3986 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3987 goto recurse;
3988 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003989
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00003991 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 // __bridge_transfer, or __bridge_retain.
3993 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3994 Out << "v1U" << Kind.size() << Kind;
3995 }
3996 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00003997 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00003998
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004000 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004002
Richard Smith520449d2015-02-05 06:15:50 +00004003 case Expr::CXXFunctionalCastExprClass: {
4004 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4005 // FIXME: Add isImplicit to CXXConstructExpr.
4006 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4007 if (CCE->getParenOrBraceRange().isInvalid())
4008 Sub = CCE->getArg(0)->IgnoreImplicit();
4009 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4010 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4011 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4012 Out << "tl";
4013 mangleType(E->getType());
4014 mangleInitListElements(IL);
4015 Out << "E";
4016 } else {
4017 mangleCastExpression(E, "cv");
4018 }
4019 break;
4020 }
4021
David Majnemer9c775c72014-09-23 04:27:55 +00004022 case Expr::CXXStaticCastExprClass:
4023 mangleCastExpression(E, "sc");
4024 break;
4025 case Expr::CXXDynamicCastExprClass:
4026 mangleCastExpression(E, "dc");
4027 break;
4028 case Expr::CXXReinterpretCastExprClass:
4029 mangleCastExpression(E, "rc");
4030 break;
4031 case Expr::CXXConstCastExprClass:
4032 mangleCastExpression(E, "cc");
4033 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004034
4035 case Expr::CXXOperatorCallExprClass: {
4036 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4037 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004038 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4039 // (the enclosing MemberExpr covers the syntactic portion).
4040 if (CE->getOperator() != OO_Arrow)
4041 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 // Mangle the arguments.
4043 for (unsigned i = 0; i != NumArgs; ++i)
4044 mangleExpression(CE->getArg(i));
4045 break;
4046 }
4047
4048 case Expr::ParenExprClass:
4049 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4050 break;
4051
4052 case Expr::DeclRefExprClass: {
4053 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4054
4055 switch (D->getKind()) {
4056 default:
4057 // <expr-primary> ::= L <mangled-name> E # external name
4058 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004059 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 Out << 'E';
4061 break;
4062
4063 case Decl::ParmVar:
4064 mangleFunctionParam(cast<ParmVarDecl>(D));
4065 break;
4066
4067 case Decl::EnumConstant: {
4068 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4069 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4070 break;
4071 }
4072
4073 case Decl::NonTypeTemplateParm: {
4074 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4075 mangleTemplateParameter(PD->getIndex());
4076 break;
4077 }
4078
4079 }
4080
4081 break;
4082 }
4083
4084 case Expr::SubstNonTypeTemplateParmPackExprClass:
4085 // FIXME: not clear how to mangle this!
4086 // template <unsigned N...> class A {
4087 // template <class U...> void foo(U (&x)[N]...);
4088 // };
4089 Out << "_SUBSTPACK_";
4090 break;
4091
4092 case Expr::FunctionParmPackExprClass: {
4093 // FIXME: not clear how to mangle this!
4094 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4095 Out << "v110_SUBSTPACK";
4096 mangleFunctionParam(FPPE->getParameterPack());
4097 break;
4098 }
4099
4100 case Expr::DependentScopeDeclRefExprClass: {
4101 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004102 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4103 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4104 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 break;
4106 }
4107
4108 case Expr::CXXBindTemporaryExprClass:
4109 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4110 break;
4111
4112 case Expr::ExprWithCleanupsClass:
4113 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4114 break;
4115
4116 case Expr::FloatingLiteralClass: {
4117 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4118 Out << 'L';
4119 mangleType(FL->getType());
4120 mangleFloat(FL->getValue());
4121 Out << 'E';
4122 break;
4123 }
4124
4125 case Expr::CharacterLiteralClass:
4126 Out << 'L';
4127 mangleType(E->getType());
4128 Out << cast<CharacterLiteral>(E)->getValue();
4129 Out << 'E';
4130 break;
4131
4132 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4133 case Expr::ObjCBoolLiteralExprClass:
4134 Out << "Lb";
4135 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4136 Out << 'E';
4137 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004138
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 case Expr::CXXBoolLiteralExprClass:
4140 Out << "Lb";
4141 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4142 Out << 'E';
4143 break;
4144
4145 case Expr::IntegerLiteralClass: {
4146 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4147 if (E->getType()->isSignedIntegerType())
4148 Value.setIsSigned(true);
4149 mangleIntegerLiteral(E->getType(), Value);
4150 break;
4151 }
4152
4153 case Expr::ImaginaryLiteralClass: {
4154 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4155 // Mangle as if a complex literal.
4156 // Proposal from David Vandevoorde, 2010.06.30.
4157 Out << 'L';
4158 mangleType(E->getType());
4159 if (const FloatingLiteral *Imag =
4160 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4161 // Mangle a floating-point zero of the appropriate type.
4162 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4163 Out << '_';
4164 mangleFloat(Imag->getValue());
4165 } else {
4166 Out << "0_";
4167 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4168 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4169 Value.setIsSigned(true);
4170 mangleNumber(Value);
4171 }
4172 Out << 'E';
4173 break;
4174 }
4175
4176 case Expr::StringLiteralClass: {
4177 // Revised proposal from David Vandervoorde, 2010.07.15.
4178 Out << 'L';
4179 assert(isa<ConstantArrayType>(E->getType()));
4180 mangleType(E->getType());
4181 Out << 'E';
4182 break;
4183 }
4184
4185 case Expr::GNUNullExprClass:
4186 // FIXME: should this really be mangled the same as nullptr?
4187 // fallthrough
4188
4189 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 Out << "LDnE";
4191 break;
4192 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004193
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 case Expr::PackExpansionExprClass:
4195 Out << "sp";
4196 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4197 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004198
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004200 auto *SPE = cast<SizeOfPackExpr>(E);
4201 if (SPE->isPartiallySubstituted()) {
4202 Out << "sP";
4203 for (const auto &A : SPE->getPartialArguments())
4204 mangleTemplateArg(A);
4205 Out << "E";
4206 break;
4207 }
4208
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004210 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4212 mangleTemplateParameter(TTP->getIndex());
4213 else if (const NonTypeTemplateParmDecl *NTTP
4214 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4215 mangleTemplateParameter(NTTP->getIndex());
4216 else if (const TemplateTemplateParmDecl *TempTP
4217 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4218 mangleTemplateParameter(TempTP->getIndex());
4219 else
4220 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4221 break;
4222 }
Richard Smith0f0af192014-11-08 05:07:16 +00004223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 case Expr::MaterializeTemporaryExprClass: {
4225 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4226 break;
4227 }
Richard Smith0f0af192014-11-08 05:07:16 +00004228
4229 case Expr::CXXFoldExprClass: {
4230 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004231 if (FE->isLeftFold())
4232 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004233 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004234 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004235
4236 if (FE->getOperator() == BO_PtrMemD)
4237 Out << "ds";
4238 else
4239 mangleOperatorName(
4240 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4241 /*Arity=*/2);
4242
4243 if (FE->getLHS())
4244 mangleExpression(FE->getLHS());
4245 if (FE->getRHS())
4246 mangleExpression(FE->getRHS());
4247 break;
4248 }
4249
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 case Expr::CXXThisExprClass:
4251 Out << "fpT";
4252 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004253
4254 case Expr::CoawaitExprClass:
4255 // FIXME: Propose a non-vendor mangling.
4256 Out << "v18co_await";
4257 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4258 break;
4259
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004260 case Expr::DependentCoawaitExprClass:
4261 // FIXME: Propose a non-vendor mangling.
4262 Out << "v18co_await";
4263 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4264 break;
4265
Richard Smith9f690bd2015-10-27 06:02:45 +00004266 case Expr::CoyieldExprClass:
4267 // FIXME: Propose a non-vendor mangling.
4268 Out << "v18co_yield";
4269 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4270 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
4272}
4273
4274/// Mangle an expression which refers to a parameter variable.
4275///
4276/// <expression> ::= <function-param>
4277/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4278/// <function-param> ::= fp <top-level CV-qualifiers>
4279/// <parameter-2 non-negative number> _ # L == 0, I > 0
4280/// <function-param> ::= fL <L-1 non-negative number>
4281/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4282/// <function-param> ::= fL <L-1 non-negative number>
4283/// p <top-level CV-qualifiers>
4284/// <I-1 non-negative number> _ # L > 0, I > 0
4285///
4286/// L is the nesting depth of the parameter, defined as 1 if the
4287/// parameter comes from the innermost function prototype scope
4288/// enclosing the current context, 2 if from the next enclosing
4289/// function prototype scope, and so on, with one special case: if
4290/// we've processed the full parameter clause for the innermost
4291/// function type, then L is one less. This definition conveniently
4292/// makes it irrelevant whether a function's result type was written
4293/// trailing or leading, but is otherwise overly complicated; the
4294/// numbering was first designed without considering references to
4295/// parameter in locations other than return types, and then the
4296/// mangling had to be generalized without changing the existing
4297/// manglings.
4298///
4299/// I is the zero-based index of the parameter within its parameter
4300/// declaration clause. Note that the original ABI document describes
4301/// this using 1-based ordinals.
4302void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4303 unsigned parmDepth = parm->getFunctionScopeDepth();
4304 unsigned parmIndex = parm->getFunctionScopeIndex();
4305
4306 // Compute 'L'.
4307 // parmDepth does not include the declaring function prototype.
4308 // FunctionTypeDepth does account for that.
4309 assert(parmDepth < FunctionTypeDepth.getDepth());
4310 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4311 if (FunctionTypeDepth.isInResultType())
4312 nestingDepth--;
4313
4314 if (nestingDepth == 0) {
4315 Out << "fp";
4316 } else {
4317 Out << "fL" << (nestingDepth - 1) << 'p';
4318 }
4319
4320 // Top-level qualifiers. We don't have to worry about arrays here,
4321 // because parameters declared as arrays should already have been
4322 // transformed to have pointer type. FIXME: apparently these don't
4323 // get mangled if used as an rvalue of a known non-class type?
4324 assert(!parm->getType()->isArrayType()
4325 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004326
4327 if (const DependentAddressSpaceType *DAST =
4328 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4329 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4330 } else {
4331 mangleQualifiers(parm->getType().getQualifiers());
4332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004333
4334 // Parameter index.
4335 if (parmIndex != 0) {
4336 Out << (parmIndex - 1);
4337 }
4338 Out << '_';
4339}
4340
Richard Smith5179eb72016-06-28 19:03:57 +00004341void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4342 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 // <ctor-dtor-name> ::= C1 # complete object constructor
4344 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004345 // ::= CI1 <type> # complete inheriting constructor
4346 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004348 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004349 Out << 'C';
4350 if (InheritedFrom)
4351 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 switch (T) {
4353 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004354 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 break;
4356 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004357 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004359 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004360 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004362 case Ctor_DefaultClosure:
4363 case Ctor_CopyingClosure:
4364 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 }
Richard Smith5179eb72016-06-28 19:03:57 +00004366 if (InheritedFrom)
4367 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004368}
4369
4370void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4371 // <ctor-dtor-name> ::= D0 # deleting destructor
4372 // ::= D1 # complete object destructor
4373 // ::= D2 # base object destructor
4374 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004375 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 switch (T) {
4377 case Dtor_Deleting:
4378 Out << "D0";
4379 break;
4380 case Dtor_Complete:
4381 Out << "D1";
4382 break;
4383 case Dtor_Base:
4384 Out << "D2";
4385 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004386 case Dtor_Comdat:
4387 Out << "D5";
4388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 }
4390}
4391
James Y Knight04ec5bf2015-12-24 02:59:37 +00004392void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4393 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 // <template-args> ::= I <template-arg>+ E
4395 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004396 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4397 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 Out << 'E';
4399}
4400
4401void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4402 // <template-args> ::= I <template-arg>+ E
4403 Out << 'I';
4404 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4405 mangleTemplateArg(AL[i]);
4406 Out << 'E';
4407}
4408
4409void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4410 unsigned NumTemplateArgs) {
4411 // <template-args> ::= I <template-arg>+ E
4412 Out << 'I';
4413 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4414 mangleTemplateArg(TemplateArgs[i]);
4415 Out << 'E';
4416}
4417
4418void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4419 // <template-arg> ::= <type> # type or template
4420 // ::= X <expression> E # expression
4421 // ::= <expr-primary> # simple expressions
4422 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 if (!A.isInstantiationDependent() || A.isDependent())
4424 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004425
Guy Benyei11169dd2012-12-18 14:30:41 +00004426 switch (A.getKind()) {
4427 case TemplateArgument::Null:
4428 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004429
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 case TemplateArgument::Type:
4431 mangleType(A.getAsType());
4432 break;
4433 case TemplateArgument::Template:
4434 // This is mangled as <type>.
4435 mangleType(A.getAsTemplate());
4436 break;
4437 case TemplateArgument::TemplateExpansion:
4438 // <type> ::= Dp <type> # pack expansion (C++0x)
4439 Out << "Dp";
4440 mangleType(A.getAsTemplateOrTemplatePattern());
4441 break;
4442 case TemplateArgument::Expression: {
4443 // It's possible to end up with a DeclRefExpr here in certain
4444 // dependent cases, in which case we should mangle as a
4445 // declaration.
4446 const Expr *E = A.getAsExpr()->IgnoreParens();
4447 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4448 const ValueDecl *D = DRE->getDecl();
4449 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004450 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004451 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 Out << 'E';
4453 break;
4454 }
4455 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004456
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 Out << 'X';
4458 mangleExpression(E);
4459 Out << 'E';
4460 break;
4461 }
4462 case TemplateArgument::Integral:
4463 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4464 break;
4465 case TemplateArgument::Declaration: {
4466 // <expr-primary> ::= L <mangled-name> E # external name
4467 // Clang produces AST's where pointer-to-member-function expressions
4468 // and pointer-to-function expressions are represented as a declaration not
4469 // an expression. We compensate for it here to produce the correct mangling.
4470 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004471 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 if (compensateMangling) {
4473 Out << 'X';
4474 mangleOperatorName(OO_Amp, 1);
4475 }
4476
4477 Out << 'L';
4478 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004479 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004480 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 Out << 'E';
4482
4483 if (compensateMangling)
4484 Out << 'E';
4485
4486 break;
4487 }
4488 case TemplateArgument::NullPtr: {
4489 // <expr-primary> ::= L <type> 0 E
4490 Out << 'L';
4491 mangleType(A.getNullPtrType());
4492 Out << "0E";
4493 break;
4494 }
4495 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004496 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004498 for (const auto &P : A.pack_elements())
4499 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 Out << 'E';
4501 }
4502 }
4503}
4504
4505void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4506 // <template-param> ::= T_ # first template parameter
4507 // ::= T <parameter-2 non-negative number> _
4508 if (Index == 0)
4509 Out << "T_";
4510 else
4511 Out << 'T' << (Index - 1) << '_';
4512}
4513
David Majnemer3b3bdb52014-05-06 22:49:16 +00004514void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4515 if (SeqID == 1)
4516 Out << '0';
4517 else if (SeqID > 1) {
4518 SeqID--;
4519
4520 // <seq-id> is encoded in base-36, using digits and upper case letters.
4521 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004522 MutableArrayRef<char> BufferRef(Buffer);
4523 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004524
4525 for (; SeqID != 0; SeqID /= 36) {
4526 unsigned C = SeqID % 36;
4527 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4528 }
4529
4530 Out.write(I.base(), I - BufferRef.rbegin());
4531 }
4532 Out << '_';
4533}
4534
Guy Benyei11169dd2012-12-18 14:30:41 +00004535void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4536 bool result = mangleSubstitution(tname);
4537 assert(result && "no existing substitution for template name");
4538 (void) result;
4539}
4540
4541// <substitution> ::= S <seq-id> _
4542// ::= S_
4543bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4544 // Try one of the standard substitutions first.
4545 if (mangleStandardSubstitution(ND))
4546 return true;
4547
4548 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4549 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4550}
4551
Justin Bognere8d762e2015-05-22 06:48:13 +00004552/// Determine whether the given type has any qualifiers that are relevant for
4553/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004554static bool hasMangledSubstitutionQualifiers(QualType T) {
4555 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004556 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004557}
4558
4559bool CXXNameMangler::mangleSubstitution(QualType T) {
4560 if (!hasMangledSubstitutionQualifiers(T)) {
4561 if (const RecordType *RT = T->getAs<RecordType>())
4562 return mangleSubstitution(RT->getDecl());
4563 }
4564
4565 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4566
4567 return mangleSubstitution(TypePtr);
4568}
4569
4570bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4571 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4572 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004573
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4575 return mangleSubstitution(
4576 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4577}
4578
4579bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4580 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4581 if (I == Substitutions.end())
4582 return false;
4583
4584 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004585 Out << 'S';
4586 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004587
4588 return true;
4589}
4590
4591static bool isCharType(QualType T) {
4592 if (T.isNull())
4593 return false;
4594
4595 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4596 T->isSpecificBuiltinType(BuiltinType::Char_U);
4597}
4598
Justin Bognere8d762e2015-05-22 06:48:13 +00004599/// Returns whether a given type is a template specialization of a given name
4600/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004601static bool isCharSpecialization(QualType T, const char *Name) {
4602 if (T.isNull())
4603 return false;
4604
4605 const RecordType *RT = T->getAs<RecordType>();
4606 if (!RT)
4607 return false;
4608
4609 const ClassTemplateSpecializationDecl *SD =
4610 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4611 if (!SD)
4612 return false;
4613
4614 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4615 return false;
4616
4617 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4618 if (TemplateArgs.size() != 1)
4619 return false;
4620
4621 if (!isCharType(TemplateArgs[0].getAsType()))
4622 return false;
4623
4624 return SD->getIdentifier()->getName() == Name;
4625}
4626
4627template <std::size_t StrLen>
4628static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4629 const char (&Str)[StrLen]) {
4630 if (!SD->getIdentifier()->isStr(Str))
4631 return false;
4632
4633 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4634 if (TemplateArgs.size() != 2)
4635 return false;
4636
4637 if (!isCharType(TemplateArgs[0].getAsType()))
4638 return false;
4639
4640 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4641 return false;
4642
4643 return true;
4644}
4645
4646bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4647 // <substitution> ::= St # ::std::
4648 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4649 if (isStd(NS)) {
4650 Out << "St";
4651 return true;
4652 }
4653 }
4654
4655 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4656 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4657 return false;
4658
4659 // <substitution> ::= Sa # ::std::allocator
4660 if (TD->getIdentifier()->isStr("allocator")) {
4661 Out << "Sa";
4662 return true;
4663 }
4664
4665 // <<substitution> ::= Sb # ::std::basic_string
4666 if (TD->getIdentifier()->isStr("basic_string")) {
4667 Out << "Sb";
4668 return true;
4669 }
4670 }
4671
4672 if (const ClassTemplateSpecializationDecl *SD =
4673 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4674 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4675 return false;
4676
4677 // <substitution> ::= Ss # ::std::basic_string<char,
4678 // ::std::char_traits<char>,
4679 // ::std::allocator<char> >
4680 if (SD->getIdentifier()->isStr("basic_string")) {
4681 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4682
4683 if (TemplateArgs.size() != 3)
4684 return false;
4685
4686 if (!isCharType(TemplateArgs[0].getAsType()))
4687 return false;
4688
4689 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4690 return false;
4691
4692 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4693 return false;
4694
4695 Out << "Ss";
4696 return true;
4697 }
4698
4699 // <substitution> ::= Si # ::std::basic_istream<char,
4700 // ::std::char_traits<char> >
4701 if (isStreamCharSpecialization(SD, "basic_istream")) {
4702 Out << "Si";
4703 return true;
4704 }
4705
4706 // <substitution> ::= So # ::std::basic_ostream<char,
4707 // ::std::char_traits<char> >
4708 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4709 Out << "So";
4710 return true;
4711 }
4712
4713 // <substitution> ::= Sd # ::std::basic_iostream<char,
4714 // ::std::char_traits<char> >
4715 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4716 Out << "Sd";
4717 return true;
4718 }
4719 }
4720 return false;
4721}
4722
4723void CXXNameMangler::addSubstitution(QualType T) {
4724 if (!hasMangledSubstitutionQualifiers(T)) {
4725 if (const RecordType *RT = T->getAs<RecordType>()) {
4726 addSubstitution(RT->getDecl());
4727 return;
4728 }
4729 }
4730
4731 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4732 addSubstitution(TypePtr);
4733}
4734
4735void CXXNameMangler::addSubstitution(TemplateName Template) {
4736 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4737 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004738
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4740 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4741}
4742
4743void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4744 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4745 Substitutions[Ptr] = SeqID++;
4746}
4747
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004748void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4749 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4750 if (Other->SeqID > SeqID) {
4751 Substitutions.swap(Other->Substitutions);
4752 SeqID = Other->SeqID;
4753 }
4754}
4755
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004756CXXNameMangler::AbiTagList
4757CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4758 // When derived abi tags are disabled there is no need to make any list.
4759 if (DisableDerivedAbiTags)
4760 return AbiTagList();
4761
4762 llvm::raw_null_ostream NullOutStream;
4763 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4764 TrackReturnTypeTags.disableDerivedAbiTags();
4765
4766 const FunctionProtoType *Proto =
4767 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004768 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004769 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4770 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4771 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004772 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004773
4774 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4775}
4776
4777CXXNameMangler::AbiTagList
4778CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4779 // When derived abi tags are disabled there is no need to make any list.
4780 if (DisableDerivedAbiTags)
4781 return AbiTagList();
4782
4783 llvm::raw_null_ostream NullOutStream;
4784 CXXNameMangler TrackVariableType(*this, NullOutStream);
4785 TrackVariableType.disableDerivedAbiTags();
4786
4787 TrackVariableType.mangleType(VD->getType());
4788
4789 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4790}
4791
4792bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4793 const VarDecl *VD) {
4794 llvm::raw_null_ostream NullOutStream;
4795 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4796 TrackAbiTags.mangle(VD);
4797 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4798}
4799
Guy Benyei11169dd2012-12-18 14:30:41 +00004800//
4801
Justin Bognere8d762e2015-05-22 06:48:13 +00004802/// Mangles the name of the declaration D and emits that name to the given
4803/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004804///
4805/// If the declaration D requires a mangled name, this routine will emit that
4806/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4807/// and this routine will return false. In this case, the caller should just
4808/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4809/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004810void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4811 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4813 "Invalid mangleName() call, argument is not a variable or function!");
4814 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4815 "Invalid mangleName() call on 'structor decl!");
4816
4817 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4818 getASTContext().getSourceManager(),
4819 "Mangling declaration");
4820
4821 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004822 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004823}
4824
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004825void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4826 CXXCtorType Type,
4827 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 CXXNameMangler Mangler(*this, Out, D, Type);
4829 Mangler.mangle(D);
4830}
4831
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004832void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4833 CXXDtorType Type,
4834 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 CXXNameMangler Mangler(*this, Out, D, Type);
4836 Mangler.mangle(D);
4837}
4838
Rafael Espindola1e4df922014-09-16 15:18:21 +00004839void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4840 raw_ostream &Out) {
4841 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4842 Mangler.mangle(D);
4843}
4844
4845void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4846 raw_ostream &Out) {
4847 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4848 Mangler.mangle(D);
4849}
4850
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004851void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4852 const ThunkInfo &Thunk,
4853 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 // <special-name> ::= T <call-offset> <base encoding>
4855 // # base is the nominal target function of thunk
4856 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4857 // # base is the nominal target function of thunk
4858 // # first call-offset is 'this' adjustment
4859 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004860
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 assert(!isa<CXXDestructorDecl>(MD) &&
4862 "Use mangleCXXDtor for destructor decls!");
4863 CXXNameMangler Mangler(*this, Out);
4864 Mangler.getStream() << "_ZT";
4865 if (!Thunk.Return.isEmpty())
4866 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004867
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004869 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4870 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4871
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 // Mangle the return pointer adjustment if there is one.
4873 if (!Thunk.Return.isEmpty())
4874 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004875 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4876
Guy Benyei11169dd2012-12-18 14:30:41 +00004877 Mangler.mangleFunctionEncoding(MD);
4878}
4879
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004880void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4881 const CXXDestructorDecl *DD, CXXDtorType Type,
4882 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 // <special-name> ::= T <call-offset> <base encoding>
4884 // # base is the nominal target function of thunk
4885 CXXNameMangler Mangler(*this, Out, DD, Type);
4886 Mangler.getStream() << "_ZT";
4887
4888 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004889 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004890 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004891
4892 Mangler.mangleFunctionEncoding(DD);
4893}
4894
Justin Bognere8d762e2015-05-22 06:48:13 +00004895/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004896void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4897 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 // <special-name> ::= GV <object name> # Guard variable for one-time
4899 // # initialization
4900 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004901 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4902 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 Mangler.getStream() << "_ZGV";
4904 Mangler.mangleName(D);
4905}
4906
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004907void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4908 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004909 // These symbols are internal in the Itanium ABI, so the names don't matter.
4910 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4911 // avoid duplicate symbols.
4912 Out << "__cxx_global_var_init";
4913}
4914
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004915void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4916 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004917 // Prefix the mangling of D with __dtor_.
4918 CXXNameMangler Mangler(*this, Out);
4919 Mangler.getStream() << "__dtor_";
4920 if (shouldMangleDeclName(D))
4921 Mangler.mangle(D);
4922 else
4923 Mangler.getStream() << D->getName();
4924}
4925
Reid Kleckner1d59f992015-01-22 01:36:17 +00004926void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4927 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4928 CXXNameMangler Mangler(*this, Out);
4929 Mangler.getStream() << "__filt_";
4930 if (shouldMangleDeclName(EnclosingDecl))
4931 Mangler.mangle(EnclosingDecl);
4932 else
4933 Mangler.getStream() << EnclosingDecl->getName();
4934}
4935
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004936void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4937 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4938 CXXNameMangler Mangler(*this, Out);
4939 Mangler.getStream() << "__fin_";
4940 if (shouldMangleDeclName(EnclosingDecl))
4941 Mangler.mangle(EnclosingDecl);
4942 else
4943 Mangler.getStream() << EnclosingDecl->getName();
4944}
4945
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004946void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4947 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004948 // <special-name> ::= TH <object name>
4949 CXXNameMangler Mangler(*this, Out);
4950 Mangler.getStream() << "_ZTH";
4951 Mangler.mangleName(D);
4952}
4953
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004954void
4955ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4956 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004957 // <special-name> ::= TW <object name>
4958 CXXNameMangler Mangler(*this, Out);
4959 Mangler.getStream() << "_ZTW";
4960 Mangler.mangleName(D);
4961}
4962
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004963void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004964 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004965 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004966 // We match the GCC mangling here.
4967 // <special-name> ::= GR <object name>
4968 CXXNameMangler Mangler(*this, Out);
4969 Mangler.getStream() << "_ZGR";
4970 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004971 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004972 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004973}
4974
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004975void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4976 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 // <special-name> ::= TV <type> # virtual table
4978 CXXNameMangler Mangler(*this, Out);
4979 Mangler.getStream() << "_ZTV";
4980 Mangler.mangleNameOrStandardSubstitution(RD);
4981}
4982
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004983void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4984 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 // <special-name> ::= TT <type> # VTT structure
4986 CXXNameMangler Mangler(*this, Out);
4987 Mangler.getStream() << "_ZTT";
4988 Mangler.mangleNameOrStandardSubstitution(RD);
4989}
4990
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004991void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4992 int64_t Offset,
4993 const CXXRecordDecl *Type,
4994 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 // <special-name> ::= TC <type> <offset number> _ <base type>
4996 CXXNameMangler Mangler(*this, Out);
4997 Mangler.getStream() << "_ZTC";
4998 Mangler.mangleNameOrStandardSubstitution(RD);
4999 Mangler.getStream() << Offset;
5000 Mangler.getStream() << '_';
5001 Mangler.mangleNameOrStandardSubstitution(Type);
5002}
5003
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005004void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 // <special-name> ::= TI <type> # typeinfo structure
5006 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5007 CXXNameMangler Mangler(*this, Out);
5008 Mangler.getStream() << "_ZTI";
5009 Mangler.mangleType(Ty);
5010}
5011
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005012void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5013 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5015 CXXNameMangler Mangler(*this, Out);
5016 Mangler.getStream() << "_ZTS";
5017 Mangler.mangleType(Ty);
5018}
5019
Reid Klecknercc99e262013-11-19 23:23:00 +00005020void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5021 mangleCXXRTTIName(Ty, Out);
5022}
5023
David Majnemer58e5bee2014-03-24 21:43:36 +00005024void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5025 llvm_unreachable("Can't mangle string literals");
5026}
5027
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005028ItaniumMangleContext *
5029ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5030 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005031}