blob: 0ab4422b6a9308150e880f88230dddaae75dfa8d [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Implements C++ name mangling according to the Itanium C++ ABI,
10// which is used in GCC 3.2 and newer (and many compilers that are
11// ABI-compatible with GCC):
12//
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +000013// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000014//
15//===----------------------------------------------------------------------===//
16#include "clang/AST/Mangle.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000022#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000024#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/ABI.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
Guy Benyei11169dd2012-12-18 14:30:41 +000035using namespace clang;
36
37namespace {
38
Justin Bognere8d762e2015-05-22 06:48:13 +000039/// Retrieve the declaration context that should be used when mangling the given
40/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000041static const DeclContext *getEffectiveDeclContext(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +000042 // The ABI assumes that lambda closure types that occur within
Guy Benyei11169dd2012-12-18 14:30:41 +000043 // default arguments live in the context of the function. However, due to
44 // the way in which Clang parses and creates function declarations, this is
Fangrui Song6907ce22018-07-30 19:24:48 +000045 // not the case: the lambda closure type ends up living in the context
Guy Benyei11169dd2012-12-18 14:30:41 +000046 // where the function itself resides, because the function declaration itself
47 // had not yet been created. Fix the context here.
48 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
49 if (RD->isLambda())
50 if (ParmVarDecl *ContextParam
51 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
52 return ContextParam->getDeclContext();
53 }
Eli Friedman0cd23352013-07-10 01:33:19 +000054
55 // Perform the same check for block literals.
56 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Fangrui Song6907ce22018-07-30 19:24:48 +000061
Eli Friedman95f50122013-07-02 17:52:28 +000062 const DeclContext *DC = D->getDeclContext();
Michael Kruse251e1482019-02-01 20:25:04 +000063 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
64 isa<OMPDeclareMapperDecl>(DC)) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000065 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);
Hamza Sood8205a812019-05-04 10:49:46 +0000489 void mangleTemplateParamDecl(const NamedDecl *Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000490 void mangleLambda(const CXXRecordDecl *Lambda);
491 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000492 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000493 bool NoFunction=false);
494 void mangleNestedName(const TemplateDecl *TD,
495 const TemplateArgument *TemplateArgs,
496 unsigned NumTemplateArgs);
497 void manglePrefix(NestedNameSpecifier *qualifier);
498 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
499 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000500 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000501 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000502 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
503 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000504 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000505 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000506 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000507 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 void mangleRefQualifier(RefQualifierKind RefQualifier);
509
510 void mangleObjCMethodName(const ObjCMethodDecl *MD);
511
512 // Declare manglers for every type class.
513#define ABSTRACT_TYPE(CLASS, PARENT)
514#define NON_CANONICAL_TYPE(CLASS, PARENT)
515#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
516#include "clang/AST/TypeNodes.def"
517
518 void mangleType(const TagType*);
519 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000520 static StringRef getCallingConvQualifierName(CallingConv CC);
521 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
522 void mangleExtFunctionInfo(const FunctionType *T);
523 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000524 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000525 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000526 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000527 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000528 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000529
530 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000531 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000532 void mangleMemberExpr(const Expr *base, bool isArrow,
533 NestedNameSpecifier *qualifier,
534 NamedDecl *firstQualifierLookup,
535 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000536 const TemplateArgumentLoc *TemplateArgs,
537 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000538 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000539 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000540 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000542 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000543 void mangleCXXDtorType(CXXDtorType T);
544
James Y Knight04ec5bf2015-12-24 02:59:37 +0000545 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
546 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
548 unsigned NumTemplateArgs);
549 void mangleTemplateArgs(const TemplateArgumentList &AL);
550 void mangleTemplateArg(TemplateArgument A);
551
552 void mangleTemplateParameter(unsigned Index);
553
554 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000555
556 void writeAbiTags(const NamedDecl *ND,
557 const AbiTagList *AdditionalAbiTags);
558
559 // Returns sorted unique list of ABI tags.
560 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
561 // Returns sorted unique list of ABI tags.
562 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000563};
564
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000565}
Guy Benyei11169dd2012-12-18 14:30:41 +0000566
Rafael Espindola002667c2013-10-16 01:40:34 +0000567bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000569 if (FD) {
570 LanguageLinkage L = FD->getLanguageLinkage();
571 // Overloadable functions need mangling.
572 if (FD->hasAttr<OverloadableAttr>())
573 return true;
574
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000575 // "main" is not mangled.
576 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000577 return false;
578
Martin Storsjo92e26612018-07-16 05:42:25 +0000579 // The Windows ABI expects that we would never mangle "typical"
580 // user-defined entry points regardless of visibility or freestanding-ness.
581 //
582 // N.B. This is distinct from asking about "main". "main" has a lot of
583 // special rules associated with it in the standard while these
584 // user-defined entry points are outside of the purview of the standard.
585 // For example, there can be only one definition for "main" in a standards
586 // compliant program; however nothing forbids the existence of wmain and
587 // WinMain in the same translation unit.
588 if (FD->isMSVCRTEntryPoint())
589 return false;
590
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000591 // C++ functions and those whose names are not a simple identifier need
592 // mangling.
593 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
594 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000595
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000596 // C functions are not mangled.
597 if (L == CLanguageLinkage)
598 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000599 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000600
601 // Otherwise, no mangling is done outside C++ mode.
602 if (!getASTContext().getLangOpts().CPlusPlus)
603 return false;
604
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000605 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000606 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000607 // C variables are not mangled.
608 if (VD->isExternC())
609 return false;
610
611 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000612 const DeclContext *DC = getEffectiveDeclContext(D);
613 // Check for extern variable declared locally.
614 if (DC->isFunctionOrMethod() && D->hasLinkage())
615 while (!DC->isNamespace() && !DC->isTranslationUnit())
616 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000617 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000618 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000619 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 return false;
621 }
622
Guy Benyei11169dd2012-12-18 14:30:41 +0000623 return true;
624}
625
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000626void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
627 const AbiTagList *AdditionalAbiTags) {
628 assert(AbiTags && "require AbiTagState");
629 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
630}
631
632void CXXNameMangler::mangleSourceNameWithAbiTags(
633 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
634 mangleSourceName(ND->getIdentifier());
635 writeAbiTags(ND, AdditionalAbiTags);
636}
637
David Majnemer7ff7eb72015-02-18 07:47:09 +0000638void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 // <mangled-name> ::= _Z <encoding>
640 // ::= <data name>
641 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000642 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
644 mangleFunctionEncoding(FD);
645 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
646 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000647 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
648 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 else
650 mangleName(cast<FieldDecl>(D));
651}
652
653void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
654 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000655
656 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000657 if (!Context.shouldMangleDeclName(FD)) {
658 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000660 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000661
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000662 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
663 if (ReturnTypeAbiTags.empty()) {
664 // There are no tags for return type, the simplest case.
665 mangleName(FD);
666 mangleFunctionEncodingBareType(FD);
667 return;
668 }
669
670 // Mangle function name and encoding to temporary buffer.
671 // We have to output name and encoding to the same mangler to get the same
672 // substitution as it will be in final mangling.
673 SmallString<256> FunctionEncodingBuf;
674 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
675 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
676 // Output name of the function.
677 FunctionEncodingMangler.disableDerivedAbiTags();
678 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
679
680 // Remember length of the function name in the buffer.
681 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
682 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
683
684 // Get tags from return type that are not present in function name or
685 // encoding.
686 const AbiTagList &UsedAbiTags =
687 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
688 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
689 AdditionalAbiTags.erase(
690 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
691 UsedAbiTags.begin(), UsedAbiTags.end(),
692 AdditionalAbiTags.begin()),
693 AdditionalAbiTags.end());
694
695 // Output name with implicit tags and function encoding from temporary buffer.
696 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
697 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000698
699 // Function encoding could create new substitutions so we have to add
700 // temp mangled substitutions to main mangler.
701 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000702}
703
704void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000705 if (FD->hasAttr<EnableIfAttr>()) {
706 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
707 Out << "Ua9enable_ifI";
Michael Krusedc5ce722018-08-03 01:21:16 +0000708 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
709 E = FD->getAttrs().end();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000710 I != E; ++I) {
711 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
712 if (!EIA)
713 continue;
714 Out << 'X';
715 mangleExpression(EIA->getCond());
716 Out << 'E';
717 }
718 Out << 'E';
719 FunctionTypeDepth.pop(Saved);
720 }
721
Richard Smith5179eb72016-06-28 19:03:57 +0000722 // When mangling an inheriting constructor, the bare function type used is
723 // that of the inherited constructor.
724 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
725 if (auto Inherited = CD->getInheritedConstructor())
726 FD = Inherited.getConstructor();
727
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 // Whether the mangling of a function type includes the return type depends on
729 // the context and the nature of the function. The rules for deciding whether
730 // the return type is included are:
731 //
732 // 1. Template functions (names or types) have return types encoded, with
733 // the exceptions listed below.
734 // 2. Function types not appearing as part of a function name mangling,
735 // e.g. parameters, pointer types, etc., have return type encoded, with the
736 // exceptions listed below.
737 // 3. Non-template function names do not have return types encoded.
738 //
739 // The exceptions mentioned in (1) and (2) above, for which the return type is
740 // never included, are
741 // 1. Constructors.
742 // 2. Destructors.
743 // 3. Conversion operator functions, e.g. operator int.
744 bool MangleReturnType = false;
745 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
746 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
747 isa<CXXConversionDecl>(FD)))
748 MangleReturnType = true;
749
750 // Mangle the type of the primary template.
751 FD = PrimaryTemplate->getTemplatedDecl();
752 }
753
John McCall07daf722016-03-01 22:18:03 +0000754 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000755 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000756}
757
758static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
759 while (isa<LinkageSpecDecl>(DC)) {
760 DC = getEffectiveParentContext(DC);
761 }
762
763 return DC;
764}
765
Justin Bognere8d762e2015-05-22 06:48:13 +0000766/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000767static bool isStd(const NamespaceDecl *NS) {
768 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
769 ->isTranslationUnit())
770 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000771
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
773 return II && II->isStr("std");
774}
775
776// isStdNamespace - Return whether a given decl context is a toplevel 'std'
777// namespace.
778static bool isStdNamespace(const DeclContext *DC) {
779 if (!DC->isNamespace())
780 return false;
781
782 return isStd(cast<NamespaceDecl>(DC));
783}
784
785static const TemplateDecl *
786isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
787 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000788 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
790 TemplateArgs = FD->getTemplateSpecializationArgs();
791 return TD;
792 }
793 }
794
795 // Check if we have a class template.
796 if (const ClassTemplateSpecializationDecl *Spec =
797 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
798 TemplateArgs = &Spec->getTemplateArgs();
799 return Spec->getSpecializedTemplate();
800 }
801
Larisse Voufo39a1e502013-08-06 01:03:05 +0000802 // Check if we have a variable template.
803 if (const VarTemplateSpecializationDecl *Spec =
804 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
805 TemplateArgs = &Spec->getTemplateArgs();
806 return Spec->getSpecializedTemplate();
807 }
808
Craig Topper36250ad2014-05-12 05:36:57 +0000809 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000810}
811
Guy Benyei11169dd2012-12-18 14:30:41 +0000812void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000813 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
814 // Variables should have implicit tags from its type.
815 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
816 if (VariableTypeAbiTags.empty()) {
817 // Simple case no variable type tags.
818 mangleNameWithAbiTags(VD, nullptr);
819 return;
820 }
821
822 // Mangle variable name to null stream to collect tags.
823 llvm::raw_null_ostream NullOutStream;
824 CXXNameMangler VariableNameMangler(*this, NullOutStream);
825 VariableNameMangler.disableDerivedAbiTags();
826 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
827
828 // Get tags from variable type that are not present in its name.
829 const AbiTagList &UsedAbiTags =
830 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
831 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
832 AdditionalAbiTags.erase(
833 std::set_difference(VariableTypeAbiTags.begin(),
834 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
835 UsedAbiTags.end(), AdditionalAbiTags.begin()),
836 AdditionalAbiTags.end());
837
838 // Output name with implicit tags.
839 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
840 } else {
841 mangleNameWithAbiTags(ND, nullptr);
842 }
843}
844
845void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
846 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000847 // <name> ::= [<module-name>] <nested-name>
848 // ::= [<module-name>] <unscoped-name>
849 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 // ::= <local-name>
851 //
852 const DeclContext *DC = getEffectiveDeclContext(ND);
853
854 // If this is an extern variable declared locally, the relevant DeclContext
855 // is that of the containing namespace, or the translation unit.
856 // FIXME: This is a hack; extern variables declared locally should have
857 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000858 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 while (!DC->isNamespace() && !DC->isTranslationUnit())
860 DC = getEffectiveParentContext(DC);
861 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000862 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 return;
864 }
865
866 DC = IgnoreLinkageSpecDecls(DC);
867
Richard Smithdd8b5332017-09-04 05:37:53 +0000868 if (isLocalContainerContext(DC)) {
869 mangleLocalName(ND, AdditionalAbiTags);
870 return;
871 }
872
873 // Do not mangle the owning module for an external linkage declaration.
874 // This enables backwards-compatibility with non-modular code, and is
875 // a valid choice since conflicts are not permitted by C++ Modules TS
876 // [basic.def.odr]/6.2.
877 if (!ND->hasExternalFormalLinkage())
878 if (Module *M = ND->getOwningModuleForLinkage())
879 mangleModuleName(M);
880
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
882 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000883 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000885 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000886 mangleTemplateArgs(*TemplateArgs);
887 return;
888 }
889
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000890 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000891 return;
892 }
893
Richard Smithdd8b5332017-09-04 05:37:53 +0000894 mangleNestedName(ND, DC, AdditionalAbiTags);
895}
896
897void CXXNameMangler::mangleModuleName(const Module *M) {
898 // Implement the C++ Modules TS name mangling proposal; see
899 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
900 //
901 // <module-name> ::= W <unscoped-name>+ E
902 // ::= W <module-subst> <unscoped-name>* E
903 Out << 'W';
904 mangleModuleNamePrefix(M->Name);
905 Out << 'E';
906}
907
908void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
909 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
910 // ::= W <seq-id - 10> _ # otherwise
911 auto It = ModuleSubstitutions.find(Name);
912 if (It != ModuleSubstitutions.end()) {
913 if (It->second < 10)
914 Out << '_' << static_cast<char>('0' + It->second);
915 else
916 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 return;
918 }
919
Richard Smithdd8b5332017-09-04 05:37:53 +0000920 // FIXME: Preserve hierarchy in module names rather than flattening
921 // them to strings; use Module*s as substitution keys.
922 auto Parts = Name.rsplit('.');
923 if (Parts.second.empty())
924 Parts.second = Parts.first;
925 else
926 mangleModuleNamePrefix(Parts.first);
927
928 Out << Parts.second.size() << Parts.second;
929 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000930}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000931
932void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
933 const TemplateArgument *TemplateArgs,
934 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
936
937 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000938 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
940 } else {
941 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
942 }
943}
944
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000945void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
946 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 // <unscoped-name> ::= <unqualified-name>
948 // ::= St <unqualified-name> # ::std::
949
950 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
951 Out << "St";
952
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000953 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000954}
955
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000956void CXXNameMangler::mangleUnscopedTemplateName(
957 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 // <unscoped-template-name> ::= <unscoped-name>
959 // ::= <substitution>
960 if (mangleSubstitution(ND))
961 return;
962
963 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000964 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
965 assert(!AdditionalAbiTags &&
966 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000968 } else if (isa<BuiltinTemplateDecl>(ND)) {
969 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000970 } else {
971 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
972 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000973
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 addSubstitution(ND);
975}
976
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000977void CXXNameMangler::mangleUnscopedTemplateName(
978 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 // <unscoped-template-name> ::= <unscoped-name>
980 // ::= <substitution>
981 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000982 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +0000983
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 if (mangleSubstitution(Template))
985 return;
986
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000987 assert(!AdditionalAbiTags &&
988 "dependent template name cannot have abi tags");
989
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
991 assert(Dependent && "Not a dependent template name?");
992 if (const IdentifierInfo *Id = Dependent->getIdentifier())
993 mangleSourceName(Id);
994 else
995 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000996
Guy Benyei11169dd2012-12-18 14:30:41 +0000997 addSubstitution(Template);
998}
999
1000void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1001 // ABI:
1002 // Floating-point literals are encoded using a fixed-length
1003 // lowercase hexadecimal string corresponding to the internal
1004 // representation (IEEE on Itanium), high-order bytes first,
1005 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1006 // on Itanium.
1007 // The 'without leading zeroes' thing seems to be an editorial
1008 // mistake; see the discussion on cxx-abi-dev beginning on
1009 // 2012-01-16.
1010
1011 // Our requirements here are just barely weird enough to justify
1012 // using a custom algorithm instead of post-processing APInt::toString().
1013
1014 llvm::APInt valueBits = f.bitcastToAPInt();
1015 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1016 assert(numCharacters != 0);
1017
1018 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001019 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001020
1021 // Fill the buffer left-to-right.
1022 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1023 // The bit-index of the next hex digit.
1024 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1025
1026 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001027 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1028 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 hexDigit &= 0xF;
1030
1031 // Map that over to a lowercase hex digit.
1032 static const char charForHex[16] = {
1033 '0', '1', '2', '3', '4', '5', '6', '7',
1034 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1035 };
1036 buffer[stringIndex] = charForHex[hexDigit];
1037 }
1038
1039 Out.write(buffer.data(), numCharacters);
1040}
1041
1042void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1043 if (Value.isSigned() && Value.isNegative()) {
1044 Out << 'n';
1045 Value.abs().print(Out, /*signed*/ false);
1046 } else {
1047 Value.print(Out, /*signed*/ false);
1048 }
1049}
1050
1051void CXXNameMangler::mangleNumber(int64_t Number) {
1052 // <number> ::= [n] <non-negative decimal integer>
1053 if (Number < 0) {
1054 Out << 'n';
1055 Number = -Number;
1056 }
1057
1058 Out << Number;
1059}
1060
1061void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1062 // <call-offset> ::= h <nv-offset> _
1063 // ::= v <v-offset> _
1064 // <nv-offset> ::= <offset number> # non-virtual base override
1065 // <v-offset> ::= <offset number> _ <virtual offset number>
1066 // # virtual base override, with vcall offset
1067 if (!Virtual) {
1068 Out << 'h';
1069 mangleNumber(NonVirtual);
1070 Out << '_';
1071 return;
1072 }
1073
1074 Out << 'v';
1075 mangleNumber(NonVirtual);
1076 Out << '_';
1077 mangleNumber(Virtual);
1078 Out << '_';
1079}
1080
1081void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001082 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001083 if (!mangleSubstitution(QualType(TST, 0))) {
1084 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001085
Guy Benyei11169dd2012-12-18 14:30:41 +00001086 // FIXME: GCC does not appear to mangle the template arguments when
1087 // the template in question is a dependent template name. Should we
1088 // emulate that badness?
1089 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1090 addSubstitution(QualType(TST, 0));
1091 }
David Majnemera88b3592015-02-18 02:28:01 +00001092 } else if (const auto *DTST =
1093 type->getAs<DependentTemplateSpecializationType>()) {
1094 if (!mangleSubstitution(QualType(DTST, 0))) {
1095 TemplateName Template = getASTContext().getDependentTemplateName(
1096 DTST->getQualifier(), DTST->getIdentifier());
1097 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001098
David Majnemera88b3592015-02-18 02:28:01 +00001099 // FIXME: GCC does not appear to mangle the template arguments when
1100 // the template in question is a dependent template name. Should we
1101 // emulate that badness?
1102 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1103 addSubstitution(QualType(DTST, 0));
1104 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 } else {
1106 // We use the QualType mangle type variant here because it handles
1107 // substitutions.
1108 mangleType(type);
1109 }
1110}
1111
1112/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1113///
Guy Benyei11169dd2012-12-18 14:30:41 +00001114/// \param recursive - true if this is being called recursively,
1115/// i.e. if there is more prefix "to the right".
1116void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 bool recursive) {
1118
1119 // x, ::x
1120 // <unresolved-name> ::= [gs] <base-unresolved-name>
1121
1122 // T::x / decltype(p)::x
1123 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1124
1125 // T::N::x /decltype(p)::N::x
1126 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1127 // <base-unresolved-name>
1128
1129 // A::x, N::y, A<T>::z; "gs" means leading "::"
1130 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1131 // <base-unresolved-name>
1132
1133 switch (qualifier->getKind()) {
1134 case NestedNameSpecifier::Global:
1135 Out << "gs";
1136
1137 // We want an 'sr' unless this is the entire NNS.
1138 if (recursive)
1139 Out << "sr";
1140
1141 // We never want an 'E' here.
1142 return;
1143
Nikola Smiljanic67860242014-09-26 00:28:20 +00001144 case NestedNameSpecifier::Super:
1145 llvm_unreachable("Can't mangle __super specifier");
1146
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 case NestedNameSpecifier::Namespace:
1148 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001149 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 /*recursive*/ true);
1151 else
1152 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001153 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 break;
1155 case NestedNameSpecifier::NamespaceAlias:
1156 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001157 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 /*recursive*/ true);
1159 else
1160 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001161 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 break;
1163
1164 case NestedNameSpecifier::TypeSpec:
1165 case NestedNameSpecifier::TypeSpecWithTemplate: {
1166 const Type *type = qualifier->getAsType();
1167
1168 // We only want to use an unresolved-type encoding if this is one of:
1169 // - a decltype
1170 // - a template type parameter
1171 // - a template template parameter with arguments
1172 // In all of these cases, we should have no prefix.
1173 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001174 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 /*recursive*/ true);
1176 } else {
1177 // Otherwise, all the cases want this.
1178 Out << "sr";
1179 }
1180
David Majnemerb8014dd2015-02-19 02:16:16 +00001181 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 return;
1183
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 break;
1185 }
1186
1187 case NestedNameSpecifier::Identifier:
1188 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001189 if (qualifier->getPrefix())
1190 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001192 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001194
1195 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001196 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 break;
1198 }
1199
1200 // If this was the innermost part of the NNS, and we fell out to
1201 // here, append an 'E'.
1202 if (!recursive)
1203 Out << 'E';
1204}
1205
1206/// Mangle an unresolved-name, which is generally used for names which
1207/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001208void CXXNameMangler::mangleUnresolvedName(
1209 NestedNameSpecifier *qualifier, DeclarationName name,
1210 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1211 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001212 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001213 switch (name.getNameKind()) {
1214 // <base-unresolved-name> ::= <simple-id>
1215 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001216 mangleSourceName(name.getAsIdentifierInfo());
1217 break;
1218 // <base-unresolved-name> ::= dn <destructor-name>
1219 case DeclarationName::CXXDestructorName:
1220 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001221 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001222 break;
1223 // <base-unresolved-name> ::= on <operator-name>
1224 case DeclarationName::CXXConversionFunctionName:
1225 case DeclarationName::CXXLiteralOperatorName:
1226 case DeclarationName::CXXOperatorName:
1227 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001228 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001229 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001230 case DeclarationName::CXXConstructorName:
1231 llvm_unreachable("Can't mangle a constructor name!");
1232 case DeclarationName::CXXUsingDirective:
1233 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001234 case DeclarationName::CXXDeductionGuideName:
1235 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001236 case DeclarationName::ObjCMultiArgSelector:
1237 case DeclarationName::ObjCOneArgSelector:
1238 case DeclarationName::ObjCZeroArgSelector:
1239 llvm_unreachable("Can't mangle Objective-C selector names here!");
1240 }
Richard Smithafecd832016-10-24 20:47:04 +00001241
1242 // The <simple-id> and on <operator-name> productions end in an optional
1243 // <template-args>.
1244 if (TemplateArgs)
1245 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246}
1247
Guy Benyei11169dd2012-12-18 14:30:41 +00001248void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1249 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001250 unsigned KnownArity,
1251 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001252 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 // <unqualified-name> ::= <operator-name>
1254 // ::= <ctor-dtor-name>
1255 // ::= <source-name>
1256 switch (Name.getNameKind()) {
1257 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001258 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1259
Richard Smithda383632016-08-15 01:33:41 +00001260 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001261 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001262 // FIXME: Non-standard mangling for decomposition declarations:
1263 //
1264 // <unqualified-name> ::= DC <source-name>* E
1265 //
1266 // These can never be referenced across translation units, so we do
1267 // not need a cross-vendor mangling for anything other than demanglers.
1268 // Proposed on cxx-abi-dev on 2016-08-12
1269 Out << "DC";
1270 for (auto *BD : DD->bindings())
1271 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1272 Out << 'E';
1273 writeAbiTags(ND, AdditionalAbiTags);
1274 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001275 }
1276
1277 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001278 // Match GCC's naming convention for internal linkage symbols, for
1279 // symbols that are not actually visible outside of this TU. GCC
1280 // distinguishes between internal and external linkage symbols in
1281 // its mangling, to support cases like this that were valid C++ prior
1282 // to DR426:
1283 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 // void test() { extern void foo(); }
1285 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001286 //
1287 // Don't bother with the L marker for names in anonymous namespaces; the
1288 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1289 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1290 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001291 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001292 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001293 getEffectiveDeclContext(ND)->isFileContext() &&
1294 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 Out << 'L';
1296
Erich Keane757d3172016-11-02 18:29:35 +00001297 auto *FD = dyn_cast<FunctionDecl>(ND);
1298 bool IsRegCall = FD &&
1299 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1300 clang::CC_X86RegCall;
1301 if (IsRegCall)
1302 mangleRegCallName(II);
1303 else
1304 mangleSourceName(II);
1305
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001306 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 break;
1308 }
1309
1310 // Otherwise, an anonymous entity. We must have a declaration.
1311 assert(ND && "mangling empty name without declaration");
1312
1313 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1314 if (NS->isAnonymousNamespace()) {
1315 // This is how gcc mangles these names.
1316 Out << "12_GLOBAL__N_1";
1317 break;
1318 }
1319 }
1320
1321 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1322 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001323 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001324
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 // Itanium C++ ABI 5.1.2:
1326 //
1327 // For the purposes of mangling, the name of an anonymous union is
1328 // considered to be the name of the first named data member found by a
1329 // pre-order, depth-first, declaration-order walk of the data members of
1330 // the anonymous union. If there is no such data member (i.e., if all of
1331 // the data members in the union are unnamed), then there is no way for
1332 // a program to refer to the anonymous union, and there is therefore no
1333 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001334 assert(RD->isAnonymousStructOrUnion()
1335 && "Expected anonymous struct or union!");
1336 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001337
1338 // It's actually possible for various reasons for us to get here
1339 // with an empty anonymous struct / union. Fortunately, it
1340 // doesn't really matter what name we generate.
1341 if (!FD) break;
1342 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001343
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001345 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 break;
1347 }
John McCall924046f2013-04-10 06:08:21 +00001348
1349 // Class extensions have no name as a category, and it's possible
1350 // for them to be the semantic parent of certain declarations
1351 // (primarily, tag decls defined within declarations). Such
1352 // declarations will always have internal linkage, so the name
1353 // doesn't really matter, but we shouldn't crash on them. For
1354 // safety, just handle all ObjC containers here.
1355 if (isa<ObjCContainerDecl>(ND))
1356 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001357
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 // We must have an anonymous struct.
1359 const TagDecl *TD = cast<TagDecl>(ND);
1360 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1361 assert(TD->getDeclContext() == D->getDeclContext() &&
1362 "Typedef should not be in another decl context!");
1363 assert(D->getDeclName().getAsIdentifierInfo() &&
1364 "Typedef was not named!");
1365 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001366 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1367 // Explicit abi tags are still possible; take from underlying type, not
1368 // from typedef.
1369 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 break;
1371 }
1372
1373 // <unnamed-type-name> ::= <closure-type-name>
Fangrui Song6907ce22018-07-30 19:24:48 +00001374 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
Hamza Sood8205a812019-05-04 10:49:46 +00001376 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1377 // # Parameter types or 'v' for 'void'.
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1379 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001380 assert(!AdditionalAbiTags &&
1381 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 mangleLambda(Record);
1383 break;
1384 }
1385 }
1386
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001387 if (TD->isExternallyVisible()) {
1388 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001390 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001391 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001393 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 break;
1395 }
1396
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001397 // Get a unique id for the anonymous struct. If it is not a real output
1398 // ID doesn't matter so use fake one.
1399 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400
1401 // Mangle it as a source name in the form
1402 // [n] $_<id>
1403 // where n is the length of the string.
1404 SmallString<8> Str;
1405 Str += "$_";
1406 Str += llvm::utostr(AnonStructId);
1407
1408 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001409 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 break;
1411 }
1412
1413 case DeclarationName::ObjCZeroArgSelector:
1414 case DeclarationName::ObjCOneArgSelector:
1415 case DeclarationName::ObjCMultiArgSelector:
1416 llvm_unreachable("Can't mangle Objective-C selector names here!");
1417
Richard Smith5179eb72016-06-28 19:03:57 +00001418 case DeclarationName::CXXConstructorName: {
1419 const CXXRecordDecl *InheritedFrom = nullptr;
1420 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1421 if (auto Inherited =
1422 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1423 InheritedFrom = Inherited.getConstructor()->getParent();
1424 InheritedTemplateArgs =
1425 Inherited.getConstructor()->getTemplateSpecializationArgs();
1426 }
1427
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 if (ND == Structor)
1429 // If the named decl is the C++ constructor we're mangling, use the type
1430 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001431 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 else
1433 // Otherwise, use the complete constructor name. This is relevant if a
1434 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001435 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1436
1437 // FIXME: The template arguments are part of the enclosing prefix or
1438 // nested-name, but it's more convenient to mangle them here.
1439 if (InheritedTemplateArgs)
1440 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001441
1442 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001444 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001445
1446 case DeclarationName::CXXDestructorName:
1447 if (ND == Structor)
1448 // If the named decl is the C++ destructor we're mangling, use the type we
1449 // were given.
1450 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1451 else
1452 // Otherwise, use the complete destructor name. This is relevant if a
1453 // class with a destructor is declared within a destructor.
1454 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001455 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001456 break;
1457
David Majnemera88b3592015-02-18 02:28:01 +00001458 case DeclarationName::CXXOperatorName:
1459 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 Arity = cast<FunctionDecl>(ND)->getNumParams();
1461
David Majnemera88b3592015-02-18 02:28:01 +00001462 // If we have a member function, we need to include the 'this' pointer.
1463 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1464 if (!MD->isStatic())
1465 Arity++;
1466 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001467 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001468 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001470 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001471 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 break;
1473
Richard Smith35845152017-02-07 01:37:30 +00001474 case DeclarationName::CXXDeductionGuideName:
1475 llvm_unreachable("Can't mangle a deduction guide name!");
1476
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 case DeclarationName::CXXUsingDirective:
1478 llvm_unreachable("Can't mangle a using directive name!");
1479 }
1480}
1481
Erich Keane757d3172016-11-02 18:29:35 +00001482void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1483 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1484 // <number> ::= [n] <non-negative decimal integer>
1485 // <identifier> ::= <unqualified source code identifier>
1486 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1487 << II->getName();
1488}
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1491 // <source-name> ::= <positive length number> <identifier>
1492 // <number> ::= [n] <non-negative decimal integer>
1493 // <identifier> ::= <unqualified source code identifier>
1494 Out << II->getLength() << II->getName();
1495}
1496
1497void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1498 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001499 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001500 bool NoFunction) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001501 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001503 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 // <template-args> E
1505
1506 Out << 'N';
1507 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00001508 Qualifiers MethodQuals = Method->getMethodQualifiers();
David Majnemer42350df2013-11-03 23:51:28 +00001509 // We do not consider restrict a distinguishing attribute for overloading
1510 // purposes so we must not mangle it.
1511 MethodQuals.removeRestrict();
1512 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 mangleRefQualifier(Method->getRefQualifier());
1514 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001517 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001519 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 mangleTemplateArgs(*TemplateArgs);
1521 }
1522 else {
1523 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001524 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 }
1526
1527 Out << 'E';
1528}
1529void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1530 const TemplateArgument *TemplateArgs,
1531 unsigned NumTemplateArgs) {
1532 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1533
1534 Out << 'N';
1535
1536 mangleTemplatePrefix(TD);
1537 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1538
1539 Out << 'E';
1540}
1541
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001542void CXXNameMangler::mangleLocalName(const Decl *D,
1543 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1545 // := Z <function encoding> E s [<discriminator>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001546 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 // _ <entity name>
1548 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001549 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001550 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001551 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001552
1553 Out << 'Z';
1554
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001555 {
1556 AbiTagState LocalAbiTags(AbiTags);
1557
1558 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1559 mangleObjCMethodName(MD);
1560 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1561 mangleBlockForPrefix(BD);
1562 else
1563 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1564
1565 // Implicit ABI tags (from namespace) are not available in the following
1566 // entity; reset to actually emitted tags, which are available.
1567 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1568 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001569
Eli Friedman92821742013-07-02 02:01:18 +00001570 Out << 'E';
1571
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001572 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1573 // be a bug that is fixed in trunk.
1574
Eli Friedman92821742013-07-02 02:01:18 +00001575 if (RD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001576 // The parameter number is omitted for the last parameter, 0 for the
1577 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1578 // <entity name> will of course contain a <closure-type-name>: Its
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 // numbering will be local to the particular argument in which it appears
1580 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001581 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001582 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001583 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001584 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 if (const FunctionDecl *Func
1586 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1587 Out << 'd';
1588 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1589 if (Num > 1)
1590 mangleNumber(Num - 2);
1591 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 }
1593 }
1594 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001595
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001597 // equality ok because RD derived from ND above
1598 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001599 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001600 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1601 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001602 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001603 mangleUnqualifiedBlock(BD);
1604 } else {
1605 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001606 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1607 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001608 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001609 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1610 // Mangle a block in a default parameter; see above explanation for
1611 // lambdas.
1612 if (const ParmVarDecl *Parm
1613 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1614 if (const FunctionDecl *Func
1615 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1616 Out << 'd';
1617 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1618 if (Num > 1)
1619 mangleNumber(Num - 2);
1620 Out << '_';
1621 }
1622 }
1623
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001624 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001625 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001626 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001627 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001629
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001630 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1631 unsigned disc;
1632 if (Context.getNextDiscriminator(ND, disc)) {
1633 if (disc < 10)
1634 Out << '_' << disc;
1635 else
1636 Out << "__" << disc << '_';
1637 }
1638 }
Eli Friedman95f50122013-07-02 17:52:28 +00001639}
1640
1641void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1642 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001643 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001644 return;
1645 }
1646 const DeclContext *DC = getEffectiveDeclContext(Block);
1647 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001648 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001649 return;
1650 }
1651 manglePrefix(getEffectiveDeclContext(Block));
1652 mangleUnqualifiedBlock(Block);
1653}
1654
1655void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1656 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1657 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1658 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001659 const auto *ND = cast<NamedDecl>(Context);
1660 if (ND->getIdentifier()) {
1661 mangleSourceNameWithAbiTags(ND);
1662 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001663 }
1664 }
1665 }
1666
1667 // If we have a block mangling number, use it.
1668 unsigned Number = Block->getBlockManglingNumber();
1669 // Otherwise, just make up a number. It doesn't matter what it is because
1670 // the symbol in question isn't externally visible.
1671 if (!Number)
1672 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001673 else {
1674 // Stored mangling numbers are 1-based.
1675 --Number;
1676 }
Eli Friedman95f50122013-07-02 17:52:28 +00001677 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001678 if (Number > 0)
1679 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001680 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001681}
1682
Hamza Sood8205a812019-05-04 10:49:46 +00001683// <template-param-decl>
1684// ::= Ty # template type parameter
1685// ::= Tn <type> # template non-type parameter
1686// ::= Tt <template-param-decl>* E # template template parameter
1687void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1688 if (isa<TemplateTypeParmDecl>(Decl)) {
1689 Out << "Ty";
1690 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1691 Out << "Tn";
1692 mangleType(Tn->getType());
1693 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1694 Out << "Tt";
1695 for (auto *Param : *Tt->getTemplateParameters())
1696 mangleTemplateParamDecl(Param);
1697 Out << "E";
1698 }
1699}
1700
Guy Benyei11169dd2012-12-18 14:30:41 +00001701void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001702 // If the context of a closure type is an initializer for a class member
1703 // (static or nonstatic), it is encoded in a qualified name with a final
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 // <prefix> of the form:
1705 //
1706 // <data-member-prefix> := <member source-name> M
1707 //
1708 // Technically, the data-member-prefix is part of the <prefix>. However,
1709 // since a closure type will always be mangled with a prefix, it's easier
1710 // to emit that last part of the prefix here.
1711 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1712 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001713 !isa<ParmVarDecl>(Context)) {
1714 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1715 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 if (const IdentifierInfo *Name
1717 = cast<NamedDecl>(Context)->getIdentifier()) {
1718 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001719 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001720 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001721 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001722 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 }
1724 }
1725 }
1726
1727 Out << "Ul";
Hamza Sood8205a812019-05-04 10:49:46 +00001728 for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1729 mangleTemplateParamDecl(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1731 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001732 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1733 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 Out << "E";
Fangrui Song6907ce22018-07-30 19:24:48 +00001735
1736 // The number is omitted for the first closure type with a given
1737 // <lambda-sig> in a given context; it is n-2 for the nth closure type
Guy Benyei11169dd2012-12-18 14:30:41 +00001738 // (in lexical order) with that same <lambda-sig> and context.
1739 //
1740 // The AST keeps track of the number for us.
1741 unsigned Number = Lambda->getLambdaManglingNumber();
1742 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1743 if (Number > 1)
1744 mangleNumber(Number - 2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001745 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001746}
1747
1748void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1749 switch (qualifier->getKind()) {
1750 case NestedNameSpecifier::Global:
1751 // nothing
1752 return;
1753
Nikola Smiljanic67860242014-09-26 00:28:20 +00001754 case NestedNameSpecifier::Super:
1755 llvm_unreachable("Can't mangle __super specifier");
1756
Guy Benyei11169dd2012-12-18 14:30:41 +00001757 case NestedNameSpecifier::Namespace:
1758 mangleName(qualifier->getAsNamespace());
1759 return;
1760
1761 case NestedNameSpecifier::NamespaceAlias:
1762 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1763 return;
1764
1765 case NestedNameSpecifier::TypeSpec:
1766 case NestedNameSpecifier::TypeSpecWithTemplate:
1767 manglePrefix(QualType(qualifier->getAsType(), 0));
1768 return;
1769
1770 case NestedNameSpecifier::Identifier:
1771 // Member expressions can have these without prefixes, but that
1772 // should end up in mangleUnresolvedPrefix instead.
1773 assert(qualifier->getPrefix());
1774 manglePrefix(qualifier->getPrefix());
1775
1776 mangleSourceName(qualifier->getAsIdentifier());
1777 return;
1778 }
1779
1780 llvm_unreachable("unexpected nested name specifier");
1781}
1782
1783void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1784 // <prefix> ::= <prefix> <unqualified-name>
1785 // ::= <template-prefix> <template-args>
1786 // ::= <template-param>
1787 // ::= # empty
1788 // ::= <substitution>
1789
1790 DC = IgnoreLinkageSpecDecls(DC);
1791
1792 if (DC->isTranslationUnit())
1793 return;
1794
Eli Friedman95f50122013-07-02 17:52:28 +00001795 if (NoFunction && isLocalContainerContext(DC))
1796 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001797
Eli Friedman95f50122013-07-02 17:52:28 +00001798 assert(!isLocalContainerContext(DC));
1799
Fangrui Song6907ce22018-07-30 19:24:48 +00001800 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 if (mangleSubstitution(ND))
1802 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001803
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001805 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1807 mangleTemplatePrefix(TD);
1808 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001809 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001811 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 }
1813
1814 addSubstitution(ND);
1815}
1816
1817void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1818 // <template-prefix> ::= <prefix> <template unqualified-name>
1819 // ::= <template-param>
1820 // ::= <substitution>
1821 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1822 return mangleTemplatePrefix(TD);
1823
1824 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1825 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001826
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 if (OverloadedTemplateStorage *Overloaded
1828 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001829 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001830 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 return;
1832 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001833
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1835 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001836 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1837 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001838 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001839}
1840
Eli Friedman86af13f02013-07-05 18:41:30 +00001841void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1842 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001843 // <template-prefix> ::= <prefix> <template unqualified-name>
1844 // ::= <template-param>
1845 // ::= <substitution>
1846 // <template-template-param> ::= <template-param>
1847 // <substitution>
1848
1849 if (mangleSubstitution(ND))
1850 return;
1851
1852 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001853 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001855 } else {
1856 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001857 if (isa<BuiltinTemplateDecl>(ND))
1858 mangleUnqualifiedName(ND, nullptr);
1859 else
1860 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 }
1862
Guy Benyei11169dd2012-12-18 14:30:41 +00001863 addSubstitution(ND);
1864}
1865
1866/// Mangles a template name under the production <type>. Required for
1867/// template template arguments.
1868/// <type> ::= <class-enum-type>
1869/// ::= <template-param>
1870/// ::= <substitution>
1871void CXXNameMangler::mangleType(TemplateName TN) {
1872 if (mangleSubstitution(TN))
1873 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001874
1875 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001876
1877 switch (TN.getKind()) {
1878 case TemplateName::QualifiedTemplate:
1879 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1880 goto HaveDecl;
1881
1882 case TemplateName::Template:
1883 TD = TN.getAsTemplateDecl();
1884 goto HaveDecl;
1885
1886 HaveDecl:
1887 if (isa<TemplateTemplateParmDecl>(TD))
1888 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1889 else
1890 mangleName(TD);
1891 break;
1892
1893 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00001894 case TemplateName::AssumedTemplate:
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1896
1897 case TemplateName::DependentTemplate: {
1898 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1899 assert(Dependent->isIdentifier());
1900
1901 // <class-enum-type> ::= <name>
1902 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001903 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001904 mangleSourceName(Dependent->getIdentifier());
1905 break;
1906 }
1907
1908 case TemplateName::SubstTemplateTemplateParm: {
1909 // Substituted template parameters are mangled as the substituted
1910 // template. This will check for the substitution twice, which is
1911 // fine, but we have to return early so that we don't try to *add*
1912 // the substitution twice.
1913 SubstTemplateTemplateParmStorage *subst
1914 = TN.getAsSubstTemplateTemplateParm();
1915 mangleType(subst->getReplacement());
1916 return;
1917 }
1918
1919 case TemplateName::SubstTemplateTemplateParmPack: {
1920 // FIXME: not clear how to mangle this!
1921 // template <template <class> class T...> class A {
1922 // template <template <class> class U...> void foo(B<T,U> x...);
1923 // };
1924 Out << "_SUBSTPACK_";
1925 break;
1926 }
1927 }
1928
1929 addSubstitution(TN);
1930}
1931
David Majnemerb8014dd2015-02-19 02:16:16 +00001932bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1933 StringRef Prefix) {
1934 // Only certain other types are valid as prefixes; enumerate them.
1935 switch (Ty->getTypeClass()) {
1936 case Type::Builtin:
1937 case Type::Complex:
1938 case Type::Adjusted:
1939 case Type::Decayed:
1940 case Type::Pointer:
1941 case Type::BlockPointer:
1942 case Type::LValueReference:
1943 case Type::RValueReference:
1944 case Type::MemberPointer:
1945 case Type::ConstantArray:
1946 case Type::IncompleteArray:
1947 case Type::VariableArray:
1948 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001949 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001950 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001951 case Type::DependentSizedExtVector:
1952 case Type::Vector:
1953 case Type::ExtVector:
1954 case Type::FunctionProto:
1955 case Type::FunctionNoProto:
1956 case Type::Paren:
1957 case Type::Attributed:
1958 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001959 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001960 case Type::PackExpansion:
1961 case Type::ObjCObject:
1962 case Type::ObjCInterface:
1963 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001964 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001965 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001966 case Type::Pipe:
Leonard Chanc72aaf62019-05-07 03:20:17 +00001967 case Type::MacroQualified:
David Majnemerb8014dd2015-02-19 02:16:16 +00001968 llvm_unreachable("type is illegal as a nested name specifier");
1969
1970 case Type::SubstTemplateTypeParmPack:
1971 // FIXME: not clear how to mangle this!
1972 // template <class T...> class A {
1973 // template <class U...> void foo(decltype(T::foo(U())) x...);
1974 // };
1975 Out << "_SUBSTPACK_";
1976 break;
1977
1978 // <unresolved-type> ::= <template-param>
1979 // ::= <decltype>
1980 // ::= <template-template-param> <template-args>
1981 // (this last is not official yet)
1982 case Type::TypeOfExpr:
1983 case Type::TypeOf:
1984 case Type::Decltype:
1985 case Type::TemplateTypeParm:
1986 case Type::UnaryTransform:
1987 case Type::SubstTemplateTypeParm:
1988 unresolvedType:
1989 // Some callers want a prefix before the mangled type.
1990 Out << Prefix;
1991
1992 // This seems to do everything we want. It's not really
1993 // sanctioned for a substituted template parameter, though.
1994 mangleType(Ty);
1995
1996 // We never want to print 'E' directly after an unresolved-type,
1997 // so we return directly.
1998 return true;
1999
2000 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002001 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002002 break;
2003
2004 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002005 mangleSourceNameWithAbiTags(
2006 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002007 break;
2008
2009 case Type::Enum:
2010 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002011 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002012 break;
2013
2014 case Type::TemplateSpecialization: {
2015 const TemplateSpecializationType *TST =
2016 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00002017 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00002018 switch (TN.getKind()) {
2019 case TemplateName::Template:
2020 case TemplateName::QualifiedTemplate: {
2021 TemplateDecl *TD = TN.getAsTemplateDecl();
2022
2023 // If the base is a template template parameter, this is an
2024 // unresolved type.
2025 assert(TD && "no template for template specialization type");
2026 if (isa<TemplateTemplateParmDecl>(TD))
2027 goto unresolvedType;
2028
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002029 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002030 break;
David Majnemera88b3592015-02-18 02:28:01 +00002031 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002032
2033 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00002034 case TemplateName::AssumedTemplate:
David Majnemerb8014dd2015-02-19 02:16:16 +00002035 case TemplateName::DependentTemplate:
2036 llvm_unreachable("invalid base for a template specialization type");
2037
2038 case TemplateName::SubstTemplateTemplateParm: {
2039 SubstTemplateTemplateParmStorage *subst =
2040 TN.getAsSubstTemplateTemplateParm();
2041 mangleExistingSubstitution(subst->getReplacement());
2042 break;
2043 }
2044
2045 case TemplateName::SubstTemplateTemplateParmPack: {
2046 // FIXME: not clear how to mangle this!
2047 // template <template <class U> class T...> class A {
2048 // template <class U...> void foo(decltype(T<U>::foo) x...);
2049 // };
2050 Out << "_SUBSTPACK_";
2051 break;
2052 }
2053 }
2054
David Majnemera88b3592015-02-18 02:28:01 +00002055 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002056 break;
David Majnemera88b3592015-02-18 02:28:01 +00002057 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002058
2059 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002060 mangleSourceNameWithAbiTags(
2061 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002062 break;
2063
2064 case Type::DependentName:
2065 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2066 break;
2067
2068 case Type::DependentTemplateSpecialization: {
2069 const DependentTemplateSpecializationType *DTST =
2070 cast<DependentTemplateSpecializationType>(Ty);
2071 mangleSourceName(DTST->getIdentifier());
2072 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2073 break;
2074 }
2075
2076 case Type::Elaborated:
2077 return mangleUnresolvedTypeOrSimpleId(
2078 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2079 }
2080
2081 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002082}
2083
2084void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2085 switch (Name.getNameKind()) {
2086 case DeclarationName::CXXConstructorName:
2087 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002088 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002089 case DeclarationName::CXXUsingDirective:
2090 case DeclarationName::Identifier:
2091 case DeclarationName::ObjCMultiArgSelector:
2092 case DeclarationName::ObjCOneArgSelector:
2093 case DeclarationName::ObjCZeroArgSelector:
2094 llvm_unreachable("Not an operator name");
2095
2096 case DeclarationName::CXXConversionFunctionName:
2097 // <operator-name> ::= cv <type> # (cast)
2098 Out << "cv";
2099 mangleType(Name.getCXXNameType());
2100 break;
2101
2102 case DeclarationName::CXXLiteralOperatorName:
2103 Out << "li";
2104 mangleSourceName(Name.getCXXLiteralIdentifier());
2105 return;
2106
2107 case DeclarationName::CXXOperatorName:
2108 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2109 break;
2110 }
2111}
2112
Guy Benyei11169dd2012-12-18 14:30:41 +00002113void
2114CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2115 switch (OO) {
2116 // <operator-name> ::= nw # new
2117 case OO_New: Out << "nw"; break;
2118 // ::= na # new[]
2119 case OO_Array_New: Out << "na"; break;
2120 // ::= dl # delete
2121 case OO_Delete: Out << "dl"; break;
2122 // ::= da # delete[]
2123 case OO_Array_Delete: Out << "da"; break;
2124 // ::= ps # + (unary)
2125 // ::= pl # + (binary or unknown)
2126 case OO_Plus:
2127 Out << (Arity == 1? "ps" : "pl"); break;
2128 // ::= ng # - (unary)
2129 // ::= mi # - (binary or unknown)
2130 case OO_Minus:
2131 Out << (Arity == 1? "ng" : "mi"); break;
2132 // ::= ad # & (unary)
2133 // ::= an # & (binary or unknown)
2134 case OO_Amp:
2135 Out << (Arity == 1? "ad" : "an"); break;
2136 // ::= de # * (unary)
2137 // ::= ml # * (binary or unknown)
2138 case OO_Star:
2139 // Use binary when unknown.
2140 Out << (Arity == 1? "de" : "ml"); break;
2141 // ::= co # ~
2142 case OO_Tilde: Out << "co"; break;
2143 // ::= dv # /
2144 case OO_Slash: Out << "dv"; break;
2145 // ::= rm # %
2146 case OO_Percent: Out << "rm"; break;
2147 // ::= or # |
2148 case OO_Pipe: Out << "or"; break;
2149 // ::= eo # ^
2150 case OO_Caret: Out << "eo"; break;
2151 // ::= aS # =
2152 case OO_Equal: Out << "aS"; break;
2153 // ::= pL # +=
2154 case OO_PlusEqual: Out << "pL"; break;
2155 // ::= mI # -=
2156 case OO_MinusEqual: Out << "mI"; break;
2157 // ::= mL # *=
2158 case OO_StarEqual: Out << "mL"; break;
2159 // ::= dV # /=
2160 case OO_SlashEqual: Out << "dV"; break;
2161 // ::= rM # %=
2162 case OO_PercentEqual: Out << "rM"; break;
2163 // ::= aN # &=
2164 case OO_AmpEqual: Out << "aN"; break;
2165 // ::= oR # |=
2166 case OO_PipeEqual: Out << "oR"; break;
2167 // ::= eO # ^=
2168 case OO_CaretEqual: Out << "eO"; break;
2169 // ::= ls # <<
2170 case OO_LessLess: Out << "ls"; break;
2171 // ::= rs # >>
2172 case OO_GreaterGreater: Out << "rs"; break;
2173 // ::= lS # <<=
2174 case OO_LessLessEqual: Out << "lS"; break;
2175 // ::= rS # >>=
2176 case OO_GreaterGreaterEqual: Out << "rS"; break;
2177 // ::= eq # ==
2178 case OO_EqualEqual: Out << "eq"; break;
2179 // ::= ne # !=
2180 case OO_ExclaimEqual: Out << "ne"; break;
2181 // ::= lt # <
2182 case OO_Less: Out << "lt"; break;
2183 // ::= gt # >
2184 case OO_Greater: Out << "gt"; break;
2185 // ::= le # <=
2186 case OO_LessEqual: Out << "le"; break;
2187 // ::= ge # >=
2188 case OO_GreaterEqual: Out << "ge"; break;
2189 // ::= nt # !
2190 case OO_Exclaim: Out << "nt"; break;
2191 // ::= aa # &&
2192 case OO_AmpAmp: Out << "aa"; break;
2193 // ::= oo # ||
2194 case OO_PipePipe: Out << "oo"; break;
2195 // ::= pp # ++
2196 case OO_PlusPlus: Out << "pp"; break;
2197 // ::= mm # --
2198 case OO_MinusMinus: Out << "mm"; break;
2199 // ::= cm # ,
2200 case OO_Comma: Out << "cm"; break;
2201 // ::= pm # ->*
2202 case OO_ArrowStar: Out << "pm"; break;
2203 // ::= pt # ->
2204 case OO_Arrow: Out << "pt"; break;
2205 // ::= cl # ()
2206 case OO_Call: Out << "cl"; break;
2207 // ::= ix # []
2208 case OO_Subscript: Out << "ix"; break;
2209
2210 // ::= qu # ?
2211 // The conditional operator can't be overloaded, but we still handle it when
2212 // mangling expressions.
2213 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002214 // Proposal on cxx-abi-dev, 2015-10-21.
2215 // ::= aw # co_await
2216 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002217 // Proposed in cxx-abi github issue 43.
2218 // ::= ss # <=>
2219 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220
2221 case OO_None:
2222 case NUM_OVERLOADED_OPERATORS:
2223 llvm_unreachable("Not an overloaded operator");
2224 }
2225}
2226
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002227void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002228 // Vendor qualifiers come first and if they are order-insensitive they must
2229 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002230
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002231 // <type> ::= U <addrspace-expr>
2232 if (DAST) {
2233 Out << "U2ASI";
2234 mangleExpression(DAST->getAddrSpaceExpr());
2235 Out << "E";
2236 }
2237
John McCall07daf722016-03-01 22:18:03 +00002238 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002240 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 //
David Tweed31d09b02013-09-13 12:04:22 +00002242 // <type> ::= U <target-addrspace>
2243 // <type> ::= U <OpenCL-addrspace>
2244 // <type> ::= U <CUDA-addrspace>
2245
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002247 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002248
2249 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2250 // <target-addrspace> ::= "AS" <address-space-number>
2251 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002252 if (TargetAS != 0)
2253 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002254 } else {
2255 switch (AS) {
2256 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002257 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2258 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002259 case LangAS::opencl_global: ASString = "CLglobal"; break;
2260 case LangAS::opencl_local: ASString = "CLlocal"; break;
2261 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002262 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002263 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002264 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2265 case LangAS::cuda_device: ASString = "CUdevice"; break;
2266 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2267 case LangAS::cuda_shared: ASString = "CUshared"; break;
2268 }
2269 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002270 if (!ASString.empty())
2271 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 }
John McCall07daf722016-03-01 22:18:03 +00002273
2274 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 // Objective-C ARC Extension:
2276 //
2277 // <type> ::= U "__strong"
2278 // <type> ::= U "__weak"
2279 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002280 //
2281 // Note: we emit __weak first to preserve the order as
2282 // required by the Itanium ABI.
2283 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2284 mangleVendorQualifier("__weak");
2285
2286 // __unaligned (from -fms-extensions)
2287 if (Quals.hasUnaligned())
2288 mangleVendorQualifier("__unaligned");
2289
2290 // Remaining ARC ownership qualifiers.
2291 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 case Qualifiers::OCL_None:
2293 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002294
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002296 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002298
Guy Benyei11169dd2012-12-18 14:30:41 +00002299 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002300 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002301 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002302
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002304 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002306
Guy Benyei11169dd2012-12-18 14:30:41 +00002307 case Qualifiers::OCL_ExplicitNone:
2308 // The __unsafe_unretained qualifier is *not* mangled, so that
2309 // __unsafe_unretained types in ARC produce the same manglings as the
2310 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2311 // better ABI compatibility.
2312 //
2313 // It's safe to do this because unqualified 'id' won't show up
2314 // in any type signatures that need to be mangled.
2315 break;
2316 }
John McCall07daf722016-03-01 22:18:03 +00002317
2318 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2319 if (Quals.hasRestrict())
2320 Out << 'r';
2321 if (Quals.hasVolatile())
2322 Out << 'V';
2323 if (Quals.hasConst())
2324 Out << 'K';
2325}
2326
2327void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2328 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329}
2330
2331void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2332 // <ref-qualifier> ::= R # lvalue reference
2333 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 switch (RefQualifier) {
2335 case RQ_None:
2336 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002337
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 case RQ_LValue:
2339 Out << 'R';
2340 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002341
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 case RQ_RValue:
2343 Out << 'O';
2344 break;
2345 }
2346}
2347
2348void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2349 Context.mangleObjCMethodName(MD, Out);
2350}
2351
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002352static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2353 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002354 if (Quals)
2355 return true;
2356 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2357 return true;
2358 if (Ty->isOpenCLSpecificType())
2359 return true;
2360 if (Ty->isBuiltinType())
2361 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002362 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2363 // substitution candidates.
2364 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2365 isa<AutoType>(Ty))
2366 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002367 return true;
2368}
2369
Guy Benyei11169dd2012-12-18 14:30:41 +00002370void CXXNameMangler::mangleType(QualType T) {
2371 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002372 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 // Otherwise, use the canonical type.
2374 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002375 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 // mangling rules, since we should really be using the type as written and
2377 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002378 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002380 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 // uniqued, so that we can handle substitutions properly
2382 // - Default template arguments will need to be represented in the
2383 // TemplateSpecializationType, since they need to be mangled even though
2384 // they aren't written.
2385 // - Conversions on non-type template arguments need to be expressed, since
2386 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002387 //
2388 // FIXME: This is wrong when mapping to the canonical type for a dependent
2389 // type discards instantiation-dependent portions of the type, such as for:
2390 //
2391 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2392 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2393 //
2394 // It's also wrong in the opposite direction when instantiation-dependent,
2395 // canonically-equivalent types differ in some irrelevant portion of inner
2396 // type sugar. In such cases, we fail to form correct substitutions, eg:
2397 //
2398 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2399 //
2400 // We should instead canonicalize the non-instantiation-dependent parts,
2401 // regardless of whether the type as a whole is dependent or instantiation
2402 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 if (!T->isInstantiationDependentType() || T->isDependentType())
2404 T = T.getCanonicalType();
2405 else {
2406 // Desugar any types that are purely sugar.
2407 do {
2408 // Don't desugar through template specialization types that aren't
2409 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002410 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 = dyn_cast<TemplateSpecializationType>(T))
2412 if (!TST->isTypeAlias())
2413 break;
2414
Fangrui Song6907ce22018-07-30 19:24:48 +00002415 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 = T.getSingleStepDesugaredType(Context.getASTContext());
2417 if (Desugared == T)
2418 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002419
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 T = Desugared;
2421 } while (true);
2422 }
2423 SplitQualType split = T.split();
2424 Qualifiers quals = split.Quals;
2425 const Type *ty = split.Ty;
2426
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002427 bool isSubstitutable =
2428 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 if (isSubstitutable && mangleSubstitution(T))
2430 return;
2431
2432 // If we're mangling a qualified array type, push the qualifiers to
2433 // the element type.
2434 if (quals && isa<ArrayType>(T)) {
2435 ty = Context.getASTContext().getAsArrayType(T);
2436 quals = Qualifiers();
2437
2438 // Note that we don't update T: we want to add the
2439 // substitution at the original type.
2440 }
2441
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002442 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002443 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002444 dyn_cast<DependentAddressSpaceType>(ty)) {
2445 SplitQualType splitDAST = DAST->getPointeeType().split();
2446 mangleQualifiers(splitDAST.Quals, DAST);
2447 mangleType(QualType(splitDAST.Ty, 0));
2448 } else {
2449 mangleQualifiers(quals);
2450
2451 // Recurse: even if the qualified type isn't yet substitutable,
2452 // the unqualified type might be.
2453 mangleType(QualType(ty, 0));
2454 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 } else {
2456 switch (ty->getTypeClass()) {
2457#define ABSTRACT_TYPE(CLASS, PARENT)
2458#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2459 case Type::CLASS: \
2460 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2461 return;
2462#define TYPE(CLASS, PARENT) \
2463 case Type::CLASS: \
2464 mangleType(static_cast<const CLASS##Type*>(ty)); \
2465 break;
2466#include "clang/AST/TypeNodes.def"
2467 }
2468 }
2469
2470 // Add the substitution.
2471 if (isSubstitutable)
2472 addSubstitution(T);
2473}
2474
2475void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2476 if (!mangleStandardSubstitution(ND))
2477 mangleName(ND);
2478}
2479
2480void CXXNameMangler::mangleType(const BuiltinType *T) {
2481 // <type> ::= <builtin-type>
2482 // <builtin-type> ::= v # void
2483 // ::= w # wchar_t
2484 // ::= b # bool
2485 // ::= c # char
2486 // ::= a # signed char
2487 // ::= h # unsigned char
2488 // ::= s # short
2489 // ::= t # unsigned short
2490 // ::= i # int
2491 // ::= j # unsigned int
2492 // ::= l # long
2493 // ::= m # unsigned long
2494 // ::= x # long long, __int64
2495 // ::= y # unsigned long long, __int64
2496 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002497 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 // ::= f # float
2499 // ::= d # double
2500 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002501 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2503 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2504 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2505 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002506 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 // ::= Di # char32_t
2508 // ::= Ds # char16_t
2509 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2510 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002511 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002513 case BuiltinType::Void:
2514 Out << 'v';
2515 break;
2516 case BuiltinType::Bool:
2517 Out << 'b';
2518 break;
2519 case BuiltinType::Char_U:
2520 case BuiltinType::Char_S:
2521 Out << 'c';
2522 break;
2523 case BuiltinType::UChar:
2524 Out << 'h';
2525 break;
2526 case BuiltinType::UShort:
2527 Out << 't';
2528 break;
2529 case BuiltinType::UInt:
2530 Out << 'j';
2531 break;
2532 case BuiltinType::ULong:
2533 Out << 'm';
2534 break;
2535 case BuiltinType::ULongLong:
2536 Out << 'y';
2537 break;
2538 case BuiltinType::UInt128:
2539 Out << 'o';
2540 break;
2541 case BuiltinType::SChar:
2542 Out << 'a';
2543 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002545 case BuiltinType::WChar_U:
2546 Out << 'w';
2547 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002548 case BuiltinType::Char8:
2549 Out << "Du";
2550 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002551 case BuiltinType::Char16:
2552 Out << "Ds";
2553 break;
2554 case BuiltinType::Char32:
2555 Out << "Di";
2556 break;
2557 case BuiltinType::Short:
2558 Out << 's';
2559 break;
2560 case BuiltinType::Int:
2561 Out << 'i';
2562 break;
2563 case BuiltinType::Long:
2564 Out << 'l';
2565 break;
2566 case BuiltinType::LongLong:
2567 Out << 'x';
2568 break;
2569 case BuiltinType::Int128:
2570 Out << 'n';
2571 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002572 case BuiltinType::Float16:
2573 Out << "DF16_";
2574 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002575 case BuiltinType::ShortAccum:
2576 case BuiltinType::Accum:
2577 case BuiltinType::LongAccum:
2578 case BuiltinType::UShortAccum:
2579 case BuiltinType::UAccum:
2580 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002581 case BuiltinType::ShortFract:
2582 case BuiltinType::Fract:
2583 case BuiltinType::LongFract:
2584 case BuiltinType::UShortFract:
2585 case BuiltinType::UFract:
2586 case BuiltinType::ULongFract:
2587 case BuiltinType::SatShortAccum:
2588 case BuiltinType::SatAccum:
2589 case BuiltinType::SatLongAccum:
2590 case BuiltinType::SatUShortAccum:
2591 case BuiltinType::SatUAccum:
2592 case BuiltinType::SatULongAccum:
2593 case BuiltinType::SatShortFract:
2594 case BuiltinType::SatFract:
2595 case BuiltinType::SatLongFract:
2596 case BuiltinType::SatUShortFract:
2597 case BuiltinType::SatUFract:
2598 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002599 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002600 case BuiltinType::Half:
2601 Out << "Dh";
2602 break;
2603 case BuiltinType::Float:
2604 Out << 'f';
2605 break;
2606 case BuiltinType::Double:
2607 Out << 'd';
2608 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002609 case BuiltinType::LongDouble:
2610 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2611 ? 'g'
2612 : 'e');
2613 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002614 case BuiltinType::Float128:
2615 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2616 Out << "U10__float128"; // Match the GCC mangling
2617 else
2618 Out << 'g';
2619 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002620 case BuiltinType::NullPtr:
2621 Out << "Dn";
2622 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623
2624#define BUILTIN_TYPE(Id, SingletonId)
2625#define PLACEHOLDER_TYPE(Id, SingletonId) \
2626 case BuiltinType::Id:
2627#include "clang/AST/BuiltinTypes.def"
2628 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002629 if (!NullOut)
2630 llvm_unreachable("mangling a placeholder type");
2631 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002632 case BuiltinType::ObjCId:
2633 Out << "11objc_object";
2634 break;
2635 case BuiltinType::ObjCClass:
2636 Out << "10objc_class";
2637 break;
2638 case BuiltinType::ObjCSel:
2639 Out << "13objc_selector";
2640 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002641#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2642 case BuiltinType::Id: \
2643 type_name = "ocl_" #ImgType "_" #Suffix; \
2644 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002645 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002646#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002647 case BuiltinType::OCLSampler:
2648 Out << "11ocl_sampler";
2649 break;
2650 case BuiltinType::OCLEvent:
2651 Out << "9ocl_event";
2652 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002653 case BuiltinType::OCLClkEvent:
2654 Out << "12ocl_clkevent";
2655 break;
2656 case BuiltinType::OCLQueue:
2657 Out << "9ocl_queue";
2658 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002659 case BuiltinType::OCLReserveID:
2660 Out << "13ocl_reserveid";
2661 break;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002662#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2663 case BuiltinType::Id: \
2664 type_name = "ocl_" #ExtType; \
2665 Out << type_name.size() << type_name; \
2666 break;
2667#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 }
2669}
2670
John McCall07daf722016-03-01 22:18:03 +00002671StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2672 switch (CC) {
2673 case CC_C:
2674 return "";
2675
John McCall07daf722016-03-01 22:18:03 +00002676 case CC_X86VectorCall:
2677 case CC_X86Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00002678 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002679 case CC_AAPCS:
2680 case CC_AAPCS_VFP:
Sander de Smalen44a22532018-11-26 16:38:37 +00002681 case CC_AArch64VectorCall:
John McCall07daf722016-03-01 22:18:03 +00002682 case CC_IntelOclBicc:
2683 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002684 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002685 case CC_PreserveMost:
2686 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002687 // FIXME: we should be mangling all of the above.
2688 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002689
Reid Kleckner0a6096b2018-12-21 01:40:29 +00002690 case CC_X86ThisCall:
2691 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2692 // used explicitly. At this point, we don't have that much information in
2693 // the AST, since clang tends to bake the convention into the canonical
2694 // function type. thiscall only rarely used explicitly, so don't mangle it
2695 // for now.
2696 return "";
2697
Reid Klecknerf5f62902018-12-14 23:42:59 +00002698 case CC_X86StdCall:
2699 return "stdcall";
2700 case CC_X86FastCall:
2701 return "fastcall";
Reid Klecknerf5f62902018-12-14 23:42:59 +00002702 case CC_X86_64SysV:
2703 return "sysv_abi";
2704 case CC_Win64:
2705 return "ms_abi";
John McCall477f2bb2016-03-03 06:39:32 +00002706 case CC_Swift:
2707 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002708 }
2709 llvm_unreachable("bad calling convention");
2710}
2711
2712void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2713 // Fast path.
2714 if (T->getExtInfo() == FunctionType::ExtInfo())
2715 return;
2716
2717 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2718 // This will get more complicated in the future if we mangle other
2719 // things here; but for now, since we mangle ns_returns_retained as
2720 // a qualifier on the result type, we can get away with this:
2721 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2722 if (!CCQualifier.empty())
2723 mangleVendorQualifier(CCQualifier);
2724
2725 // FIXME: regparm
2726 // FIXME: noreturn
2727}
2728
2729void
2730CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2731 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2732
2733 // Note that these are *not* substitution candidates. Demanglers might
2734 // have trouble with this if the parameter type is fully substituted.
2735
John McCall477f2bb2016-03-03 06:39:32 +00002736 switch (PI.getABI()) {
2737 case ParameterABI::Ordinary:
2738 break;
2739
2740 // All of these start with "swift", so they come before "ns_consumed".
2741 case ParameterABI::SwiftContext:
2742 case ParameterABI::SwiftErrorResult:
2743 case ParameterABI::SwiftIndirectResult:
2744 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2745 break;
2746 }
2747
John McCall07daf722016-03-01 22:18:03 +00002748 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002749 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002750
2751 if (PI.isNoEscape())
2752 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002753}
2754
Guy Benyei11169dd2012-12-18 14:30:41 +00002755// <type> ::= <function-type>
2756// <function-type> ::= [<CV-qualifiers>] F [Y]
2757// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002758void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002759 mangleExtFunctionInfo(T);
2760
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2762 // e.g. "const" in "int (A::*)() const".
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00002763 mangleQualifiers(T->getMethodQuals());
Guy Benyei11169dd2012-12-18 14:30:41 +00002764
Richard Smithfda59e52016-10-26 01:05:54 +00002765 // Mangle instantiation-dependent exception-specification, if present,
2766 // per cxx-abi-dev proposal on 2016-10-11.
2767 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002768 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002769 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002770 mangleExpression(T->getNoexceptExpr());
2771 Out << "E";
2772 } else {
2773 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002774 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002775 for (auto ExceptTy : T->exceptions())
2776 mangleType(ExceptTy);
2777 Out << "E";
2778 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002779 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002780 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002781 }
2782
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 Out << 'F';
2784
2785 // FIXME: We don't have enough information in the AST to produce the 'Y'
2786 // encoding for extern "C" function types.
2787 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2788
2789 // Mangle the ref-qualifier, if present.
2790 mangleRefQualifier(T->getRefQualifier());
2791
2792 Out << 'E';
2793}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002794
Guy Benyei11169dd2012-12-18 14:30:41 +00002795void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002796 // Function types without prototypes can arise when mangling a function type
2797 // within an overloadable function in C. We mangle these as the absence of any
2798 // parameter types (not even an empty parameter list).
2799 Out << 'F';
2800
2801 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2802
2803 FunctionTypeDepth.enterResultType();
2804 mangleType(T->getReturnType());
2805 FunctionTypeDepth.leaveResultType();
2806
2807 FunctionTypeDepth.pop(saved);
2808 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002809}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002810
John McCall07daf722016-03-01 22:18:03 +00002811void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002812 bool MangleReturnType,
2813 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 // Record that we're in a function type. See mangleFunctionParam
2815 // for details on what we're trying to achieve here.
2816 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2817
2818 // <bare-function-type> ::= <signature type>+
2819 if (MangleReturnType) {
2820 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002821
2822 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002823 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002824 mangleVendorQualifier("ns_returns_retained");
2825
2826 // Mangle the return type without any direct ARC ownership qualifiers.
2827 QualType ReturnTy = Proto->getReturnType();
2828 if (ReturnTy.getObjCLifetime()) {
2829 auto SplitReturnTy = ReturnTy.split();
2830 SplitReturnTy.Quals.removeObjCLifetime();
2831 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2832 }
2833 mangleType(ReturnTy);
2834
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 FunctionTypeDepth.leaveResultType();
2836 }
2837
Alp Toker9cacbab2014-01-20 20:26:09 +00002838 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 // <builtin-type> ::= v # void
2840 Out << 'v';
2841
2842 FunctionTypeDepth.pop(saved);
2843 return;
2844 }
2845
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002846 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2847 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002848 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002849 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002850 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2851 }
2852
2853 // Mangle the type.
2854 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002855 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2856
2857 if (FD) {
2858 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2859 // Attr can only take 1 character, so we can hardcode the length below.
2860 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
Erik Pilkington02d5fb12019-03-19 20:44:18 +00002861 if (Attr->isDynamic())
2862 Out << "U25pass_dynamic_object_size" << Attr->getType();
2863 else
2864 Out << "U17pass_object_size" << Attr->getType();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002865 }
2866 }
2867 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002868
2869 FunctionTypeDepth.pop(saved);
2870
2871 // <builtin-type> ::= z # ellipsis
2872 if (Proto->isVariadic())
2873 Out << 'z';
2874}
2875
2876// <type> ::= <class-enum-type>
2877// <class-enum-type> ::= <name>
2878void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2879 mangleName(T->getDecl());
2880}
2881
2882// <type> ::= <class-enum-type>
2883// <class-enum-type> ::= <name>
2884void CXXNameMangler::mangleType(const EnumType *T) {
2885 mangleType(static_cast<const TagType*>(T));
2886}
2887void CXXNameMangler::mangleType(const RecordType *T) {
2888 mangleType(static_cast<const TagType*>(T));
2889}
2890void CXXNameMangler::mangleType(const TagType *T) {
2891 mangleName(T->getDecl());
2892}
2893
2894// <type> ::= <array-type>
2895// <array-type> ::= A <positive dimension number> _ <element type>
2896// ::= A [<dimension expression>] _ <element type>
2897void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2898 Out << 'A' << T->getSize() << '_';
2899 mangleType(T->getElementType());
2900}
2901void CXXNameMangler::mangleType(const VariableArrayType *T) {
2902 Out << 'A';
2903 // decayed vla types (size 0) will just be skipped.
2904 if (T->getSizeExpr())
2905 mangleExpression(T->getSizeExpr());
2906 Out << '_';
2907 mangleType(T->getElementType());
2908}
2909void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2910 Out << 'A';
2911 mangleExpression(T->getSizeExpr());
2912 Out << '_';
2913 mangleType(T->getElementType());
2914}
2915void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2916 Out << "A_";
2917 mangleType(T->getElementType());
2918}
2919
2920// <type> ::= <pointer-to-member-type>
2921// <pointer-to-member-type> ::= M <class type> <member type>
2922void CXXNameMangler::mangleType(const MemberPointerType *T) {
2923 Out << 'M';
2924 mangleType(QualType(T->getClass(), 0));
2925 QualType PointeeType = T->getPointeeType();
2926 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2927 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002928
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 // Itanium C++ ABI 5.1.8:
2930 //
2931 // The type of a non-static member function is considered to be different,
2932 // for the purposes of substitution, from the type of a namespace-scope or
2933 // static member function whose type appears similar. The types of two
2934 // non-static member functions are considered to be different, for the
2935 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002936 // classes. In other words, for the purposes of substitution, the class of
2937 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 // function.
2939
2940 // Given that we already substitute member function pointers as a
2941 // whole, the net effect of this rule is just to unconditionally
2942 // suppress substitution on the function type in a member pointer.
2943 // We increment the SeqID here to emulate adding an entry to the
2944 // substitution table.
2945 ++SeqID;
2946 } else
2947 mangleType(PointeeType);
2948}
2949
2950// <type> ::= <template-param>
2951void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2952 mangleTemplateParameter(T->getIndex());
2953}
2954
2955// <type> ::= <template-param>
2956void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2957 // FIXME: not clear how to mangle this!
2958 // template <class T...> class A {
2959 // template <class U...> void foo(T(*)(U) x...);
2960 // };
2961 Out << "_SUBSTPACK_";
2962}
2963
2964// <type> ::= P <type> # pointer-to
2965void CXXNameMangler::mangleType(const PointerType *T) {
2966 Out << 'P';
2967 mangleType(T->getPointeeType());
2968}
2969void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2970 Out << 'P';
2971 mangleType(T->getPointeeType());
2972}
2973
2974// <type> ::= R <type> # reference-to
2975void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2976 Out << 'R';
2977 mangleType(T->getPointeeType());
2978}
2979
2980// <type> ::= O <type> # rvalue reference-to (C++0x)
2981void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2982 Out << 'O';
2983 mangleType(T->getPointeeType());
2984}
2985
2986// <type> ::= C <type> # complex pair (C 2000)
2987void CXXNameMangler::mangleType(const ComplexType *T) {
2988 Out << 'C';
2989 mangleType(T->getElementType());
2990}
2991
2992// ARM's ABI for Neon vector types specifies that they should be mangled as
2993// if they are structs (to match ARM's initial implementation). The
2994// vector type must be one of the special types predefined by ARM.
2995void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2996 QualType EltType = T->getElementType();
2997 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002998 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3000 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003001 case BuiltinType::SChar:
3002 case BuiltinType::UChar:
3003 EltName = "poly8_t";
3004 break;
3005 case BuiltinType::Short:
3006 case BuiltinType::UShort:
3007 EltName = "poly16_t";
3008 break;
3009 case BuiltinType::ULongLong:
3010 EltName = "poly64_t";
3011 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 default: llvm_unreachable("unexpected Neon polynomial vector element type");
3013 }
3014 } else {
3015 switch (cast<BuiltinType>(EltType)->getKind()) {
3016 case BuiltinType::SChar: EltName = "int8_t"; break;
3017 case BuiltinType::UChar: EltName = "uint8_t"; break;
3018 case BuiltinType::Short: EltName = "int16_t"; break;
3019 case BuiltinType::UShort: EltName = "uint16_t"; break;
3020 case BuiltinType::Int: EltName = "int32_t"; break;
3021 case BuiltinType::UInt: EltName = "uint32_t"; break;
3022 case BuiltinType::LongLong: EltName = "int64_t"; break;
3023 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00003024 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003026 case BuiltinType::Half: EltName = "float16_t";break;
3027 default:
3028 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 }
3030 }
Craig Topper36250ad2014-05-12 05:36:57 +00003031 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 unsigned BitSize = (T->getNumElements() *
3033 getASTContext().getTypeSize(EltType));
3034 if (BitSize == 64)
3035 BaseName = "__simd64_";
3036 else {
3037 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3038 BaseName = "__simd128_";
3039 }
3040 Out << strlen(BaseName) + strlen(EltName);
3041 Out << BaseName << EltName;
3042}
3043
Erich Keanef702b022018-07-13 19:46:04 +00003044void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3045 DiagnosticsEngine &Diags = Context.getDiags();
3046 unsigned DiagID = Diags.getCustomDiagID(
3047 DiagnosticsEngine::Error,
3048 "cannot mangle this dependent neon vector type yet");
3049 Diags.Report(T->getAttributeLoc(), DiagID);
3050}
3051
Tim Northover2fe823a2013-08-01 09:23:19 +00003052static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3053 switch (EltType->getKind()) {
3054 case BuiltinType::SChar:
3055 return "Int8";
3056 case BuiltinType::Short:
3057 return "Int16";
3058 case BuiltinType::Int:
3059 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003060 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003061 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003062 return "Int64";
3063 case BuiltinType::UChar:
3064 return "Uint8";
3065 case BuiltinType::UShort:
3066 return "Uint16";
3067 case BuiltinType::UInt:
3068 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003069 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003070 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003071 return "Uint64";
3072 case BuiltinType::Half:
3073 return "Float16";
3074 case BuiltinType::Float:
3075 return "Float32";
3076 case BuiltinType::Double:
3077 return "Float64";
3078 default:
3079 llvm_unreachable("Unexpected vector element base type");
3080 }
3081}
3082
3083// AArch64's ABI for Neon vector types specifies that they should be mangled as
3084// the equivalent internal name. The vector type must be one of the special
3085// types predefined by ARM.
3086void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3087 QualType EltType = T->getElementType();
3088 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3089 unsigned BitSize =
3090 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003091 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003092
3093 assert((BitSize == 64 || BitSize == 128) &&
3094 "Neon vector type not 64 or 128 bits");
3095
Tim Northover2fe823a2013-08-01 09:23:19 +00003096 StringRef EltName;
3097 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3098 switch (cast<BuiltinType>(EltType)->getKind()) {
3099 case BuiltinType::UChar:
3100 EltName = "Poly8";
3101 break;
3102 case BuiltinType::UShort:
3103 EltName = "Poly16";
3104 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003105 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003106 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003107 EltName = "Poly64";
3108 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003109 default:
3110 llvm_unreachable("unexpected Neon polynomial vector element type");
3111 }
3112 } else
3113 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3114
3115 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003116 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003117 Out << TypeName.length() << TypeName;
3118}
Erich Keanef702b022018-07-13 19:46:04 +00003119void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3120 DiagnosticsEngine &Diags = Context.getDiags();
3121 unsigned DiagID = Diags.getCustomDiagID(
3122 DiagnosticsEngine::Error,
3123 "cannot mangle this dependent neon vector type yet");
3124 Diags.Report(T->getAttributeLoc(), DiagID);
3125}
Tim Northover2fe823a2013-08-01 09:23:19 +00003126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127// GNU extension: vector types
3128// <type> ::= <vector-type>
3129// <vector-type> ::= Dv <positive dimension number> _
3130// <extended element type>
3131// ::= Dv [<dimension expression>] _ <element type>
3132// <extended element type> ::= <element type>
3133// ::= p # AltiVec vector pixel
3134// ::= b # Altivec vector bool
3135void CXXNameMangler::mangleType(const VectorType *T) {
3136 if ((T->getVectorKind() == VectorType::NeonVector ||
3137 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003138 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003139 llvm::Triple::ArchType Arch =
3140 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003141 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003142 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003143 mangleAArch64NeonVectorType(T);
3144 else
3145 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 return;
3147 }
3148 Out << "Dv" << T->getNumElements() << '_';
3149 if (T->getVectorKind() == VectorType::AltiVecPixel)
3150 Out << 'p';
3151 else if (T->getVectorKind() == VectorType::AltiVecBool)
3152 Out << 'b';
3153 else
3154 mangleType(T->getElementType());
3155}
Erich Keanef702b022018-07-13 19:46:04 +00003156
3157void CXXNameMangler::mangleType(const DependentVectorType *T) {
3158 if ((T->getVectorKind() == VectorType::NeonVector ||
3159 T->getVectorKind() == VectorType::NeonPolyVector)) {
3160 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3161 llvm::Triple::ArchType Arch =
3162 getASTContext().getTargetInfo().getTriple().getArch();
3163 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3164 !Target.isOSDarwin())
3165 mangleAArch64NeonVectorType(T);
3166 else
3167 mangleNeonVectorType(T);
3168 return;
3169 }
3170
3171 Out << "Dv";
3172 mangleExpression(T->getSizeExpr());
3173 Out << '_';
3174 if (T->getVectorKind() == VectorType::AltiVecPixel)
3175 Out << 'p';
3176 else if (T->getVectorKind() == VectorType::AltiVecBool)
3177 Out << 'b';
3178 else
3179 mangleType(T->getElementType());
3180}
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182void CXXNameMangler::mangleType(const ExtVectorType *T) {
3183 mangleType(static_cast<const VectorType*>(T));
3184}
3185void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3186 Out << "Dv";
3187 mangleExpression(T->getSizeExpr());
3188 Out << '_';
3189 mangleType(T->getElementType());
3190}
3191
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003192void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3193 SplitQualType split = T->getPointeeType().split();
3194 mangleQualifiers(split.Quals, T);
3195 mangleType(QualType(split.Ty, 0));
3196}
3197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198void CXXNameMangler::mangleType(const PackExpansionType *T) {
3199 // <type> ::= Dp <type> # pack expansion (C++0x)
3200 Out << "Dp";
3201 mangleType(T->getPattern());
3202}
3203
3204void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3205 mangleSourceName(T->getDecl()->getIdentifier());
3206}
3207
3208void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003209 // Treat __kindof as a vendor extended type qualifier.
3210 if (T->isKindOfType())
3211 Out << "U8__kindof";
3212
Eli Friedman5f508952013-06-18 22:41:37 +00003213 if (!T->qual_empty()) {
3214 // Mangle protocol qualifiers.
3215 SmallString<64> QualStr;
3216 llvm::raw_svector_ostream QualOS(QualStr);
3217 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003218 for (const auto *I : T->quals()) {
3219 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003220 QualOS << name.size() << name;
3221 }
Eli Friedman5f508952013-06-18 22:41:37 +00003222 Out << 'U' << QualStr.size() << QualStr;
3223 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003224
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003226
3227 if (T->isSpecialized()) {
3228 // Mangle type arguments as I <type>+ E
3229 Out << 'I';
3230 for (auto typeArg : T->getTypeArgs())
3231 mangleType(typeArg);
3232 Out << 'E';
3233 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003234}
3235
3236void CXXNameMangler::mangleType(const BlockPointerType *T) {
3237 Out << "U13block_pointer";
3238 mangleType(T->getPointeeType());
3239}
3240
3241void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3242 // Mangle injected class name types as if the user had written the
3243 // specialization out fully. It may not actually be possible to see
3244 // this mangling, though.
3245 mangleType(T->getInjectedSpecializationType());
3246}
3247
3248void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3249 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003250 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 } else {
3252 if (mangleSubstitution(QualType(T, 0)))
3253 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003254
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003256
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 // FIXME: GCC does not appear to mangle the template arguments when
3258 // the template in question is a dependent template name. Should we
3259 // emulate that badness?
3260 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3261 addSubstitution(QualType(T, 0));
3262 }
3263}
3264
3265void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003266 // Proposal by cxx-abi-dev, 2014-03-26
3267 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3268 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003269 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003270 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003271 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003272 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003273 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003274 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003275 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003276 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003277 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003278 case ETK_Typename:
3279 break;
3280 case ETK_Struct:
3281 case ETK_Class:
3282 case ETK_Interface:
3283 Out << "Ts";
3284 break;
3285 case ETK_Union:
3286 Out << "Tu";
3287 break;
3288 case ETK_Enum:
3289 Out << "Te";
3290 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003291 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003292 // Typename types are always nested
3293 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003295 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 Out << 'E';
3297}
3298
3299void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3300 // Dependently-scoped template types are nested if they have a prefix.
3301 Out << 'N';
3302
3303 // TODO: avoid making this TemplateName.
3304 TemplateName Prefix =
3305 getASTContext().getDependentTemplateName(T->getQualifier(),
3306 T->getIdentifier());
3307 mangleTemplatePrefix(Prefix);
3308
3309 // FIXME: GCC does not appear to mangle the template arguments when
3310 // the template in question is a dependent template name. Should we
3311 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003312 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 Out << 'E';
3314}
3315
3316void CXXNameMangler::mangleType(const TypeOfType *T) {
3317 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3318 // "extension with parameters" mangling.
3319 Out << "u6typeof";
3320}
3321
3322void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3323 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3324 // "extension with parameters" mangling.
3325 Out << "u6typeof";
3326}
3327
3328void CXXNameMangler::mangleType(const DecltypeType *T) {
3329 Expr *E = T->getUnderlyingExpr();
3330
3331 // type ::= Dt <expression> E # decltype of an id-expression
3332 // # or class member access
3333 // ::= DT <expression> E # decltype of an expression
3334
3335 // This purports to be an exhaustive list of id-expressions and
3336 // class member accesses. Note that we do not ignore parentheses;
3337 // parentheses change the semantics of decltype for these
3338 // expressions (and cause the mangler to use the other form).
3339 if (isa<DeclRefExpr>(E) ||
3340 isa<MemberExpr>(E) ||
3341 isa<UnresolvedLookupExpr>(E) ||
3342 isa<DependentScopeDeclRefExpr>(E) ||
3343 isa<CXXDependentScopeMemberExpr>(E) ||
3344 isa<UnresolvedMemberExpr>(E))
3345 Out << "Dt";
3346 else
3347 Out << "DT";
3348 mangleExpression(E);
3349 Out << 'E';
3350}
3351
3352void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3353 // If this is dependent, we need to record that. If not, we simply
3354 // mangle it as the underlying type since they are equivalent.
3355 if (T->isDependentType()) {
3356 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003357
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 switch (T->getUTTKind()) {
3359 case UnaryTransformType::EnumUnderlyingType:
3360 Out << "3eut";
3361 break;
3362 }
3363 }
3364
David Majnemer140065a2016-06-08 00:34:15 +00003365 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003366}
3367
3368void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003369 assert(T->getDeducedType().isNull() &&
3370 "Deduced AutoType shouldn't be handled here!");
3371 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3372 "shouldn't need to mangle __auto_type!");
3373 // <builtin-type> ::= Da # auto
3374 // ::= Dc # decltype(auto)
3375 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003376}
3377
Richard Smith600b5262017-01-26 20:40:47 +00003378void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3379 // FIXME: This is not the right mangling. We also need to include a scope
3380 // here in some cases.
3381 QualType D = T->getDeducedType();
3382 if (D.isNull())
3383 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3384 else
3385 mangleType(D);
3386}
3387
Guy Benyei11169dd2012-12-18 14:30:41 +00003388void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003389 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 // (Until there's a standardized mangling...)
3391 Out << "U7_Atomic";
3392 mangleType(T->getValueType());
3393}
3394
Xiuli Pan9c14e282016-01-09 12:53:17 +00003395void CXXNameMangler::mangleType(const PipeType *T) {
3396 // Pipe type mangling rules are described in SPIR 2.0 specification
3397 // A.1 Data types and A.3 Summary of changes
3398 // <type> ::= 8ocl_pipe
3399 Out << "8ocl_pipe";
3400}
3401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402void CXXNameMangler::mangleIntegerLiteral(QualType T,
3403 const llvm::APSInt &Value) {
3404 // <expr-primary> ::= L <type> <value number> E # integer literal
3405 Out << 'L';
3406
3407 mangleType(T);
3408 if (T->isBooleanType()) {
3409 // Boolean values are encoded as 0/1.
3410 Out << (Value.getBoolValue() ? '1' : '0');
3411 } else {
3412 mangleNumber(Value);
3413 }
3414 Out << 'E';
3415
3416}
3417
David Majnemer1dabfdc2015-02-14 13:23:54 +00003418void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3419 // Ignore member expressions involving anonymous unions.
3420 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3421 if (!RT->getDecl()->isAnonymousStructOrUnion())
3422 break;
3423 const auto *ME = dyn_cast<MemberExpr>(Base);
3424 if (!ME)
3425 break;
3426 Base = ME->getBase();
3427 IsArrow = ME->isArrow();
3428 }
3429
3430 if (Base->isImplicitCXXThis()) {
3431 // Note: GCC mangles member expressions to the implicit 'this' as
3432 // *this., whereas we represent them as this->. The Itanium C++ ABI
3433 // does not specify anything here, so we follow GCC.
3434 Out << "dtdefpT";
3435 } else {
3436 Out << (IsArrow ? "pt" : "dt");
3437 mangleExpression(Base);
3438 }
3439}
3440
Guy Benyei11169dd2012-12-18 14:30:41 +00003441/// Mangles a member expression.
3442void CXXNameMangler::mangleMemberExpr(const Expr *base,
3443 bool isArrow,
3444 NestedNameSpecifier *qualifier,
3445 NamedDecl *firstQualifierLookup,
3446 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003447 const TemplateArgumentLoc *TemplateArgs,
3448 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 unsigned arity) {
3450 // <expression> ::= dt <expression> <unresolved-name>
3451 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003452 if (base)
3453 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003454 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003455}
3456
3457/// Look at the callee of the given call expression and determine if
3458/// it's a parenthesized id-expression which would have triggered ADL
3459/// otherwise.
3460static bool isParenthesizedADLCallee(const CallExpr *call) {
3461 const Expr *callee = call->getCallee();
3462 const Expr *fn = callee->IgnoreParens();
3463
3464 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3465 // too, but for those to appear in the callee, it would have to be
3466 // parenthesized.
3467 if (callee == fn) return false;
3468
3469 // Must be an unresolved lookup.
3470 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3471 if (!lookup) return false;
3472
3473 assert(!lookup->requiresADL());
3474
3475 // Must be an unqualified lookup.
3476 if (lookup->getQualifier()) return false;
3477
3478 // Must not have found a class member. Note that if one is a class
3479 // member, they're all class members.
3480 if (lookup->getNumDecls() > 0 &&
3481 (*lookup->decls_begin())->isCXXClassMember())
3482 return false;
3483
3484 // Otherwise, ADL would have been triggered.
3485 return true;
3486}
3487
David Majnemer9c775c72014-09-23 04:27:55 +00003488void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3489 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3490 Out << CastEncoding;
3491 mangleType(ECE->getType());
3492 mangleExpression(ECE->getSubExpr());
3493}
3494
Richard Smith520449d2015-02-05 06:15:50 +00003495void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3496 if (auto *Syntactic = InitList->getSyntacticForm())
3497 InitList = Syntactic;
3498 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3499 mangleExpression(InitList->getInit(i));
3500}
3501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3503 // <expression> ::= <unary operator-name> <expression>
3504 // ::= <binary operator-name> <expression> <expression>
3505 // ::= <trinary operator-name> <expression> <expression> <expression>
3506 // ::= cv <type> expression # conversion with one argument
3507 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003508 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3509 // ::= sc <type> <expression> # static_cast<type> (expression)
3510 // ::= cc <type> <expression> # const_cast<type> (expression)
3511 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003512 // ::= st <type> # sizeof (a type)
3513 // ::= at <type> # alignof (a type)
3514 // ::= <template-param>
3515 // ::= <function-param>
3516 // ::= sr <type> <unqualified-name> # dependent name
3517 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3518 // ::= ds <expression> <expression> # expr.*expr
3519 // ::= sZ <template-param> # size of a parameter pack
3520 // ::= sZ <function-param> # size of a function parameter pack
3521 // ::= <expr-primary>
3522 // <expr-primary> ::= L <type> <value number> E # integer literal
3523 // ::= L <type <value float> E # floating literal
3524 // ::= L <mangled-name> E # external name
3525 // ::= fpT # 'this' expression
3526 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003527
Guy Benyei11169dd2012-12-18 14:30:41 +00003528recurse:
3529 switch (E->getStmtClass()) {
3530 case Expr::NoStmtClass:
3531#define ABSTRACT_STMT(Type)
3532#define EXPR(Type, Base)
3533#define STMT(Type, Base) \
3534 case Expr::Type##Class:
3535#include "clang/AST/StmtNodes.inc"
3536 // fallthrough
3537
3538 // These all can only appear in local or variable-initialization
3539 // contexts and so should never appear in a mangling.
3540 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003541 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003543 case Expr::ArrayInitLoopExprClass:
3544 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003545 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 case Expr::ParenListExprClass:
3547 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003548 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003549 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003550 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003551 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003552 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 llvm_unreachable("unexpected statement kind");
3554
Bill Wendling7c44da22018-10-31 03:48:47 +00003555 case Expr::ConstantExprClass:
3556 E = cast<ConstantExpr>(E)->getSubExpr();
3557 goto recurse;
3558
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 // FIXME: invent manglings for all these.
3560 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 case Expr::ChooseExprClass:
3562 case Expr::CompoundLiteralExprClass:
3563 case Expr::ExtVectorElementExprClass:
3564 case Expr::GenericSelectionExprClass:
3565 case Expr::ObjCEncodeExprClass:
3566 case Expr::ObjCIsaExprClass:
3567 case Expr::ObjCIvarRefExprClass:
3568 case Expr::ObjCMessageExprClass:
3569 case Expr::ObjCPropertyRefExprClass:
3570 case Expr::ObjCProtocolExprClass:
3571 case Expr::ObjCSelectorExprClass:
3572 case Expr::ObjCStringLiteralClass:
3573 case Expr::ObjCBoxedExprClass:
3574 case Expr::ObjCArrayLiteralClass:
3575 case Expr::ObjCDictionaryLiteralClass:
3576 case Expr::ObjCSubscriptRefExprClass:
3577 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003578 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 case Expr::OffsetOfExprClass:
3580 case Expr::PredefinedExprClass:
3581 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003582 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003584 case Expr::TypeTraitExprClass:
3585 case Expr::ArrayTypeTraitExprClass:
3586 case Expr::ExpressionTraitExprClass:
3587 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 case Expr::CUDAKernelCallExprClass:
3589 case Expr::AsTypeExprClass:
3590 case Expr::PseudoObjectExprClass:
3591 case Expr::AtomicExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +00003592 case Expr::SourceLocExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003593 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003594 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003595 if (!NullOut) {
3596 // As bad as this diagnostic is, it's better than crashing.
3597 DiagnosticsEngine &Diags = Context.getDiags();
3598 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3599 "cannot yet mangle expression type %0");
3600 Diags.Report(E->getExprLoc(), DiagID)
3601 << E->getStmtClassName() << E->getSourceRange();
3602 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 break;
3604 }
3605
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003606 case Expr::CXXUuidofExprClass: {
3607 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3608 if (UE->isTypeOperand()) {
3609 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3610 Out << "u8__uuidoft";
3611 mangleType(UuidT);
3612 } else {
3613 Expr *UuidExp = UE->getExprOperand();
3614 Out << "u8__uuidofz";
3615 mangleExpression(UuidExp, Arity);
3616 }
3617 break;
3618 }
3619
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 // Even gcc-4.5 doesn't mangle this.
3621 case Expr::BinaryConditionalOperatorClass: {
3622 DiagnosticsEngine &Diags = Context.getDiags();
3623 unsigned DiagID =
3624 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3625 "?: operator with omitted middle operand cannot be mangled");
3626 Diags.Report(E->getExprLoc(), DiagID)
3627 << E->getStmtClassName() << E->getSourceRange();
3628 break;
3629 }
3630
3631 // These are used for internal purposes and cannot be meaningfully mangled.
3632 case Expr::OpaqueValueExprClass:
3633 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3634
3635 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003637 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 Out << "E";
3639 break;
3640 }
3641
Richard Smith39eca9b2017-08-23 22:12:08 +00003642 case Expr::DesignatedInitExprClass: {
3643 auto *DIE = cast<DesignatedInitExpr>(E);
3644 for (const auto &Designator : DIE->designators()) {
3645 if (Designator.isFieldDesignator()) {
3646 Out << "di";
3647 mangleSourceName(Designator.getFieldName());
3648 } else if (Designator.isArrayDesignator()) {
3649 Out << "dx";
3650 mangleExpression(DIE->getArrayIndex(Designator));
3651 } else {
3652 assert(Designator.isArrayRangeDesignator() &&
3653 "unknown designator kind");
3654 Out << "dX";
3655 mangleExpression(DIE->getArrayRangeStart(Designator));
3656 mangleExpression(DIE->getArrayRangeEnd(Designator));
3657 }
3658 }
3659 mangleExpression(DIE->getInit());
3660 break;
3661 }
3662
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 case Expr::CXXDefaultArgExprClass:
3664 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3665 break;
3666
Richard Smith852c9db2013-04-20 22:23:05 +00003667 case Expr::CXXDefaultInitExprClass:
3668 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3669 break;
3670
Richard Smithcc1b96d2013-06-12 22:31:48 +00003671 case Expr::CXXStdInitializerListExprClass:
3672 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3673 break;
3674
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 case Expr::SubstNonTypeTemplateParmExprClass:
3676 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3677 Arity);
3678 break;
3679
3680 case Expr::UserDefinedLiteralClass:
3681 // We follow g++'s approach of mangling a UDL as a call to the literal
3682 // operator.
3683 case Expr::CXXMemberCallExprClass: // fallthrough
3684 case Expr::CallExprClass: {
3685 const CallExpr *CE = cast<CallExpr>(E);
3686
3687 // <expression> ::= cp <simple-id> <expression>* E
3688 // We use this mangling only when the call would use ADL except
3689 // for being parenthesized. Per discussion with David
3690 // Vandervoorde, 2011.04.25.
3691 if (isParenthesizedADLCallee(CE)) {
3692 Out << "cp";
3693 // The callee here is a parenthesized UnresolvedLookupExpr with
3694 // no qualifier and should always get mangled as a <simple-id>
3695 // anyway.
3696
3697 // <expression> ::= cl <expression>* E
3698 } else {
3699 Out << "cl";
3700 }
3701
David Majnemer67a8ec62015-02-19 21:41:48 +00003702 unsigned CallArity = CE->getNumArgs();
3703 for (const Expr *Arg : CE->arguments())
3704 if (isa<PackExpansionExpr>(Arg))
3705 CallArity = UnknownArity;
3706
3707 mangleExpression(CE->getCallee(), CallArity);
3708 for (const Expr *Arg : CE->arguments())
3709 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 Out << 'E';
3711 break;
3712 }
3713
3714 case Expr::CXXNewExprClass: {
3715 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3716 if (New->isGlobalNew()) Out << "gs";
3717 Out << (New->isArray() ? "na" : "nw");
3718 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3719 E = New->placement_arg_end(); I != E; ++I)
3720 mangleExpression(*I);
3721 Out << '_';
3722 mangleType(New->getAllocatedType());
3723 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3725 Out << "il";
3726 else
3727 Out << "pi";
3728 const Expr *Init = New->getInitializer();
3729 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3730 // Directly inline the initializers.
3731 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3732 E = CCE->arg_end();
3733 I != E; ++I)
3734 mangleExpression(*I);
3735 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3736 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3737 mangleExpression(PLE->getExpr(i));
3738 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3739 isa<InitListExpr>(Init)) {
3740 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003741 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 } else
3743 mangleExpression(Init);
3744 }
3745 Out << 'E';
3746 break;
3747 }
3748
David Majnemer1dabfdc2015-02-14 13:23:54 +00003749 case Expr::CXXPseudoDestructorExprClass: {
3750 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3751 if (const Expr *Base = PDE->getBase())
3752 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003753 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003754 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3755 if (Qualifier) {
3756 mangleUnresolvedPrefix(Qualifier,
3757 /*Recursive=*/true);
3758 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3759 Out << 'E';
3760 } else {
3761 Out << "sr";
3762 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3763 Out << 'E';
3764 }
3765 } else if (Qualifier) {
3766 mangleUnresolvedPrefix(Qualifier);
3767 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003768 // <base-unresolved-name> ::= dn <destructor-name>
3769 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003770 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003771 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003772 break;
3773 }
3774
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 case Expr::MemberExprClass: {
3776 const MemberExpr *ME = cast<MemberExpr>(E);
3777 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003778 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003779 ME->getMemberDecl()->getDeclName(),
3780 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3781 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 break;
3783 }
3784
3785 case Expr::UnresolvedMemberExprClass: {
3786 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003787 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3788 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003789 ME->getMemberName(),
3790 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3791 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 break;
3793 }
3794
3795 case Expr::CXXDependentScopeMemberExprClass: {
3796 const CXXDependentScopeMemberExpr *ME
3797 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003798 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3799 ME->isArrow(), ME->getQualifier(),
3800 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003801 ME->getMember(),
3802 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3803 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 break;
3805 }
3806
3807 case Expr::UnresolvedLookupExprClass: {
3808 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003809 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3810 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3811 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 break;
3813 }
3814
3815 case Expr::CXXUnresolvedConstructExprClass: {
3816 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3817 unsigned N = CE->arg_size();
3818
Richard Smith39eca9b2017-08-23 22:12:08 +00003819 if (CE->isListInitialization()) {
3820 assert(N == 1 && "unexpected form for list initialization");
3821 auto *IL = cast<InitListExpr>(CE->getArg(0));
3822 Out << "tl";
3823 mangleType(CE->getType());
3824 mangleInitListElements(IL);
3825 Out << "E";
3826 return;
3827 }
3828
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 Out << "cv";
3830 mangleType(CE->getType());
3831 if (N != 1) Out << '_';
3832 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3833 if (N != 1) Out << 'E';
3834 break;
3835 }
3836
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003838 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003839 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003840 assert(
3841 CE->getNumArgs() >= 1 &&
3842 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3843 "implicit CXXConstructExpr must have one argument");
3844 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3845 }
3846 Out << "il";
3847 for (auto *E : CE->arguments())
3848 mangleExpression(E);
3849 Out << "E";
3850 break;
3851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003852
Richard Smith520449d2015-02-05 06:15:50 +00003853 case Expr::CXXTemporaryObjectExprClass: {
3854 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3855 unsigned N = CE->getNumArgs();
3856 bool List = CE->isListInitialization();
3857
3858 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 Out << "tl";
3860 else
3861 Out << "cv";
3862 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003863 if (!List && N != 1)
3864 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003865 if (CE->isStdInitListInitialization()) {
3866 // We implicitly created a std::initializer_list<T> for the first argument
3867 // of a constructor of type U in an expression of the form U{a, b, c}.
3868 // Strip all the semantic gunk off the initializer list.
3869 auto *SILE =
3870 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3871 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3872 mangleInitListElements(ILE);
3873 } else {
3874 for (auto *E : CE->arguments())
3875 mangleExpression(E);
3876 }
Richard Smith520449d2015-02-05 06:15:50 +00003877 if (List || N != 1)
3878 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 break;
3880 }
3881
3882 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003883 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003885 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 break;
3887
3888 case Expr::CXXNoexceptExprClass:
3889 Out << "nx";
3890 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3891 break;
3892
3893 case Expr::UnaryExprOrTypeTraitExprClass: {
3894 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003895
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 if (!SAE->isInstantiationDependent()) {
3897 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003898 // If the operand of a sizeof or alignof operator is not
3899 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003900 // reflecting the result of the operator.
3901 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003902 // If the result of the operator is implicitly converted to a known
3903 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003905 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3907 : ImplicitlyConvertedToType;
3908 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3909 mangleIntegerLiteral(T, V);
3910 break;
3911 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003912
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 switch(SAE->getKind()) {
3914 case UETT_SizeOf:
3915 Out << 's';
3916 break;
Richard Smith6822bd72018-10-26 19:26:45 +00003917 case UETT_PreferredAlignOf:
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 case UETT_AlignOf:
3919 Out << 'a';
3920 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003921 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 DiagnosticsEngine &Diags = Context.getDiags();
3923 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3924 "cannot yet mangle vec_step expression");
3925 Diags.Report(DiagID);
3926 return;
3927 }
Alexey Bataev00396512015-07-02 03:40:19 +00003928 case UETT_OpenMPRequiredSimdAlign:
3929 DiagnosticsEngine &Diags = Context.getDiags();
3930 unsigned DiagID = Diags.getCustomDiagID(
3931 DiagnosticsEngine::Error,
3932 "cannot yet mangle __builtin_omp_required_simd_align expression");
3933 Diags.Report(DiagID);
3934 return;
3935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 if (SAE->isArgumentType()) {
3937 Out << 't';
3938 mangleType(SAE->getArgumentType());
3939 } else {
3940 Out << 'z';
3941 mangleExpression(SAE->getArgumentExpr());
3942 }
3943 break;
3944 }
3945
3946 case Expr::CXXThrowExprClass: {
3947 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003948 // <expression> ::= tw <expression> # throw expression
3949 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 if (TE->getSubExpr()) {
3951 Out << "tw";
3952 mangleExpression(TE->getSubExpr());
3953 } else {
3954 Out << "tr";
3955 }
3956 break;
3957 }
3958
3959 case Expr::CXXTypeidExprClass: {
3960 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003961 // <expression> ::= ti <type> # typeid (type)
3962 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 if (TIE->isTypeOperand()) {
3964 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003965 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 } else {
3967 Out << "te";
3968 mangleExpression(TIE->getExprOperand());
3969 }
3970 break;
3971 }
3972
3973 case Expr::CXXDeleteExprClass: {
3974 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003975 // <expression> ::= [gs] dl <expression> # [::] delete expr
3976 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 if (DE->isGlobalDelete()) Out << "gs";
3978 Out << (DE->isArrayForm() ? "da" : "dl");
3979 mangleExpression(DE->getArgument());
3980 break;
3981 }
3982
3983 case Expr::UnaryOperatorClass: {
3984 const UnaryOperator *UO = cast<UnaryOperator>(E);
3985 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3986 /*Arity=*/1);
3987 mangleExpression(UO->getSubExpr());
3988 break;
3989 }
3990
3991 case Expr::ArraySubscriptExprClass: {
3992 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3993
3994 // Array subscript is treated as a syntactically weird form of
3995 // binary operator.
3996 Out << "ix";
3997 mangleExpression(AE->getLHS());
3998 mangleExpression(AE->getRHS());
3999 break;
4000 }
4001
4002 case Expr::CompoundAssignOperatorClass: // fallthrough
4003 case Expr::BinaryOperatorClass: {
4004 const BinaryOperator *BO = cast<BinaryOperator>(E);
4005 if (BO->getOpcode() == BO_PtrMemD)
4006 Out << "ds";
4007 else
4008 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4009 /*Arity=*/2);
4010 mangleExpression(BO->getLHS());
4011 mangleExpression(BO->getRHS());
4012 break;
4013 }
4014
4015 case Expr::ConditionalOperatorClass: {
4016 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4017 mangleOperatorName(OO_Conditional, /*Arity=*/3);
4018 mangleExpression(CO->getCond());
4019 mangleExpression(CO->getLHS(), Arity);
4020 mangleExpression(CO->getRHS(), Arity);
4021 break;
4022 }
4023
4024 case Expr::ImplicitCastExprClass: {
4025 ImplicitlyConvertedToType = E->getType();
4026 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4027 goto recurse;
4028 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004029
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00004031 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 // __bridge_transfer, or __bridge_retain.
4033 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4034 Out << "v1U" << Kind.size() << Kind;
4035 }
4036 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00004037 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004038
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004040 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004042
Richard Smith520449d2015-02-05 06:15:50 +00004043 case Expr::CXXFunctionalCastExprClass: {
4044 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4045 // FIXME: Add isImplicit to CXXConstructExpr.
4046 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4047 if (CCE->getParenOrBraceRange().isInvalid())
4048 Sub = CCE->getArg(0)->IgnoreImplicit();
4049 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4050 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4051 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4052 Out << "tl";
4053 mangleType(E->getType());
4054 mangleInitListElements(IL);
4055 Out << "E";
4056 } else {
4057 mangleCastExpression(E, "cv");
4058 }
4059 break;
4060 }
4061
David Majnemer9c775c72014-09-23 04:27:55 +00004062 case Expr::CXXStaticCastExprClass:
4063 mangleCastExpression(E, "sc");
4064 break;
4065 case Expr::CXXDynamicCastExprClass:
4066 mangleCastExpression(E, "dc");
4067 break;
4068 case Expr::CXXReinterpretCastExprClass:
4069 mangleCastExpression(E, "rc");
4070 break;
4071 case Expr::CXXConstCastExprClass:
4072 mangleCastExpression(E, "cc");
4073 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
4075 case Expr::CXXOperatorCallExprClass: {
4076 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4077 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004078 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4079 // (the enclosing MemberExpr covers the syntactic portion).
4080 if (CE->getOperator() != OO_Arrow)
4081 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004082 // Mangle the arguments.
4083 for (unsigned i = 0; i != NumArgs; ++i)
4084 mangleExpression(CE->getArg(i));
4085 break;
4086 }
4087
4088 case Expr::ParenExprClass:
4089 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4090 break;
4091
4092 case Expr::DeclRefExprClass: {
4093 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4094
4095 switch (D->getKind()) {
4096 default:
4097 // <expr-primary> ::= L <mangled-name> E # external name
4098 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004099 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 Out << 'E';
4101 break;
4102
4103 case Decl::ParmVar:
4104 mangleFunctionParam(cast<ParmVarDecl>(D));
4105 break;
4106
4107 case Decl::EnumConstant: {
4108 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4109 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4110 break;
4111 }
4112
4113 case Decl::NonTypeTemplateParm: {
4114 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4115 mangleTemplateParameter(PD->getIndex());
4116 break;
4117 }
4118
4119 }
4120
4121 break;
4122 }
4123
4124 case Expr::SubstNonTypeTemplateParmPackExprClass:
4125 // FIXME: not clear how to mangle this!
4126 // template <unsigned N...> class A {
4127 // template <class U...> void foo(U (&x)[N]...);
4128 // };
4129 Out << "_SUBSTPACK_";
4130 break;
4131
4132 case Expr::FunctionParmPackExprClass: {
4133 // FIXME: not clear how to mangle this!
4134 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4135 Out << "v110_SUBSTPACK";
4136 mangleFunctionParam(FPPE->getParameterPack());
4137 break;
4138 }
4139
4140 case Expr::DependentScopeDeclRefExprClass: {
4141 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004142 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4143 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4144 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 break;
4146 }
4147
4148 case Expr::CXXBindTemporaryExprClass:
4149 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4150 break;
4151
4152 case Expr::ExprWithCleanupsClass:
4153 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4154 break;
4155
4156 case Expr::FloatingLiteralClass: {
4157 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4158 Out << 'L';
4159 mangleType(FL->getType());
4160 mangleFloat(FL->getValue());
4161 Out << 'E';
4162 break;
4163 }
4164
4165 case Expr::CharacterLiteralClass:
4166 Out << 'L';
4167 mangleType(E->getType());
4168 Out << cast<CharacterLiteral>(E)->getValue();
4169 Out << 'E';
4170 break;
4171
4172 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4173 case Expr::ObjCBoolLiteralExprClass:
4174 Out << "Lb";
4175 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4176 Out << 'E';
4177 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004178
Guy Benyei11169dd2012-12-18 14:30:41 +00004179 case Expr::CXXBoolLiteralExprClass:
4180 Out << "Lb";
4181 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4182 Out << 'E';
4183 break;
4184
4185 case Expr::IntegerLiteralClass: {
4186 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4187 if (E->getType()->isSignedIntegerType())
4188 Value.setIsSigned(true);
4189 mangleIntegerLiteral(E->getType(), Value);
4190 break;
4191 }
4192
4193 case Expr::ImaginaryLiteralClass: {
4194 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4195 // Mangle as if a complex literal.
4196 // Proposal from David Vandevoorde, 2010.06.30.
4197 Out << 'L';
4198 mangleType(E->getType());
4199 if (const FloatingLiteral *Imag =
4200 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4201 // Mangle a floating-point zero of the appropriate type.
4202 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4203 Out << '_';
4204 mangleFloat(Imag->getValue());
4205 } else {
4206 Out << "0_";
4207 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4208 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4209 Value.setIsSigned(true);
4210 mangleNumber(Value);
4211 }
4212 Out << 'E';
4213 break;
4214 }
4215
4216 case Expr::StringLiteralClass: {
4217 // Revised proposal from David Vandervoorde, 2010.07.15.
4218 Out << 'L';
4219 assert(isa<ConstantArrayType>(E->getType()));
4220 mangleType(E->getType());
4221 Out << 'E';
4222 break;
4223 }
4224
4225 case Expr::GNUNullExprClass:
4226 // FIXME: should this really be mangled the same as nullptr?
4227 // fallthrough
4228
4229 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 Out << "LDnE";
4231 break;
4232 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004233
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 case Expr::PackExpansionExprClass:
4235 Out << "sp";
4236 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4237 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004238
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004240 auto *SPE = cast<SizeOfPackExpr>(E);
4241 if (SPE->isPartiallySubstituted()) {
4242 Out << "sP";
4243 for (const auto &A : SPE->getPartialArguments())
4244 mangleTemplateArg(A);
4245 Out << "E";
4246 break;
4247 }
4248
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004250 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4252 mangleTemplateParameter(TTP->getIndex());
4253 else if (const NonTypeTemplateParmDecl *NTTP
4254 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4255 mangleTemplateParameter(NTTP->getIndex());
4256 else if (const TemplateTemplateParmDecl *TempTP
4257 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4258 mangleTemplateParameter(TempTP->getIndex());
4259 else
4260 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4261 break;
4262 }
Richard Smith0f0af192014-11-08 05:07:16 +00004263
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 case Expr::MaterializeTemporaryExprClass: {
4265 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4266 break;
4267 }
Richard Smith0f0af192014-11-08 05:07:16 +00004268
4269 case Expr::CXXFoldExprClass: {
4270 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004271 if (FE->isLeftFold())
4272 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004273 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004274 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004275
4276 if (FE->getOperator() == BO_PtrMemD)
4277 Out << "ds";
4278 else
4279 mangleOperatorName(
4280 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4281 /*Arity=*/2);
4282
4283 if (FE->getLHS())
4284 mangleExpression(FE->getLHS());
4285 if (FE->getRHS())
4286 mangleExpression(FE->getRHS());
4287 break;
4288 }
4289
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 case Expr::CXXThisExprClass:
4291 Out << "fpT";
4292 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004293
4294 case Expr::CoawaitExprClass:
4295 // FIXME: Propose a non-vendor mangling.
4296 Out << "v18co_await";
4297 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4298 break;
4299
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004300 case Expr::DependentCoawaitExprClass:
4301 // FIXME: Propose a non-vendor mangling.
4302 Out << "v18co_await";
4303 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4304 break;
4305
Richard Smith9f690bd2015-10-27 06:02:45 +00004306 case Expr::CoyieldExprClass:
4307 // FIXME: Propose a non-vendor mangling.
4308 Out << "v18co_yield";
4309 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 }
4312}
4313
4314/// Mangle an expression which refers to a parameter variable.
4315///
4316/// <expression> ::= <function-param>
4317/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4318/// <function-param> ::= fp <top-level CV-qualifiers>
4319/// <parameter-2 non-negative number> _ # L == 0, I > 0
4320/// <function-param> ::= fL <L-1 non-negative number>
4321/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4322/// <function-param> ::= fL <L-1 non-negative number>
4323/// p <top-level CV-qualifiers>
4324/// <I-1 non-negative number> _ # L > 0, I > 0
4325///
4326/// L is the nesting depth of the parameter, defined as 1 if the
4327/// parameter comes from the innermost function prototype scope
4328/// enclosing the current context, 2 if from the next enclosing
4329/// function prototype scope, and so on, with one special case: if
4330/// we've processed the full parameter clause for the innermost
4331/// function type, then L is one less. This definition conveniently
4332/// makes it irrelevant whether a function's result type was written
4333/// trailing or leading, but is otherwise overly complicated; the
4334/// numbering was first designed without considering references to
4335/// parameter in locations other than return types, and then the
4336/// mangling had to be generalized without changing the existing
4337/// manglings.
4338///
4339/// I is the zero-based index of the parameter within its parameter
4340/// declaration clause. Note that the original ABI document describes
4341/// this using 1-based ordinals.
4342void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4343 unsigned parmDepth = parm->getFunctionScopeDepth();
4344 unsigned parmIndex = parm->getFunctionScopeIndex();
4345
4346 // Compute 'L'.
4347 // parmDepth does not include the declaring function prototype.
4348 // FunctionTypeDepth does account for that.
4349 assert(parmDepth < FunctionTypeDepth.getDepth());
4350 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4351 if (FunctionTypeDepth.isInResultType())
4352 nestingDepth--;
4353
4354 if (nestingDepth == 0) {
4355 Out << "fp";
4356 } else {
4357 Out << "fL" << (nestingDepth - 1) << 'p';
4358 }
4359
4360 // Top-level qualifiers. We don't have to worry about arrays here,
4361 // because parameters declared as arrays should already have been
4362 // transformed to have pointer type. FIXME: apparently these don't
4363 // get mangled if used as an rvalue of a known non-class type?
4364 assert(!parm->getType()->isArrayType()
4365 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004366
4367 if (const DependentAddressSpaceType *DAST =
4368 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4369 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4370 } else {
4371 mangleQualifiers(parm->getType().getQualifiers());
4372 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004373
4374 // Parameter index.
4375 if (parmIndex != 0) {
4376 Out << (parmIndex - 1);
4377 }
4378 Out << '_';
4379}
4380
Richard Smith5179eb72016-06-28 19:03:57 +00004381void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4382 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 // <ctor-dtor-name> ::= C1 # complete object constructor
4384 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004385 // ::= CI1 <type> # complete inheriting constructor
4386 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004388 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004389 Out << 'C';
4390 if (InheritedFrom)
4391 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 switch (T) {
4393 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004394 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 break;
4396 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004397 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004399 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004400 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004402 case Ctor_DefaultClosure:
4403 case Ctor_CopyingClosure:
4404 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004405 }
Richard Smith5179eb72016-06-28 19:03:57 +00004406 if (InheritedFrom)
4407 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004408}
4409
4410void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4411 // <ctor-dtor-name> ::= D0 # deleting destructor
4412 // ::= D1 # complete object destructor
4413 // ::= D2 # base object destructor
4414 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004415 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 switch (T) {
4417 case Dtor_Deleting:
4418 Out << "D0";
4419 break;
4420 case Dtor_Complete:
4421 Out << "D1";
4422 break;
4423 case Dtor_Base:
4424 Out << "D2";
4425 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004426 case Dtor_Comdat:
4427 Out << "D5";
4428 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 }
4430}
4431
James Y Knight04ec5bf2015-12-24 02:59:37 +00004432void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4433 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 // <template-args> ::= I <template-arg>+ E
4435 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004436 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4437 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 Out << 'E';
4439}
4440
4441void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4442 // <template-args> ::= I <template-arg>+ E
4443 Out << 'I';
4444 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4445 mangleTemplateArg(AL[i]);
4446 Out << 'E';
4447}
4448
4449void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4450 unsigned NumTemplateArgs) {
4451 // <template-args> ::= I <template-arg>+ E
4452 Out << 'I';
4453 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4454 mangleTemplateArg(TemplateArgs[i]);
4455 Out << 'E';
4456}
4457
4458void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4459 // <template-arg> ::= <type> # type or template
4460 // ::= X <expression> E # expression
4461 // ::= <expr-primary> # simple expressions
4462 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 if (!A.isInstantiationDependent() || A.isDependent())
4464 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004465
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 switch (A.getKind()) {
4467 case TemplateArgument::Null:
4468 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004469
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 case TemplateArgument::Type:
4471 mangleType(A.getAsType());
4472 break;
4473 case TemplateArgument::Template:
4474 // This is mangled as <type>.
4475 mangleType(A.getAsTemplate());
4476 break;
4477 case TemplateArgument::TemplateExpansion:
4478 // <type> ::= Dp <type> # pack expansion (C++0x)
4479 Out << "Dp";
4480 mangleType(A.getAsTemplateOrTemplatePattern());
4481 break;
4482 case TemplateArgument::Expression: {
4483 // It's possible to end up with a DeclRefExpr here in certain
4484 // dependent cases, in which case we should mangle as a
4485 // declaration.
4486 const Expr *E = A.getAsExpr()->IgnoreParens();
4487 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4488 const ValueDecl *D = DRE->getDecl();
4489 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004490 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004491 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 Out << 'E';
4493 break;
4494 }
4495 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004496
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 Out << 'X';
4498 mangleExpression(E);
4499 Out << 'E';
4500 break;
4501 }
4502 case TemplateArgument::Integral:
4503 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4504 break;
4505 case TemplateArgument::Declaration: {
4506 // <expr-primary> ::= L <mangled-name> E # external name
4507 // Clang produces AST's where pointer-to-member-function expressions
4508 // and pointer-to-function expressions are represented as a declaration not
4509 // an expression. We compensate for it here to produce the correct mangling.
4510 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004511 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 if (compensateMangling) {
4513 Out << 'X';
4514 mangleOperatorName(OO_Amp, 1);
4515 }
4516
4517 Out << 'L';
4518 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004519 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004520 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 Out << 'E';
4522
4523 if (compensateMangling)
4524 Out << 'E';
4525
4526 break;
4527 }
4528 case TemplateArgument::NullPtr: {
4529 // <expr-primary> ::= L <type> 0 E
4530 Out << 'L';
4531 mangleType(A.getNullPtrType());
4532 Out << "0E";
4533 break;
4534 }
4535 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004536 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004538 for (const auto &P : A.pack_elements())
4539 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 Out << 'E';
4541 }
4542 }
4543}
4544
4545void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4546 // <template-param> ::= T_ # first template parameter
4547 // ::= T <parameter-2 non-negative number> _
4548 if (Index == 0)
4549 Out << "T_";
4550 else
4551 Out << 'T' << (Index - 1) << '_';
4552}
4553
David Majnemer3b3bdb52014-05-06 22:49:16 +00004554void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4555 if (SeqID == 1)
4556 Out << '0';
4557 else if (SeqID > 1) {
4558 SeqID--;
4559
4560 // <seq-id> is encoded in base-36, using digits and upper case letters.
4561 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004562 MutableArrayRef<char> BufferRef(Buffer);
4563 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004564
4565 for (; SeqID != 0; SeqID /= 36) {
4566 unsigned C = SeqID % 36;
4567 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4568 }
4569
4570 Out.write(I.base(), I - BufferRef.rbegin());
4571 }
4572 Out << '_';
4573}
4574
Guy Benyei11169dd2012-12-18 14:30:41 +00004575void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4576 bool result = mangleSubstitution(tname);
4577 assert(result && "no existing substitution for template name");
4578 (void) result;
4579}
4580
4581// <substitution> ::= S <seq-id> _
4582// ::= S_
4583bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4584 // Try one of the standard substitutions first.
4585 if (mangleStandardSubstitution(ND))
4586 return true;
4587
4588 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4589 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4590}
4591
Justin Bognere8d762e2015-05-22 06:48:13 +00004592/// Determine whether the given type has any qualifiers that are relevant for
4593/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004594static bool hasMangledSubstitutionQualifiers(QualType T) {
4595 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004596 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004597}
4598
4599bool CXXNameMangler::mangleSubstitution(QualType T) {
4600 if (!hasMangledSubstitutionQualifiers(T)) {
4601 if (const RecordType *RT = T->getAs<RecordType>())
4602 return mangleSubstitution(RT->getDecl());
4603 }
4604
4605 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4606
4607 return mangleSubstitution(TypePtr);
4608}
4609
4610bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4611 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4612 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004613
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4615 return mangleSubstitution(
4616 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4617}
4618
4619bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4620 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4621 if (I == Substitutions.end())
4622 return false;
4623
4624 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004625 Out << 'S';
4626 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627
4628 return true;
4629}
4630
4631static bool isCharType(QualType T) {
4632 if (T.isNull())
4633 return false;
4634
4635 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4636 T->isSpecificBuiltinType(BuiltinType::Char_U);
4637}
4638
Justin Bognere8d762e2015-05-22 06:48:13 +00004639/// Returns whether a given type is a template specialization of a given name
4640/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004641static bool isCharSpecialization(QualType T, const char *Name) {
4642 if (T.isNull())
4643 return false;
4644
4645 const RecordType *RT = T->getAs<RecordType>();
4646 if (!RT)
4647 return false;
4648
4649 const ClassTemplateSpecializationDecl *SD =
4650 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4651 if (!SD)
4652 return false;
4653
4654 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4655 return false;
4656
4657 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4658 if (TemplateArgs.size() != 1)
4659 return false;
4660
4661 if (!isCharType(TemplateArgs[0].getAsType()))
4662 return false;
4663
4664 return SD->getIdentifier()->getName() == Name;
4665}
4666
4667template <std::size_t StrLen>
4668static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4669 const char (&Str)[StrLen]) {
4670 if (!SD->getIdentifier()->isStr(Str))
4671 return false;
4672
4673 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4674 if (TemplateArgs.size() != 2)
4675 return false;
4676
4677 if (!isCharType(TemplateArgs[0].getAsType()))
4678 return false;
4679
4680 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4681 return false;
4682
4683 return true;
4684}
4685
4686bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4687 // <substitution> ::= St # ::std::
4688 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4689 if (isStd(NS)) {
4690 Out << "St";
4691 return true;
4692 }
4693 }
4694
4695 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4696 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4697 return false;
4698
4699 // <substitution> ::= Sa # ::std::allocator
4700 if (TD->getIdentifier()->isStr("allocator")) {
4701 Out << "Sa";
4702 return true;
4703 }
4704
4705 // <<substitution> ::= Sb # ::std::basic_string
4706 if (TD->getIdentifier()->isStr("basic_string")) {
4707 Out << "Sb";
4708 return true;
4709 }
4710 }
4711
4712 if (const ClassTemplateSpecializationDecl *SD =
4713 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4714 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4715 return false;
4716
4717 // <substitution> ::= Ss # ::std::basic_string<char,
4718 // ::std::char_traits<char>,
4719 // ::std::allocator<char> >
4720 if (SD->getIdentifier()->isStr("basic_string")) {
4721 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4722
4723 if (TemplateArgs.size() != 3)
4724 return false;
4725
4726 if (!isCharType(TemplateArgs[0].getAsType()))
4727 return false;
4728
4729 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4730 return false;
4731
4732 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4733 return false;
4734
4735 Out << "Ss";
4736 return true;
4737 }
4738
4739 // <substitution> ::= Si # ::std::basic_istream<char,
4740 // ::std::char_traits<char> >
4741 if (isStreamCharSpecialization(SD, "basic_istream")) {
4742 Out << "Si";
4743 return true;
4744 }
4745
4746 // <substitution> ::= So # ::std::basic_ostream<char,
4747 // ::std::char_traits<char> >
4748 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4749 Out << "So";
4750 return true;
4751 }
4752
4753 // <substitution> ::= Sd # ::std::basic_iostream<char,
4754 // ::std::char_traits<char> >
4755 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4756 Out << "Sd";
4757 return true;
4758 }
4759 }
4760 return false;
4761}
4762
4763void CXXNameMangler::addSubstitution(QualType T) {
4764 if (!hasMangledSubstitutionQualifiers(T)) {
4765 if (const RecordType *RT = T->getAs<RecordType>()) {
4766 addSubstitution(RT->getDecl());
4767 return;
4768 }
4769 }
4770
4771 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4772 addSubstitution(TypePtr);
4773}
4774
4775void CXXNameMangler::addSubstitution(TemplateName Template) {
4776 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4777 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004778
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4780 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4781}
4782
4783void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4784 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4785 Substitutions[Ptr] = SeqID++;
4786}
4787
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004788void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4789 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4790 if (Other->SeqID > SeqID) {
4791 Substitutions.swap(Other->Substitutions);
4792 SeqID = Other->SeqID;
4793 }
4794}
4795
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004796CXXNameMangler::AbiTagList
4797CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4798 // When derived abi tags are disabled there is no need to make any list.
4799 if (DisableDerivedAbiTags)
4800 return AbiTagList();
4801
4802 llvm::raw_null_ostream NullOutStream;
4803 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4804 TrackReturnTypeTags.disableDerivedAbiTags();
4805
4806 const FunctionProtoType *Proto =
4807 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004808 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004809 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4810 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4811 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004812 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004813
4814 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4815}
4816
4817CXXNameMangler::AbiTagList
4818CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4819 // When derived abi tags are disabled there is no need to make any list.
4820 if (DisableDerivedAbiTags)
4821 return AbiTagList();
4822
4823 llvm::raw_null_ostream NullOutStream;
4824 CXXNameMangler TrackVariableType(*this, NullOutStream);
4825 TrackVariableType.disableDerivedAbiTags();
4826
4827 TrackVariableType.mangleType(VD->getType());
4828
4829 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4830}
4831
4832bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4833 const VarDecl *VD) {
4834 llvm::raw_null_ostream NullOutStream;
4835 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4836 TrackAbiTags.mangle(VD);
4837 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4838}
4839
Guy Benyei11169dd2012-12-18 14:30:41 +00004840//
4841
Justin Bognere8d762e2015-05-22 06:48:13 +00004842/// Mangles the name of the declaration D and emits that name to the given
4843/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004844///
4845/// If the declaration D requires a mangled name, this routine will emit that
4846/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4847/// and this routine will return false. In this case, the caller should just
4848/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4849/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004850void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4851 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4853 "Invalid mangleName() call, argument is not a variable or function!");
4854 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4855 "Invalid mangleName() call on 'structor decl!");
4856
4857 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4858 getASTContext().getSourceManager(),
4859 "Mangling declaration");
4860
4861 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004862 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004863}
4864
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004865void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4866 CXXCtorType Type,
4867 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 CXXNameMangler Mangler(*this, Out, D, Type);
4869 Mangler.mangle(D);
4870}
4871
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004872void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4873 CXXDtorType Type,
4874 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 CXXNameMangler Mangler(*this, Out, D, Type);
4876 Mangler.mangle(D);
4877}
4878
Rafael Espindola1e4df922014-09-16 15:18:21 +00004879void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4880 raw_ostream &Out) {
4881 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4882 Mangler.mangle(D);
4883}
4884
4885void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4886 raw_ostream &Out) {
4887 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4888 Mangler.mangle(D);
4889}
4890
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004891void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4892 const ThunkInfo &Thunk,
4893 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 // <special-name> ::= T <call-offset> <base encoding>
4895 // # base is the nominal target function of thunk
4896 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4897 // # base is the nominal target function of thunk
4898 // # first call-offset is 'this' adjustment
4899 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004900
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 assert(!isa<CXXDestructorDecl>(MD) &&
4902 "Use mangleCXXDtor for destructor decls!");
4903 CXXNameMangler Mangler(*this, Out);
4904 Mangler.getStream() << "_ZT";
4905 if (!Thunk.Return.isEmpty())
4906 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004907
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004909 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4910 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4911
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 // Mangle the return pointer adjustment if there is one.
4913 if (!Thunk.Return.isEmpty())
4914 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004915 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4916
Guy Benyei11169dd2012-12-18 14:30:41 +00004917 Mangler.mangleFunctionEncoding(MD);
4918}
4919
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004920void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4921 const CXXDestructorDecl *DD, CXXDtorType Type,
4922 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 // <special-name> ::= T <call-offset> <base encoding>
4924 // # base is the nominal target function of thunk
4925 CXXNameMangler Mangler(*this, Out, DD, Type);
4926 Mangler.getStream() << "_ZT";
4927
4928 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004929 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004930 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004931
4932 Mangler.mangleFunctionEncoding(DD);
4933}
4934
Justin Bognere8d762e2015-05-22 06:48:13 +00004935/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004936void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4937 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 // <special-name> ::= GV <object name> # Guard variable for one-time
4939 // # initialization
4940 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004941 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4942 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 Mangler.getStream() << "_ZGV";
4944 Mangler.mangleName(D);
4945}
4946
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004947void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4948 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004949 // These symbols are internal in the Itanium ABI, so the names don't matter.
4950 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4951 // avoid duplicate symbols.
4952 Out << "__cxx_global_var_init";
4953}
4954
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004955void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4956 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004957 // Prefix the mangling of D with __dtor_.
4958 CXXNameMangler Mangler(*this, Out);
4959 Mangler.getStream() << "__dtor_";
4960 if (shouldMangleDeclName(D))
4961 Mangler.mangle(D);
4962 else
4963 Mangler.getStream() << D->getName();
4964}
4965
Reid Kleckner1d59f992015-01-22 01:36:17 +00004966void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4967 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4968 CXXNameMangler Mangler(*this, Out);
4969 Mangler.getStream() << "__filt_";
4970 if (shouldMangleDeclName(EnclosingDecl))
4971 Mangler.mangle(EnclosingDecl);
4972 else
4973 Mangler.getStream() << EnclosingDecl->getName();
4974}
4975
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004976void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4977 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4978 CXXNameMangler Mangler(*this, Out);
4979 Mangler.getStream() << "__fin_";
4980 if (shouldMangleDeclName(EnclosingDecl))
4981 Mangler.mangle(EnclosingDecl);
4982 else
4983 Mangler.getStream() << EnclosingDecl->getName();
4984}
4985
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004986void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4987 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004988 // <special-name> ::= TH <object name>
4989 CXXNameMangler Mangler(*this, Out);
4990 Mangler.getStream() << "_ZTH";
4991 Mangler.mangleName(D);
4992}
4993
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004994void
4995ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4996 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004997 // <special-name> ::= TW <object name>
4998 CXXNameMangler Mangler(*this, Out);
4999 Mangler.getStream() << "_ZTW";
5000 Mangler.mangleName(D);
5001}
5002
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005003void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00005004 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005005 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 // We match the GCC mangling here.
5007 // <special-name> ::= GR <object name>
5008 CXXNameMangler Mangler(*this, Out);
5009 Mangler.getStream() << "_ZGR";
5010 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00005011 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00005012 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005013}
5014
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005015void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5016 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 // <special-name> ::= TV <type> # virtual table
5018 CXXNameMangler Mangler(*this, Out);
5019 Mangler.getStream() << "_ZTV";
5020 Mangler.mangleNameOrStandardSubstitution(RD);
5021}
5022
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005023void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5024 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 // <special-name> ::= TT <type> # VTT structure
5026 CXXNameMangler Mangler(*this, Out);
5027 Mangler.getStream() << "_ZTT";
5028 Mangler.mangleNameOrStandardSubstitution(RD);
5029}
5030
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005031void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5032 int64_t Offset,
5033 const CXXRecordDecl *Type,
5034 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005035 // <special-name> ::= TC <type> <offset number> _ <base type>
5036 CXXNameMangler Mangler(*this, Out);
5037 Mangler.getStream() << "_ZTC";
5038 Mangler.mangleNameOrStandardSubstitution(RD);
5039 Mangler.getStream() << Offset;
5040 Mangler.getStream() << '_';
5041 Mangler.mangleNameOrStandardSubstitution(Type);
5042}
5043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005044void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 // <special-name> ::= TI <type> # typeinfo structure
5046 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5047 CXXNameMangler Mangler(*this, Out);
5048 Mangler.getStream() << "_ZTI";
5049 Mangler.mangleType(Ty);
5050}
5051
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005052void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5053 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5055 CXXNameMangler Mangler(*this, Out);
5056 Mangler.getStream() << "_ZTS";
5057 Mangler.mangleType(Ty);
5058}
5059
Reid Klecknercc99e262013-11-19 23:23:00 +00005060void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5061 mangleCXXRTTIName(Ty, Out);
5062}
5063
David Majnemer58e5bee2014-03-24 21:43:36 +00005064void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5065 llvm_unreachable("Can't mangle string literals");
5066}
5067
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005068ItaniumMangleContext *
5069ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5070 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005071}