blob: 9f2979dba03fbd3fc25124b1b767cc315ca057a1 [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();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000063 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
64 return getEffectiveDeclContext(cast<Decl>(DC));
65 }
Eli Friedman95f50122013-07-02 17:52:28 +000066
David Majnemerf8c02e62015-02-18 19:08:11 +000067 if (const auto *VD = dyn_cast<VarDecl>(D))
68 if (VD->isExternC())
69 return VD->getASTContext().getTranslationUnitDecl();
70
71 if (const auto *FD = dyn_cast<FunctionDecl>(D))
72 if (FD->isExternC())
73 return FD->getASTContext().getTranslationUnitDecl();
74
Richard Smithec24bbe2016-04-29 01:23:20 +000075 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000076}
77
78static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
79 return getEffectiveDeclContext(cast<Decl>(DC));
80}
Eli Friedman95f50122013-07-02 17:52:28 +000081
82static bool isLocalContainerContext(const DeclContext *DC) {
83 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
84}
85
Eli Friedmaneecc09a2013-07-05 20:27:40 +000086static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000087 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000088 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000089 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000090 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000091 D = cast<Decl>(DC);
92 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000093 }
Craig Topper36250ad2014-05-12 05:36:57 +000094 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +000095}
96
97static const FunctionDecl *getStructor(const FunctionDecl *fn) {
98 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
99 return ftd->getTemplatedDecl();
100
101 return fn;
102}
103
104static const NamedDecl *getStructor(const NamedDecl *decl) {
105 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
106 return (fn ? getStructor(fn) : decl);
107}
David Majnemer2206bf52014-03-05 08:57:59 +0000108
109static bool isLambda(const NamedDecl *ND) {
110 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
111 if (!Record)
112 return false;
113
114 return Record->isLambda();
115}
116
Guy Benyei11169dd2012-12-18 14:30:41 +0000117static const unsigned UnknownArity = ~0U;
118
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000119class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000120 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
121 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000122 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000125 explicit ItaniumMangleContextImpl(ASTContext &Context,
126 DiagnosticsEngine &Diags)
127 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000128
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 /// @name Mangler Entry Points
130 /// @{
131
Craig Toppercbce6e92014-03-11 06:22:39 +0000132 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000133 bool shouldMangleStringLiteral(const StringLiteral *) override {
134 return false;
135 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000136 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
137 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
138 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000139 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
140 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000141 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000142 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
143 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000144 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
145 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000147 const CXXRecordDecl *Type, raw_ostream &) override;
148 void mangleCXXRTTI(QualType T, raw_ostream &) override;
149 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
150 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000152 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000155
Rafael Espindola1e4df922014-09-16 15:18:21 +0000156 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
157 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000158 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
159 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
160 void mangleDynamicAtExitDestructor(const VarDecl *D,
161 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000162 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
163 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000164 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
165 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000166 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
167 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
168 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000169
David Majnemer58e5bee2014-03-24 21:43:36 +0000170 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
171
Guy Benyei11169dd2012-12-18 14:30:41 +0000172 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000173 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000174 if (isLambda(ND))
175 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000176
177 // Anonymous tags are already numbered.
178 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
179 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
180 return false;
181 }
182
183 // Use the canonical number for externally visible decls.
184 if (ND->isExternallyVisible()) {
185 unsigned discriminator = getASTContext().getManglingNumber(ND);
186 if (discriminator == 1)
187 return false;
188 disc = discriminator - 2;
189 return true;
190 }
191
192 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000194 if (!discriminator) {
195 const DeclContext *DC = getEffectiveDeclContext(ND);
196 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
197 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000198 if (discriminator == 1)
199 return false;
200 disc = discriminator-2;
201 return true;
202 }
203 /// @}
204};
205
Justin Bognere8d762e2015-05-22 06:48:13 +0000206/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000207class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000208 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000209 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000210 bool NullOut = false;
211 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
212 /// This mode is used when mangler creates another mangler recursively to
213 /// calculate ABI tags for the function return value or the variable type.
214 /// Also it is required to avoid infinite recursion in some cases.
215 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216
217 /// The "structor" is the top-level declaration being mangled, if
218 /// that's not a template specialization; otherwise it's the pattern
219 /// for that specialization.
220 const NamedDecl *Structor;
221 unsigned StructorType;
222
Justin Bognere8d762e2015-05-22 06:48:13 +0000223 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000224 unsigned SeqID;
225
226 class FunctionTypeDepthState {
227 unsigned Bits;
228
229 enum { InResultTypeMask = 1 };
230
231 public:
232 FunctionTypeDepthState() : Bits(0) {}
233
234 /// The number of function types we're inside.
235 unsigned getDepth() const {
236 return Bits >> 1;
237 }
238
239 /// True if we're in the return type of the innermost function type.
240 bool isInResultType() const {
241 return Bits & InResultTypeMask;
242 }
243
244 FunctionTypeDepthState push() {
245 FunctionTypeDepthState tmp = *this;
246 Bits = (Bits & ~InResultTypeMask) + 2;
247 return tmp;
248 }
249
250 void enterResultType() {
251 Bits |= InResultTypeMask;
252 }
253
254 void leaveResultType() {
255 Bits &= ~InResultTypeMask;
256 }
257
258 void pop(FunctionTypeDepthState saved) {
259 assert(getDepth() == saved.getDepth() + 1);
260 Bits = saved.Bits;
261 }
262
263 } FunctionTypeDepth;
264
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000265 // abi_tag is a gcc attribute, taking one or more strings called "tags".
266 // The goal is to annotate against which version of a library an object was
267 // built and to be able to provide backwards compatibility ("dual abi").
268 // For more information see docs/ItaniumMangleAbiTags.rst.
269 typedef SmallVector<StringRef, 4> AbiTagList;
270
271 // State to gather all implicit and explicit tags used in a mangled name.
272 // Must always have an instance of this while emitting any name to keep
273 // track.
274 class AbiTagState final {
275 public:
276 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
277 Parent = LinkHead;
278 LinkHead = this;
279 }
280
281 // No copy, no move.
282 AbiTagState(const AbiTagState &) = delete;
283 AbiTagState &operator=(const AbiTagState &) = delete;
284
285 ~AbiTagState() { pop(); }
286
287 void write(raw_ostream &Out, const NamedDecl *ND,
288 const AbiTagList *AdditionalAbiTags) {
289 ND = cast<NamedDecl>(ND->getCanonicalDecl());
290 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
291 assert(
292 !AdditionalAbiTags &&
293 "only function and variables need a list of additional abi tags");
294 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
295 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
296 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
297 AbiTag->tags().end());
298 }
299 // Don't emit abi tags for namespaces.
300 return;
301 }
302 }
303
304 AbiTagList TagList;
305 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
306 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
307 AbiTag->tags().end());
308 TagList.insert(TagList.end(), AbiTag->tags().begin(),
309 AbiTag->tags().end());
310 }
311
312 if (AdditionalAbiTags) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
314 AdditionalAbiTags->end());
315 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
316 AdditionalAbiTags->end());
317 }
318
Fangrui Song55fab262018-09-26 22:16:28 +0000319 llvm::sort(TagList);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000320 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
321
322 writeSortedUniqueAbiTags(Out, TagList);
323 }
324
325 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
326 void setUsedAbiTags(const AbiTagList &AbiTags) {
327 UsedAbiTags = AbiTags;
328 }
329
330 const AbiTagList &getEmittedAbiTags() const {
331 return EmittedAbiTags;
332 }
333
334 const AbiTagList &getSortedUniqueUsedAbiTags() {
Fangrui Song55fab262018-09-26 22:16:28 +0000335 llvm::sort(UsedAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000336 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
337 UsedAbiTags.end());
338 return UsedAbiTags;
339 }
340
341 private:
342 //! All abi tags used implicitly or explicitly.
343 AbiTagList UsedAbiTags;
344 //! All explicit abi tags (i.e. not from namespace).
345 AbiTagList EmittedAbiTags;
346
347 AbiTagState *&LinkHead;
348 AbiTagState *Parent = nullptr;
349
350 void pop() {
351 assert(LinkHead == this &&
352 "abi tag link head must point to us on destruction");
353 if (Parent) {
354 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
355 UsedAbiTags.begin(), UsedAbiTags.end());
356 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
357 EmittedAbiTags.begin(),
358 EmittedAbiTags.end());
359 }
360 LinkHead = Parent;
361 }
362
363 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
364 for (const auto &Tag : AbiTags) {
365 EmittedAbiTags.push_back(Tag);
366 Out << "B";
367 Out << Tag.size();
368 Out << Tag;
369 }
370 }
371 };
372
373 AbiTagState *AbiTags = nullptr;
374 AbiTagState AbiTagsRoot;
375
Guy Benyei11169dd2012-12-18 14:30:41 +0000376 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000377 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000378
379 ASTContext &getASTContext() const { return Context.getASTContext(); }
380
381public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000382 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000383 const NamedDecl *D = nullptr, bool NullOut_ = false)
384 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
385 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 // These can't be mangled without a ctor type or dtor type.
387 assert(!D || (!isa<CXXDestructorDecl>(D) &&
388 !isa<CXXConstructorDecl>(D)));
389 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000390 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000391 const CXXConstructorDecl *D, CXXCtorType Type)
392 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000393 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000394 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000395 const CXXDestructorDecl *D, CXXDtorType Type)
396 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000397 SeqID(0), AbiTagsRoot(AbiTags) { }
398
399 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
400 : Context(Outer.Context), Out(Out_), NullOut(false),
401 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000402 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
403 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000404
405 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
406 : Context(Outer.Context), Out(Out_), NullOut(true),
407 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000408 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
409 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000410
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 raw_ostream &getStream() { return Out; }
412
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000413 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
414 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
415
David Majnemer7ff7eb72015-02-18 07:47:09 +0000416 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000417 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
418 void mangleNumber(const llvm::APSInt &I);
419 void mangleNumber(int64_t Number);
420 void mangleFloat(const llvm::APFloat &F);
421 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000422 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 void mangleName(const NamedDecl *ND);
424 void mangleType(QualType T);
425 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
Fangrui Song6907ce22018-07-30 19:24:48 +0000426
Guy Benyei11169dd2012-12-18 14:30:41 +0000427private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000428
Guy Benyei11169dd2012-12-18 14:30:41 +0000429 bool mangleSubstitution(const NamedDecl *ND);
430 bool mangleSubstitution(QualType T);
431 bool mangleSubstitution(TemplateName Template);
432 bool mangleSubstitution(uintptr_t Ptr);
433
Guy Benyei11169dd2012-12-18 14:30:41 +0000434 void mangleExistingSubstitution(TemplateName name);
435
436 bool mangleStandardSubstitution(const NamedDecl *ND);
437
438 void addSubstitution(const NamedDecl *ND) {
439 ND = cast<NamedDecl>(ND->getCanonicalDecl());
440
441 addSubstitution(reinterpret_cast<uintptr_t>(ND));
442 }
443 void addSubstitution(QualType T);
444 void addSubstitution(TemplateName Template);
445 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000446 // Destructive copy substitutions from other mangler.
447 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000448
449 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 bool recursive = false);
451 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000453 const TemplateArgumentLoc *TemplateArgs,
454 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000455 unsigned KnownArity = UnknownArity);
456
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000457 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
458
459 void mangleNameWithAbiTags(const NamedDecl *ND,
460 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000461 void mangleModuleName(const Module *M);
462 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000463 void mangleTemplateName(const TemplateDecl *TD,
464 const TemplateArgument *TemplateArgs,
465 unsigned NumTemplateArgs);
466 void mangleUnqualifiedName(const NamedDecl *ND,
467 const AbiTagList *AdditionalAbiTags) {
468 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
469 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 }
471 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000472 unsigned KnownArity,
473 const AbiTagList *AdditionalAbiTags);
474 void mangleUnscopedName(const NamedDecl *ND,
475 const AbiTagList *AdditionalAbiTags);
476 void mangleUnscopedTemplateName(const TemplateDecl *ND,
477 const AbiTagList *AdditionalAbiTags);
478 void mangleUnscopedTemplateName(TemplateName,
479 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000480 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000481 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000482 void mangleSourceNameWithAbiTags(
483 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
484 void mangleLocalName(const Decl *D,
485 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000486 void mangleBlockForPrefix(const BlockDecl *Block);
487 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 void mangleLambda(const CXXRecordDecl *Lambda);
489 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000490 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000491 bool NoFunction=false);
492 void mangleNestedName(const TemplateDecl *TD,
493 const TemplateArgument *TemplateArgs,
494 unsigned NumTemplateArgs);
495 void manglePrefix(NestedNameSpecifier *qualifier);
496 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
497 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000498 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000499 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000500 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
501 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000502 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000503 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000504 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000505 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 void mangleRefQualifier(RefQualifierKind RefQualifier);
507
508 void mangleObjCMethodName(const ObjCMethodDecl *MD);
509
510 // Declare manglers for every type class.
511#define ABSTRACT_TYPE(CLASS, PARENT)
512#define NON_CANONICAL_TYPE(CLASS, PARENT)
513#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
514#include "clang/AST/TypeNodes.def"
515
516 void mangleType(const TagType*);
517 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000518 static StringRef getCallingConvQualifierName(CallingConv CC);
519 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
520 void mangleExtFunctionInfo(const FunctionType *T);
521 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000522 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000523 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000524 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000525 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000526 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000527
528 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000529 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000530 void mangleMemberExpr(const Expr *base, bool isArrow,
531 NestedNameSpecifier *qualifier,
532 NamedDecl *firstQualifierLookup,
533 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000534 const TemplateArgumentLoc *TemplateArgs,
535 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000537 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000538 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000539 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000540 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 void mangleCXXDtorType(CXXDtorType T);
542
James Y Knight04ec5bf2015-12-24 02:59:37 +0000543 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
544 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000545 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
546 unsigned NumTemplateArgs);
547 void mangleTemplateArgs(const TemplateArgumentList &AL);
548 void mangleTemplateArg(TemplateArgument A);
549
550 void mangleTemplateParameter(unsigned Index);
551
552 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000553
554 void writeAbiTags(const NamedDecl *ND,
555 const AbiTagList *AdditionalAbiTags);
556
557 // Returns sorted unique list of ABI tags.
558 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
559 // Returns sorted unique list of ABI tags.
560 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000561};
562
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000563}
Guy Benyei11169dd2012-12-18 14:30:41 +0000564
Rafael Espindola002667c2013-10-16 01:40:34 +0000565bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000567 if (FD) {
568 LanguageLinkage L = FD->getLanguageLinkage();
569 // Overloadable functions need mangling.
570 if (FD->hasAttr<OverloadableAttr>())
571 return true;
572
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000573 // "main" is not mangled.
574 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000575 return false;
576
Martin Storsjo92e26612018-07-16 05:42:25 +0000577 // The Windows ABI expects that we would never mangle "typical"
578 // user-defined entry points regardless of visibility or freestanding-ness.
579 //
580 // N.B. This is distinct from asking about "main". "main" has a lot of
581 // special rules associated with it in the standard while these
582 // user-defined entry points are outside of the purview of the standard.
583 // For example, there can be only one definition for "main" in a standards
584 // compliant program; however nothing forbids the existence of wmain and
585 // WinMain in the same translation unit.
586 if (FD->isMSVCRTEntryPoint())
587 return false;
588
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000589 // C++ functions and those whose names are not a simple identifier need
590 // mangling.
591 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
592 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000593
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000594 // C functions are not mangled.
595 if (L == CLanguageLinkage)
596 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000597 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000598
599 // Otherwise, no mangling is done outside C++ mode.
600 if (!getASTContext().getLangOpts().CPlusPlus)
601 return false;
602
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000603 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000604 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000605 // C variables are not mangled.
606 if (VD->isExternC())
607 return false;
608
609 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000610 const DeclContext *DC = getEffectiveDeclContext(D);
611 // Check for extern variable declared locally.
612 if (DC->isFunctionOrMethod() && D->hasLinkage())
613 while (!DC->isNamespace() && !DC->isTranslationUnit())
614 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000615 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000616 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000617 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000618 return false;
619 }
620
Guy Benyei11169dd2012-12-18 14:30:41 +0000621 return true;
622}
623
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000624void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
625 const AbiTagList *AdditionalAbiTags) {
626 assert(AbiTags && "require AbiTagState");
627 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
628}
629
630void CXXNameMangler::mangleSourceNameWithAbiTags(
631 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
632 mangleSourceName(ND->getIdentifier());
633 writeAbiTags(ND, AdditionalAbiTags);
634}
635
David Majnemer7ff7eb72015-02-18 07:47:09 +0000636void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 // <mangled-name> ::= _Z <encoding>
638 // ::= <data name>
639 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000640 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
642 mangleFunctionEncoding(FD);
643 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
644 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000645 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
646 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 else
648 mangleName(cast<FieldDecl>(D));
649}
650
651void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
652 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000653
654 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000655 if (!Context.shouldMangleDeclName(FD)) {
656 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000658 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000659
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000660 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
661 if (ReturnTypeAbiTags.empty()) {
662 // There are no tags for return type, the simplest case.
663 mangleName(FD);
664 mangleFunctionEncodingBareType(FD);
665 return;
666 }
667
668 // Mangle function name and encoding to temporary buffer.
669 // We have to output name and encoding to the same mangler to get the same
670 // substitution as it will be in final mangling.
671 SmallString<256> FunctionEncodingBuf;
672 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
673 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
674 // Output name of the function.
675 FunctionEncodingMangler.disableDerivedAbiTags();
676 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
677
678 // Remember length of the function name in the buffer.
679 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
680 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
681
682 // Get tags from return type that are not present in function name or
683 // encoding.
684 const AbiTagList &UsedAbiTags =
685 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
686 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
687 AdditionalAbiTags.erase(
688 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
689 UsedAbiTags.begin(), UsedAbiTags.end(),
690 AdditionalAbiTags.begin()),
691 AdditionalAbiTags.end());
692
693 // Output name with implicit tags and function encoding from temporary buffer.
694 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
695 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000696
697 // Function encoding could create new substitutions so we have to add
698 // temp mangled substitutions to main mangler.
699 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000700}
701
702void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000703 if (FD->hasAttr<EnableIfAttr>()) {
704 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
705 Out << "Ua9enable_ifI";
Michael Krusedc5ce722018-08-03 01:21:16 +0000706 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
707 E = FD->getAttrs().end();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000708 I != E; ++I) {
709 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
710 if (!EIA)
711 continue;
712 Out << 'X';
713 mangleExpression(EIA->getCond());
714 Out << 'E';
715 }
716 Out << 'E';
717 FunctionTypeDepth.pop(Saved);
718 }
719
Richard Smith5179eb72016-06-28 19:03:57 +0000720 // When mangling an inheriting constructor, the bare function type used is
721 // that of the inherited constructor.
722 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
723 if (auto Inherited = CD->getInheritedConstructor())
724 FD = Inherited.getConstructor();
725
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 // Whether the mangling of a function type includes the return type depends on
727 // the context and the nature of the function. The rules for deciding whether
728 // the return type is included are:
729 //
730 // 1. Template functions (names or types) have return types encoded, with
731 // the exceptions listed below.
732 // 2. Function types not appearing as part of a function name mangling,
733 // e.g. parameters, pointer types, etc., have return type encoded, with the
734 // exceptions listed below.
735 // 3. Non-template function names do not have return types encoded.
736 //
737 // The exceptions mentioned in (1) and (2) above, for which the return type is
738 // never included, are
739 // 1. Constructors.
740 // 2. Destructors.
741 // 3. Conversion operator functions, e.g. operator int.
742 bool MangleReturnType = false;
743 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
744 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
745 isa<CXXConversionDecl>(FD)))
746 MangleReturnType = true;
747
748 // Mangle the type of the primary template.
749 FD = PrimaryTemplate->getTemplatedDecl();
750 }
751
John McCall07daf722016-03-01 22:18:03 +0000752 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000753 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000754}
755
756static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
757 while (isa<LinkageSpecDecl>(DC)) {
758 DC = getEffectiveParentContext(DC);
759 }
760
761 return DC;
762}
763
Justin Bognere8d762e2015-05-22 06:48:13 +0000764/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000765static bool isStd(const NamespaceDecl *NS) {
766 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
767 ->isTranslationUnit())
768 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000769
Guy Benyei11169dd2012-12-18 14:30:41 +0000770 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
771 return II && II->isStr("std");
772}
773
774// isStdNamespace - Return whether a given decl context is a toplevel 'std'
775// namespace.
776static bool isStdNamespace(const DeclContext *DC) {
777 if (!DC->isNamespace())
778 return false;
779
780 return isStd(cast<NamespaceDecl>(DC));
781}
782
783static const TemplateDecl *
784isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
785 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000786 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000787 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
788 TemplateArgs = FD->getTemplateSpecializationArgs();
789 return TD;
790 }
791 }
792
793 // Check if we have a class template.
794 if (const ClassTemplateSpecializationDecl *Spec =
795 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
796 TemplateArgs = &Spec->getTemplateArgs();
797 return Spec->getSpecializedTemplate();
798 }
799
Larisse Voufo39a1e502013-08-06 01:03:05 +0000800 // Check if we have a variable template.
801 if (const VarTemplateSpecializationDecl *Spec =
802 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
803 TemplateArgs = &Spec->getTemplateArgs();
804 return Spec->getSpecializedTemplate();
805 }
806
Craig Topper36250ad2014-05-12 05:36:57 +0000807 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000808}
809
Guy Benyei11169dd2012-12-18 14:30:41 +0000810void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000811 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
812 // Variables should have implicit tags from its type.
813 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
814 if (VariableTypeAbiTags.empty()) {
815 // Simple case no variable type tags.
816 mangleNameWithAbiTags(VD, nullptr);
817 return;
818 }
819
820 // Mangle variable name to null stream to collect tags.
821 llvm::raw_null_ostream NullOutStream;
822 CXXNameMangler VariableNameMangler(*this, NullOutStream);
823 VariableNameMangler.disableDerivedAbiTags();
824 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
825
826 // Get tags from variable type that are not present in its name.
827 const AbiTagList &UsedAbiTags =
828 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
829 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
830 AdditionalAbiTags.erase(
831 std::set_difference(VariableTypeAbiTags.begin(),
832 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
833 UsedAbiTags.end(), AdditionalAbiTags.begin()),
834 AdditionalAbiTags.end());
835
836 // Output name with implicit tags.
837 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
838 } else {
839 mangleNameWithAbiTags(ND, nullptr);
840 }
841}
842
843void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
844 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000845 // <name> ::= [<module-name>] <nested-name>
846 // ::= [<module-name>] <unscoped-name>
847 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 // ::= <local-name>
849 //
850 const DeclContext *DC = getEffectiveDeclContext(ND);
851
852 // If this is an extern variable declared locally, the relevant DeclContext
853 // is that of the containing namespace, or the translation unit.
854 // FIXME: This is a hack; extern variables declared locally should have
855 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000856 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000857 while (!DC->isNamespace() && !DC->isTranslationUnit())
858 DC = getEffectiveParentContext(DC);
859 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000860 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861 return;
862 }
863
864 DC = IgnoreLinkageSpecDecls(DC);
865
Richard Smithdd8b5332017-09-04 05:37:53 +0000866 if (isLocalContainerContext(DC)) {
867 mangleLocalName(ND, AdditionalAbiTags);
868 return;
869 }
870
871 // Do not mangle the owning module for an external linkage declaration.
872 // This enables backwards-compatibility with non-modular code, and is
873 // a valid choice since conflicts are not permitted by C++ Modules TS
874 // [basic.def.odr]/6.2.
875 if (!ND->hasExternalFormalLinkage())
876 if (Module *M = ND->getOwningModuleForLinkage())
877 mangleModuleName(M);
878
Guy Benyei11169dd2012-12-18 14:30:41 +0000879 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
880 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000881 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000882 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000883 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 mangleTemplateArgs(*TemplateArgs);
885 return;
886 }
887
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000888 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000889 return;
890 }
891
Richard Smithdd8b5332017-09-04 05:37:53 +0000892 mangleNestedName(ND, DC, AdditionalAbiTags);
893}
894
895void CXXNameMangler::mangleModuleName(const Module *M) {
896 // Implement the C++ Modules TS name mangling proposal; see
897 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
898 //
899 // <module-name> ::= W <unscoped-name>+ E
900 // ::= W <module-subst> <unscoped-name>* E
901 Out << 'W';
902 mangleModuleNamePrefix(M->Name);
903 Out << 'E';
904}
905
906void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
907 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
908 // ::= W <seq-id - 10> _ # otherwise
909 auto It = ModuleSubstitutions.find(Name);
910 if (It != ModuleSubstitutions.end()) {
911 if (It->second < 10)
912 Out << '_' << static_cast<char>('0' + It->second);
913 else
914 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000915 return;
916 }
917
Richard Smithdd8b5332017-09-04 05:37:53 +0000918 // FIXME: Preserve hierarchy in module names rather than flattening
919 // them to strings; use Module*s as substitution keys.
920 auto Parts = Name.rsplit('.');
921 if (Parts.second.empty())
922 Parts.second = Parts.first;
923 else
924 mangleModuleNamePrefix(Parts.first);
925
926 Out << Parts.second.size() << Parts.second;
927 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000928}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000929
930void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
931 const TemplateArgument *TemplateArgs,
932 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
934
935 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000936 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000937 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
938 } else {
939 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
940 }
941}
942
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000943void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
944 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 // <unscoped-name> ::= <unqualified-name>
946 // ::= St <unqualified-name> # ::std::
947
948 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
949 Out << "St";
950
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000951 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000952}
953
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000954void CXXNameMangler::mangleUnscopedTemplateName(
955 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 // <unscoped-template-name> ::= <unscoped-name>
957 // ::= <substitution>
958 if (mangleSubstitution(ND))
959 return;
960
961 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000962 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
963 assert(!AdditionalAbiTags &&
964 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000966 } else if (isa<BuiltinTemplateDecl>(ND)) {
967 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000968 } else {
969 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
970 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000971
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 addSubstitution(ND);
973}
974
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000975void CXXNameMangler::mangleUnscopedTemplateName(
976 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 // <unscoped-template-name> ::= <unscoped-name>
978 // ::= <substitution>
979 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000980 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +0000981
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 if (mangleSubstitution(Template))
983 return;
984
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000985 assert(!AdditionalAbiTags &&
986 "dependent template name cannot have abi tags");
987
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
989 assert(Dependent && "Not a dependent template name?");
990 if (const IdentifierInfo *Id = Dependent->getIdentifier())
991 mangleSourceName(Id);
992 else
993 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000994
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 addSubstitution(Template);
996}
997
998void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
999 // ABI:
1000 // Floating-point literals are encoded using a fixed-length
1001 // lowercase hexadecimal string corresponding to the internal
1002 // representation (IEEE on Itanium), high-order bytes first,
1003 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1004 // on Itanium.
1005 // The 'without leading zeroes' thing seems to be an editorial
1006 // mistake; see the discussion on cxx-abi-dev beginning on
1007 // 2012-01-16.
1008
1009 // Our requirements here are just barely weird enough to justify
1010 // using a custom algorithm instead of post-processing APInt::toString().
1011
1012 llvm::APInt valueBits = f.bitcastToAPInt();
1013 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1014 assert(numCharacters != 0);
1015
1016 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001017 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018
1019 // Fill the buffer left-to-right.
1020 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1021 // The bit-index of the next hex digit.
1022 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1023
1024 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001025 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1026 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 hexDigit &= 0xF;
1028
1029 // Map that over to a lowercase hex digit.
1030 static const char charForHex[16] = {
1031 '0', '1', '2', '3', '4', '5', '6', '7',
1032 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1033 };
1034 buffer[stringIndex] = charForHex[hexDigit];
1035 }
1036
1037 Out.write(buffer.data(), numCharacters);
1038}
1039
1040void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1041 if (Value.isSigned() && Value.isNegative()) {
1042 Out << 'n';
1043 Value.abs().print(Out, /*signed*/ false);
1044 } else {
1045 Value.print(Out, /*signed*/ false);
1046 }
1047}
1048
1049void CXXNameMangler::mangleNumber(int64_t Number) {
1050 // <number> ::= [n] <non-negative decimal integer>
1051 if (Number < 0) {
1052 Out << 'n';
1053 Number = -Number;
1054 }
1055
1056 Out << Number;
1057}
1058
1059void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1060 // <call-offset> ::= h <nv-offset> _
1061 // ::= v <v-offset> _
1062 // <nv-offset> ::= <offset number> # non-virtual base override
1063 // <v-offset> ::= <offset number> _ <virtual offset number>
1064 // # virtual base override, with vcall offset
1065 if (!Virtual) {
1066 Out << 'h';
1067 mangleNumber(NonVirtual);
1068 Out << '_';
1069 return;
1070 }
1071
1072 Out << 'v';
1073 mangleNumber(NonVirtual);
1074 Out << '_';
1075 mangleNumber(Virtual);
1076 Out << '_';
1077}
1078
1079void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001080 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001081 if (!mangleSubstitution(QualType(TST, 0))) {
1082 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001083
Guy Benyei11169dd2012-12-18 14:30:41 +00001084 // FIXME: GCC does not appear to mangle the template arguments when
1085 // the template in question is a dependent template name. Should we
1086 // emulate that badness?
1087 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1088 addSubstitution(QualType(TST, 0));
1089 }
David Majnemera88b3592015-02-18 02:28:01 +00001090 } else if (const auto *DTST =
1091 type->getAs<DependentTemplateSpecializationType>()) {
1092 if (!mangleSubstitution(QualType(DTST, 0))) {
1093 TemplateName Template = getASTContext().getDependentTemplateName(
1094 DTST->getQualifier(), DTST->getIdentifier());
1095 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001096
David Majnemera88b3592015-02-18 02:28:01 +00001097 // FIXME: GCC does not appear to mangle the template arguments when
1098 // the template in question is a dependent template name. Should we
1099 // emulate that badness?
1100 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1101 addSubstitution(QualType(DTST, 0));
1102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 } else {
1104 // We use the QualType mangle type variant here because it handles
1105 // substitutions.
1106 mangleType(type);
1107 }
1108}
1109
1110/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1111///
Guy Benyei11169dd2012-12-18 14:30:41 +00001112/// \param recursive - true if this is being called recursively,
1113/// i.e. if there is more prefix "to the right".
1114void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 bool recursive) {
1116
1117 // x, ::x
1118 // <unresolved-name> ::= [gs] <base-unresolved-name>
1119
1120 // T::x / decltype(p)::x
1121 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1122
1123 // T::N::x /decltype(p)::N::x
1124 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1125 // <base-unresolved-name>
1126
1127 // A::x, N::y, A<T>::z; "gs" means leading "::"
1128 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1129 // <base-unresolved-name>
1130
1131 switch (qualifier->getKind()) {
1132 case NestedNameSpecifier::Global:
1133 Out << "gs";
1134
1135 // We want an 'sr' unless this is the entire NNS.
1136 if (recursive)
1137 Out << "sr";
1138
1139 // We never want an 'E' here.
1140 return;
1141
Nikola Smiljanic67860242014-09-26 00:28:20 +00001142 case NestedNameSpecifier::Super:
1143 llvm_unreachable("Can't mangle __super specifier");
1144
Guy Benyei11169dd2012-12-18 14:30:41 +00001145 case NestedNameSpecifier::Namespace:
1146 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001147 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 /*recursive*/ true);
1149 else
1150 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001151 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 break;
1153 case NestedNameSpecifier::NamespaceAlias:
1154 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001155 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001156 /*recursive*/ true);
1157 else
1158 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001159 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 break;
1161
1162 case NestedNameSpecifier::TypeSpec:
1163 case NestedNameSpecifier::TypeSpecWithTemplate: {
1164 const Type *type = qualifier->getAsType();
1165
1166 // We only want to use an unresolved-type encoding if this is one of:
1167 // - a decltype
1168 // - a template type parameter
1169 // - a template template parameter with arguments
1170 // In all of these cases, we should have no prefix.
1171 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001172 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 /*recursive*/ true);
1174 } else {
1175 // Otherwise, all the cases want this.
1176 Out << "sr";
1177 }
1178
David Majnemerb8014dd2015-02-19 02:16:16 +00001179 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 return;
1181
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 break;
1183 }
1184
1185 case NestedNameSpecifier::Identifier:
1186 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001187 if (qualifier->getPrefix())
1188 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001190 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001192
1193 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001194 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 break;
1196 }
1197
1198 // If this was the innermost part of the NNS, and we fell out to
1199 // here, append an 'E'.
1200 if (!recursive)
1201 Out << 'E';
1202}
1203
1204/// Mangle an unresolved-name, which is generally used for names which
1205/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001206void CXXNameMangler::mangleUnresolvedName(
1207 NestedNameSpecifier *qualifier, DeclarationName name,
1208 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1209 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001210 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001211 switch (name.getNameKind()) {
1212 // <base-unresolved-name> ::= <simple-id>
1213 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001214 mangleSourceName(name.getAsIdentifierInfo());
1215 break;
1216 // <base-unresolved-name> ::= dn <destructor-name>
1217 case DeclarationName::CXXDestructorName:
1218 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001219 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001220 break;
1221 // <base-unresolved-name> ::= on <operator-name>
1222 case DeclarationName::CXXConversionFunctionName:
1223 case DeclarationName::CXXLiteralOperatorName:
1224 case DeclarationName::CXXOperatorName:
1225 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001226 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001227 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001228 case DeclarationName::CXXConstructorName:
1229 llvm_unreachable("Can't mangle a constructor name!");
1230 case DeclarationName::CXXUsingDirective:
1231 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001232 case DeclarationName::CXXDeductionGuideName:
1233 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001234 case DeclarationName::ObjCMultiArgSelector:
1235 case DeclarationName::ObjCOneArgSelector:
1236 case DeclarationName::ObjCZeroArgSelector:
1237 llvm_unreachable("Can't mangle Objective-C selector names here!");
1238 }
Richard Smithafecd832016-10-24 20:47:04 +00001239
1240 // The <simple-id> and on <operator-name> productions end in an optional
1241 // <template-args>.
1242 if (TemplateArgs)
1243 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001244}
1245
Guy Benyei11169dd2012-12-18 14:30:41 +00001246void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1247 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001248 unsigned KnownArity,
1249 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001250 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 // <unqualified-name> ::= <operator-name>
1252 // ::= <ctor-dtor-name>
1253 // ::= <source-name>
1254 switch (Name.getNameKind()) {
1255 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001256 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1257
Richard Smithda383632016-08-15 01:33:41 +00001258 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001259 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001260 // FIXME: Non-standard mangling for decomposition declarations:
1261 //
1262 // <unqualified-name> ::= DC <source-name>* E
1263 //
1264 // These can never be referenced across translation units, so we do
1265 // not need a cross-vendor mangling for anything other than demanglers.
1266 // Proposed on cxx-abi-dev on 2016-08-12
1267 Out << "DC";
1268 for (auto *BD : DD->bindings())
1269 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1270 Out << 'E';
1271 writeAbiTags(ND, AdditionalAbiTags);
1272 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001273 }
1274
1275 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001276 // Match GCC's naming convention for internal linkage symbols, for
1277 // symbols that are not actually visible outside of this TU. GCC
1278 // distinguishes between internal and external linkage symbols in
1279 // its mangling, to support cases like this that were valid C++ prior
1280 // to DR426:
1281 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 // void test() { extern void foo(); }
1283 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001284 //
1285 // Don't bother with the L marker for names in anonymous namespaces; the
1286 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1287 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1288 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001289 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001290 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001291 getEffectiveDeclContext(ND)->isFileContext() &&
1292 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 Out << 'L';
1294
Erich Keane757d3172016-11-02 18:29:35 +00001295 auto *FD = dyn_cast<FunctionDecl>(ND);
1296 bool IsRegCall = FD &&
1297 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1298 clang::CC_X86RegCall;
1299 if (IsRegCall)
1300 mangleRegCallName(II);
1301 else
1302 mangleSourceName(II);
1303
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001304 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 break;
1306 }
1307
1308 // Otherwise, an anonymous entity. We must have a declaration.
1309 assert(ND && "mangling empty name without declaration");
1310
1311 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1312 if (NS->isAnonymousNamespace()) {
1313 // This is how gcc mangles these names.
1314 Out << "12_GLOBAL__N_1";
1315 break;
1316 }
1317 }
1318
1319 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1320 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001321 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001322
Guy Benyei11169dd2012-12-18 14:30:41 +00001323 // Itanium C++ ABI 5.1.2:
1324 //
1325 // For the purposes of mangling, the name of an anonymous union is
1326 // considered to be the name of the first named data member found by a
1327 // pre-order, depth-first, declaration-order walk of the data members of
1328 // the anonymous union. If there is no such data member (i.e., if all of
1329 // the data members in the union are unnamed), then there is no way for
1330 // a program to refer to the anonymous union, and there is therefore no
1331 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001332 assert(RD->isAnonymousStructOrUnion()
1333 && "Expected anonymous struct or union!");
1334 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001335
1336 // It's actually possible for various reasons for us to get here
1337 // with an empty anonymous struct / union. Fortunately, it
1338 // doesn't really matter what name we generate.
1339 if (!FD) break;
1340 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001341
Guy Benyei11169dd2012-12-18 14:30:41 +00001342 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001343 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 break;
1345 }
John McCall924046f2013-04-10 06:08:21 +00001346
1347 // Class extensions have no name as a category, and it's possible
1348 // for them to be the semantic parent of certain declarations
1349 // (primarily, tag decls defined within declarations). Such
1350 // declarations will always have internal linkage, so the name
1351 // doesn't really matter, but we shouldn't crash on them. For
1352 // safety, just handle all ObjC containers here.
1353 if (isa<ObjCContainerDecl>(ND))
1354 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001355
Guy Benyei11169dd2012-12-18 14:30:41 +00001356 // We must have an anonymous struct.
1357 const TagDecl *TD = cast<TagDecl>(ND);
1358 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1359 assert(TD->getDeclContext() == D->getDeclContext() &&
1360 "Typedef should not be in another decl context!");
1361 assert(D->getDeclName().getAsIdentifierInfo() &&
1362 "Typedef was not named!");
1363 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001364 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1365 // Explicit abi tags are still possible; take from underlying type, not
1366 // from typedef.
1367 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 break;
1369 }
1370
1371 // <unnamed-type-name> ::= <closure-type-name>
Fangrui Song6907ce22018-07-30 19:24:48 +00001372 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001373 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1374 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1375 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1376 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001377 assert(!AdditionalAbiTags &&
1378 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 mangleLambda(Record);
1380 break;
1381 }
1382 }
1383
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001384 if (TD->isExternallyVisible()) {
1385 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001387 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001388 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001390 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 break;
1392 }
1393
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001394 // Get a unique id for the anonymous struct. If it is not a real output
1395 // ID doesn't matter so use fake one.
1396 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
1398 // Mangle it as a source name in the form
1399 // [n] $_<id>
1400 // where n is the length of the string.
1401 SmallString<8> Str;
1402 Str += "$_";
1403 Str += llvm::utostr(AnonStructId);
1404
1405 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001406 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 break;
1408 }
1409
1410 case DeclarationName::ObjCZeroArgSelector:
1411 case DeclarationName::ObjCOneArgSelector:
1412 case DeclarationName::ObjCMultiArgSelector:
1413 llvm_unreachable("Can't mangle Objective-C selector names here!");
1414
Richard Smith5179eb72016-06-28 19:03:57 +00001415 case DeclarationName::CXXConstructorName: {
1416 const CXXRecordDecl *InheritedFrom = nullptr;
1417 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1418 if (auto Inherited =
1419 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1420 InheritedFrom = Inherited.getConstructor()->getParent();
1421 InheritedTemplateArgs =
1422 Inherited.getConstructor()->getTemplateSpecializationArgs();
1423 }
1424
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 if (ND == Structor)
1426 // If the named decl is the C++ constructor we're mangling, use the type
1427 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001428 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 else
1430 // Otherwise, use the complete constructor name. This is relevant if a
1431 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001432 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1433
1434 // FIXME: The template arguments are part of the enclosing prefix or
1435 // nested-name, but it's more convenient to mangle them here.
1436 if (InheritedTemplateArgs)
1437 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001438
1439 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001441 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001442
1443 case DeclarationName::CXXDestructorName:
1444 if (ND == Structor)
1445 // If the named decl is the C++ destructor we're mangling, use the type we
1446 // were given.
1447 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1448 else
1449 // Otherwise, use the complete destructor name. This is relevant if a
1450 // class with a destructor is declared within a destructor.
1451 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001452 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 break;
1454
David Majnemera88b3592015-02-18 02:28:01 +00001455 case DeclarationName::CXXOperatorName:
1456 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 Arity = cast<FunctionDecl>(ND)->getNumParams();
1458
David Majnemera88b3592015-02-18 02:28:01 +00001459 // If we have a member function, we need to include the 'this' pointer.
1460 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1461 if (!MD->isStatic())
1462 Arity++;
1463 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001464 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001465 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001467 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001468 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 break;
1470
Richard Smith35845152017-02-07 01:37:30 +00001471 case DeclarationName::CXXDeductionGuideName:
1472 llvm_unreachable("Can't mangle a deduction guide name!");
1473
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 case DeclarationName::CXXUsingDirective:
1475 llvm_unreachable("Can't mangle a using directive name!");
1476 }
1477}
1478
Erich Keane757d3172016-11-02 18:29:35 +00001479void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1480 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1481 // <number> ::= [n] <non-negative decimal integer>
1482 // <identifier> ::= <unqualified source code identifier>
1483 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1484 << II->getName();
1485}
1486
Guy Benyei11169dd2012-12-18 14:30:41 +00001487void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1488 // <source-name> ::= <positive length number> <identifier>
1489 // <number> ::= [n] <non-negative decimal integer>
1490 // <identifier> ::= <unqualified source code identifier>
1491 Out << II->getLength() << II->getName();
1492}
1493
1494void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1495 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001496 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 bool NoFunction) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001498 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001500 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001501 // <template-args> E
1502
1503 Out << 'N';
1504 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001505 Qualifiers MethodQuals = Method->getTypeQualifiers();
David Majnemer42350df2013-11-03 23:51:28 +00001506 // We do not consider restrict a distinguishing attribute for overloading
1507 // purposes so we must not mangle it.
1508 MethodQuals.removeRestrict();
1509 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 mangleRefQualifier(Method->getRefQualifier());
1511 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001514 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001516 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 mangleTemplateArgs(*TemplateArgs);
1518 }
1519 else {
1520 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001521 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 }
1523
1524 Out << 'E';
1525}
1526void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1527 const TemplateArgument *TemplateArgs,
1528 unsigned NumTemplateArgs) {
1529 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1530
1531 Out << 'N';
1532
1533 mangleTemplatePrefix(TD);
1534 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1535
1536 Out << 'E';
1537}
1538
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001539void CXXNameMangler::mangleLocalName(const Decl *D,
1540 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1542 // := Z <function encoding> E s [<discriminator>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001543 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // _ <entity name>
1545 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001546 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001547 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001548 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001549
1550 Out << 'Z';
1551
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001552 {
1553 AbiTagState LocalAbiTags(AbiTags);
1554
1555 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1556 mangleObjCMethodName(MD);
1557 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1558 mangleBlockForPrefix(BD);
1559 else
1560 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1561
1562 // Implicit ABI tags (from namespace) are not available in the following
1563 // entity; reset to actually emitted tags, which are available.
1564 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001566
Eli Friedman92821742013-07-02 02:01:18 +00001567 Out << 'E';
1568
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001569 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1570 // be a bug that is fixed in trunk.
1571
Eli Friedman92821742013-07-02 02:01:18 +00001572 if (RD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001573 // The parameter number is omitted for the last parameter, 0 for the
1574 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1575 // <entity name> will of course contain a <closure-type-name>: Its
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 // numbering will be local to the particular argument in which it appears
1577 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001578 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001579 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001581 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 if (const FunctionDecl *Func
1583 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1584 Out << 'd';
1585 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1586 if (Num > 1)
1587 mangleNumber(Num - 2);
1588 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 }
1590 }
1591 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001594 // equality ok because RD derived from ND above
1595 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001596 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001597 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1598 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001599 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001600 mangleUnqualifiedBlock(BD);
1601 } else {
1602 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001603 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1604 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001605 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001606 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1607 // Mangle a block in a default parameter; see above explanation for
1608 // lambdas.
1609 if (const ParmVarDecl *Parm
1610 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1611 if (const FunctionDecl *Func
1612 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1613 Out << 'd';
1614 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1615 if (Num > 1)
1616 mangleNumber(Num - 2);
1617 Out << '_';
1618 }
1619 }
1620
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001621 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001622 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001623 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001624 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001626
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001627 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1628 unsigned disc;
1629 if (Context.getNextDiscriminator(ND, disc)) {
1630 if (disc < 10)
1631 Out << '_' << disc;
1632 else
1633 Out << "__" << disc << '_';
1634 }
1635 }
Eli Friedman95f50122013-07-02 17:52:28 +00001636}
1637
1638void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1639 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001640 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001641 return;
1642 }
1643 const DeclContext *DC = getEffectiveDeclContext(Block);
1644 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001645 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001646 return;
1647 }
1648 manglePrefix(getEffectiveDeclContext(Block));
1649 mangleUnqualifiedBlock(Block);
1650}
1651
1652void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1653 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1654 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1655 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001656 const auto *ND = cast<NamedDecl>(Context);
1657 if (ND->getIdentifier()) {
1658 mangleSourceNameWithAbiTags(ND);
1659 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001660 }
1661 }
1662 }
1663
1664 // If we have a block mangling number, use it.
1665 unsigned Number = Block->getBlockManglingNumber();
1666 // Otherwise, just make up a number. It doesn't matter what it is because
1667 // the symbol in question isn't externally visible.
1668 if (!Number)
1669 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001670 else {
1671 // Stored mangling numbers are 1-based.
1672 --Number;
1673 }
Eli Friedman95f50122013-07-02 17:52:28 +00001674 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001675 if (Number > 0)
1676 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001677 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001678}
1679
1680void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001681 // If the context of a closure type is an initializer for a class member
1682 // (static or nonstatic), it is encoded in a qualified name with a final
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 // <prefix> of the form:
1684 //
1685 // <data-member-prefix> := <member source-name> M
1686 //
1687 // Technically, the data-member-prefix is part of the <prefix>. However,
1688 // since a closure type will always be mangled with a prefix, it's easier
1689 // to emit that last part of the prefix here.
1690 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1691 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001692 !isa<ParmVarDecl>(Context)) {
1693 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1694 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001695 if (const IdentifierInfo *Name
1696 = cast<NamedDecl>(Context)->getIdentifier()) {
1697 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001698 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001699 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001700 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001701 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 }
1703 }
1704 }
1705
1706 Out << "Ul";
1707 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1708 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001709 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1710 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001711 Out << "E";
Fangrui Song6907ce22018-07-30 19:24:48 +00001712
1713 // The number is omitted for the first closure type with a given
1714 // <lambda-sig> in a given context; it is n-2 for the nth closure type
Guy Benyei11169dd2012-12-18 14:30:41 +00001715 // (in lexical order) with that same <lambda-sig> and context.
1716 //
1717 // The AST keeps track of the number for us.
1718 unsigned Number = Lambda->getLambdaManglingNumber();
1719 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1720 if (Number > 1)
1721 mangleNumber(Number - 2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001722 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001723}
1724
1725void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1726 switch (qualifier->getKind()) {
1727 case NestedNameSpecifier::Global:
1728 // nothing
1729 return;
1730
Nikola Smiljanic67860242014-09-26 00:28:20 +00001731 case NestedNameSpecifier::Super:
1732 llvm_unreachable("Can't mangle __super specifier");
1733
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 case NestedNameSpecifier::Namespace:
1735 mangleName(qualifier->getAsNamespace());
1736 return;
1737
1738 case NestedNameSpecifier::NamespaceAlias:
1739 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1740 return;
1741
1742 case NestedNameSpecifier::TypeSpec:
1743 case NestedNameSpecifier::TypeSpecWithTemplate:
1744 manglePrefix(QualType(qualifier->getAsType(), 0));
1745 return;
1746
1747 case NestedNameSpecifier::Identifier:
1748 // Member expressions can have these without prefixes, but that
1749 // should end up in mangleUnresolvedPrefix instead.
1750 assert(qualifier->getPrefix());
1751 manglePrefix(qualifier->getPrefix());
1752
1753 mangleSourceName(qualifier->getAsIdentifier());
1754 return;
1755 }
1756
1757 llvm_unreachable("unexpected nested name specifier");
1758}
1759
1760void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1761 // <prefix> ::= <prefix> <unqualified-name>
1762 // ::= <template-prefix> <template-args>
1763 // ::= <template-param>
1764 // ::= # empty
1765 // ::= <substitution>
1766
1767 DC = IgnoreLinkageSpecDecls(DC);
1768
1769 if (DC->isTranslationUnit())
1770 return;
1771
Eli Friedman95f50122013-07-02 17:52:28 +00001772 if (NoFunction && isLocalContainerContext(DC))
1773 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001774
Eli Friedman95f50122013-07-02 17:52:28 +00001775 assert(!isLocalContainerContext(DC));
1776
Fangrui Song6907ce22018-07-30 19:24:48 +00001777 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001778 if (mangleSubstitution(ND))
1779 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001780
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001782 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1784 mangleTemplatePrefix(TD);
1785 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001786 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001787 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001788 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 }
1790
1791 addSubstitution(ND);
1792}
1793
1794void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1795 // <template-prefix> ::= <prefix> <template unqualified-name>
1796 // ::= <template-param>
1797 // ::= <substitution>
1798 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1799 return mangleTemplatePrefix(TD);
1800
1801 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1802 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001803
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 if (OverloadedTemplateStorage *Overloaded
1805 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001806 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001807 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 return;
1809 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001810
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1812 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001813 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1814 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001815 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001816}
1817
Eli Friedman86af13f02013-07-05 18:41:30 +00001818void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1819 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 // <template-prefix> ::= <prefix> <template unqualified-name>
1821 // ::= <template-param>
1822 // ::= <substitution>
1823 // <template-template-param> ::= <template-param>
1824 // <substitution>
1825
1826 if (mangleSubstitution(ND))
1827 return;
1828
1829 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001830 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001832 } else {
1833 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001834 if (isa<BuiltinTemplateDecl>(ND))
1835 mangleUnqualifiedName(ND, nullptr);
1836 else
1837 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001838 }
1839
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 addSubstitution(ND);
1841}
1842
1843/// Mangles a template name under the production <type>. Required for
1844/// template template arguments.
1845/// <type> ::= <class-enum-type>
1846/// ::= <template-param>
1847/// ::= <substitution>
1848void CXXNameMangler::mangleType(TemplateName TN) {
1849 if (mangleSubstitution(TN))
1850 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001851
1852 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853
1854 switch (TN.getKind()) {
1855 case TemplateName::QualifiedTemplate:
1856 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1857 goto HaveDecl;
1858
1859 case TemplateName::Template:
1860 TD = TN.getAsTemplateDecl();
1861 goto HaveDecl;
1862
1863 HaveDecl:
1864 if (isa<TemplateTemplateParmDecl>(TD))
1865 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1866 else
1867 mangleName(TD);
1868 break;
1869
1870 case TemplateName::OverloadedTemplate:
1871 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1872
1873 case TemplateName::DependentTemplate: {
1874 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1875 assert(Dependent->isIdentifier());
1876
1877 // <class-enum-type> ::= <name>
1878 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001879 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 mangleSourceName(Dependent->getIdentifier());
1881 break;
1882 }
1883
1884 case TemplateName::SubstTemplateTemplateParm: {
1885 // Substituted template parameters are mangled as the substituted
1886 // template. This will check for the substitution twice, which is
1887 // fine, but we have to return early so that we don't try to *add*
1888 // the substitution twice.
1889 SubstTemplateTemplateParmStorage *subst
1890 = TN.getAsSubstTemplateTemplateParm();
1891 mangleType(subst->getReplacement());
1892 return;
1893 }
1894
1895 case TemplateName::SubstTemplateTemplateParmPack: {
1896 // FIXME: not clear how to mangle this!
1897 // template <template <class> class T...> class A {
1898 // template <template <class> class U...> void foo(B<T,U> x...);
1899 // };
1900 Out << "_SUBSTPACK_";
1901 break;
1902 }
1903 }
1904
1905 addSubstitution(TN);
1906}
1907
David Majnemerb8014dd2015-02-19 02:16:16 +00001908bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1909 StringRef Prefix) {
1910 // Only certain other types are valid as prefixes; enumerate them.
1911 switch (Ty->getTypeClass()) {
1912 case Type::Builtin:
1913 case Type::Complex:
1914 case Type::Adjusted:
1915 case Type::Decayed:
1916 case Type::Pointer:
1917 case Type::BlockPointer:
1918 case Type::LValueReference:
1919 case Type::RValueReference:
1920 case Type::MemberPointer:
1921 case Type::ConstantArray:
1922 case Type::IncompleteArray:
1923 case Type::VariableArray:
1924 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001925 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001926 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001927 case Type::DependentSizedExtVector:
1928 case Type::Vector:
1929 case Type::ExtVector:
1930 case Type::FunctionProto:
1931 case Type::FunctionNoProto:
1932 case Type::Paren:
1933 case Type::Attributed:
1934 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001935 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001936 case Type::PackExpansion:
1937 case Type::ObjCObject:
1938 case Type::ObjCInterface:
1939 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001940 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001941 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001942 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001943 llvm_unreachable("type is illegal as a nested name specifier");
1944
1945 case Type::SubstTemplateTypeParmPack:
1946 // FIXME: not clear how to mangle this!
1947 // template <class T...> class A {
1948 // template <class U...> void foo(decltype(T::foo(U())) x...);
1949 // };
1950 Out << "_SUBSTPACK_";
1951 break;
1952
1953 // <unresolved-type> ::= <template-param>
1954 // ::= <decltype>
1955 // ::= <template-template-param> <template-args>
1956 // (this last is not official yet)
1957 case Type::TypeOfExpr:
1958 case Type::TypeOf:
1959 case Type::Decltype:
1960 case Type::TemplateTypeParm:
1961 case Type::UnaryTransform:
1962 case Type::SubstTemplateTypeParm:
1963 unresolvedType:
1964 // Some callers want a prefix before the mangled type.
1965 Out << Prefix;
1966
1967 // This seems to do everything we want. It's not really
1968 // sanctioned for a substituted template parameter, though.
1969 mangleType(Ty);
1970
1971 // We never want to print 'E' directly after an unresolved-type,
1972 // so we return directly.
1973 return true;
1974
1975 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001976 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001977 break;
1978
1979 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001980 mangleSourceNameWithAbiTags(
1981 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001982 break;
1983
1984 case Type::Enum:
1985 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001986 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001987 break;
1988
1989 case Type::TemplateSpecialization: {
1990 const TemplateSpecializationType *TST =
1991 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001992 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001993 switch (TN.getKind()) {
1994 case TemplateName::Template:
1995 case TemplateName::QualifiedTemplate: {
1996 TemplateDecl *TD = TN.getAsTemplateDecl();
1997
1998 // If the base is a template template parameter, this is an
1999 // unresolved type.
2000 assert(TD && "no template for template specialization type");
2001 if (isa<TemplateTemplateParmDecl>(TD))
2002 goto unresolvedType;
2003
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002004 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002005 break;
David Majnemera88b3592015-02-18 02:28:01 +00002006 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002007
2008 case TemplateName::OverloadedTemplate:
2009 case TemplateName::DependentTemplate:
2010 llvm_unreachable("invalid base for a template specialization type");
2011
2012 case TemplateName::SubstTemplateTemplateParm: {
2013 SubstTemplateTemplateParmStorage *subst =
2014 TN.getAsSubstTemplateTemplateParm();
2015 mangleExistingSubstitution(subst->getReplacement());
2016 break;
2017 }
2018
2019 case TemplateName::SubstTemplateTemplateParmPack: {
2020 // FIXME: not clear how to mangle this!
2021 // template <template <class U> class T...> class A {
2022 // template <class U...> void foo(decltype(T<U>::foo) x...);
2023 // };
2024 Out << "_SUBSTPACK_";
2025 break;
2026 }
2027 }
2028
David Majnemera88b3592015-02-18 02:28:01 +00002029 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002030 break;
David Majnemera88b3592015-02-18 02:28:01 +00002031 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002032
2033 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002034 mangleSourceNameWithAbiTags(
2035 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002036 break;
2037
2038 case Type::DependentName:
2039 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2040 break;
2041
2042 case Type::DependentTemplateSpecialization: {
2043 const DependentTemplateSpecializationType *DTST =
2044 cast<DependentTemplateSpecializationType>(Ty);
2045 mangleSourceName(DTST->getIdentifier());
2046 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2047 break;
2048 }
2049
2050 case Type::Elaborated:
2051 return mangleUnresolvedTypeOrSimpleId(
2052 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2053 }
2054
2055 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002056}
2057
2058void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2059 switch (Name.getNameKind()) {
2060 case DeclarationName::CXXConstructorName:
2061 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002062 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002063 case DeclarationName::CXXUsingDirective:
2064 case DeclarationName::Identifier:
2065 case DeclarationName::ObjCMultiArgSelector:
2066 case DeclarationName::ObjCOneArgSelector:
2067 case DeclarationName::ObjCZeroArgSelector:
2068 llvm_unreachable("Not an operator name");
2069
2070 case DeclarationName::CXXConversionFunctionName:
2071 // <operator-name> ::= cv <type> # (cast)
2072 Out << "cv";
2073 mangleType(Name.getCXXNameType());
2074 break;
2075
2076 case DeclarationName::CXXLiteralOperatorName:
2077 Out << "li";
2078 mangleSourceName(Name.getCXXLiteralIdentifier());
2079 return;
2080
2081 case DeclarationName::CXXOperatorName:
2082 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2083 break;
2084 }
2085}
2086
Guy Benyei11169dd2012-12-18 14:30:41 +00002087void
2088CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2089 switch (OO) {
2090 // <operator-name> ::= nw # new
2091 case OO_New: Out << "nw"; break;
2092 // ::= na # new[]
2093 case OO_Array_New: Out << "na"; break;
2094 // ::= dl # delete
2095 case OO_Delete: Out << "dl"; break;
2096 // ::= da # delete[]
2097 case OO_Array_Delete: Out << "da"; break;
2098 // ::= ps # + (unary)
2099 // ::= pl # + (binary or unknown)
2100 case OO_Plus:
2101 Out << (Arity == 1? "ps" : "pl"); break;
2102 // ::= ng # - (unary)
2103 // ::= mi # - (binary or unknown)
2104 case OO_Minus:
2105 Out << (Arity == 1? "ng" : "mi"); break;
2106 // ::= ad # & (unary)
2107 // ::= an # & (binary or unknown)
2108 case OO_Amp:
2109 Out << (Arity == 1? "ad" : "an"); break;
2110 // ::= de # * (unary)
2111 // ::= ml # * (binary or unknown)
2112 case OO_Star:
2113 // Use binary when unknown.
2114 Out << (Arity == 1? "de" : "ml"); break;
2115 // ::= co # ~
2116 case OO_Tilde: Out << "co"; break;
2117 // ::= dv # /
2118 case OO_Slash: Out << "dv"; break;
2119 // ::= rm # %
2120 case OO_Percent: Out << "rm"; break;
2121 // ::= or # |
2122 case OO_Pipe: Out << "or"; break;
2123 // ::= eo # ^
2124 case OO_Caret: Out << "eo"; break;
2125 // ::= aS # =
2126 case OO_Equal: Out << "aS"; break;
2127 // ::= pL # +=
2128 case OO_PlusEqual: Out << "pL"; break;
2129 // ::= mI # -=
2130 case OO_MinusEqual: Out << "mI"; break;
2131 // ::= mL # *=
2132 case OO_StarEqual: Out << "mL"; break;
2133 // ::= dV # /=
2134 case OO_SlashEqual: Out << "dV"; break;
2135 // ::= rM # %=
2136 case OO_PercentEqual: Out << "rM"; break;
2137 // ::= aN # &=
2138 case OO_AmpEqual: Out << "aN"; break;
2139 // ::= oR # |=
2140 case OO_PipeEqual: Out << "oR"; break;
2141 // ::= eO # ^=
2142 case OO_CaretEqual: Out << "eO"; break;
2143 // ::= ls # <<
2144 case OO_LessLess: Out << "ls"; break;
2145 // ::= rs # >>
2146 case OO_GreaterGreater: Out << "rs"; break;
2147 // ::= lS # <<=
2148 case OO_LessLessEqual: Out << "lS"; break;
2149 // ::= rS # >>=
2150 case OO_GreaterGreaterEqual: Out << "rS"; break;
2151 // ::= eq # ==
2152 case OO_EqualEqual: Out << "eq"; break;
2153 // ::= ne # !=
2154 case OO_ExclaimEqual: Out << "ne"; break;
2155 // ::= lt # <
2156 case OO_Less: Out << "lt"; break;
2157 // ::= gt # >
2158 case OO_Greater: Out << "gt"; break;
2159 // ::= le # <=
2160 case OO_LessEqual: Out << "le"; break;
2161 // ::= ge # >=
2162 case OO_GreaterEqual: Out << "ge"; break;
2163 // ::= nt # !
2164 case OO_Exclaim: Out << "nt"; break;
2165 // ::= aa # &&
2166 case OO_AmpAmp: Out << "aa"; break;
2167 // ::= oo # ||
2168 case OO_PipePipe: Out << "oo"; break;
2169 // ::= pp # ++
2170 case OO_PlusPlus: Out << "pp"; break;
2171 // ::= mm # --
2172 case OO_MinusMinus: Out << "mm"; break;
2173 // ::= cm # ,
2174 case OO_Comma: Out << "cm"; break;
2175 // ::= pm # ->*
2176 case OO_ArrowStar: Out << "pm"; break;
2177 // ::= pt # ->
2178 case OO_Arrow: Out << "pt"; break;
2179 // ::= cl # ()
2180 case OO_Call: Out << "cl"; break;
2181 // ::= ix # []
2182 case OO_Subscript: Out << "ix"; break;
2183
2184 // ::= qu # ?
2185 // The conditional operator can't be overloaded, but we still handle it when
2186 // mangling expressions.
2187 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002188 // Proposal on cxx-abi-dev, 2015-10-21.
2189 // ::= aw # co_await
2190 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002191 // Proposed in cxx-abi github issue 43.
2192 // ::= ss # <=>
2193 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002194
2195 case OO_None:
2196 case NUM_OVERLOADED_OPERATORS:
2197 llvm_unreachable("Not an overloaded operator");
2198 }
2199}
2200
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002201void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002202 // Vendor qualifiers come first and if they are order-insensitive they must
2203 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002205 // <type> ::= U <addrspace-expr>
2206 if (DAST) {
2207 Out << "U2ASI";
2208 mangleExpression(DAST->getAddrSpaceExpr());
2209 Out << "E";
2210 }
2211
John McCall07daf722016-03-01 22:18:03 +00002212 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002213 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002214 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 //
David Tweed31d09b02013-09-13 12:04:22 +00002216 // <type> ::= U <target-addrspace>
2217 // <type> ::= U <OpenCL-addrspace>
2218 // <type> ::= U <CUDA-addrspace>
2219
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002221 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002222
2223 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2224 // <target-addrspace> ::= "AS" <address-space-number>
2225 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002226 if (TargetAS != 0)
2227 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002228 } else {
2229 switch (AS) {
2230 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002231 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2232 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002233 case LangAS::opencl_global: ASString = "CLglobal"; break;
2234 case LangAS::opencl_local: ASString = "CLlocal"; break;
2235 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002236 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002237 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002238 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2239 case LangAS::cuda_device: ASString = "CUdevice"; break;
2240 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2241 case LangAS::cuda_shared: ASString = "CUshared"; break;
2242 }
2243 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002244 if (!ASString.empty())
2245 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 }
John McCall07daf722016-03-01 22:18:03 +00002247
2248 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 // Objective-C ARC Extension:
2250 //
2251 // <type> ::= U "__strong"
2252 // <type> ::= U "__weak"
2253 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002254 //
2255 // Note: we emit __weak first to preserve the order as
2256 // required by the Itanium ABI.
2257 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2258 mangleVendorQualifier("__weak");
2259
2260 // __unaligned (from -fms-extensions)
2261 if (Quals.hasUnaligned())
2262 mangleVendorQualifier("__unaligned");
2263
2264 // Remaining ARC ownership qualifiers.
2265 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 case Qualifiers::OCL_None:
2267 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002268
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002270 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002271 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002272
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002274 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002276
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002278 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002280
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 case Qualifiers::OCL_ExplicitNone:
2282 // The __unsafe_unretained qualifier is *not* mangled, so that
2283 // __unsafe_unretained types in ARC produce the same manglings as the
2284 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2285 // better ABI compatibility.
2286 //
2287 // It's safe to do this because unqualified 'id' won't show up
2288 // in any type signatures that need to be mangled.
2289 break;
2290 }
John McCall07daf722016-03-01 22:18:03 +00002291
2292 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2293 if (Quals.hasRestrict())
2294 Out << 'r';
2295 if (Quals.hasVolatile())
2296 Out << 'V';
2297 if (Quals.hasConst())
2298 Out << 'K';
2299}
2300
2301void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2302 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002303}
2304
2305void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2306 // <ref-qualifier> ::= R # lvalue reference
2307 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 switch (RefQualifier) {
2309 case RQ_None:
2310 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002311
Guy Benyei11169dd2012-12-18 14:30:41 +00002312 case RQ_LValue:
2313 Out << 'R';
2314 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002315
Guy Benyei11169dd2012-12-18 14:30:41 +00002316 case RQ_RValue:
2317 Out << 'O';
2318 break;
2319 }
2320}
2321
2322void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2323 Context.mangleObjCMethodName(MD, Out);
2324}
2325
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002326static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2327 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002328 if (Quals)
2329 return true;
2330 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2331 return true;
2332 if (Ty->isOpenCLSpecificType())
2333 return true;
2334 if (Ty->isBuiltinType())
2335 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002336 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2337 // substitution candidates.
2338 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2339 isa<AutoType>(Ty))
2340 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002341 return true;
2342}
2343
Guy Benyei11169dd2012-12-18 14:30:41 +00002344void CXXNameMangler::mangleType(QualType T) {
2345 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002346 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002347 // Otherwise, use the canonical type.
2348 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002349 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002350 // mangling rules, since we should really be using the type as written and
2351 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002352 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002354 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 // uniqued, so that we can handle substitutions properly
2356 // - Default template arguments will need to be represented in the
2357 // TemplateSpecializationType, since they need to be mangled even though
2358 // they aren't written.
2359 // - Conversions on non-type template arguments need to be expressed, since
2360 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002361 //
2362 // FIXME: This is wrong when mapping to the canonical type for a dependent
2363 // type discards instantiation-dependent portions of the type, such as for:
2364 //
2365 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2366 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2367 //
2368 // It's also wrong in the opposite direction when instantiation-dependent,
2369 // canonically-equivalent types differ in some irrelevant portion of inner
2370 // type sugar. In such cases, we fail to form correct substitutions, eg:
2371 //
2372 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2373 //
2374 // We should instead canonicalize the non-instantiation-dependent parts,
2375 // regardless of whether the type as a whole is dependent or instantiation
2376 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 if (!T->isInstantiationDependentType() || T->isDependentType())
2378 T = T.getCanonicalType();
2379 else {
2380 // Desugar any types that are purely sugar.
2381 do {
2382 // Don't desugar through template specialization types that aren't
2383 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002384 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 = dyn_cast<TemplateSpecializationType>(T))
2386 if (!TST->isTypeAlias())
2387 break;
2388
Fangrui Song6907ce22018-07-30 19:24:48 +00002389 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 = T.getSingleStepDesugaredType(Context.getASTContext());
2391 if (Desugared == T)
2392 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002393
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 T = Desugared;
2395 } while (true);
2396 }
2397 SplitQualType split = T.split();
2398 Qualifiers quals = split.Quals;
2399 const Type *ty = split.Ty;
2400
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002401 bool isSubstitutable =
2402 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 if (isSubstitutable && mangleSubstitution(T))
2404 return;
2405
2406 // If we're mangling a qualified array type, push the qualifiers to
2407 // the element type.
2408 if (quals && isa<ArrayType>(T)) {
2409 ty = Context.getASTContext().getAsArrayType(T);
2410 quals = Qualifiers();
2411
2412 // Note that we don't update T: we want to add the
2413 // substitution at the original type.
2414 }
2415
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002416 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002417 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002418 dyn_cast<DependentAddressSpaceType>(ty)) {
2419 SplitQualType splitDAST = DAST->getPointeeType().split();
2420 mangleQualifiers(splitDAST.Quals, DAST);
2421 mangleType(QualType(splitDAST.Ty, 0));
2422 } else {
2423 mangleQualifiers(quals);
2424
2425 // Recurse: even if the qualified type isn't yet substitutable,
2426 // the unqualified type might be.
2427 mangleType(QualType(ty, 0));
2428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 } else {
2430 switch (ty->getTypeClass()) {
2431#define ABSTRACT_TYPE(CLASS, PARENT)
2432#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2433 case Type::CLASS: \
2434 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2435 return;
2436#define TYPE(CLASS, PARENT) \
2437 case Type::CLASS: \
2438 mangleType(static_cast<const CLASS##Type*>(ty)); \
2439 break;
2440#include "clang/AST/TypeNodes.def"
2441 }
2442 }
2443
2444 // Add the substitution.
2445 if (isSubstitutable)
2446 addSubstitution(T);
2447}
2448
2449void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2450 if (!mangleStandardSubstitution(ND))
2451 mangleName(ND);
2452}
2453
2454void CXXNameMangler::mangleType(const BuiltinType *T) {
2455 // <type> ::= <builtin-type>
2456 // <builtin-type> ::= v # void
2457 // ::= w # wchar_t
2458 // ::= b # bool
2459 // ::= c # char
2460 // ::= a # signed char
2461 // ::= h # unsigned char
2462 // ::= s # short
2463 // ::= t # unsigned short
2464 // ::= i # int
2465 // ::= j # unsigned int
2466 // ::= l # long
2467 // ::= m # unsigned long
2468 // ::= x # long long, __int64
2469 // ::= y # unsigned long long, __int64
2470 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002471 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // ::= f # float
2473 // ::= d # double
2474 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002475 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2477 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2478 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2479 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002480 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 // ::= Di # char32_t
2482 // ::= Ds # char16_t
2483 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2484 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002485 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002487 case BuiltinType::Void:
2488 Out << 'v';
2489 break;
2490 case BuiltinType::Bool:
2491 Out << 'b';
2492 break;
2493 case BuiltinType::Char_U:
2494 case BuiltinType::Char_S:
2495 Out << 'c';
2496 break;
2497 case BuiltinType::UChar:
2498 Out << 'h';
2499 break;
2500 case BuiltinType::UShort:
2501 Out << 't';
2502 break;
2503 case BuiltinType::UInt:
2504 Out << 'j';
2505 break;
2506 case BuiltinType::ULong:
2507 Out << 'm';
2508 break;
2509 case BuiltinType::ULongLong:
2510 Out << 'y';
2511 break;
2512 case BuiltinType::UInt128:
2513 Out << 'o';
2514 break;
2515 case BuiltinType::SChar:
2516 Out << 'a';
2517 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002519 case BuiltinType::WChar_U:
2520 Out << 'w';
2521 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002522 case BuiltinType::Char8:
2523 Out << "Du";
2524 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002525 case BuiltinType::Char16:
2526 Out << "Ds";
2527 break;
2528 case BuiltinType::Char32:
2529 Out << "Di";
2530 break;
2531 case BuiltinType::Short:
2532 Out << 's';
2533 break;
2534 case BuiltinType::Int:
2535 Out << 'i';
2536 break;
2537 case BuiltinType::Long:
2538 Out << 'l';
2539 break;
2540 case BuiltinType::LongLong:
2541 Out << 'x';
2542 break;
2543 case BuiltinType::Int128:
2544 Out << 'n';
2545 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002546 case BuiltinType::Float16:
2547 Out << "DF16_";
2548 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002549 case BuiltinType::ShortAccum:
2550 case BuiltinType::Accum:
2551 case BuiltinType::LongAccum:
2552 case BuiltinType::UShortAccum:
2553 case BuiltinType::UAccum:
2554 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002555 case BuiltinType::ShortFract:
2556 case BuiltinType::Fract:
2557 case BuiltinType::LongFract:
2558 case BuiltinType::UShortFract:
2559 case BuiltinType::UFract:
2560 case BuiltinType::ULongFract:
2561 case BuiltinType::SatShortAccum:
2562 case BuiltinType::SatAccum:
2563 case BuiltinType::SatLongAccum:
2564 case BuiltinType::SatUShortAccum:
2565 case BuiltinType::SatUAccum:
2566 case BuiltinType::SatULongAccum:
2567 case BuiltinType::SatShortFract:
2568 case BuiltinType::SatFract:
2569 case BuiltinType::SatLongFract:
2570 case BuiltinType::SatUShortFract:
2571 case BuiltinType::SatUFract:
2572 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002573 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002574 case BuiltinType::Half:
2575 Out << "Dh";
2576 break;
2577 case BuiltinType::Float:
2578 Out << 'f';
2579 break;
2580 case BuiltinType::Double:
2581 Out << 'd';
2582 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002583 case BuiltinType::LongDouble:
2584 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2585 ? 'g'
2586 : 'e');
2587 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002588 case BuiltinType::Float128:
2589 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2590 Out << "U10__float128"; // Match the GCC mangling
2591 else
2592 Out << 'g';
2593 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002594 case BuiltinType::NullPtr:
2595 Out << "Dn";
2596 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597
2598#define BUILTIN_TYPE(Id, SingletonId)
2599#define PLACEHOLDER_TYPE(Id, SingletonId) \
2600 case BuiltinType::Id:
2601#include "clang/AST/BuiltinTypes.def"
2602 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002603 if (!NullOut)
2604 llvm_unreachable("mangling a placeholder type");
2605 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002606 case BuiltinType::ObjCId:
2607 Out << "11objc_object";
2608 break;
2609 case BuiltinType::ObjCClass:
2610 Out << "10objc_class";
2611 break;
2612 case BuiltinType::ObjCSel:
2613 Out << "13objc_selector";
2614 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002615#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2616 case BuiltinType::Id: \
2617 type_name = "ocl_" #ImgType "_" #Suffix; \
2618 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002619 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002620#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002621 case BuiltinType::OCLSampler:
2622 Out << "11ocl_sampler";
2623 break;
2624 case BuiltinType::OCLEvent:
2625 Out << "9ocl_event";
2626 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002627 case BuiltinType::OCLClkEvent:
2628 Out << "12ocl_clkevent";
2629 break;
2630 case BuiltinType::OCLQueue:
2631 Out << "9ocl_queue";
2632 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002633 case BuiltinType::OCLReserveID:
2634 Out << "13ocl_reserveid";
2635 break;
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002636#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2637 case BuiltinType::Id: \
2638 type_name = "ocl_" #ExtType; \
2639 Out << type_name.size() << type_name; \
2640 break;
2641#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
2643}
2644
John McCall07daf722016-03-01 22:18:03 +00002645StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2646 switch (CC) {
2647 case CC_C:
2648 return "";
2649
John McCall07daf722016-03-01 22:18:03 +00002650 case CC_X86VectorCall:
2651 case CC_X86Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00002652 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002653 case CC_AAPCS:
2654 case CC_AAPCS_VFP:
Sander de Smalen44a22532018-11-26 16:38:37 +00002655 case CC_AArch64VectorCall:
John McCall07daf722016-03-01 22:18:03 +00002656 case CC_IntelOclBicc:
2657 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002658 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002659 case CC_PreserveMost:
2660 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002661 // FIXME: we should be mangling all of the above.
2662 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002663
Reid Kleckner0a6096b2018-12-21 01:40:29 +00002664 case CC_X86ThisCall:
2665 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2666 // used explicitly. At this point, we don't have that much information in
2667 // the AST, since clang tends to bake the convention into the canonical
2668 // function type. thiscall only rarely used explicitly, so don't mangle it
2669 // for now.
2670 return "";
2671
Reid Klecknerf5f62902018-12-14 23:42:59 +00002672 case CC_X86StdCall:
2673 return "stdcall";
2674 case CC_X86FastCall:
2675 return "fastcall";
Reid Klecknerf5f62902018-12-14 23:42:59 +00002676 case CC_X86_64SysV:
2677 return "sysv_abi";
2678 case CC_Win64:
2679 return "ms_abi";
John McCall477f2bb2016-03-03 06:39:32 +00002680 case CC_Swift:
2681 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002682 }
2683 llvm_unreachable("bad calling convention");
2684}
2685
2686void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2687 // Fast path.
2688 if (T->getExtInfo() == FunctionType::ExtInfo())
2689 return;
2690
2691 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2692 // This will get more complicated in the future if we mangle other
2693 // things here; but for now, since we mangle ns_returns_retained as
2694 // a qualifier on the result type, we can get away with this:
2695 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2696 if (!CCQualifier.empty())
2697 mangleVendorQualifier(CCQualifier);
2698
2699 // FIXME: regparm
2700 // FIXME: noreturn
2701}
2702
2703void
2704CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2705 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2706
2707 // Note that these are *not* substitution candidates. Demanglers might
2708 // have trouble with this if the parameter type is fully substituted.
2709
John McCall477f2bb2016-03-03 06:39:32 +00002710 switch (PI.getABI()) {
2711 case ParameterABI::Ordinary:
2712 break;
2713
2714 // All of these start with "swift", so they come before "ns_consumed".
2715 case ParameterABI::SwiftContext:
2716 case ParameterABI::SwiftErrorResult:
2717 case ParameterABI::SwiftIndirectResult:
2718 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2719 break;
2720 }
2721
John McCall07daf722016-03-01 22:18:03 +00002722 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002723 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002724
2725 if (PI.isNoEscape())
2726 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002727}
2728
Guy Benyei11169dd2012-12-18 14:30:41 +00002729// <type> ::= <function-type>
2730// <function-type> ::= [<CV-qualifiers>] F [Y]
2731// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002732void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002733 mangleExtFunctionInfo(T);
2734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2736 // e.g. "const" in "int (A::*)() const".
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002737 mangleQualifiers(T->getTypeQuals());
Guy Benyei11169dd2012-12-18 14:30:41 +00002738
Richard Smithfda59e52016-10-26 01:05:54 +00002739 // Mangle instantiation-dependent exception-specification, if present,
2740 // per cxx-abi-dev proposal on 2016-10-11.
2741 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002742 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002743 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002744 mangleExpression(T->getNoexceptExpr());
2745 Out << "E";
2746 } else {
2747 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002748 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002749 for (auto ExceptTy : T->exceptions())
2750 mangleType(ExceptTy);
2751 Out << "E";
2752 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002753 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002754 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002755 }
2756
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 Out << 'F';
2758
2759 // FIXME: We don't have enough information in the AST to produce the 'Y'
2760 // encoding for extern "C" function types.
2761 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2762
2763 // Mangle the ref-qualifier, if present.
2764 mangleRefQualifier(T->getRefQualifier());
2765
2766 Out << 'E';
2767}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002768
Guy Benyei11169dd2012-12-18 14:30:41 +00002769void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002770 // Function types without prototypes can arise when mangling a function type
2771 // within an overloadable function in C. We mangle these as the absence of any
2772 // parameter types (not even an empty parameter list).
2773 Out << 'F';
2774
2775 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2776
2777 FunctionTypeDepth.enterResultType();
2778 mangleType(T->getReturnType());
2779 FunctionTypeDepth.leaveResultType();
2780
2781 FunctionTypeDepth.pop(saved);
2782 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002783}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002784
John McCall07daf722016-03-01 22:18:03 +00002785void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002786 bool MangleReturnType,
2787 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 // Record that we're in a function type. See mangleFunctionParam
2789 // for details on what we're trying to achieve here.
2790 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2791
2792 // <bare-function-type> ::= <signature type>+
2793 if (MangleReturnType) {
2794 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002795
2796 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002797 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002798 mangleVendorQualifier("ns_returns_retained");
2799
2800 // Mangle the return type without any direct ARC ownership qualifiers.
2801 QualType ReturnTy = Proto->getReturnType();
2802 if (ReturnTy.getObjCLifetime()) {
2803 auto SplitReturnTy = ReturnTy.split();
2804 SplitReturnTy.Quals.removeObjCLifetime();
2805 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2806 }
2807 mangleType(ReturnTy);
2808
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 FunctionTypeDepth.leaveResultType();
2810 }
2811
Alp Toker9cacbab2014-01-20 20:26:09 +00002812 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 // <builtin-type> ::= v # void
2814 Out << 'v';
2815
2816 FunctionTypeDepth.pop(saved);
2817 return;
2818 }
2819
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002820 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2821 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002822 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002823 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002824 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2825 }
2826
2827 // Mangle the type.
2828 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002829 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2830
2831 if (FD) {
2832 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2833 // Attr can only take 1 character, so we can hardcode the length below.
2834 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2835 Out << "U17pass_object_size" << Attr->getType();
2836 }
2837 }
2838 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002839
2840 FunctionTypeDepth.pop(saved);
2841
2842 // <builtin-type> ::= z # ellipsis
2843 if (Proto->isVariadic())
2844 Out << 'z';
2845}
2846
2847// <type> ::= <class-enum-type>
2848// <class-enum-type> ::= <name>
2849void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2850 mangleName(T->getDecl());
2851}
2852
2853// <type> ::= <class-enum-type>
2854// <class-enum-type> ::= <name>
2855void CXXNameMangler::mangleType(const EnumType *T) {
2856 mangleType(static_cast<const TagType*>(T));
2857}
2858void CXXNameMangler::mangleType(const RecordType *T) {
2859 mangleType(static_cast<const TagType*>(T));
2860}
2861void CXXNameMangler::mangleType(const TagType *T) {
2862 mangleName(T->getDecl());
2863}
2864
2865// <type> ::= <array-type>
2866// <array-type> ::= A <positive dimension number> _ <element type>
2867// ::= A [<dimension expression>] _ <element type>
2868void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2869 Out << 'A' << T->getSize() << '_';
2870 mangleType(T->getElementType());
2871}
2872void CXXNameMangler::mangleType(const VariableArrayType *T) {
2873 Out << 'A';
2874 // decayed vla types (size 0) will just be skipped.
2875 if (T->getSizeExpr())
2876 mangleExpression(T->getSizeExpr());
2877 Out << '_';
2878 mangleType(T->getElementType());
2879}
2880void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2881 Out << 'A';
2882 mangleExpression(T->getSizeExpr());
2883 Out << '_';
2884 mangleType(T->getElementType());
2885}
2886void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2887 Out << "A_";
2888 mangleType(T->getElementType());
2889}
2890
2891// <type> ::= <pointer-to-member-type>
2892// <pointer-to-member-type> ::= M <class type> <member type>
2893void CXXNameMangler::mangleType(const MemberPointerType *T) {
2894 Out << 'M';
2895 mangleType(QualType(T->getClass(), 0));
2896 QualType PointeeType = T->getPointeeType();
2897 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2898 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002899
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 // Itanium C++ ABI 5.1.8:
2901 //
2902 // The type of a non-static member function is considered to be different,
2903 // for the purposes of substitution, from the type of a namespace-scope or
2904 // static member function whose type appears similar. The types of two
2905 // non-static member functions are considered to be different, for the
2906 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002907 // classes. In other words, for the purposes of substitution, the class of
2908 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 // function.
2910
2911 // Given that we already substitute member function pointers as a
2912 // whole, the net effect of this rule is just to unconditionally
2913 // suppress substitution on the function type in a member pointer.
2914 // We increment the SeqID here to emulate adding an entry to the
2915 // substitution table.
2916 ++SeqID;
2917 } else
2918 mangleType(PointeeType);
2919}
2920
2921// <type> ::= <template-param>
2922void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2923 mangleTemplateParameter(T->getIndex());
2924}
2925
2926// <type> ::= <template-param>
2927void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2928 // FIXME: not clear how to mangle this!
2929 // template <class T...> class A {
2930 // template <class U...> void foo(T(*)(U) x...);
2931 // };
2932 Out << "_SUBSTPACK_";
2933}
2934
2935// <type> ::= P <type> # pointer-to
2936void CXXNameMangler::mangleType(const PointerType *T) {
2937 Out << 'P';
2938 mangleType(T->getPointeeType());
2939}
2940void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2941 Out << 'P';
2942 mangleType(T->getPointeeType());
2943}
2944
2945// <type> ::= R <type> # reference-to
2946void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2947 Out << 'R';
2948 mangleType(T->getPointeeType());
2949}
2950
2951// <type> ::= O <type> # rvalue reference-to (C++0x)
2952void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2953 Out << 'O';
2954 mangleType(T->getPointeeType());
2955}
2956
2957// <type> ::= C <type> # complex pair (C 2000)
2958void CXXNameMangler::mangleType(const ComplexType *T) {
2959 Out << 'C';
2960 mangleType(T->getElementType());
2961}
2962
2963// ARM's ABI for Neon vector types specifies that they should be mangled as
2964// if they are structs (to match ARM's initial implementation). The
2965// vector type must be one of the special types predefined by ARM.
2966void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2967 QualType EltType = T->getElementType();
2968 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002969 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2971 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002972 case BuiltinType::SChar:
2973 case BuiltinType::UChar:
2974 EltName = "poly8_t";
2975 break;
2976 case BuiltinType::Short:
2977 case BuiltinType::UShort:
2978 EltName = "poly16_t";
2979 break;
2980 case BuiltinType::ULongLong:
2981 EltName = "poly64_t";
2982 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2984 }
2985 } else {
2986 switch (cast<BuiltinType>(EltType)->getKind()) {
2987 case BuiltinType::SChar: EltName = "int8_t"; break;
2988 case BuiltinType::UChar: EltName = "uint8_t"; break;
2989 case BuiltinType::Short: EltName = "int16_t"; break;
2990 case BuiltinType::UShort: EltName = "uint16_t"; break;
2991 case BuiltinType::Int: EltName = "int32_t"; break;
2992 case BuiltinType::UInt: EltName = "uint32_t"; break;
2993 case BuiltinType::LongLong: EltName = "int64_t"; break;
2994 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002995 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002997 case BuiltinType::Half: EltName = "float16_t";break;
2998 default:
2999 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 }
3001 }
Craig Topper36250ad2014-05-12 05:36:57 +00003002 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 unsigned BitSize = (T->getNumElements() *
3004 getASTContext().getTypeSize(EltType));
3005 if (BitSize == 64)
3006 BaseName = "__simd64_";
3007 else {
3008 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3009 BaseName = "__simd128_";
3010 }
3011 Out << strlen(BaseName) + strlen(EltName);
3012 Out << BaseName << EltName;
3013}
3014
Erich Keanef702b022018-07-13 19:46:04 +00003015void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3016 DiagnosticsEngine &Diags = Context.getDiags();
3017 unsigned DiagID = Diags.getCustomDiagID(
3018 DiagnosticsEngine::Error,
3019 "cannot mangle this dependent neon vector type yet");
3020 Diags.Report(T->getAttributeLoc(), DiagID);
3021}
3022
Tim Northover2fe823a2013-08-01 09:23:19 +00003023static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3024 switch (EltType->getKind()) {
3025 case BuiltinType::SChar:
3026 return "Int8";
3027 case BuiltinType::Short:
3028 return "Int16";
3029 case BuiltinType::Int:
3030 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003031 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003032 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003033 return "Int64";
3034 case BuiltinType::UChar:
3035 return "Uint8";
3036 case BuiltinType::UShort:
3037 return "Uint16";
3038 case BuiltinType::UInt:
3039 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003040 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003041 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003042 return "Uint64";
3043 case BuiltinType::Half:
3044 return "Float16";
3045 case BuiltinType::Float:
3046 return "Float32";
3047 case BuiltinType::Double:
3048 return "Float64";
3049 default:
3050 llvm_unreachable("Unexpected vector element base type");
3051 }
3052}
3053
3054// AArch64's ABI for Neon vector types specifies that they should be mangled as
3055// the equivalent internal name. The vector type must be one of the special
3056// types predefined by ARM.
3057void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3058 QualType EltType = T->getElementType();
3059 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3060 unsigned BitSize =
3061 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003062 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003063
3064 assert((BitSize == 64 || BitSize == 128) &&
3065 "Neon vector type not 64 or 128 bits");
3066
Tim Northover2fe823a2013-08-01 09:23:19 +00003067 StringRef EltName;
3068 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3069 switch (cast<BuiltinType>(EltType)->getKind()) {
3070 case BuiltinType::UChar:
3071 EltName = "Poly8";
3072 break;
3073 case BuiltinType::UShort:
3074 EltName = "Poly16";
3075 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003076 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003077 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003078 EltName = "Poly64";
3079 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003080 default:
3081 llvm_unreachable("unexpected Neon polynomial vector element type");
3082 }
3083 } else
3084 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3085
3086 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003087 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003088 Out << TypeName.length() << TypeName;
3089}
Erich Keanef702b022018-07-13 19:46:04 +00003090void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3091 DiagnosticsEngine &Diags = Context.getDiags();
3092 unsigned DiagID = Diags.getCustomDiagID(
3093 DiagnosticsEngine::Error,
3094 "cannot mangle this dependent neon vector type yet");
3095 Diags.Report(T->getAttributeLoc(), DiagID);
3096}
Tim Northover2fe823a2013-08-01 09:23:19 +00003097
Guy Benyei11169dd2012-12-18 14:30:41 +00003098// GNU extension: vector types
3099// <type> ::= <vector-type>
3100// <vector-type> ::= Dv <positive dimension number> _
3101// <extended element type>
3102// ::= Dv [<dimension expression>] _ <element type>
3103// <extended element type> ::= <element type>
3104// ::= p # AltiVec vector pixel
3105// ::= b # Altivec vector bool
3106void CXXNameMangler::mangleType(const VectorType *T) {
3107 if ((T->getVectorKind() == VectorType::NeonVector ||
3108 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003109 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003110 llvm::Triple::ArchType Arch =
3111 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003112 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003113 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003114 mangleAArch64NeonVectorType(T);
3115 else
3116 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 return;
3118 }
3119 Out << "Dv" << T->getNumElements() << '_';
3120 if (T->getVectorKind() == VectorType::AltiVecPixel)
3121 Out << 'p';
3122 else if (T->getVectorKind() == VectorType::AltiVecBool)
3123 Out << 'b';
3124 else
3125 mangleType(T->getElementType());
3126}
Erich Keanef702b022018-07-13 19:46:04 +00003127
3128void CXXNameMangler::mangleType(const DependentVectorType *T) {
3129 if ((T->getVectorKind() == VectorType::NeonVector ||
3130 T->getVectorKind() == VectorType::NeonPolyVector)) {
3131 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3132 llvm::Triple::ArchType Arch =
3133 getASTContext().getTargetInfo().getTriple().getArch();
3134 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3135 !Target.isOSDarwin())
3136 mangleAArch64NeonVectorType(T);
3137 else
3138 mangleNeonVectorType(T);
3139 return;
3140 }
3141
3142 Out << "Dv";
3143 mangleExpression(T->getSizeExpr());
3144 Out << '_';
3145 if (T->getVectorKind() == VectorType::AltiVecPixel)
3146 Out << 'p';
3147 else if (T->getVectorKind() == VectorType::AltiVecBool)
3148 Out << 'b';
3149 else
3150 mangleType(T->getElementType());
3151}
3152
Guy Benyei11169dd2012-12-18 14:30:41 +00003153void CXXNameMangler::mangleType(const ExtVectorType *T) {
3154 mangleType(static_cast<const VectorType*>(T));
3155}
3156void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3157 Out << "Dv";
3158 mangleExpression(T->getSizeExpr());
3159 Out << '_';
3160 mangleType(T->getElementType());
3161}
3162
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003163void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3164 SplitQualType split = T->getPointeeType().split();
3165 mangleQualifiers(split.Quals, T);
3166 mangleType(QualType(split.Ty, 0));
3167}
3168
Guy Benyei11169dd2012-12-18 14:30:41 +00003169void CXXNameMangler::mangleType(const PackExpansionType *T) {
3170 // <type> ::= Dp <type> # pack expansion (C++0x)
3171 Out << "Dp";
3172 mangleType(T->getPattern());
3173}
3174
3175void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3176 mangleSourceName(T->getDecl()->getIdentifier());
3177}
3178
3179void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003180 // Treat __kindof as a vendor extended type qualifier.
3181 if (T->isKindOfType())
3182 Out << "U8__kindof";
3183
Eli Friedman5f508952013-06-18 22:41:37 +00003184 if (!T->qual_empty()) {
3185 // Mangle protocol qualifiers.
3186 SmallString<64> QualStr;
3187 llvm::raw_svector_ostream QualOS(QualStr);
3188 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003189 for (const auto *I : T->quals()) {
3190 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003191 QualOS << name.size() << name;
3192 }
Eli Friedman5f508952013-06-18 22:41:37 +00003193 Out << 'U' << QualStr.size() << QualStr;
3194 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003195
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003197
3198 if (T->isSpecialized()) {
3199 // Mangle type arguments as I <type>+ E
3200 Out << 'I';
3201 for (auto typeArg : T->getTypeArgs())
3202 mangleType(typeArg);
3203 Out << 'E';
3204 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003205}
3206
3207void CXXNameMangler::mangleType(const BlockPointerType *T) {
3208 Out << "U13block_pointer";
3209 mangleType(T->getPointeeType());
3210}
3211
3212void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3213 // Mangle injected class name types as if the user had written the
3214 // specialization out fully. It may not actually be possible to see
3215 // this mangling, though.
3216 mangleType(T->getInjectedSpecializationType());
3217}
3218
3219void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3220 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003221 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 } else {
3223 if (mangleSubstitution(QualType(T, 0)))
3224 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003225
Guy Benyei11169dd2012-12-18 14:30:41 +00003226 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003227
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 // FIXME: GCC does not appear to mangle the template arguments when
3229 // the template in question is a dependent template name. Should we
3230 // emulate that badness?
3231 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3232 addSubstitution(QualType(T, 0));
3233 }
3234}
3235
3236void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003237 // Proposal by cxx-abi-dev, 2014-03-26
3238 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3239 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003240 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003241 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003242 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003243 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003244 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003245 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003246 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003247 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003248 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003249 case ETK_Typename:
3250 break;
3251 case ETK_Struct:
3252 case ETK_Class:
3253 case ETK_Interface:
3254 Out << "Ts";
3255 break;
3256 case ETK_Union:
3257 Out << "Tu";
3258 break;
3259 case ETK_Enum:
3260 Out << "Te";
3261 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003262 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003263 // Typename types are always nested
3264 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003266 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 Out << 'E';
3268}
3269
3270void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3271 // Dependently-scoped template types are nested if they have a prefix.
3272 Out << 'N';
3273
3274 // TODO: avoid making this TemplateName.
3275 TemplateName Prefix =
3276 getASTContext().getDependentTemplateName(T->getQualifier(),
3277 T->getIdentifier());
3278 mangleTemplatePrefix(Prefix);
3279
3280 // FIXME: GCC does not appear to mangle the template arguments when
3281 // the template in question is a dependent template name. Should we
3282 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003283 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 Out << 'E';
3285}
3286
3287void CXXNameMangler::mangleType(const TypeOfType *T) {
3288 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3289 // "extension with parameters" mangling.
3290 Out << "u6typeof";
3291}
3292
3293void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3294 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3295 // "extension with parameters" mangling.
3296 Out << "u6typeof";
3297}
3298
3299void CXXNameMangler::mangleType(const DecltypeType *T) {
3300 Expr *E = T->getUnderlyingExpr();
3301
3302 // type ::= Dt <expression> E # decltype of an id-expression
3303 // # or class member access
3304 // ::= DT <expression> E # decltype of an expression
3305
3306 // This purports to be an exhaustive list of id-expressions and
3307 // class member accesses. Note that we do not ignore parentheses;
3308 // parentheses change the semantics of decltype for these
3309 // expressions (and cause the mangler to use the other form).
3310 if (isa<DeclRefExpr>(E) ||
3311 isa<MemberExpr>(E) ||
3312 isa<UnresolvedLookupExpr>(E) ||
3313 isa<DependentScopeDeclRefExpr>(E) ||
3314 isa<CXXDependentScopeMemberExpr>(E) ||
3315 isa<UnresolvedMemberExpr>(E))
3316 Out << "Dt";
3317 else
3318 Out << "DT";
3319 mangleExpression(E);
3320 Out << 'E';
3321}
3322
3323void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3324 // If this is dependent, we need to record that. If not, we simply
3325 // mangle it as the underlying type since they are equivalent.
3326 if (T->isDependentType()) {
3327 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003328
Guy Benyei11169dd2012-12-18 14:30:41 +00003329 switch (T->getUTTKind()) {
3330 case UnaryTransformType::EnumUnderlyingType:
3331 Out << "3eut";
3332 break;
3333 }
3334 }
3335
David Majnemer140065a2016-06-08 00:34:15 +00003336 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003337}
3338
3339void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003340 assert(T->getDeducedType().isNull() &&
3341 "Deduced AutoType shouldn't be handled here!");
3342 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3343 "shouldn't need to mangle __auto_type!");
3344 // <builtin-type> ::= Da # auto
3345 // ::= Dc # decltype(auto)
3346 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003347}
3348
Richard Smith600b5262017-01-26 20:40:47 +00003349void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3350 // FIXME: This is not the right mangling. We also need to include a scope
3351 // here in some cases.
3352 QualType D = T->getDeducedType();
3353 if (D.isNull())
3354 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3355 else
3356 mangleType(D);
3357}
3358
Guy Benyei11169dd2012-12-18 14:30:41 +00003359void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003360 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 // (Until there's a standardized mangling...)
3362 Out << "U7_Atomic";
3363 mangleType(T->getValueType());
3364}
3365
Xiuli Pan9c14e282016-01-09 12:53:17 +00003366void CXXNameMangler::mangleType(const PipeType *T) {
3367 // Pipe type mangling rules are described in SPIR 2.0 specification
3368 // A.1 Data types and A.3 Summary of changes
3369 // <type> ::= 8ocl_pipe
3370 Out << "8ocl_pipe";
3371}
3372
Guy Benyei11169dd2012-12-18 14:30:41 +00003373void CXXNameMangler::mangleIntegerLiteral(QualType T,
3374 const llvm::APSInt &Value) {
3375 // <expr-primary> ::= L <type> <value number> E # integer literal
3376 Out << 'L';
3377
3378 mangleType(T);
3379 if (T->isBooleanType()) {
3380 // Boolean values are encoded as 0/1.
3381 Out << (Value.getBoolValue() ? '1' : '0');
3382 } else {
3383 mangleNumber(Value);
3384 }
3385 Out << 'E';
3386
3387}
3388
David Majnemer1dabfdc2015-02-14 13:23:54 +00003389void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3390 // Ignore member expressions involving anonymous unions.
3391 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3392 if (!RT->getDecl()->isAnonymousStructOrUnion())
3393 break;
3394 const auto *ME = dyn_cast<MemberExpr>(Base);
3395 if (!ME)
3396 break;
3397 Base = ME->getBase();
3398 IsArrow = ME->isArrow();
3399 }
3400
3401 if (Base->isImplicitCXXThis()) {
3402 // Note: GCC mangles member expressions to the implicit 'this' as
3403 // *this., whereas we represent them as this->. The Itanium C++ ABI
3404 // does not specify anything here, so we follow GCC.
3405 Out << "dtdefpT";
3406 } else {
3407 Out << (IsArrow ? "pt" : "dt");
3408 mangleExpression(Base);
3409 }
3410}
3411
Guy Benyei11169dd2012-12-18 14:30:41 +00003412/// Mangles a member expression.
3413void CXXNameMangler::mangleMemberExpr(const Expr *base,
3414 bool isArrow,
3415 NestedNameSpecifier *qualifier,
3416 NamedDecl *firstQualifierLookup,
3417 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003418 const TemplateArgumentLoc *TemplateArgs,
3419 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003420 unsigned arity) {
3421 // <expression> ::= dt <expression> <unresolved-name>
3422 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003423 if (base)
3424 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003425 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003426}
3427
3428/// Look at the callee of the given call expression and determine if
3429/// it's a parenthesized id-expression which would have triggered ADL
3430/// otherwise.
3431static bool isParenthesizedADLCallee(const CallExpr *call) {
3432 const Expr *callee = call->getCallee();
3433 const Expr *fn = callee->IgnoreParens();
3434
3435 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3436 // too, but for those to appear in the callee, it would have to be
3437 // parenthesized.
3438 if (callee == fn) return false;
3439
3440 // Must be an unresolved lookup.
3441 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3442 if (!lookup) return false;
3443
3444 assert(!lookup->requiresADL());
3445
3446 // Must be an unqualified lookup.
3447 if (lookup->getQualifier()) return false;
3448
3449 // Must not have found a class member. Note that if one is a class
3450 // member, they're all class members.
3451 if (lookup->getNumDecls() > 0 &&
3452 (*lookup->decls_begin())->isCXXClassMember())
3453 return false;
3454
3455 // Otherwise, ADL would have been triggered.
3456 return true;
3457}
3458
David Majnemer9c775c72014-09-23 04:27:55 +00003459void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3460 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3461 Out << CastEncoding;
3462 mangleType(ECE->getType());
3463 mangleExpression(ECE->getSubExpr());
3464}
3465
Richard Smith520449d2015-02-05 06:15:50 +00003466void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3467 if (auto *Syntactic = InitList->getSyntacticForm())
3468 InitList = Syntactic;
3469 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3470 mangleExpression(InitList->getInit(i));
3471}
3472
Guy Benyei11169dd2012-12-18 14:30:41 +00003473void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3474 // <expression> ::= <unary operator-name> <expression>
3475 // ::= <binary operator-name> <expression> <expression>
3476 // ::= <trinary operator-name> <expression> <expression> <expression>
3477 // ::= cv <type> expression # conversion with one argument
3478 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003479 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3480 // ::= sc <type> <expression> # static_cast<type> (expression)
3481 // ::= cc <type> <expression> # const_cast<type> (expression)
3482 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 // ::= st <type> # sizeof (a type)
3484 // ::= at <type> # alignof (a type)
3485 // ::= <template-param>
3486 // ::= <function-param>
3487 // ::= sr <type> <unqualified-name> # dependent name
3488 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3489 // ::= ds <expression> <expression> # expr.*expr
3490 // ::= sZ <template-param> # size of a parameter pack
3491 // ::= sZ <function-param> # size of a function parameter pack
3492 // ::= <expr-primary>
3493 // <expr-primary> ::= L <type> <value number> E # integer literal
3494 // ::= L <type <value float> E # floating literal
3495 // ::= L <mangled-name> E # external name
3496 // ::= fpT # 'this' expression
3497 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003498
Guy Benyei11169dd2012-12-18 14:30:41 +00003499recurse:
3500 switch (E->getStmtClass()) {
3501 case Expr::NoStmtClass:
3502#define ABSTRACT_STMT(Type)
3503#define EXPR(Type, Base)
3504#define STMT(Type, Base) \
3505 case Expr::Type##Class:
3506#include "clang/AST/StmtNodes.inc"
3507 // fallthrough
3508
3509 // These all can only appear in local or variable-initialization
3510 // contexts and so should never appear in a mangling.
3511 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003512 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003514 case Expr::ArrayInitLoopExprClass:
3515 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003516 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 case Expr::ParenListExprClass:
3518 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003519 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003520 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003521 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003522 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003523 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 llvm_unreachable("unexpected statement kind");
3525
Bill Wendling7c44da22018-10-31 03:48:47 +00003526 case Expr::ConstantExprClass:
3527 E = cast<ConstantExpr>(E)->getSubExpr();
3528 goto recurse;
3529
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 // FIXME: invent manglings for all these.
3531 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 case Expr::ChooseExprClass:
3533 case Expr::CompoundLiteralExprClass:
3534 case Expr::ExtVectorElementExprClass:
3535 case Expr::GenericSelectionExprClass:
3536 case Expr::ObjCEncodeExprClass:
3537 case Expr::ObjCIsaExprClass:
3538 case Expr::ObjCIvarRefExprClass:
3539 case Expr::ObjCMessageExprClass:
3540 case Expr::ObjCPropertyRefExprClass:
3541 case Expr::ObjCProtocolExprClass:
3542 case Expr::ObjCSelectorExprClass:
3543 case Expr::ObjCStringLiteralClass:
3544 case Expr::ObjCBoxedExprClass:
3545 case Expr::ObjCArrayLiteralClass:
3546 case Expr::ObjCDictionaryLiteralClass:
3547 case Expr::ObjCSubscriptRefExprClass:
3548 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003549 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 case Expr::OffsetOfExprClass:
3551 case Expr::PredefinedExprClass:
3552 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003553 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 case Expr::TypeTraitExprClass:
3556 case Expr::ArrayTypeTraitExprClass:
3557 case Expr::ExpressionTraitExprClass:
3558 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 case Expr::CUDAKernelCallExprClass:
3560 case Expr::AsTypeExprClass:
3561 case Expr::PseudoObjectExprClass:
3562 case Expr::AtomicExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003563 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003565 if (!NullOut) {
3566 // As bad as this diagnostic is, it's better than crashing.
3567 DiagnosticsEngine &Diags = Context.getDiags();
3568 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3569 "cannot yet mangle expression type %0");
3570 Diags.Report(E->getExprLoc(), DiagID)
3571 << E->getStmtClassName() << E->getSourceRange();
3572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003573 break;
3574 }
3575
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003576 case Expr::CXXUuidofExprClass: {
3577 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3578 if (UE->isTypeOperand()) {
3579 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3580 Out << "u8__uuidoft";
3581 mangleType(UuidT);
3582 } else {
3583 Expr *UuidExp = UE->getExprOperand();
3584 Out << "u8__uuidofz";
3585 mangleExpression(UuidExp, Arity);
3586 }
3587 break;
3588 }
3589
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 // Even gcc-4.5 doesn't mangle this.
3591 case Expr::BinaryConditionalOperatorClass: {
3592 DiagnosticsEngine &Diags = Context.getDiags();
3593 unsigned DiagID =
3594 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3595 "?: operator with omitted middle operand cannot be mangled");
3596 Diags.Report(E->getExprLoc(), DiagID)
3597 << E->getStmtClassName() << E->getSourceRange();
3598 break;
3599 }
3600
3601 // These are used for internal purposes and cannot be meaningfully mangled.
3602 case Expr::OpaqueValueExprClass:
3603 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3604
3605 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003607 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 Out << "E";
3609 break;
3610 }
3611
Richard Smith39eca9b2017-08-23 22:12:08 +00003612 case Expr::DesignatedInitExprClass: {
3613 auto *DIE = cast<DesignatedInitExpr>(E);
3614 for (const auto &Designator : DIE->designators()) {
3615 if (Designator.isFieldDesignator()) {
3616 Out << "di";
3617 mangleSourceName(Designator.getFieldName());
3618 } else if (Designator.isArrayDesignator()) {
3619 Out << "dx";
3620 mangleExpression(DIE->getArrayIndex(Designator));
3621 } else {
3622 assert(Designator.isArrayRangeDesignator() &&
3623 "unknown designator kind");
3624 Out << "dX";
3625 mangleExpression(DIE->getArrayRangeStart(Designator));
3626 mangleExpression(DIE->getArrayRangeEnd(Designator));
3627 }
3628 }
3629 mangleExpression(DIE->getInit());
3630 break;
3631 }
3632
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 case Expr::CXXDefaultArgExprClass:
3634 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3635 break;
3636
Richard Smith852c9db2013-04-20 22:23:05 +00003637 case Expr::CXXDefaultInitExprClass:
3638 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3639 break;
3640
Richard Smithcc1b96d2013-06-12 22:31:48 +00003641 case Expr::CXXStdInitializerListExprClass:
3642 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3643 break;
3644
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 case Expr::SubstNonTypeTemplateParmExprClass:
3646 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3647 Arity);
3648 break;
3649
3650 case Expr::UserDefinedLiteralClass:
3651 // We follow g++'s approach of mangling a UDL as a call to the literal
3652 // operator.
3653 case Expr::CXXMemberCallExprClass: // fallthrough
3654 case Expr::CallExprClass: {
3655 const CallExpr *CE = cast<CallExpr>(E);
3656
3657 // <expression> ::= cp <simple-id> <expression>* E
3658 // We use this mangling only when the call would use ADL except
3659 // for being parenthesized. Per discussion with David
3660 // Vandervoorde, 2011.04.25.
3661 if (isParenthesizedADLCallee(CE)) {
3662 Out << "cp";
3663 // The callee here is a parenthesized UnresolvedLookupExpr with
3664 // no qualifier and should always get mangled as a <simple-id>
3665 // anyway.
3666
3667 // <expression> ::= cl <expression>* E
3668 } else {
3669 Out << "cl";
3670 }
3671
David Majnemer67a8ec62015-02-19 21:41:48 +00003672 unsigned CallArity = CE->getNumArgs();
3673 for (const Expr *Arg : CE->arguments())
3674 if (isa<PackExpansionExpr>(Arg))
3675 CallArity = UnknownArity;
3676
3677 mangleExpression(CE->getCallee(), CallArity);
3678 for (const Expr *Arg : CE->arguments())
3679 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 Out << 'E';
3681 break;
3682 }
3683
3684 case Expr::CXXNewExprClass: {
3685 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3686 if (New->isGlobalNew()) Out << "gs";
3687 Out << (New->isArray() ? "na" : "nw");
3688 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3689 E = New->placement_arg_end(); I != E; ++I)
3690 mangleExpression(*I);
3691 Out << '_';
3692 mangleType(New->getAllocatedType());
3693 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3695 Out << "il";
3696 else
3697 Out << "pi";
3698 const Expr *Init = New->getInitializer();
3699 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3700 // Directly inline the initializers.
3701 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3702 E = CCE->arg_end();
3703 I != E; ++I)
3704 mangleExpression(*I);
3705 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3706 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3707 mangleExpression(PLE->getExpr(i));
3708 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3709 isa<InitListExpr>(Init)) {
3710 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003711 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 } else
3713 mangleExpression(Init);
3714 }
3715 Out << 'E';
3716 break;
3717 }
3718
David Majnemer1dabfdc2015-02-14 13:23:54 +00003719 case Expr::CXXPseudoDestructorExprClass: {
3720 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3721 if (const Expr *Base = PDE->getBase())
3722 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003723 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003724 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3725 if (Qualifier) {
3726 mangleUnresolvedPrefix(Qualifier,
3727 /*Recursive=*/true);
3728 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3729 Out << 'E';
3730 } else {
3731 Out << "sr";
3732 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3733 Out << 'E';
3734 }
3735 } else if (Qualifier) {
3736 mangleUnresolvedPrefix(Qualifier);
3737 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003738 // <base-unresolved-name> ::= dn <destructor-name>
3739 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003740 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003741 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003742 break;
3743 }
3744
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 case Expr::MemberExprClass: {
3746 const MemberExpr *ME = cast<MemberExpr>(E);
3747 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003748 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003749 ME->getMemberDecl()->getDeclName(),
3750 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3751 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 break;
3753 }
3754
3755 case Expr::UnresolvedMemberExprClass: {
3756 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003757 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3758 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003759 ME->getMemberName(),
3760 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3761 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003762 break;
3763 }
3764
3765 case Expr::CXXDependentScopeMemberExprClass: {
3766 const CXXDependentScopeMemberExpr *ME
3767 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003768 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3769 ME->isArrow(), ME->getQualifier(),
3770 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003771 ME->getMember(),
3772 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3773 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 break;
3775 }
3776
3777 case Expr::UnresolvedLookupExprClass: {
3778 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003779 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3780 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3781 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 break;
3783 }
3784
3785 case Expr::CXXUnresolvedConstructExprClass: {
3786 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3787 unsigned N = CE->arg_size();
3788
Richard Smith39eca9b2017-08-23 22:12:08 +00003789 if (CE->isListInitialization()) {
3790 assert(N == 1 && "unexpected form for list initialization");
3791 auto *IL = cast<InitListExpr>(CE->getArg(0));
3792 Out << "tl";
3793 mangleType(CE->getType());
3794 mangleInitListElements(IL);
3795 Out << "E";
3796 return;
3797 }
3798
Guy Benyei11169dd2012-12-18 14:30:41 +00003799 Out << "cv";
3800 mangleType(CE->getType());
3801 if (N != 1) Out << '_';
3802 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3803 if (N != 1) Out << 'E';
3804 break;
3805 }
3806
Guy Benyei11169dd2012-12-18 14:30:41 +00003807 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003808 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003809 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003810 assert(
3811 CE->getNumArgs() >= 1 &&
3812 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3813 "implicit CXXConstructExpr must have one argument");
3814 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3815 }
3816 Out << "il";
3817 for (auto *E : CE->arguments())
3818 mangleExpression(E);
3819 Out << "E";
3820 break;
3821 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003822
Richard Smith520449d2015-02-05 06:15:50 +00003823 case Expr::CXXTemporaryObjectExprClass: {
3824 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3825 unsigned N = CE->getNumArgs();
3826 bool List = CE->isListInitialization();
3827
3828 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 Out << "tl";
3830 else
3831 Out << "cv";
3832 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003833 if (!List && N != 1)
3834 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003835 if (CE->isStdInitListInitialization()) {
3836 // We implicitly created a std::initializer_list<T> for the first argument
3837 // of a constructor of type U in an expression of the form U{a, b, c}.
3838 // Strip all the semantic gunk off the initializer list.
3839 auto *SILE =
3840 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3841 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3842 mangleInitListElements(ILE);
3843 } else {
3844 for (auto *E : CE->arguments())
3845 mangleExpression(E);
3846 }
Richard Smith520449d2015-02-05 06:15:50 +00003847 if (List || N != 1)
3848 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003849 break;
3850 }
3851
3852 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003853 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003855 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 break;
3857
3858 case Expr::CXXNoexceptExprClass:
3859 Out << "nx";
3860 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3861 break;
3862
3863 case Expr::UnaryExprOrTypeTraitExprClass: {
3864 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003865
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 if (!SAE->isInstantiationDependent()) {
3867 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003868 // If the operand of a sizeof or alignof operator is not
3869 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003870 // reflecting the result of the operator.
3871 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003872 // If the result of the operator is implicitly converted to a known
3873 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003875 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3877 : ImplicitlyConvertedToType;
3878 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3879 mangleIntegerLiteral(T, V);
3880 break;
3881 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003882
Guy Benyei11169dd2012-12-18 14:30:41 +00003883 switch(SAE->getKind()) {
3884 case UETT_SizeOf:
3885 Out << 's';
3886 break;
Richard Smith6822bd72018-10-26 19:26:45 +00003887 case UETT_PreferredAlignOf:
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 case UETT_AlignOf:
3889 Out << 'a';
3890 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003891 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 DiagnosticsEngine &Diags = Context.getDiags();
3893 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3894 "cannot yet mangle vec_step expression");
3895 Diags.Report(DiagID);
3896 return;
3897 }
Alexey Bataev00396512015-07-02 03:40:19 +00003898 case UETT_OpenMPRequiredSimdAlign:
3899 DiagnosticsEngine &Diags = Context.getDiags();
3900 unsigned DiagID = Diags.getCustomDiagID(
3901 DiagnosticsEngine::Error,
3902 "cannot yet mangle __builtin_omp_required_simd_align expression");
3903 Diags.Report(DiagID);
3904 return;
3905 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 if (SAE->isArgumentType()) {
3907 Out << 't';
3908 mangleType(SAE->getArgumentType());
3909 } else {
3910 Out << 'z';
3911 mangleExpression(SAE->getArgumentExpr());
3912 }
3913 break;
3914 }
3915
3916 case Expr::CXXThrowExprClass: {
3917 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003918 // <expression> ::= tw <expression> # throw expression
3919 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 if (TE->getSubExpr()) {
3921 Out << "tw";
3922 mangleExpression(TE->getSubExpr());
3923 } else {
3924 Out << "tr";
3925 }
3926 break;
3927 }
3928
3929 case Expr::CXXTypeidExprClass: {
3930 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003931 // <expression> ::= ti <type> # typeid (type)
3932 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 if (TIE->isTypeOperand()) {
3934 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003935 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 } else {
3937 Out << "te";
3938 mangleExpression(TIE->getExprOperand());
3939 }
3940 break;
3941 }
3942
3943 case Expr::CXXDeleteExprClass: {
3944 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003945 // <expression> ::= [gs] dl <expression> # [::] delete expr
3946 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 if (DE->isGlobalDelete()) Out << "gs";
3948 Out << (DE->isArrayForm() ? "da" : "dl");
3949 mangleExpression(DE->getArgument());
3950 break;
3951 }
3952
3953 case Expr::UnaryOperatorClass: {
3954 const UnaryOperator *UO = cast<UnaryOperator>(E);
3955 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3956 /*Arity=*/1);
3957 mangleExpression(UO->getSubExpr());
3958 break;
3959 }
3960
3961 case Expr::ArraySubscriptExprClass: {
3962 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3963
3964 // Array subscript is treated as a syntactically weird form of
3965 // binary operator.
3966 Out << "ix";
3967 mangleExpression(AE->getLHS());
3968 mangleExpression(AE->getRHS());
3969 break;
3970 }
3971
3972 case Expr::CompoundAssignOperatorClass: // fallthrough
3973 case Expr::BinaryOperatorClass: {
3974 const BinaryOperator *BO = cast<BinaryOperator>(E);
3975 if (BO->getOpcode() == BO_PtrMemD)
3976 Out << "ds";
3977 else
3978 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3979 /*Arity=*/2);
3980 mangleExpression(BO->getLHS());
3981 mangleExpression(BO->getRHS());
3982 break;
3983 }
3984
3985 case Expr::ConditionalOperatorClass: {
3986 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3987 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3988 mangleExpression(CO->getCond());
3989 mangleExpression(CO->getLHS(), Arity);
3990 mangleExpression(CO->getRHS(), Arity);
3991 break;
3992 }
3993
3994 case Expr::ImplicitCastExprClass: {
3995 ImplicitlyConvertedToType = E->getType();
3996 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3997 goto recurse;
3998 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003999
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00004001 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 // __bridge_transfer, or __bridge_retain.
4003 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4004 Out << "v1U" << Kind.size() << Kind;
4005 }
4006 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00004007 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004008
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004010 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004012
Richard Smith520449d2015-02-05 06:15:50 +00004013 case Expr::CXXFunctionalCastExprClass: {
4014 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4015 // FIXME: Add isImplicit to CXXConstructExpr.
4016 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4017 if (CCE->getParenOrBraceRange().isInvalid())
4018 Sub = CCE->getArg(0)->IgnoreImplicit();
4019 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4020 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4021 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4022 Out << "tl";
4023 mangleType(E->getType());
4024 mangleInitListElements(IL);
4025 Out << "E";
4026 } else {
4027 mangleCastExpression(E, "cv");
4028 }
4029 break;
4030 }
4031
David Majnemer9c775c72014-09-23 04:27:55 +00004032 case Expr::CXXStaticCastExprClass:
4033 mangleCastExpression(E, "sc");
4034 break;
4035 case Expr::CXXDynamicCastExprClass:
4036 mangleCastExpression(E, "dc");
4037 break;
4038 case Expr::CXXReinterpretCastExprClass:
4039 mangleCastExpression(E, "rc");
4040 break;
4041 case Expr::CXXConstCastExprClass:
4042 mangleCastExpression(E, "cc");
4043 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004044
4045 case Expr::CXXOperatorCallExprClass: {
4046 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4047 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004048 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4049 // (the enclosing MemberExpr covers the syntactic portion).
4050 if (CE->getOperator() != OO_Arrow)
4051 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 // Mangle the arguments.
4053 for (unsigned i = 0; i != NumArgs; ++i)
4054 mangleExpression(CE->getArg(i));
4055 break;
4056 }
4057
4058 case Expr::ParenExprClass:
4059 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4060 break;
4061
4062 case Expr::DeclRefExprClass: {
4063 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4064
4065 switch (D->getKind()) {
4066 default:
4067 // <expr-primary> ::= L <mangled-name> E # external name
4068 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004069 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 Out << 'E';
4071 break;
4072
4073 case Decl::ParmVar:
4074 mangleFunctionParam(cast<ParmVarDecl>(D));
4075 break;
4076
4077 case Decl::EnumConstant: {
4078 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4079 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4080 break;
4081 }
4082
4083 case Decl::NonTypeTemplateParm: {
4084 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4085 mangleTemplateParameter(PD->getIndex());
4086 break;
4087 }
4088
4089 }
4090
4091 break;
4092 }
4093
4094 case Expr::SubstNonTypeTemplateParmPackExprClass:
4095 // FIXME: not clear how to mangle this!
4096 // template <unsigned N...> class A {
4097 // template <class U...> void foo(U (&x)[N]...);
4098 // };
4099 Out << "_SUBSTPACK_";
4100 break;
4101
4102 case Expr::FunctionParmPackExprClass: {
4103 // FIXME: not clear how to mangle this!
4104 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4105 Out << "v110_SUBSTPACK";
4106 mangleFunctionParam(FPPE->getParameterPack());
4107 break;
4108 }
4109
4110 case Expr::DependentScopeDeclRefExprClass: {
4111 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004112 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4113 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4114 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 break;
4116 }
4117
4118 case Expr::CXXBindTemporaryExprClass:
4119 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4120 break;
4121
4122 case Expr::ExprWithCleanupsClass:
4123 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4124 break;
4125
4126 case Expr::FloatingLiteralClass: {
4127 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4128 Out << 'L';
4129 mangleType(FL->getType());
4130 mangleFloat(FL->getValue());
4131 Out << 'E';
4132 break;
4133 }
4134
4135 case Expr::CharacterLiteralClass:
4136 Out << 'L';
4137 mangleType(E->getType());
4138 Out << cast<CharacterLiteral>(E)->getValue();
4139 Out << 'E';
4140 break;
4141
4142 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4143 case Expr::ObjCBoolLiteralExprClass:
4144 Out << "Lb";
4145 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4146 Out << 'E';
4147 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004148
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 case Expr::CXXBoolLiteralExprClass:
4150 Out << "Lb";
4151 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4152 Out << 'E';
4153 break;
4154
4155 case Expr::IntegerLiteralClass: {
4156 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4157 if (E->getType()->isSignedIntegerType())
4158 Value.setIsSigned(true);
4159 mangleIntegerLiteral(E->getType(), Value);
4160 break;
4161 }
4162
4163 case Expr::ImaginaryLiteralClass: {
4164 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4165 // Mangle as if a complex literal.
4166 // Proposal from David Vandevoorde, 2010.06.30.
4167 Out << 'L';
4168 mangleType(E->getType());
4169 if (const FloatingLiteral *Imag =
4170 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4171 // Mangle a floating-point zero of the appropriate type.
4172 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4173 Out << '_';
4174 mangleFloat(Imag->getValue());
4175 } else {
4176 Out << "0_";
4177 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4178 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4179 Value.setIsSigned(true);
4180 mangleNumber(Value);
4181 }
4182 Out << 'E';
4183 break;
4184 }
4185
4186 case Expr::StringLiteralClass: {
4187 // Revised proposal from David Vandervoorde, 2010.07.15.
4188 Out << 'L';
4189 assert(isa<ConstantArrayType>(E->getType()));
4190 mangleType(E->getType());
4191 Out << 'E';
4192 break;
4193 }
4194
4195 case Expr::GNUNullExprClass:
4196 // FIXME: should this really be mangled the same as nullptr?
4197 // fallthrough
4198
4199 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 Out << "LDnE";
4201 break;
4202 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004203
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 case Expr::PackExpansionExprClass:
4205 Out << "sp";
4206 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4207 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004208
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004210 auto *SPE = cast<SizeOfPackExpr>(E);
4211 if (SPE->isPartiallySubstituted()) {
4212 Out << "sP";
4213 for (const auto &A : SPE->getPartialArguments())
4214 mangleTemplateArg(A);
4215 Out << "E";
4216 break;
4217 }
4218
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004220 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4222 mangleTemplateParameter(TTP->getIndex());
4223 else if (const NonTypeTemplateParmDecl *NTTP
4224 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4225 mangleTemplateParameter(NTTP->getIndex());
4226 else if (const TemplateTemplateParmDecl *TempTP
4227 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4228 mangleTemplateParameter(TempTP->getIndex());
4229 else
4230 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4231 break;
4232 }
Richard Smith0f0af192014-11-08 05:07:16 +00004233
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 case Expr::MaterializeTemporaryExprClass: {
4235 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4236 break;
4237 }
Richard Smith0f0af192014-11-08 05:07:16 +00004238
4239 case Expr::CXXFoldExprClass: {
4240 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004241 if (FE->isLeftFold())
4242 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004243 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004244 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004245
4246 if (FE->getOperator() == BO_PtrMemD)
4247 Out << "ds";
4248 else
4249 mangleOperatorName(
4250 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4251 /*Arity=*/2);
4252
4253 if (FE->getLHS())
4254 mangleExpression(FE->getLHS());
4255 if (FE->getRHS())
4256 mangleExpression(FE->getRHS());
4257 break;
4258 }
4259
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 case Expr::CXXThisExprClass:
4261 Out << "fpT";
4262 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004263
4264 case Expr::CoawaitExprClass:
4265 // FIXME: Propose a non-vendor mangling.
4266 Out << "v18co_await";
4267 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4268 break;
4269
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004270 case Expr::DependentCoawaitExprClass:
4271 // FIXME: Propose a non-vendor mangling.
4272 Out << "v18co_await";
4273 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4274 break;
4275
Richard Smith9f690bd2015-10-27 06:02:45 +00004276 case Expr::CoyieldExprClass:
4277 // FIXME: Propose a non-vendor mangling.
4278 Out << "v18co_yield";
4279 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4280 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 }
4282}
4283
4284/// Mangle an expression which refers to a parameter variable.
4285///
4286/// <expression> ::= <function-param>
4287/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4288/// <function-param> ::= fp <top-level CV-qualifiers>
4289/// <parameter-2 non-negative number> _ # L == 0, I > 0
4290/// <function-param> ::= fL <L-1 non-negative number>
4291/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4292/// <function-param> ::= fL <L-1 non-negative number>
4293/// p <top-level CV-qualifiers>
4294/// <I-1 non-negative number> _ # L > 0, I > 0
4295///
4296/// L is the nesting depth of the parameter, defined as 1 if the
4297/// parameter comes from the innermost function prototype scope
4298/// enclosing the current context, 2 if from the next enclosing
4299/// function prototype scope, and so on, with one special case: if
4300/// we've processed the full parameter clause for the innermost
4301/// function type, then L is one less. This definition conveniently
4302/// makes it irrelevant whether a function's result type was written
4303/// trailing or leading, but is otherwise overly complicated; the
4304/// numbering was first designed without considering references to
4305/// parameter in locations other than return types, and then the
4306/// mangling had to be generalized without changing the existing
4307/// manglings.
4308///
4309/// I is the zero-based index of the parameter within its parameter
4310/// declaration clause. Note that the original ABI document describes
4311/// this using 1-based ordinals.
4312void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4313 unsigned parmDepth = parm->getFunctionScopeDepth();
4314 unsigned parmIndex = parm->getFunctionScopeIndex();
4315
4316 // Compute 'L'.
4317 // parmDepth does not include the declaring function prototype.
4318 // FunctionTypeDepth does account for that.
4319 assert(parmDepth < FunctionTypeDepth.getDepth());
4320 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4321 if (FunctionTypeDepth.isInResultType())
4322 nestingDepth--;
4323
4324 if (nestingDepth == 0) {
4325 Out << "fp";
4326 } else {
4327 Out << "fL" << (nestingDepth - 1) << 'p';
4328 }
4329
4330 // Top-level qualifiers. We don't have to worry about arrays here,
4331 // because parameters declared as arrays should already have been
4332 // transformed to have pointer type. FIXME: apparently these don't
4333 // get mangled if used as an rvalue of a known non-class type?
4334 assert(!parm->getType()->isArrayType()
4335 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004336
4337 if (const DependentAddressSpaceType *DAST =
4338 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4339 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4340 } else {
4341 mangleQualifiers(parm->getType().getQualifiers());
4342 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004343
4344 // Parameter index.
4345 if (parmIndex != 0) {
4346 Out << (parmIndex - 1);
4347 }
4348 Out << '_';
4349}
4350
Richard Smith5179eb72016-06-28 19:03:57 +00004351void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4352 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 // <ctor-dtor-name> ::= C1 # complete object constructor
4354 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004355 // ::= CI1 <type> # complete inheriting constructor
4356 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004358 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004359 Out << 'C';
4360 if (InheritedFrom)
4361 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 switch (T) {
4363 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004364 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 break;
4366 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004367 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004369 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004370 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004372 case Ctor_DefaultClosure:
4373 case Ctor_CopyingClosure:
4374 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 }
Richard Smith5179eb72016-06-28 19:03:57 +00004376 if (InheritedFrom)
4377 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004378}
4379
4380void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4381 // <ctor-dtor-name> ::= D0 # deleting destructor
4382 // ::= D1 # complete object destructor
4383 // ::= D2 # base object destructor
4384 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004385 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 switch (T) {
4387 case Dtor_Deleting:
4388 Out << "D0";
4389 break;
4390 case Dtor_Complete:
4391 Out << "D1";
4392 break;
4393 case Dtor_Base:
4394 Out << "D2";
4395 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004396 case Dtor_Comdat:
4397 Out << "D5";
4398 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 }
4400}
4401
James Y Knight04ec5bf2015-12-24 02:59:37 +00004402void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4403 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 // <template-args> ::= I <template-arg>+ E
4405 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004406 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4407 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004408 Out << 'E';
4409}
4410
4411void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4412 // <template-args> ::= I <template-arg>+ E
4413 Out << 'I';
4414 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4415 mangleTemplateArg(AL[i]);
4416 Out << 'E';
4417}
4418
4419void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4420 unsigned NumTemplateArgs) {
4421 // <template-args> ::= I <template-arg>+ E
4422 Out << 'I';
4423 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4424 mangleTemplateArg(TemplateArgs[i]);
4425 Out << 'E';
4426}
4427
4428void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4429 // <template-arg> ::= <type> # type or template
4430 // ::= X <expression> E # expression
4431 // ::= <expr-primary> # simple expressions
4432 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 if (!A.isInstantiationDependent() || A.isDependent())
4434 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004435
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 switch (A.getKind()) {
4437 case TemplateArgument::Null:
4438 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004439
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 case TemplateArgument::Type:
4441 mangleType(A.getAsType());
4442 break;
4443 case TemplateArgument::Template:
4444 // This is mangled as <type>.
4445 mangleType(A.getAsTemplate());
4446 break;
4447 case TemplateArgument::TemplateExpansion:
4448 // <type> ::= Dp <type> # pack expansion (C++0x)
4449 Out << "Dp";
4450 mangleType(A.getAsTemplateOrTemplatePattern());
4451 break;
4452 case TemplateArgument::Expression: {
4453 // It's possible to end up with a DeclRefExpr here in certain
4454 // dependent cases, in which case we should mangle as a
4455 // declaration.
4456 const Expr *E = A.getAsExpr()->IgnoreParens();
4457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4458 const ValueDecl *D = DRE->getDecl();
4459 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004460 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004461 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 Out << 'E';
4463 break;
4464 }
4465 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004466
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 Out << 'X';
4468 mangleExpression(E);
4469 Out << 'E';
4470 break;
4471 }
4472 case TemplateArgument::Integral:
4473 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4474 break;
4475 case TemplateArgument::Declaration: {
4476 // <expr-primary> ::= L <mangled-name> E # external name
4477 // Clang produces AST's where pointer-to-member-function expressions
4478 // and pointer-to-function expressions are represented as a declaration not
4479 // an expression. We compensate for it here to produce the correct mangling.
4480 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004481 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 if (compensateMangling) {
4483 Out << 'X';
4484 mangleOperatorName(OO_Amp, 1);
4485 }
4486
4487 Out << 'L';
4488 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004489 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004490 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 Out << 'E';
4492
4493 if (compensateMangling)
4494 Out << 'E';
4495
4496 break;
4497 }
4498 case TemplateArgument::NullPtr: {
4499 // <expr-primary> ::= L <type> 0 E
4500 Out << 'L';
4501 mangleType(A.getNullPtrType());
4502 Out << "0E";
4503 break;
4504 }
4505 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004506 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004508 for (const auto &P : A.pack_elements())
4509 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 Out << 'E';
4511 }
4512 }
4513}
4514
4515void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4516 // <template-param> ::= T_ # first template parameter
4517 // ::= T <parameter-2 non-negative number> _
4518 if (Index == 0)
4519 Out << "T_";
4520 else
4521 Out << 'T' << (Index - 1) << '_';
4522}
4523
David Majnemer3b3bdb52014-05-06 22:49:16 +00004524void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4525 if (SeqID == 1)
4526 Out << '0';
4527 else if (SeqID > 1) {
4528 SeqID--;
4529
4530 // <seq-id> is encoded in base-36, using digits and upper case letters.
4531 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004532 MutableArrayRef<char> BufferRef(Buffer);
4533 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004534
4535 for (; SeqID != 0; SeqID /= 36) {
4536 unsigned C = SeqID % 36;
4537 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4538 }
4539
4540 Out.write(I.base(), I - BufferRef.rbegin());
4541 }
4542 Out << '_';
4543}
4544
Guy Benyei11169dd2012-12-18 14:30:41 +00004545void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4546 bool result = mangleSubstitution(tname);
4547 assert(result && "no existing substitution for template name");
4548 (void) result;
4549}
4550
4551// <substitution> ::= S <seq-id> _
4552// ::= S_
4553bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4554 // Try one of the standard substitutions first.
4555 if (mangleStandardSubstitution(ND))
4556 return true;
4557
4558 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4559 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4560}
4561
Justin Bognere8d762e2015-05-22 06:48:13 +00004562/// Determine whether the given type has any qualifiers that are relevant for
4563/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004564static bool hasMangledSubstitutionQualifiers(QualType T) {
4565 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004566 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004567}
4568
4569bool CXXNameMangler::mangleSubstitution(QualType T) {
4570 if (!hasMangledSubstitutionQualifiers(T)) {
4571 if (const RecordType *RT = T->getAs<RecordType>())
4572 return mangleSubstitution(RT->getDecl());
4573 }
4574
4575 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4576
4577 return mangleSubstitution(TypePtr);
4578}
4579
4580bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4581 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4582 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004583
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4585 return mangleSubstitution(
4586 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4587}
4588
4589bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4590 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4591 if (I == Substitutions.end())
4592 return false;
4593
4594 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004595 Out << 'S';
4596 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004597
4598 return true;
4599}
4600
4601static bool isCharType(QualType T) {
4602 if (T.isNull())
4603 return false;
4604
4605 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4606 T->isSpecificBuiltinType(BuiltinType::Char_U);
4607}
4608
Justin Bognere8d762e2015-05-22 06:48:13 +00004609/// Returns whether a given type is a template specialization of a given name
4610/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004611static bool isCharSpecialization(QualType T, const char *Name) {
4612 if (T.isNull())
4613 return false;
4614
4615 const RecordType *RT = T->getAs<RecordType>();
4616 if (!RT)
4617 return false;
4618
4619 const ClassTemplateSpecializationDecl *SD =
4620 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4621 if (!SD)
4622 return false;
4623
4624 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4625 return false;
4626
4627 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4628 if (TemplateArgs.size() != 1)
4629 return false;
4630
4631 if (!isCharType(TemplateArgs[0].getAsType()))
4632 return false;
4633
4634 return SD->getIdentifier()->getName() == Name;
4635}
4636
4637template <std::size_t StrLen>
4638static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4639 const char (&Str)[StrLen]) {
4640 if (!SD->getIdentifier()->isStr(Str))
4641 return false;
4642
4643 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4644 if (TemplateArgs.size() != 2)
4645 return false;
4646
4647 if (!isCharType(TemplateArgs[0].getAsType()))
4648 return false;
4649
4650 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4651 return false;
4652
4653 return true;
4654}
4655
4656bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4657 // <substitution> ::= St # ::std::
4658 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4659 if (isStd(NS)) {
4660 Out << "St";
4661 return true;
4662 }
4663 }
4664
4665 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4666 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4667 return false;
4668
4669 // <substitution> ::= Sa # ::std::allocator
4670 if (TD->getIdentifier()->isStr("allocator")) {
4671 Out << "Sa";
4672 return true;
4673 }
4674
4675 // <<substitution> ::= Sb # ::std::basic_string
4676 if (TD->getIdentifier()->isStr("basic_string")) {
4677 Out << "Sb";
4678 return true;
4679 }
4680 }
4681
4682 if (const ClassTemplateSpecializationDecl *SD =
4683 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4684 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4685 return false;
4686
4687 // <substitution> ::= Ss # ::std::basic_string<char,
4688 // ::std::char_traits<char>,
4689 // ::std::allocator<char> >
4690 if (SD->getIdentifier()->isStr("basic_string")) {
4691 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4692
4693 if (TemplateArgs.size() != 3)
4694 return false;
4695
4696 if (!isCharType(TemplateArgs[0].getAsType()))
4697 return false;
4698
4699 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4700 return false;
4701
4702 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4703 return false;
4704
4705 Out << "Ss";
4706 return true;
4707 }
4708
4709 // <substitution> ::= Si # ::std::basic_istream<char,
4710 // ::std::char_traits<char> >
4711 if (isStreamCharSpecialization(SD, "basic_istream")) {
4712 Out << "Si";
4713 return true;
4714 }
4715
4716 // <substitution> ::= So # ::std::basic_ostream<char,
4717 // ::std::char_traits<char> >
4718 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4719 Out << "So";
4720 return true;
4721 }
4722
4723 // <substitution> ::= Sd # ::std::basic_iostream<char,
4724 // ::std::char_traits<char> >
4725 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4726 Out << "Sd";
4727 return true;
4728 }
4729 }
4730 return false;
4731}
4732
4733void CXXNameMangler::addSubstitution(QualType T) {
4734 if (!hasMangledSubstitutionQualifiers(T)) {
4735 if (const RecordType *RT = T->getAs<RecordType>()) {
4736 addSubstitution(RT->getDecl());
4737 return;
4738 }
4739 }
4740
4741 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4742 addSubstitution(TypePtr);
4743}
4744
4745void CXXNameMangler::addSubstitution(TemplateName Template) {
4746 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4747 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004748
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4750 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4751}
4752
4753void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4754 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4755 Substitutions[Ptr] = SeqID++;
4756}
4757
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004758void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4759 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4760 if (Other->SeqID > SeqID) {
4761 Substitutions.swap(Other->Substitutions);
4762 SeqID = Other->SeqID;
4763 }
4764}
4765
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004766CXXNameMangler::AbiTagList
4767CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4768 // When derived abi tags are disabled there is no need to make any list.
4769 if (DisableDerivedAbiTags)
4770 return AbiTagList();
4771
4772 llvm::raw_null_ostream NullOutStream;
4773 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4774 TrackReturnTypeTags.disableDerivedAbiTags();
4775
4776 const FunctionProtoType *Proto =
4777 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004778 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004779 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4780 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4781 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004782 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004783
4784 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4785}
4786
4787CXXNameMangler::AbiTagList
4788CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4789 // When derived abi tags are disabled there is no need to make any list.
4790 if (DisableDerivedAbiTags)
4791 return AbiTagList();
4792
4793 llvm::raw_null_ostream NullOutStream;
4794 CXXNameMangler TrackVariableType(*this, NullOutStream);
4795 TrackVariableType.disableDerivedAbiTags();
4796
4797 TrackVariableType.mangleType(VD->getType());
4798
4799 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4800}
4801
4802bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4803 const VarDecl *VD) {
4804 llvm::raw_null_ostream NullOutStream;
4805 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4806 TrackAbiTags.mangle(VD);
4807 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4808}
4809
Guy Benyei11169dd2012-12-18 14:30:41 +00004810//
4811
Justin Bognere8d762e2015-05-22 06:48:13 +00004812/// Mangles the name of the declaration D and emits that name to the given
4813/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004814///
4815/// If the declaration D requires a mangled name, this routine will emit that
4816/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4817/// and this routine will return false. In this case, the caller should just
4818/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4819/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004820void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4821 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4823 "Invalid mangleName() call, argument is not a variable or function!");
4824 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4825 "Invalid mangleName() call on 'structor decl!");
4826
4827 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4828 getASTContext().getSourceManager(),
4829 "Mangling declaration");
4830
4831 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004832 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004833}
4834
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004835void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4836 CXXCtorType Type,
4837 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 CXXNameMangler Mangler(*this, Out, D, Type);
4839 Mangler.mangle(D);
4840}
4841
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004842void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4843 CXXDtorType Type,
4844 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 CXXNameMangler Mangler(*this, Out, D, Type);
4846 Mangler.mangle(D);
4847}
4848
Rafael Espindola1e4df922014-09-16 15:18:21 +00004849void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4850 raw_ostream &Out) {
4851 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4852 Mangler.mangle(D);
4853}
4854
4855void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4856 raw_ostream &Out) {
4857 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4858 Mangler.mangle(D);
4859}
4860
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004861void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4862 const ThunkInfo &Thunk,
4863 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 // <special-name> ::= T <call-offset> <base encoding>
4865 // # base is the nominal target function of thunk
4866 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4867 // # base is the nominal target function of thunk
4868 // # first call-offset is 'this' adjustment
4869 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004870
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 assert(!isa<CXXDestructorDecl>(MD) &&
4872 "Use mangleCXXDtor for destructor decls!");
4873 CXXNameMangler Mangler(*this, Out);
4874 Mangler.getStream() << "_ZT";
4875 if (!Thunk.Return.isEmpty())
4876 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004877
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004879 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4880 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4881
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 // Mangle the return pointer adjustment if there is one.
4883 if (!Thunk.Return.isEmpty())
4884 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004885 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4886
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 Mangler.mangleFunctionEncoding(MD);
4888}
4889
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004890void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4891 const CXXDestructorDecl *DD, CXXDtorType Type,
4892 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 // <special-name> ::= T <call-offset> <base encoding>
4894 // # base is the nominal target function of thunk
4895 CXXNameMangler Mangler(*this, Out, DD, Type);
4896 Mangler.getStream() << "_ZT";
4897
4898 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004899 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004900 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004901
4902 Mangler.mangleFunctionEncoding(DD);
4903}
4904
Justin Bognere8d762e2015-05-22 06:48:13 +00004905/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004906void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4907 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 // <special-name> ::= GV <object name> # Guard variable for one-time
4909 // # initialization
4910 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004911 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4912 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 Mangler.getStream() << "_ZGV";
4914 Mangler.mangleName(D);
4915}
4916
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004917void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4918 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004919 // These symbols are internal in the Itanium ABI, so the names don't matter.
4920 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4921 // avoid duplicate symbols.
4922 Out << "__cxx_global_var_init";
4923}
4924
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004925void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4926 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004927 // Prefix the mangling of D with __dtor_.
4928 CXXNameMangler Mangler(*this, Out);
4929 Mangler.getStream() << "__dtor_";
4930 if (shouldMangleDeclName(D))
4931 Mangler.mangle(D);
4932 else
4933 Mangler.getStream() << D->getName();
4934}
4935
Reid Kleckner1d59f992015-01-22 01:36:17 +00004936void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4937 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4938 CXXNameMangler Mangler(*this, Out);
4939 Mangler.getStream() << "__filt_";
4940 if (shouldMangleDeclName(EnclosingDecl))
4941 Mangler.mangle(EnclosingDecl);
4942 else
4943 Mangler.getStream() << EnclosingDecl->getName();
4944}
4945
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004946void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4947 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4948 CXXNameMangler Mangler(*this, Out);
4949 Mangler.getStream() << "__fin_";
4950 if (shouldMangleDeclName(EnclosingDecl))
4951 Mangler.mangle(EnclosingDecl);
4952 else
4953 Mangler.getStream() << EnclosingDecl->getName();
4954}
4955
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004956void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4957 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004958 // <special-name> ::= TH <object name>
4959 CXXNameMangler Mangler(*this, Out);
4960 Mangler.getStream() << "_ZTH";
4961 Mangler.mangleName(D);
4962}
4963
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004964void
4965ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4966 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004967 // <special-name> ::= TW <object name>
4968 CXXNameMangler Mangler(*this, Out);
4969 Mangler.getStream() << "_ZTW";
4970 Mangler.mangleName(D);
4971}
4972
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004973void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004974 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004975 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 // We match the GCC mangling here.
4977 // <special-name> ::= GR <object name>
4978 CXXNameMangler Mangler(*this, Out);
4979 Mangler.getStream() << "_ZGR";
4980 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004981 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004982 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004983}
4984
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004985void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4986 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004987 // <special-name> ::= TV <type> # virtual table
4988 CXXNameMangler Mangler(*this, Out);
4989 Mangler.getStream() << "_ZTV";
4990 Mangler.mangleNameOrStandardSubstitution(RD);
4991}
4992
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004993void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4994 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 // <special-name> ::= TT <type> # VTT structure
4996 CXXNameMangler Mangler(*this, Out);
4997 Mangler.getStream() << "_ZTT";
4998 Mangler.mangleNameOrStandardSubstitution(RD);
4999}
5000
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005001void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5002 int64_t Offset,
5003 const CXXRecordDecl *Type,
5004 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 // <special-name> ::= TC <type> <offset number> _ <base type>
5006 CXXNameMangler Mangler(*this, Out);
5007 Mangler.getStream() << "_ZTC";
5008 Mangler.mangleNameOrStandardSubstitution(RD);
5009 Mangler.getStream() << Offset;
5010 Mangler.getStream() << '_';
5011 Mangler.mangleNameOrStandardSubstitution(Type);
5012}
5013
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005014void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 // <special-name> ::= TI <type> # typeinfo structure
5016 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5017 CXXNameMangler Mangler(*this, Out);
5018 Mangler.getStream() << "_ZTI";
5019 Mangler.mangleType(Ty);
5020}
5021
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005022void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5023 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5025 CXXNameMangler Mangler(*this, Out);
5026 Mangler.getStream() << "_ZTS";
5027 Mangler.mangleType(Ty);
5028}
5029
Reid Klecknercc99e262013-11-19 23:23:00 +00005030void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5031 mangleCXXRTTIName(Ty, Out);
5032}
5033
David Majnemer58e5bee2014-03-24 21:43:36 +00005034void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5035 llvm_unreachable("Can't mangle string literals");
5036}
5037
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005038ItaniumMangleContext *
5039ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5040 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005041}