clang  12.0.0git
ItaniumMangle.cpp
Go to the documentation of this file.
1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2 //
3 // 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
6 //
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 //
13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/Module.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 
38 using namespace clang;
39 
40 namespace {
41 
42 /// Retrieve the declaration context that should be used when mangling the given
43 /// declaration.
44 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
45  // The ABI assumes that lambda closure types that occur within
46  // default arguments live in the context of the function. However, due to
47  // the way in which Clang parses and creates function declarations, this is
48  // not the case: the lambda closure type ends up living in the context
49  // where the function itself resides, because the function declaration itself
50  // had not yet been created. Fix the context here.
51  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
52  if (RD->isLambda())
53  if (ParmVarDecl *ContextParam
54  = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
55  return ContextParam->getDeclContext();
56  }
57 
58  // Perform the same check for block literals.
59  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
60  if (ParmVarDecl *ContextParam
61  = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
62  return ContextParam->getDeclContext();
63  }
64 
65  const DeclContext *DC = D->getDeclContext();
66  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
67  isa<OMPDeclareMapperDecl>(DC)) {
68  return getEffectiveDeclContext(cast<Decl>(DC));
69  }
70 
71  if (const auto *VD = dyn_cast<VarDecl>(D))
72  if (VD->isExternC())
73  return VD->getASTContext().getTranslationUnitDecl();
74 
75  if (const auto *FD = dyn_cast<FunctionDecl>(D))
76  if (FD->isExternC())
77  return FD->getASTContext().getTranslationUnitDecl();
78 
79  return DC->getRedeclContext();
80 }
81 
82 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
83  return getEffectiveDeclContext(cast<Decl>(DC));
84 }
85 
86 static bool isLocalContainerContext(const DeclContext *DC) {
87  return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
88 }
89 
90 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
91  const DeclContext *DC = getEffectiveDeclContext(D);
92  while (!DC->isNamespace() && !DC->isTranslationUnit()) {
93  if (isLocalContainerContext(DC))
94  return dyn_cast<RecordDecl>(D);
95  D = cast<Decl>(DC);
96  DC = getEffectiveDeclContext(D);
97  }
98  return nullptr;
99 }
100 
101 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
102  if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
103  return ftd->getTemplatedDecl();
104 
105  return fn;
106 }
107 
108 static const NamedDecl *getStructor(const NamedDecl *decl) {
109  const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
110  return (fn ? getStructor(fn) : decl);
111 }
112 
113 static bool isLambda(const NamedDecl *ND) {
114  const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
115  if (!Record)
116  return false;
117 
118  return Record->isLambda();
119 }
120 
121 static const unsigned UnknownArity = ~0U;
122 
123 class ItaniumMangleContextImpl : public ItaniumMangleContext {
124  typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
125  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
126  llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
127 
128 public:
129  explicit ItaniumMangleContextImpl(ASTContext &Context,
130  DiagnosticsEngine &Diags)
131  : ItaniumMangleContext(Context, Diags) {}
132 
133  /// @name Mangler Entry Points
134  /// @{
135 
136  bool shouldMangleCXXName(const NamedDecl *D) override;
137  bool shouldMangleStringLiteral(const StringLiteral *) override {
138  return false;
139  }
140  void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
141  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
142  raw_ostream &) override;
143  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145  raw_ostream &) override;
146  void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
147  raw_ostream &) override;
148  void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
149  void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
150  void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
151  const CXXRecordDecl *Type, raw_ostream &) override;
152  void mangleCXXRTTI(QualType T, raw_ostream &) override;
153  void mangleCXXRTTIName(QualType T, raw_ostream &) override;
154  void mangleTypeName(QualType T, raw_ostream &) override;
155 
156  void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
157  void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
158  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;
162  void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
163  void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
164  raw_ostream &Out) override;
165  void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
166  raw_ostream &Out) override;
167  void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
168  void mangleItaniumThreadLocalWrapper(const VarDecl *D,
169  raw_ostream &) override;
170 
171  void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
172 
173  void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
174 
175  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
176  // Lambda closure types are already numbered.
177  if (isLambda(ND))
178  return false;
179 
180  // Anonymous tags are already numbered.
181  if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
182  if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
183  return false;
184  }
185 
186  // Use the canonical number for externally visible decls.
187  if (ND->isExternallyVisible()) {
188  unsigned discriminator = getASTContext().getManglingNumber(ND);
189  if (discriminator == 1)
190  return false;
191  disc = discriminator - 2;
192  return true;
193  }
194 
195  // Make up a reasonable number for internal decls.
196  unsigned &discriminator = Uniquifier[ND];
197  if (!discriminator) {
198  const DeclContext *DC = getEffectiveDeclContext(ND);
199  discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
200  }
201  if (discriminator == 1)
202  return false;
203  disc = discriminator-2;
204  return true;
205  }
206  /// @}
207 };
208 
209 /// Manage the mangling of a single name.
210 class CXXNameMangler {
211  ItaniumMangleContextImpl &Context;
212  raw_ostream &Out;
213  bool NullOut = false;
214  /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
215  /// This mode is used when mangler creates another mangler recursively to
216  /// calculate ABI tags for the function return value or the variable type.
217  /// Also it is required to avoid infinite recursion in some cases.
218  bool DisableDerivedAbiTags = false;
219 
220  /// The "structor" is the top-level declaration being mangled, if
221  /// that's not a template specialization; otherwise it's the pattern
222  /// for that specialization.
223  const NamedDecl *Structor;
224  unsigned StructorType;
225 
226  /// The next substitution sequence number.
227  unsigned SeqID;
228 
229  class FunctionTypeDepthState {
230  unsigned Bits;
231 
232  enum { InResultTypeMask = 1 };
233 
234  public:
235  FunctionTypeDepthState() : Bits(0) {}
236 
237  /// The number of function types we're inside.
238  unsigned getDepth() const {
239  return Bits >> 1;
240  }
241 
242  /// True if we're in the return type of the innermost function type.
243  bool isInResultType() const {
244  return Bits & InResultTypeMask;
245  }
246 
247  FunctionTypeDepthState push() {
248  FunctionTypeDepthState tmp = *this;
249  Bits = (Bits & ~InResultTypeMask) + 2;
250  return tmp;
251  }
252 
253  void enterResultType() {
254  Bits |= InResultTypeMask;
255  }
256 
257  void leaveResultType() {
258  Bits &= ~InResultTypeMask;
259  }
260 
261  void pop(FunctionTypeDepthState saved) {
262  assert(getDepth() == saved.getDepth() + 1);
263  Bits = saved.Bits;
264  }
265 
266  } FunctionTypeDepth;
267 
268  // abi_tag is a gcc attribute, taking one or more strings called "tags".
269  // The goal is to annotate against which version of a library an object was
270  // built and to be able to provide backwards compatibility ("dual abi").
271  // For more information see docs/ItaniumMangleAbiTags.rst.
272  typedef SmallVector<StringRef, 4> AbiTagList;
273 
274  // State to gather all implicit and explicit tags used in a mangled name.
275  // Must always have an instance of this while emitting any name to keep
276  // track.
277  class AbiTagState final {
278  public:
279  explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
280  Parent = LinkHead;
281  LinkHead = this;
282  }
283 
284  // No copy, no move.
285  AbiTagState(const AbiTagState &) = delete;
286  AbiTagState &operator=(const AbiTagState &) = delete;
287 
288  ~AbiTagState() { pop(); }
289 
290  void write(raw_ostream &Out, const NamedDecl *ND,
291  const AbiTagList *AdditionalAbiTags) {
292  ND = cast<NamedDecl>(ND->getCanonicalDecl());
293  if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
294  assert(
295  !AdditionalAbiTags &&
296  "only function and variables need a list of additional abi tags");
297  if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
298  if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
299  UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
300  AbiTag->tags().end());
301  }
302  // Don't emit abi tags for namespaces.
303  return;
304  }
305  }
306 
307  AbiTagList TagList;
308  if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
309  UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
310  AbiTag->tags().end());
311  TagList.insert(TagList.end(), AbiTag->tags().begin(),
312  AbiTag->tags().end());
313  }
314 
315  if (AdditionalAbiTags) {
316  UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
317  AdditionalAbiTags->end());
318  TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
319  AdditionalAbiTags->end());
320  }
321 
322  llvm::sort(TagList);
323  TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
324 
325  writeSortedUniqueAbiTags(Out, TagList);
326  }
327 
328  const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
329  void setUsedAbiTags(const AbiTagList &AbiTags) {
330  UsedAbiTags = AbiTags;
331  }
332 
333  const AbiTagList &getEmittedAbiTags() const {
334  return EmittedAbiTags;
335  }
336 
337  const AbiTagList &getSortedUniqueUsedAbiTags() {
338  llvm::sort(UsedAbiTags);
339  UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
340  UsedAbiTags.end());
341  return UsedAbiTags;
342  }
343 
344  private:
345  //! All abi tags used implicitly or explicitly.
346  AbiTagList UsedAbiTags;
347  //! All explicit abi tags (i.e. not from namespace).
348  AbiTagList EmittedAbiTags;
349 
350  AbiTagState *&LinkHead;
351  AbiTagState *Parent = nullptr;
352 
353  void pop() {
354  assert(LinkHead == this &&
355  "abi tag link head must point to us on destruction");
356  if (Parent) {
357  Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
358  UsedAbiTags.begin(), UsedAbiTags.end());
359  Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
360  EmittedAbiTags.begin(),
361  EmittedAbiTags.end());
362  }
363  LinkHead = Parent;
364  }
365 
366  void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
367  for (const auto &Tag : AbiTags) {
368  EmittedAbiTags.push_back(Tag);
369  Out << "B";
370  Out << Tag.size();
371  Out << Tag;
372  }
373  }
374  };
375 
376  AbiTagState *AbiTags = nullptr;
377  AbiTagState AbiTagsRoot;
378 
379  llvm::DenseMap<uintptr_t, unsigned> Substitutions;
380  llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
381 
382  ASTContext &getASTContext() const { return Context.getASTContext(); }
383 
384 public:
385  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
386  const NamedDecl *D = nullptr, bool NullOut_ = false)
387  : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
388  StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
389  // These can't be mangled without a ctor type or dtor type.
390  assert(!D || (!isa<CXXDestructorDecl>(D) &&
391  !isa<CXXConstructorDecl>(D)));
392  }
393  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
395  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
396  SeqID(0), AbiTagsRoot(AbiTags) { }
397  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
399  : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
400  SeqID(0), AbiTagsRoot(AbiTags) { }
401 
402  CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
403  : Context(Outer.Context), Out(Out_), NullOut(false),
404  Structor(Outer.Structor), StructorType(Outer.StructorType),
405  SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
406  AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
407 
408  CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
409  : Context(Outer.Context), Out(Out_), NullOut(true),
410  Structor(Outer.Structor), StructorType(Outer.StructorType),
411  SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
412  AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
413 
414  raw_ostream &getStream() { return Out; }
415 
416  void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
417  static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
418 
419  void mangle(GlobalDecl GD);
420  void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
421  void mangleNumber(const llvm::APSInt &I);
422  void mangleNumber(int64_t Number);
423  void mangleFloat(const llvm::APFloat &F);
424  void mangleFunctionEncoding(GlobalDecl GD);
425  void mangleSeqID(unsigned SeqID);
426  void mangleName(GlobalDecl GD);
427  void mangleType(QualType T);
428  void mangleNameOrStandardSubstitution(const NamedDecl *ND);
429  void mangleLambdaSig(const CXXRecordDecl *Lambda);
430 
431 private:
432 
433  bool mangleSubstitution(const NamedDecl *ND);
434  bool mangleSubstitution(QualType T);
435  bool mangleSubstitution(TemplateName Template);
436  bool mangleSubstitution(uintptr_t Ptr);
437 
438  void mangleExistingSubstitution(TemplateName name);
439 
440  bool mangleStandardSubstitution(const NamedDecl *ND);
441 
442  void addSubstitution(const NamedDecl *ND) {
443  ND = cast<NamedDecl>(ND->getCanonicalDecl());
444 
445  addSubstitution(reinterpret_cast<uintptr_t>(ND));
446  }
447  void addSubstitution(QualType T);
448  void addSubstitution(TemplateName Template);
449  void addSubstitution(uintptr_t Ptr);
450  // Destructive copy substitutions from other mangler.
451  void extendSubstitutions(CXXNameMangler* Other);
452 
453  void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
454  bool recursive = false);
455  void mangleUnresolvedName(NestedNameSpecifier *qualifier,
457  const TemplateArgumentLoc *TemplateArgs,
458  unsigned NumTemplateArgs,
459  unsigned KnownArity = UnknownArity);
460 
461  void mangleFunctionEncodingBareType(const FunctionDecl *FD);
462 
463  void mangleNameWithAbiTags(GlobalDecl GD,
464  const AbiTagList *AdditionalAbiTags);
465  void mangleModuleName(const Module *M);
466  void mangleModuleNamePrefix(StringRef Name);
467  void mangleTemplateName(const TemplateDecl *TD,
468  const TemplateArgument *TemplateArgs,
469  unsigned NumTemplateArgs);
470  void mangleUnqualifiedName(GlobalDecl GD,
471  const AbiTagList *AdditionalAbiTags) {
472  mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), UnknownArity,
473  AdditionalAbiTags);
474  }
475  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
476  unsigned KnownArity,
477  const AbiTagList *AdditionalAbiTags);
478  void mangleUnscopedName(GlobalDecl GD,
479  const AbiTagList *AdditionalAbiTags);
480  void mangleUnscopedTemplateName(GlobalDecl GD,
481  const AbiTagList *AdditionalAbiTags);
482  void mangleSourceName(const IdentifierInfo *II);
483  void mangleRegCallName(const IdentifierInfo *II);
484  void mangleDeviceStubName(const IdentifierInfo *II);
485  void mangleSourceNameWithAbiTags(
486  const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
487  void mangleLocalName(GlobalDecl GD,
488  const AbiTagList *AdditionalAbiTags);
489  void mangleBlockForPrefix(const BlockDecl *Block);
490  void mangleUnqualifiedBlock(const BlockDecl *Block);
491  void mangleTemplateParamDecl(const NamedDecl *Decl);
492  void mangleLambda(const CXXRecordDecl *Lambda);
493  void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
494  const AbiTagList *AdditionalAbiTags,
495  bool NoFunction=false);
496  void mangleNestedName(const TemplateDecl *TD,
497  const TemplateArgument *TemplateArgs,
498  unsigned NumTemplateArgs);
499  void manglePrefix(NestedNameSpecifier *qualifier);
500  void manglePrefix(const DeclContext *DC, bool NoFunction=false);
501  void manglePrefix(QualType type);
502  void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
503  void mangleTemplatePrefix(TemplateName Template);
504  bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
505  StringRef Prefix = "");
506  void mangleOperatorName(DeclarationName Name, unsigned Arity);
507  void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
508  void mangleVendorQualifier(StringRef qualifier);
509  void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
510  void mangleRefQualifier(RefQualifierKind RefQualifier);
511 
512  void mangleObjCMethodName(const ObjCMethodDecl *MD);
513 
514  // Declare manglers for every type class.
515 #define ABSTRACT_TYPE(CLASS, PARENT)
516 #define NON_CANONICAL_TYPE(CLASS, PARENT)
517 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
518 #include "clang/AST/TypeNodes.inc"
519 
520  void mangleType(const TagType*);
521  void mangleType(TemplateName);
522  static StringRef getCallingConvQualifierName(CallingConv CC);
523  void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
524  void mangleExtFunctionInfo(const FunctionType *T);
525  void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
526  const FunctionDecl *FD = nullptr);
527  void mangleNeonVectorType(const VectorType *T);
528  void mangleNeonVectorType(const DependentVectorType *T);
529  void mangleAArch64NeonVectorType(const VectorType *T);
530  void mangleAArch64NeonVectorType(const DependentVectorType *T);
531  void mangleAArch64FixedSveVectorType(const VectorType *T);
532  void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
533 
534  void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
535  void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
536  void mangleFixedPointLiteral();
537  void mangleNullPointer(QualType T);
538 
539  void mangleMemberExprBase(const Expr *base, bool isArrow);
540  void mangleMemberExpr(const Expr *base, bool isArrow,
541  NestedNameSpecifier *qualifier,
542  NamedDecl *firstQualifierLookup,
544  const TemplateArgumentLoc *TemplateArgs,
545  unsigned NumTemplateArgs,
546  unsigned knownArity);
547  void mangleCastExpression(const Expr *E, StringRef CastEncoding);
548  void mangleInitListElements(const InitListExpr *InitList);
549  void mangleDeclRefExpr(const NamedDecl *D);
550  void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
551  void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
552  void mangleCXXDtorType(CXXDtorType T);
553 
554  void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
555  unsigned NumTemplateArgs);
556  void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
557  unsigned NumTemplateArgs);
558  void mangleTemplateArgs(const TemplateArgumentList &AL);
559  void mangleTemplateArg(TemplateArgument A);
560  void mangleValueInTemplateArg(QualType T, const APValue &V);
561 
562  void mangleTemplateParameter(unsigned Depth, unsigned Index);
563 
564  void mangleFunctionParam(const ParmVarDecl *parm);
565 
566  void writeAbiTags(const NamedDecl *ND,
567  const AbiTagList *AdditionalAbiTags);
568 
569  // Returns sorted unique list of ABI tags.
570  AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
571  // Returns sorted unique list of ABI tags.
572  AbiTagList makeVariableTypeTags(const VarDecl *VD);
573 };
574 
575 }
576 
577 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
578  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
579  if (FD) {
581  // Overloadable functions need mangling.
582  if (FD->hasAttr<OverloadableAttr>())
583  return true;
584 
585  // "main" is not mangled.
586  if (FD->isMain())
587  return false;
588 
589  // The Windows ABI expects that we would never mangle "typical"
590  // user-defined entry points regardless of visibility or freestanding-ness.
591  //
592  // N.B. This is distinct from asking about "main". "main" has a lot of
593  // special rules associated with it in the standard while these
594  // user-defined entry points are outside of the purview of the standard.
595  // For example, there can be only one definition for "main" in a standards
596  // compliant program; however nothing forbids the existence of wmain and
597  // WinMain in the same translation unit.
598  if (FD->isMSVCRTEntryPoint())
599  return false;
600 
601  // C++ functions and those whose names are not a simple identifier need
602  // mangling.
603  if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
604  return true;
605 
606  // C functions are not mangled.
607  if (L == CLanguageLinkage)
608  return false;
609  }
610 
611  // Otherwise, no mangling is done outside C++ mode.
612  if (!getASTContext().getLangOpts().CPlusPlus)
613  return false;
614 
615  const VarDecl *VD = dyn_cast<VarDecl>(D);
616  if (VD && !isa<DecompositionDecl>(D)) {
617  // C variables are not mangled.
618  if (VD->isExternC())
619  return false;
620 
621  // Variables at global scope with non-internal linkage are not mangled
622  const DeclContext *DC = getEffectiveDeclContext(D);
623  // Check for extern variable declared locally.
624  if (DC->isFunctionOrMethod() && D->hasLinkage())
625  while (!DC->isNamespace() && !DC->isTranslationUnit())
626  DC = getEffectiveParentContext(DC);
627  if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
628  !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
629  !isa<VarTemplateSpecializationDecl>(D))
630  return false;
631  }
632 
633  return true;
634 }
635 
636 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
637  const AbiTagList *AdditionalAbiTags) {
638  assert(AbiTags && "require AbiTagState");
639  AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
640 }
641 
642 void CXXNameMangler::mangleSourceNameWithAbiTags(
643  const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
644  mangleSourceName(ND->getIdentifier());
645  writeAbiTags(ND, AdditionalAbiTags);
646 }
647 
648 void CXXNameMangler::mangle(GlobalDecl GD) {
649  // <mangled-name> ::= _Z <encoding>
650  // ::= <data name>
651  // ::= <special-name>
652  Out << "_Z";
653  if (isa<FunctionDecl>(GD.getDecl()))
654  mangleFunctionEncoding(GD);
656  BindingDecl>(GD.getDecl()))
657  mangleName(GD);
658  else if (const IndirectFieldDecl *IFD =
659  dyn_cast<IndirectFieldDecl>(GD.getDecl()))
660  mangleName(IFD->getAnonField());
661  else
662  llvm_unreachable("unexpected kind of global decl");
663 }
664 
665 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
666  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
667  // <encoding> ::= <function name> <bare-function-type>
668 
669  // Don't mangle in the type if this isn't a decl we should typically mangle.
670  if (!Context.shouldMangleDeclName(FD)) {
671  mangleName(GD);
672  return;
673  }
674 
675  AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
676  if (ReturnTypeAbiTags.empty()) {
677  // There are no tags for return type, the simplest case.
678  mangleName(GD);
679  mangleFunctionEncodingBareType(FD);
680  return;
681  }
682 
683  // Mangle function name and encoding to temporary buffer.
684  // We have to output name and encoding to the same mangler to get the same
685  // substitution as it will be in final mangling.
686  SmallString<256> FunctionEncodingBuf;
687  llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
688  CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
689  // Output name of the function.
690  FunctionEncodingMangler.disableDerivedAbiTags();
691  FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
692 
693  // Remember length of the function name in the buffer.
694  size_t EncodingPositionStart = FunctionEncodingStream.str().size();
695  FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
696 
697  // Get tags from return type that are not present in function name or
698  // encoding.
699  const AbiTagList &UsedAbiTags =
700  FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
701  AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
702  AdditionalAbiTags.erase(
703  std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
704  UsedAbiTags.begin(), UsedAbiTags.end(),
705  AdditionalAbiTags.begin()),
706  AdditionalAbiTags.end());
707 
708  // Output name with implicit tags and function encoding from temporary buffer.
709  mangleNameWithAbiTags(FD, &AdditionalAbiTags);
710  Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
711 
712  // Function encoding could create new substitutions so we have to add
713  // temp mangled substitutions to main mangler.
714  extendSubstitutions(&FunctionEncodingMangler);
715 }
716 
717 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
718  if (FD->hasAttr<EnableIfAttr>()) {
719  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
720  Out << "Ua9enable_ifI";
721  for (AttrVec::const_iterator I = FD->getAttrs().begin(),
722  E = FD->getAttrs().end();
723  I != E; ++I) {
724  EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
725  if (!EIA)
726  continue;
727  Out << 'X';
728  mangleExpression(EIA->getCond());
729  Out << 'E';
730  }
731  Out << 'E';
732  FunctionTypeDepth.pop(Saved);
733  }
734 
735  // When mangling an inheriting constructor, the bare function type used is
736  // that of the inherited constructor.
737  if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
738  if (auto Inherited = CD->getInheritedConstructor())
739  FD = Inherited.getConstructor();
740 
741  // Whether the mangling of a function type includes the return type depends on
742  // the context and the nature of the function. The rules for deciding whether
743  // the return type is included are:
744  //
745  // 1. Template functions (names or types) have return types encoded, with
746  // the exceptions listed below.
747  // 2. Function types not appearing as part of a function name mangling,
748  // e.g. parameters, pointer types, etc., have return type encoded, with the
749  // exceptions listed below.
750  // 3. Non-template function names do not have return types encoded.
751  //
752  // The exceptions mentioned in (1) and (2) above, for which the return type is
753  // never included, are
754  // 1. Constructors.
755  // 2. Destructors.
756  // 3. Conversion operator functions, e.g. operator int.
757  bool MangleReturnType = false;
758  if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
759  if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
760  isa<CXXConversionDecl>(FD)))
761  MangleReturnType = true;
762 
763  // Mangle the type of the primary template.
764  FD = PrimaryTemplate->getTemplatedDecl();
765  }
766 
767  mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
768  MangleReturnType, FD);
769 }
770 
772  while (isa<LinkageSpecDecl>(DC)) {
773  DC = getEffectiveParentContext(DC);
774  }
775 
776  return DC;
777 }
778 
779 /// Return whether a given namespace is the 'std' namespace.
780 static bool isStd(const NamespaceDecl *NS) {
781  if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
782  ->isTranslationUnit())
783  return false;
784 
786  return II && II->isStr("std");
787 }
788 
789 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
790 // namespace.
791 static bool isStdNamespace(const DeclContext *DC) {
792  if (!DC->isNamespace())
793  return false;
794 
795  return isStd(cast<NamespaceDecl>(DC));
796 }
797 
798 static const GlobalDecl
799 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
800  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
801  // Check if we have a function template.
802  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
803  if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
804  TemplateArgs = FD->getTemplateSpecializationArgs();
805  return GD.getWithDecl(TD);
806  }
807  }
808 
809  // Check if we have a class template.
810  if (const ClassTemplateSpecializationDecl *Spec =
811  dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
812  TemplateArgs = &Spec->getTemplateArgs();
813  return GD.getWithDecl(Spec->getSpecializedTemplate());
814  }
815 
816  // Check if we have a variable template.
817  if (const VarTemplateSpecializationDecl *Spec =
818  dyn_cast<VarTemplateSpecializationDecl>(ND)) {
819  TemplateArgs = &Spec->getTemplateArgs();
820  return GD.getWithDecl(Spec->getSpecializedTemplate());
821  }
822 
823  return GlobalDecl();
824 }
825 
826 void CXXNameMangler::mangleName(GlobalDecl GD) {
827  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
828  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
829  // Variables should have implicit tags from its type.
830  AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
831  if (VariableTypeAbiTags.empty()) {
832  // Simple case no variable type tags.
833  mangleNameWithAbiTags(VD, nullptr);
834  return;
835  }
836 
837  // Mangle variable name to null stream to collect tags.
838  llvm::raw_null_ostream NullOutStream;
839  CXXNameMangler VariableNameMangler(*this, NullOutStream);
840  VariableNameMangler.disableDerivedAbiTags();
841  VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
842 
843  // Get tags from variable type that are not present in its name.
844  const AbiTagList &UsedAbiTags =
845  VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
846  AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
847  AdditionalAbiTags.erase(
848  std::set_difference(VariableTypeAbiTags.begin(),
849  VariableTypeAbiTags.end(), UsedAbiTags.begin(),
850  UsedAbiTags.end(), AdditionalAbiTags.begin()),
851  AdditionalAbiTags.end());
852 
853  // Output name with implicit tags.
854  mangleNameWithAbiTags(VD, &AdditionalAbiTags);
855  } else {
856  mangleNameWithAbiTags(GD, nullptr);
857  }
858 }
859 
860 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
861  const AbiTagList *AdditionalAbiTags) {
862  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
863  // <name> ::= [<module-name>] <nested-name>
864  // ::= [<module-name>] <unscoped-name>
865  // ::= [<module-name>] <unscoped-template-name> <template-args>
866  // ::= <local-name>
867  //
868  const DeclContext *DC = getEffectiveDeclContext(ND);
869 
870  // If this is an extern variable declared locally, the relevant DeclContext
871  // is that of the containing namespace, or the translation unit.
872  // FIXME: This is a hack; extern variables declared locally should have
873  // a proper semantic declaration context!
874  if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
875  while (!DC->isNamespace() && !DC->isTranslationUnit())
876  DC = getEffectiveParentContext(DC);
877  else if (GetLocalClassDecl(ND)) {
878  mangleLocalName(GD, AdditionalAbiTags);
879  return;
880  }
881 
882  DC = IgnoreLinkageSpecDecls(DC);
883 
884  if (isLocalContainerContext(DC)) {
885  mangleLocalName(GD, AdditionalAbiTags);
886  return;
887  }
888 
889  // Do not mangle the owning module for an external linkage declaration.
890  // This enables backwards-compatibility with non-modular code, and is
891  // a valid choice since conflicts are not permitted by C++ Modules TS
892  // [basic.def.odr]/6.2.
893  if (!ND->hasExternalFormalLinkage())
894  if (Module *M = ND->getOwningModuleForLinkage())
895  mangleModuleName(M);
896 
897  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
898  // Check if we have a template.
899  const TemplateArgumentList *TemplateArgs = nullptr;
900  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
901  mangleUnscopedTemplateName(TD, AdditionalAbiTags);
902  mangleTemplateArgs(*TemplateArgs);
903  return;
904  }
905 
906  mangleUnscopedName(GD, AdditionalAbiTags);
907  return;
908  }
909 
910  mangleNestedName(GD, DC, AdditionalAbiTags);
911 }
912 
913 void CXXNameMangler::mangleModuleName(const Module *M) {
914  // Implement the C++ Modules TS name mangling proposal; see
915  // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
916  //
917  // <module-name> ::= W <unscoped-name>+ E
918  // ::= W <module-subst> <unscoped-name>* E
919  Out << 'W';
920  mangleModuleNamePrefix(M->Name);
921  Out << 'E';
922 }
923 
924 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
925  // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
926  // ::= W <seq-id - 10> _ # otherwise
927  auto It = ModuleSubstitutions.find(Name);
928  if (It != ModuleSubstitutions.end()) {
929  if (It->second < 10)
930  Out << '_' << static_cast<char>('0' + It->second);
931  else
932  Out << 'W' << (It->second - 10) << '_';
933  return;
934  }
935 
936  // FIXME: Preserve hierarchy in module names rather than flattening
937  // them to strings; use Module*s as substitution keys.
938  auto Parts = Name.rsplit('.');
939  if (Parts.second.empty())
940  Parts.second = Parts.first;
941  else
942  mangleModuleNamePrefix(Parts.first);
943 
944  Out << Parts.second.size() << Parts.second;
945  ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
946 }
947 
948 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
949  const TemplateArgument *TemplateArgs,
950  unsigned NumTemplateArgs) {
951  const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
952 
953  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
954  mangleUnscopedTemplateName(TD, nullptr);
955  mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
956  } else {
957  mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
958  }
959 }
960 
961 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD,
962  const AbiTagList *AdditionalAbiTags) {
963  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
964  // <unscoped-name> ::= <unqualified-name>
965  // ::= St <unqualified-name> # ::std::
966 
967  if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
968  Out << "St";
969 
970  mangleUnqualifiedName(GD, AdditionalAbiTags);
971 }
972 
973 void CXXNameMangler::mangleUnscopedTemplateName(
974  GlobalDecl GD, const AbiTagList *AdditionalAbiTags) {
975  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
976  // <unscoped-template-name> ::= <unscoped-name>
977  // ::= <substitution>
978  if (mangleSubstitution(ND))
979  return;
980 
981  // <template-template-param> ::= <template-param>
982  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
983  assert(!AdditionalAbiTags &&
984  "template template param cannot have abi tags");
985  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
986  } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
987  mangleUnscopedName(GD, AdditionalAbiTags);
988  } else {
989  mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), AdditionalAbiTags);
990  }
991 
992  addSubstitution(ND);
993 }
994 
995 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
996  // ABI:
997  // Floating-point literals are encoded using a fixed-length
998  // lowercase hexadecimal string corresponding to the internal
999  // representation (IEEE on Itanium), high-order bytes first,
1000  // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1001  // on Itanium.
1002  // The 'without leading zeroes' thing seems to be an editorial
1003  // mistake; see the discussion on cxx-abi-dev beginning on
1004  // 2012-01-16.
1005 
1006  // Our requirements here are just barely weird enough to justify
1007  // using a custom algorithm instead of post-processing APInt::toString().
1008 
1009  llvm::APInt valueBits = f.bitcastToAPInt();
1010  unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1011  assert(numCharacters != 0);
1012 
1013  // Allocate a buffer of the right number of characters.
1014  SmallVector<char, 20> buffer(numCharacters);
1015 
1016  // Fill the buffer left-to-right.
1017  for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1018  // The bit-index of the next hex digit.
1019  unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1020 
1021  // Project out 4 bits starting at 'digitIndex'.
1022  uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1023  hexDigit >>= (digitBitIndex % 64);
1024  hexDigit &= 0xF;
1025 
1026  // Map that over to a lowercase hex digit.
1027  static const char charForHex[16] = {
1028  '0', '1', '2', '3', '4', '5', '6', '7',
1029  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1030  };
1031  buffer[stringIndex] = charForHex[hexDigit];
1032  }
1033 
1034  Out.write(buffer.data(), numCharacters);
1035 }
1036 
1037 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1038  Out << 'L';
1039  mangleType(T);
1040  mangleFloat(V);
1041  Out << 'E';
1042 }
1043 
1044 void CXXNameMangler::mangleFixedPointLiteral() {
1045  DiagnosticsEngine &Diags = Context.getDiags();
1046  unsigned DiagID = Diags.getCustomDiagID(
1047  DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1048  Diags.Report(DiagID);
1049 }
1050 
1051 void CXXNameMangler::mangleNullPointer(QualType T) {
1052  // <expr-primary> ::= L <type> 0 E
1053  Out << 'L';
1054  mangleType(T);
1055  Out << "0E";
1056 }
1057 
1058 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1059  if (Value.isSigned() && Value.isNegative()) {
1060  Out << 'n';
1061  Value.abs().print(Out, /*signed*/ false);
1062  } else {
1063  Value.print(Out, /*signed*/ false);
1064  }
1065 }
1066 
1067 void CXXNameMangler::mangleNumber(int64_t Number) {
1068  // <number> ::= [n] <non-negative decimal integer>
1069  if (Number < 0) {
1070  Out << 'n';
1071  Number = -Number;
1072  }
1073 
1074  Out << Number;
1075 }
1076 
1077 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1078  // <call-offset> ::= h <nv-offset> _
1079  // ::= v <v-offset> _
1080  // <nv-offset> ::= <offset number> # non-virtual base override
1081  // <v-offset> ::= <offset number> _ <virtual offset number>
1082  // # virtual base override, with vcall offset
1083  if (!Virtual) {
1084  Out << 'h';
1085  mangleNumber(NonVirtual);
1086  Out << '_';
1087  return;
1088  }
1089 
1090  Out << 'v';
1091  mangleNumber(NonVirtual);
1092  Out << '_';
1093  mangleNumber(Virtual);
1094  Out << '_';
1095 }
1096 
1097 void CXXNameMangler::manglePrefix(QualType type) {
1098  if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1099  if (!mangleSubstitution(QualType(TST, 0))) {
1100  mangleTemplatePrefix(TST->getTemplateName());
1101 
1102  // FIXME: GCC does not appear to mangle the template arguments when
1103  // the template in question is a dependent template name. Should we
1104  // emulate that badness?
1105  mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1106  addSubstitution(QualType(TST, 0));
1107  }
1108  } else if (const auto *DTST =
1110  if (!mangleSubstitution(QualType(DTST, 0))) {
1111  TemplateName Template = getASTContext().getDependentTemplateName(
1112  DTST->getQualifier(), DTST->getIdentifier());
1113  mangleTemplatePrefix(Template);
1114 
1115  // FIXME: GCC does not appear to mangle the template arguments when
1116  // the template in question is a dependent template name. Should we
1117  // emulate that badness?
1118  mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1119  addSubstitution(QualType(DTST, 0));
1120  }
1121  } else {
1122  // We use the QualType mangle type variant here because it handles
1123  // substitutions.
1124  mangleType(type);
1125  }
1126 }
1127 
1128 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1129 ///
1130 /// \param recursive - true if this is being called recursively,
1131 /// i.e. if there is more prefix "to the right".
1132 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1133  bool recursive) {
1134 
1135  // x, ::x
1136  // <unresolved-name> ::= [gs] <base-unresolved-name>
1137 
1138  // T::x / decltype(p)::x
1139  // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1140 
1141  // T::N::x /decltype(p)::N::x
1142  // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1143  // <base-unresolved-name>
1144 
1145  // A::x, N::y, A<T>::z; "gs" means leading "::"
1146  // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1147  // <base-unresolved-name>
1148 
1149  switch (qualifier->getKind()) {
1151  Out << "gs";
1152 
1153  // We want an 'sr' unless this is the entire NNS.
1154  if (recursive)
1155  Out << "sr";
1156 
1157  // We never want an 'E' here.
1158  return;
1159 
1161  llvm_unreachable("Can't mangle __super specifier");
1162 
1164  if (qualifier->getPrefix())
1165  mangleUnresolvedPrefix(qualifier->getPrefix(),
1166  /*recursive*/ true);
1167  else
1168  Out << "sr";
1169  mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1170  break;
1172  if (qualifier->getPrefix())
1173  mangleUnresolvedPrefix(qualifier->getPrefix(),
1174  /*recursive*/ true);
1175  else
1176  Out << "sr";
1177  mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1178  break;
1179 
1182  const Type *type = qualifier->getAsType();
1183 
1184  // We only want to use an unresolved-type encoding if this is one of:
1185  // - a decltype
1186  // - a template type parameter
1187  // - a template template parameter with arguments
1188  // In all of these cases, we should have no prefix.
1189  if (qualifier->getPrefix()) {
1190  mangleUnresolvedPrefix(qualifier->getPrefix(),
1191  /*recursive*/ true);
1192  } else {
1193  // Otherwise, all the cases want this.
1194  Out << "sr";
1195  }
1196 
1197  if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1198  return;
1199 
1200  break;
1201  }
1202 
1204  // Member expressions can have these without prefixes.
1205  if (qualifier->getPrefix())
1206  mangleUnresolvedPrefix(qualifier->getPrefix(),
1207  /*recursive*/ true);
1208  else
1209  Out << "sr";
1210 
1211  mangleSourceName(qualifier->getAsIdentifier());
1212  // An Identifier has no type information, so we can't emit abi tags for it.
1213  break;
1214  }
1215 
1216  // If this was the innermost part of the NNS, and we fell out to
1217  // here, append an 'E'.
1218  if (!recursive)
1219  Out << 'E';
1220 }
1221 
1222 /// Mangle an unresolved-name, which is generally used for names which
1223 /// weren't resolved to specific entities.
1224 void CXXNameMangler::mangleUnresolvedName(
1226  const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1227  unsigned knownArity) {
1228  if (qualifier) mangleUnresolvedPrefix(qualifier);
1229  switch (name.getNameKind()) {
1230  // <base-unresolved-name> ::= <simple-id>
1232  mangleSourceName(name.getAsIdentifierInfo());
1233  break;
1234  // <base-unresolved-name> ::= dn <destructor-name>
1236  Out << "dn";
1237  mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1238  break;
1239  // <base-unresolved-name> ::= on <operator-name>
1243  Out << "on";
1244  mangleOperatorName(name, knownArity);
1245  break;
1247  llvm_unreachable("Can't mangle a constructor name!");
1249  llvm_unreachable("Can't mangle a using directive name!");
1251  llvm_unreachable("Can't mangle a deduction guide name!");
1255  llvm_unreachable("Can't mangle Objective-C selector names here!");
1256  }
1257 
1258  // The <simple-id> and on <operator-name> productions end in an optional
1259  // <template-args>.
1260  if (TemplateArgs)
1261  mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1262 }
1263 
1264 void CXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
1265  DeclarationName Name,
1266  unsigned KnownArity,
1267  const AbiTagList *AdditionalAbiTags) {
1268  const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1269  unsigned Arity = KnownArity;
1270  // <unqualified-name> ::= <operator-name>
1271  // ::= <ctor-dtor-name>
1272  // ::= <source-name>
1273  switch (Name.getNameKind()) {
1275  const IdentifierInfo *II = Name.getAsIdentifierInfo();
1276 
1277  // We mangle decomposition declarations as the names of their bindings.
1278  if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1279  // FIXME: Non-standard mangling for decomposition declarations:
1280  //
1281  // <unqualified-name> ::= DC <source-name>* E
1282  //
1283  // These can never be referenced across translation units, so we do
1284  // not need a cross-vendor mangling for anything other than demanglers.
1285  // Proposed on cxx-abi-dev on 2016-08-12
1286  Out << "DC";
1287  for (auto *BD : DD->bindings())
1288  mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1289  Out << 'E';
1290  writeAbiTags(ND, AdditionalAbiTags);
1291  break;
1292  }
1293 
1294  if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1295  // We follow MSVC in mangling GUID declarations as if they were variables
1296  // with a particular reserved name. Continue the pretense here.
1297  SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1298  llvm::raw_svector_ostream GUIDOS(GUID);
1299  Context.mangleMSGuidDecl(GD, GUIDOS);
1300  Out << GUID.size() << GUID;
1301  break;
1302  }
1303 
1304  if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1305  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1306  Out << "TAX";
1307  mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1308  TPO->getValue());
1309  Out << "E";
1310  break;
1311  }
1312 
1313  if (II) {
1314  // Match GCC's naming convention for internal linkage symbols, for
1315  // symbols that are not actually visible outside of this TU. GCC
1316  // distinguishes between internal and external linkage symbols in
1317  // its mangling, to support cases like this that were valid C++ prior
1318  // to DR426:
1319  //
1320  // void test() { extern void foo(); }
1321  // static void foo();
1322  //
1323  // Don't bother with the L marker for names in anonymous namespaces; the
1324  // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1325  // matches GCC anyway, because GCC does not treat anonymous namespaces as
1326  // implying internal linkage.
1327  if (ND && ND->getFormalLinkage() == InternalLinkage &&
1328  !ND->isExternallyVisible() &&
1329  getEffectiveDeclContext(ND)->isFileContext() &&
1330  !ND->isInAnonymousNamespace())
1331  Out << 'L';
1332 
1333  auto *FD = dyn_cast<FunctionDecl>(ND);
1334  bool IsRegCall = FD &&
1335  FD->getType()->castAs<FunctionType>()->getCallConv() ==
1337  bool IsDeviceStub =
1338  FD && FD->hasAttr<CUDAGlobalAttr>() &&
1340  if (IsDeviceStub)
1341  mangleDeviceStubName(II);
1342  else if (IsRegCall)
1343  mangleRegCallName(II);
1344  else
1345  mangleSourceName(II);
1346 
1347  writeAbiTags(ND, AdditionalAbiTags);
1348  break;
1349  }
1350 
1351  // Otherwise, an anonymous entity. We must have a declaration.
1352  assert(ND && "mangling empty name without declaration");
1353 
1354  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1355  if (NS->isAnonymousNamespace()) {
1356  // This is how gcc mangles these names.
1357  Out << "12_GLOBAL__N_1";
1358  break;
1359  }
1360  }
1361 
1362  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1363  // We must have an anonymous union or struct declaration.
1364  const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1365 
1366  // Itanium C++ ABI 5.1.2:
1367  //
1368  // For the purposes of mangling, the name of an anonymous union is
1369  // considered to be the name of the first named data member found by a
1370  // pre-order, depth-first, declaration-order walk of the data members of
1371  // the anonymous union. If there is no such data member (i.e., if all of
1372  // the data members in the union are unnamed), then there is no way for
1373  // a program to refer to the anonymous union, and there is therefore no
1374  // need to mangle its name.
1375  assert(RD->isAnonymousStructOrUnion()
1376  && "Expected anonymous struct or union!");
1377  const FieldDecl *FD = RD->findFirstNamedDataMember();
1378 
1379  // It's actually possible for various reasons for us to get here
1380  // with an empty anonymous struct / union. Fortunately, it
1381  // doesn't really matter what name we generate.
1382  if (!FD) break;
1383  assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1384 
1385  mangleSourceName(FD->getIdentifier());
1386  // Not emitting abi tags: internal name anyway.
1387  break;
1388  }
1389 
1390  // Class extensions have no name as a category, and it's possible
1391  // for them to be the semantic parent of certain declarations
1392  // (primarily, tag decls defined within declarations). Such
1393  // declarations will always have internal linkage, so the name
1394  // doesn't really matter, but we shouldn't crash on them. For
1395  // safety, just handle all ObjC containers here.
1396  if (isa<ObjCContainerDecl>(ND))
1397  break;
1398 
1399  // We must have an anonymous struct.
1400  const TagDecl *TD = cast<TagDecl>(ND);
1401  if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1402  assert(TD->getDeclContext() == D->getDeclContext() &&
1403  "Typedef should not be in another decl context!");
1404  assert(D->getDeclName().getAsIdentifierInfo() &&
1405  "Typedef was not named!");
1406  mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1407  assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1408  // Explicit abi tags are still possible; take from underlying type, not
1409  // from typedef.
1410  writeAbiTags(TD, nullptr);
1411  break;
1412  }
1413 
1414  // <unnamed-type-name> ::= <closure-type-name>
1415  //
1416  // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1417  // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1418  // # Parameter types or 'v' for 'void'.
1419  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1420  if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1421  assert(!AdditionalAbiTags &&
1422  "Lambda type cannot have additional abi tags");
1423  mangleLambda(Record);
1424  break;
1425  }
1426  }
1427 
1428  if (TD->isExternallyVisible()) {
1429  unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1430  Out << "Ut";
1431  if (UnnamedMangle > 1)
1432  Out << UnnamedMangle - 2;
1433  Out << '_';
1434  writeAbiTags(TD, AdditionalAbiTags);
1435  break;
1436  }
1437 
1438  // Get a unique id for the anonymous struct. If it is not a real output
1439  // ID doesn't matter so use fake one.
1440  unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1441 
1442  // Mangle it as a source name in the form
1443  // [n] $_<id>
1444  // where n is the length of the string.
1445  SmallString<8> Str;
1446  Str += "$_";
1447  Str += llvm::utostr(AnonStructId);
1448 
1449  Out << Str.size();
1450  Out << Str;
1451  break;
1452  }
1453 
1457  llvm_unreachable("Can't mangle Objective-C selector names here!");
1458 
1460  const CXXRecordDecl *InheritedFrom = nullptr;
1461  const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1462  if (auto Inherited =
1463  cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1464  InheritedFrom = Inherited.getConstructor()->getParent();
1465  InheritedTemplateArgs =
1466  Inherited.getConstructor()->getTemplateSpecializationArgs();
1467  }
1468 
1469  if (ND == Structor)
1470  // If the named decl is the C++ constructor we're mangling, use the type
1471  // we were given.
1472  mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1473  else
1474  // Otherwise, use the complete constructor name. This is relevant if a
1475  // class with a constructor is declared within a constructor.
1476  mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1477 
1478  // FIXME: The template arguments are part of the enclosing prefix or
1479  // nested-name, but it's more convenient to mangle them here.
1480  if (InheritedTemplateArgs)
1481  mangleTemplateArgs(*InheritedTemplateArgs);
1482 
1483  writeAbiTags(ND, AdditionalAbiTags);
1484  break;
1485  }
1486 
1488  if (ND == Structor)
1489  // If the named decl is the C++ destructor we're mangling, use the type we
1490  // were given.
1491  mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1492  else
1493  // Otherwise, use the complete destructor name. This is relevant if a
1494  // class with a destructor is declared within a destructor.
1495  mangleCXXDtorType(Dtor_Complete);
1496  writeAbiTags(ND, AdditionalAbiTags);
1497  break;
1498 
1500  if (ND && Arity == UnknownArity) {
1501  Arity = cast<FunctionDecl>(ND)->getNumParams();
1502 
1503  // If we have a member function, we need to include the 'this' pointer.
1504  if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1505  if (!MD->isStatic())
1506  Arity++;
1507  }
1508  LLVM_FALLTHROUGH;
1511  mangleOperatorName(Name, Arity);
1512  writeAbiTags(ND, AdditionalAbiTags);
1513  break;
1514 
1516  llvm_unreachable("Can't mangle a deduction guide name!");
1517 
1519  llvm_unreachable("Can't mangle a using directive name!");
1520  }
1521 }
1522 
1523 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1524  // <source-name> ::= <positive length number> __regcall3__ <identifier>
1525  // <number> ::= [n] <non-negative decimal integer>
1526  // <identifier> ::= <unqualified source code identifier>
1527  Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1528  << II->getName();
1529 }
1530 
1531 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1532  // <source-name> ::= <positive length number> __device_stub__ <identifier>
1533  // <number> ::= [n] <non-negative decimal integer>
1534  // <identifier> ::= <unqualified source code identifier>
1535  Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1536  << II->getName();
1537 }
1538 
1539 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1540  // <source-name> ::= <positive length number> <identifier>
1541  // <number> ::= [n] <non-negative decimal integer>
1542  // <identifier> ::= <unqualified source code identifier>
1543  Out << II->getLength() << II->getName();
1544 }
1545 
1546 void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1547  const DeclContext *DC,
1548  const AbiTagList *AdditionalAbiTags,
1549  bool NoFunction) {
1550  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1551  // <nested-name>
1552  // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1553  // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1554  // <template-args> E
1555 
1556  Out << 'N';
1557  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1558  Qualifiers MethodQuals = Method->getMethodQualifiers();
1559  // We do not consider restrict a distinguishing attribute for overloading
1560  // purposes so we must not mangle it.
1561  MethodQuals.removeRestrict();
1562  mangleQualifiers(MethodQuals);
1563  mangleRefQualifier(Method->getRefQualifier());
1564  }
1565 
1566  // Check if we have a template.
1567  const TemplateArgumentList *TemplateArgs = nullptr;
1568  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1569  mangleTemplatePrefix(TD, NoFunction);
1570  mangleTemplateArgs(*TemplateArgs);
1571  }
1572  else {
1573  manglePrefix(DC, NoFunction);
1574  mangleUnqualifiedName(GD, AdditionalAbiTags);
1575  }
1576 
1577  Out << 'E';
1578 }
1579 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1580  const TemplateArgument *TemplateArgs,
1581  unsigned NumTemplateArgs) {
1582  // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1583 
1584  Out << 'N';
1585 
1586  mangleTemplatePrefix(TD);
1587  mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1588 
1589  Out << 'E';
1590 }
1591 
1593  GlobalDecl GD;
1594  // The Itanium spec says:
1595  // For entities in constructors and destructors, the mangling of the
1596  // complete object constructor or destructor is used as the base function
1597  // name, i.e. the C1 or D1 version.
1598  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1599  GD = GlobalDecl(CD, Ctor_Complete);
1600  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1601  GD = GlobalDecl(DD, Dtor_Complete);
1602  else
1603  GD = GlobalDecl(cast<FunctionDecl>(DC));
1604  return GD;
1605 }
1606 
1607 void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1608  const AbiTagList *AdditionalAbiTags) {
1609  const Decl *D = GD.getDecl();
1610  // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1611  // := Z <function encoding> E s [<discriminator>]
1612  // <local-name> := Z <function encoding> E d [ <parameter number> ]
1613  // _ <entity name>
1614  // <discriminator> := _ <non-negative number>
1615  assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1616  const RecordDecl *RD = GetLocalClassDecl(D);
1617  const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1618 
1619  Out << 'Z';
1620 
1621  {
1622  AbiTagState LocalAbiTags(AbiTags);
1623 
1624  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1625  mangleObjCMethodName(MD);
1626  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1627  mangleBlockForPrefix(BD);
1628  else
1629  mangleFunctionEncoding(getParentOfLocalEntity(DC));
1630 
1631  // Implicit ABI tags (from namespace) are not available in the following
1632  // entity; reset to actually emitted tags, which are available.
1633  LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1634  }
1635 
1636  Out << 'E';
1637 
1638  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1639  // be a bug that is fixed in trunk.
1640 
1641  if (RD) {
1642  // The parameter number is omitted for the last parameter, 0 for the
1643  // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1644  // <entity name> will of course contain a <closure-type-name>: Its
1645  // numbering will be local to the particular argument in which it appears
1646  // -- other default arguments do not affect its encoding.
1647  const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1648  if (CXXRD && CXXRD->isLambda()) {
1649  if (const ParmVarDecl *Parm
1650  = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1651  if (const FunctionDecl *Func
1652  = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1653  Out << 'd';
1654  unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1655  if (Num > 1)
1656  mangleNumber(Num - 2);
1657  Out << '_';
1658  }
1659  }
1660  }
1661 
1662  // Mangle the name relative to the closest enclosing function.
1663  // equality ok because RD derived from ND above
1664  if (D == RD) {
1665  mangleUnqualifiedName(RD, AdditionalAbiTags);
1666  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1667  manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1668  assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1669  mangleUnqualifiedBlock(BD);
1670  } else {
1671  const NamedDecl *ND = cast<NamedDecl>(D);
1672  mangleNestedName(GD, getEffectiveDeclContext(ND), AdditionalAbiTags,
1673  true /*NoFunction*/);
1674  }
1675  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1676  // Mangle a block in a default parameter; see above explanation for
1677  // lambdas.
1678  if (const ParmVarDecl *Parm
1679  = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1680  if (const FunctionDecl *Func
1681  = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1682  Out << 'd';
1683  unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1684  if (Num > 1)
1685  mangleNumber(Num - 2);
1686  Out << '_';
1687  }
1688  }
1689 
1690  assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1691  mangleUnqualifiedBlock(BD);
1692  } else {
1693  mangleUnqualifiedName(GD, AdditionalAbiTags);
1694  }
1695 
1696  if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1697  unsigned disc;
1698  if (Context.getNextDiscriminator(ND, disc)) {
1699  if (disc < 10)
1700  Out << '_' << disc;
1701  else
1702  Out << "__" << disc << '_';
1703  }
1704  }
1705 }
1706 
1707 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1708  if (GetLocalClassDecl(Block)) {
1709  mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1710  return;
1711  }
1712  const DeclContext *DC = getEffectiveDeclContext(Block);
1713  if (isLocalContainerContext(DC)) {
1714  mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1715  return;
1716  }
1717  manglePrefix(getEffectiveDeclContext(Block));
1718  mangleUnqualifiedBlock(Block);
1719 }
1720 
1721 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1722  if (Decl *Context = Block->getBlockManglingContextDecl()) {
1723  if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1724  Context->getDeclContext()->isRecord()) {
1725  const auto *ND = cast<NamedDecl>(Context);
1726  if (ND->getIdentifier()) {
1727  mangleSourceNameWithAbiTags(ND);
1728  Out << 'M';
1729  }
1730  }
1731  }
1732 
1733  // If we have a block mangling number, use it.
1734  unsigned Number = Block->getBlockManglingNumber();
1735  // Otherwise, just make up a number. It doesn't matter what it is because
1736  // the symbol in question isn't externally visible.
1737  if (!Number)
1738  Number = Context.getBlockId(Block, false);
1739  else {
1740  // Stored mangling numbers are 1-based.
1741  --Number;
1742  }
1743  Out << "Ub";
1744  if (Number > 0)
1745  Out << Number - 1;
1746  Out << '_';
1747 }
1748 
1749 // <template-param-decl>
1750 // ::= Ty # template type parameter
1751 // ::= Tn <type> # template non-type parameter
1752 // ::= Tt <template-param-decl>* E # template template parameter
1753 // ::= Tp <template-param-decl> # template parameter pack
1754 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
1755  if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
1756  if (Ty->isParameterPack())
1757  Out << "Tp";
1758  Out << "Ty";
1759  } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
1760  if (Tn->isExpandedParameterPack()) {
1761  for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
1762  Out << "Tn";
1763  mangleType(Tn->getExpansionType(I));
1764  }
1765  } else {
1766  QualType T = Tn->getType();
1767  if (Tn->isParameterPack()) {
1768  Out << "Tp";
1769  if (auto *PackExpansion = T->getAs<PackExpansionType>())
1770  T = PackExpansion->getPattern();
1771  }
1772  Out << "Tn";
1773  mangleType(T);
1774  }
1775  } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
1776  if (Tt->isExpandedParameterPack()) {
1777  for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
1778  ++I) {
1779  Out << "Tt";
1780  for (auto *Param : *Tt->getExpansionTemplateParameters(I))
1781  mangleTemplateParamDecl(Param);
1782  Out << "E";
1783  }
1784  } else {
1785  if (Tt->isParameterPack())
1786  Out << "Tp";
1787  Out << "Tt";
1788  for (auto *Param : *Tt->getTemplateParameters())
1789  mangleTemplateParamDecl(Param);
1790  Out << "E";
1791  }
1792  }
1793 }
1794 
1795 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1796  // If the context of a closure type is an initializer for a class member
1797  // (static or nonstatic), it is encoded in a qualified name with a final
1798  // <prefix> of the form:
1799  //
1800  // <data-member-prefix> := <member source-name> M
1801  //
1802  // Technically, the data-member-prefix is part of the <prefix>. However,
1803  // since a closure type will always be mangled with a prefix, it's easier
1804  // to emit that last part of the prefix here.
1805  if (Decl *Context = Lambda->getLambdaContextDecl()) {
1806  if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1807  !isa<ParmVarDecl>(Context)) {
1808  // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1809  // reasonable mangling here.
1810  if (const IdentifierInfo *Name
1811  = cast<NamedDecl>(Context)->getIdentifier()) {
1812  mangleSourceName(Name);
1813  const TemplateArgumentList *TemplateArgs = nullptr;
1814  if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
1815  mangleTemplateArgs(*TemplateArgs);
1816  Out << 'M';
1817  }
1818  }
1819  }
1820 
1821  Out << "Ul";
1822  mangleLambdaSig(Lambda);
1823  Out << "E";
1824 
1825  // The number is omitted for the first closure type with a given
1826  // <lambda-sig> in a given context; it is n-2 for the nth closure type
1827  // (in lexical order) with that same <lambda-sig> and context.
1828  //
1829  // The AST keeps track of the number for us.
1830  unsigned Number = Lambda->getLambdaManglingNumber();
1831  assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1832  if (Number > 1)
1833  mangleNumber(Number - 2);
1834  Out << '_';
1835 }
1836 
1837 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
1838  for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
1839  mangleTemplateParamDecl(D);
1840  auto *Proto =
1842  mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1843  Lambda->getLambdaStaticInvoker());
1844 }
1845 
1846 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1847  switch (qualifier->getKind()) {
1849  // nothing
1850  return;
1851 
1853  llvm_unreachable("Can't mangle __super specifier");
1854 
1856  mangleName(qualifier->getAsNamespace());
1857  return;
1858 
1860  mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1861  return;
1862 
1865  manglePrefix(QualType(qualifier->getAsType(), 0));
1866  return;
1867 
1869  // Member expressions can have these without prefixes, but that
1870  // should end up in mangleUnresolvedPrefix instead.
1871  assert(qualifier->getPrefix());
1872  manglePrefix(qualifier->getPrefix());
1873 
1874  mangleSourceName(qualifier->getAsIdentifier());
1875  return;
1876  }
1877 
1878  llvm_unreachable("unexpected nested name specifier");
1879 }
1880 
1881 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1882  // <prefix> ::= <prefix> <unqualified-name>
1883  // ::= <template-prefix> <template-args>
1884  // ::= <template-param>
1885  // ::= # empty
1886  // ::= <substitution>
1887 
1888  DC = IgnoreLinkageSpecDecls(DC);
1889 
1890  if (DC->isTranslationUnit())
1891  return;
1892 
1893  if (NoFunction && isLocalContainerContext(DC))
1894  return;
1895 
1896  assert(!isLocalContainerContext(DC));
1897 
1898  const NamedDecl *ND = cast<NamedDecl>(DC);
1899  if (mangleSubstitution(ND))
1900  return;
1901 
1902  // Check if we have a template.
1903  const TemplateArgumentList *TemplateArgs = nullptr;
1904  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
1905  mangleTemplatePrefix(TD);
1906  mangleTemplateArgs(*TemplateArgs);
1907  } else {
1908  manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1909  mangleUnqualifiedName(ND, nullptr);
1910  }
1911 
1912  addSubstitution(ND);
1913 }
1914 
1915 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1916  // <template-prefix> ::= <prefix> <template unqualified-name>
1917  // ::= <template-param>
1918  // ::= <substitution>
1919  if (TemplateDecl *TD = Template.getAsTemplateDecl())
1920  return mangleTemplatePrefix(TD);
1921 
1922  DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1923  assert(Dependent && "unexpected template name kind");
1924 
1925  // Clang 11 and before mangled the substitution for a dependent template name
1926  // after already having emitted (a substitution for) the prefix.
1927  bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
1929  if (!Clang11Compat && mangleSubstitution(Template))
1930  return;
1931 
1932  if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1933  manglePrefix(Qualifier);
1934 
1935  if (Clang11Compat && mangleSubstitution(Template))
1936  return;
1937 
1938  if (const IdentifierInfo *Id = Dependent->getIdentifier())
1939  mangleSourceName(Id);
1940  else
1941  mangleOperatorName(Dependent->getOperator(), UnknownArity);
1942 
1943  addSubstitution(Template);
1944 }
1945 
1946 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
1947  bool NoFunction) {
1948  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1949  // <template-prefix> ::= <prefix> <template unqualified-name>
1950  // ::= <template-param>
1951  // ::= <substitution>
1952  // <template-template-param> ::= <template-param>
1953  // <substitution>
1954 
1955  if (mangleSubstitution(ND))
1956  return;
1957 
1958  // <template-template-param> ::= <template-param>
1959  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1960  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1961  } else {
1962  manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1963  if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
1964  mangleUnqualifiedName(GD, nullptr);
1965  else
1966  mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), nullptr);
1967  }
1968 
1969  addSubstitution(ND);
1970 }
1971 
1972 /// Mangles a template name under the production <type>. Required for
1973 /// template template arguments.
1974 /// <type> ::= <class-enum-type>
1975 /// ::= <template-param>
1976 /// ::= <substitution>
1977 void CXXNameMangler::mangleType(TemplateName TN) {
1978  if (mangleSubstitution(TN))
1979  return;
1980 
1981  TemplateDecl *TD = nullptr;
1982 
1983  switch (TN.getKind()) {
1986  goto HaveDecl;
1987 
1989  TD = TN.getAsTemplateDecl();
1990  goto HaveDecl;
1991 
1992  HaveDecl:
1993  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
1994  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1995  else
1996  mangleName(TD);
1997  break;
1998 
2001  llvm_unreachable("can't mangle an overloaded template name as a <type>");
2002 
2004  const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2005  assert(Dependent->isIdentifier());
2006 
2007  // <class-enum-type> ::= <name>
2008  // <name> ::= <nested-name>
2009  mangleUnresolvedPrefix(Dependent->getQualifier());
2010  mangleSourceName(Dependent->getIdentifier());
2011  break;
2012  }
2013 
2015  // Substituted template parameters are mangled as the substituted
2016  // template. This will check for the substitution twice, which is
2017  // fine, but we have to return early so that we don't try to *add*
2018  // the substitution twice.
2021  mangleType(subst->getReplacement());
2022  return;
2023  }
2024 
2026  // FIXME: not clear how to mangle this!
2027  // template <template <class> class T...> class A {
2028  // template <template <class> class U...> void foo(B<T,U> x...);
2029  // };
2030  Out << "_SUBSTPACK_";
2031  break;
2032  }
2033  }
2034 
2035  addSubstitution(TN);
2036 }
2037 
2038 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2039  StringRef Prefix) {
2040  // Only certain other types are valid as prefixes; enumerate them.
2041  switch (Ty->getTypeClass()) {
2042  case Type::Builtin:
2043  case Type::Complex:
2044  case Type::Adjusted:
2045  case Type::Decayed:
2046  case Type::Pointer:
2047  case Type::BlockPointer:
2048  case Type::LValueReference:
2049  case Type::RValueReference:
2050  case Type::MemberPointer:
2051  case Type::ConstantArray:
2052  case Type::IncompleteArray:
2053  case Type::VariableArray:
2054  case Type::DependentSizedArray:
2055  case Type::DependentAddressSpace:
2056  case Type::DependentVector:
2057  case Type::DependentSizedExtVector:
2058  case Type::Vector:
2059  case Type::ExtVector:
2060  case Type::ConstantMatrix:
2061  case Type::DependentSizedMatrix:
2062  case Type::FunctionProto:
2063  case Type::FunctionNoProto:
2064  case Type::Paren:
2065  case Type::Attributed:
2066  case Type::Auto:
2067  case Type::DeducedTemplateSpecialization:
2068  case Type::PackExpansion:
2069  case Type::ObjCObject:
2070  case Type::ObjCInterface:
2071  case Type::ObjCObjectPointer:
2072  case Type::ObjCTypeParam:
2073  case Type::Atomic:
2074  case Type::Pipe:
2075  case Type::MacroQualified:
2076  case Type::ExtInt:
2077  case Type::DependentExtInt:
2078  llvm_unreachable("type is illegal as a nested name specifier");
2079 
2080  case Type::SubstTemplateTypeParmPack:
2081  // FIXME: not clear how to mangle this!
2082  // template <class T...> class A {
2083  // template <class U...> void foo(decltype(T::foo(U())) x...);
2084  // };
2085  Out << "_SUBSTPACK_";
2086  break;
2087 
2088  // <unresolved-type> ::= <template-param>
2089  // ::= <decltype>
2090  // ::= <template-template-param> <template-args>
2091  // (this last is not official yet)
2092  case Type::TypeOfExpr:
2093  case Type::TypeOf:
2094  case Type::Decltype:
2095  case Type::TemplateTypeParm:
2096  case Type::UnaryTransform:
2097  case Type::SubstTemplateTypeParm:
2098  unresolvedType:
2099  // Some callers want a prefix before the mangled type.
2100  Out << Prefix;
2101 
2102  // This seems to do everything we want. It's not really
2103  // sanctioned for a substituted template parameter, though.
2104  mangleType(Ty);
2105 
2106  // We never want to print 'E' directly after an unresolved-type,
2107  // so we return directly.
2108  return true;
2109 
2110  case Type::Typedef:
2111  mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2112  break;
2113 
2114  case Type::UnresolvedUsing:
2115  mangleSourceNameWithAbiTags(
2116  cast<UnresolvedUsingType>(Ty)->getDecl());
2117  break;
2118 
2119  case Type::Enum:
2120  case Type::Record:
2121  mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2122  break;
2123 
2124  case Type::TemplateSpecialization: {
2125  const TemplateSpecializationType *TST =
2126  cast<TemplateSpecializationType>(Ty);
2127  TemplateName TN = TST->getTemplateName();
2128  switch (TN.getKind()) {
2131  TemplateDecl *TD = TN.getAsTemplateDecl();
2132 
2133  // If the base is a template template parameter, this is an
2134  // unresolved type.
2135  assert(TD && "no template for template specialization type");
2136  if (isa<TemplateTemplateParmDecl>(TD))
2137  goto unresolvedType;
2138 
2139  mangleSourceNameWithAbiTags(TD);
2140  break;
2141  }
2142 
2146  llvm_unreachable("invalid base for a template specialization type");
2147 
2151  mangleExistingSubstitution(subst->getReplacement());
2152  break;
2153  }
2154 
2156  // FIXME: not clear how to mangle this!
2157  // template <template <class U> class T...> class A {
2158  // template <class U...> void foo(decltype(T<U>::foo) x...);
2159  // };
2160  Out << "_SUBSTPACK_";
2161  break;
2162  }
2163  }
2164 
2165  mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
2166  break;
2167  }
2168 
2169  case Type::InjectedClassName:
2170  mangleSourceNameWithAbiTags(
2171  cast<InjectedClassNameType>(Ty)->getDecl());
2172  break;
2173 
2174  case Type::DependentName:
2175  mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2176  break;
2177 
2178  case Type::DependentTemplateSpecialization: {
2180  cast<DependentTemplateSpecializationType>(Ty);
2181  mangleSourceName(DTST->getIdentifier());
2182  mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2183  break;
2184  }
2185 
2186  case Type::Elaborated:
2187  return mangleUnresolvedTypeOrSimpleId(
2188  cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2189  }
2190 
2191  return false;
2192 }
2193 
2194 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2195  switch (Name.getNameKind()) {
2204  llvm_unreachable("Not an operator name");
2205 
2207  // <operator-name> ::= cv <type> # (cast)
2208  Out << "cv";
2209  mangleType(Name.getCXXNameType());
2210  break;
2211 
2213  Out << "li";
2214  mangleSourceName(Name.getCXXLiteralIdentifier());
2215  return;
2216 
2218  mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2219  break;
2220  }
2221 }
2222 
2223 void
2224 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2225  switch (OO) {
2226  // <operator-name> ::= nw # new
2227  case OO_New: Out << "nw"; break;
2228  // ::= na # new[]
2229  case OO_Array_New: Out << "na"; break;
2230  // ::= dl # delete
2231  case OO_Delete: Out << "dl"; break;
2232  // ::= da # delete[]
2233  case OO_Array_Delete: Out << "da"; break;
2234  // ::= ps # + (unary)
2235  // ::= pl # + (binary or unknown)
2236  case OO_Plus:
2237  Out << (Arity == 1? "ps" : "pl"); break;
2238  // ::= ng # - (unary)
2239  // ::= mi # - (binary or unknown)
2240  case OO_Minus:
2241  Out << (Arity == 1? "ng" : "mi"); break;
2242  // ::= ad # & (unary)
2243  // ::= an # & (binary or unknown)
2244  case OO_Amp:
2245  Out << (Arity == 1? "ad" : "an"); break;
2246  // ::= de # * (unary)
2247  // ::= ml # * (binary or unknown)
2248  case OO_Star:
2249  // Use binary when unknown.
2250  Out << (Arity == 1? "de" : "ml"); break;
2251  // ::= co # ~
2252  case OO_Tilde: Out << "co"; break;
2253  // ::= dv # /
2254  case OO_Slash: Out << "dv"; break;
2255  // ::= rm # %
2256  case OO_Percent: Out << "rm"; break;
2257  // ::= or # |
2258  case OO_Pipe: Out << "or"; break;
2259  // ::= eo # ^
2260  case OO_Caret: Out << "eo"; break;
2261  // ::= aS # =
2262  case OO_Equal: Out << "aS"; break;
2263  // ::= pL # +=
2264  case OO_PlusEqual: Out << "pL"; break;
2265  // ::= mI # -=
2266  case OO_MinusEqual: Out << "mI"; break;
2267  // ::= mL # *=
2268  case OO_StarEqual: Out << "mL"; break;
2269  // ::= dV # /=
2270  case OO_SlashEqual: Out << "dV"; break;
2271  // ::= rM # %=
2272  case OO_PercentEqual: Out << "rM"; break;
2273  // ::= aN # &=
2274  case OO_AmpEqual: Out << "aN"; break;
2275  // ::= oR # |=
2276  case OO_PipeEqual: Out << "oR"; break;
2277  // ::= eO # ^=
2278  case OO_CaretEqual: Out << "eO"; break;
2279  // ::= ls # <<
2280  case OO_LessLess: Out << "ls"; break;
2281  // ::= rs # >>
2282  case OO_GreaterGreater: Out << "rs"; break;
2283  // ::= lS # <<=
2284  case OO_LessLessEqual: Out << "lS"; break;
2285  // ::= rS # >>=
2286  case OO_GreaterGreaterEqual: Out << "rS"; break;
2287  // ::= eq # ==
2288  case OO_EqualEqual: Out << "eq"; break;
2289  // ::= ne # !=
2290  case OO_ExclaimEqual: Out << "ne"; break;
2291  // ::= lt # <
2292  case OO_Less: Out << "lt"; break;
2293  // ::= gt # >
2294  case OO_Greater: Out << "gt"; break;
2295  // ::= le # <=
2296  case OO_LessEqual: Out << "le"; break;
2297  // ::= ge # >=
2298  case OO_GreaterEqual: Out << "ge"; break;
2299  // ::= nt # !
2300  case OO_Exclaim: Out << "nt"; break;
2301  // ::= aa # &&
2302  case OO_AmpAmp: Out << "aa"; break;
2303  // ::= oo # ||
2304  case OO_PipePipe: Out << "oo"; break;
2305  // ::= pp # ++
2306  case OO_PlusPlus: Out << "pp"; break;
2307  // ::= mm # --
2308  case OO_MinusMinus: Out << "mm"; break;
2309  // ::= cm # ,
2310  case OO_Comma: Out << "cm"; break;
2311  // ::= pm # ->*
2312  case OO_ArrowStar: Out << "pm"; break;
2313  // ::= pt # ->
2314  case OO_Arrow: Out << "pt"; break;
2315  // ::= cl # ()
2316  case OO_Call: Out << "cl"; break;
2317  // ::= ix # []
2318  case OO_Subscript: Out << "ix"; break;
2319 
2320  // ::= qu # ?
2321  // The conditional operator can't be overloaded, but we still handle it when
2322  // mangling expressions.
2323  case OO_Conditional: Out << "qu"; break;
2324  // Proposal on cxx-abi-dev, 2015-10-21.
2325  // ::= aw # co_await
2326  case OO_Coawait: Out << "aw"; break;
2327  // Proposed in cxx-abi github issue 43.
2328  // ::= ss # <=>
2329  case OO_Spaceship: Out << "ss"; break;
2330 
2331  case OO_None:
2333  llvm_unreachable("Not an overloaded operator");
2334  }
2335 }
2336 
2337 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2338  // Vendor qualifiers come first and if they are order-insensitive they must
2339  // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2340 
2341  // <type> ::= U <addrspace-expr>
2342  if (DAST) {
2343  Out << "U2ASI";
2344  mangleExpression(DAST->getAddrSpaceExpr());
2345  Out << "E";
2346  }
2347 
2348  // Address space qualifiers start with an ordinary letter.
2349  if (Quals.hasAddressSpace()) {
2350  // Address space extension:
2351  //
2352  // <type> ::= U <target-addrspace>
2353  // <type> ::= U <OpenCL-addrspace>
2354  // <type> ::= U <CUDA-addrspace>
2355 
2356  SmallString<64> ASString;
2357  LangAS AS = Quals.getAddressSpace();
2358 
2359  if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2360  // <target-addrspace> ::= "AS" <address-space-number>
2361  unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2362  if (TargetAS != 0)
2363  ASString = "AS" + llvm::utostr(TargetAS);
2364  } else {
2365  switch (AS) {
2366  default: llvm_unreachable("Not a language specific address space");
2367  // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2368  // "private"| "generic" | "device" |
2369  // "host" ]
2370  case LangAS::opencl_global:
2371  ASString = "CLglobal";
2372  break;
2374  ASString = "CLdevice";
2375  break;
2377  ASString = "CLhost";
2378  break;
2379  case LangAS::opencl_local:
2380  ASString = "CLlocal";
2381  break;
2383  ASString = "CLconstant";
2384  break;
2386  ASString = "CLprivate";
2387  break;
2389  ASString = "CLgeneric";
2390  break;
2391  // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2392  case LangAS::cuda_device:
2393  ASString = "CUdevice";
2394  break;
2395  case LangAS::cuda_constant:
2396  ASString = "CUconstant";
2397  break;
2398  case LangAS::cuda_shared:
2399  ASString = "CUshared";
2400  break;
2401  // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2402  case LangAS::ptr32_sptr:
2403  ASString = "ptr32_sptr";
2404  break;
2405  case LangAS::ptr32_uptr:
2406  ASString = "ptr32_uptr";
2407  break;
2408  case LangAS::ptr64:
2409  ASString = "ptr64";
2410  break;
2411  }
2412  }
2413  if (!ASString.empty())
2414  mangleVendorQualifier(ASString);
2415  }
2416 
2417  // The ARC ownership qualifiers start with underscores.
2418  // Objective-C ARC Extension:
2419  //
2420  // <type> ::= U "__strong"
2421  // <type> ::= U "__weak"
2422  // <type> ::= U "__autoreleasing"
2423  //
2424  // Note: we emit __weak first to preserve the order as
2425  // required by the Itanium ABI.
2426  if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2427  mangleVendorQualifier("__weak");
2428 
2429  // __unaligned (from -fms-extensions)
2430  if (Quals.hasUnaligned())
2431  mangleVendorQualifier("__unaligned");
2432 
2433  // Remaining ARC ownership qualifiers.
2434  switch (Quals.getObjCLifetime()) {
2435  case Qualifiers::OCL_None:
2436  break;
2437 
2438  case Qualifiers::OCL_Weak:
2439  // Do nothing as we already handled this case above.
2440  break;
2441 
2443  mangleVendorQualifier("__strong");
2444  break;
2445 
2447  mangleVendorQualifier("__autoreleasing");
2448  break;
2449 
2451  // The __unsafe_unretained qualifier is *not* mangled, so that
2452  // __unsafe_unretained types in ARC produce the same manglings as the
2453  // equivalent (but, naturally, unqualified) types in non-ARC, providing
2454  // better ABI compatibility.
2455  //
2456  // It's safe to do this because unqualified 'id' won't show up
2457  // in any type signatures that need to be mangled.
2458  break;
2459  }
2460 
2461  // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2462  if (Quals.hasRestrict())
2463  Out << 'r';
2464  if (Quals.hasVolatile())
2465  Out << 'V';
2466  if (Quals.hasConst())
2467  Out << 'K';
2468 }
2469 
2470 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2471  Out << 'U' << name.size() << name;
2472 }
2473 
2474 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2475  // <ref-qualifier> ::= R # lvalue reference
2476  // ::= O # rvalue-reference
2477  switch (RefQualifier) {
2478  case RQ_None:
2479  break;
2480 
2481  case RQ_LValue:
2482  Out << 'R';
2483  break;
2484 
2485  case RQ_RValue:
2486  Out << 'O';
2487  break;
2488  }
2489 }
2490 
2491 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2492  Context.mangleObjCMethodNameAsSourceName(MD, Out);
2493 }
2494 
2495 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2496  ASTContext &Ctx) {
2497  if (Quals)
2498  return true;
2499  if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2500  return true;
2501  if (Ty->isOpenCLSpecificType())
2502  return true;
2503  if (Ty->isBuiltinType())
2504  return false;
2505  // Through to Clang 6.0, we accidentally treated undeduced auto types as
2506  // substitution candidates.
2507  if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2508  isa<AutoType>(Ty))
2509  return false;
2510  // A placeholder type for class template deduction is substitutable with
2511  // its corresponding template name; this is handled specially when mangling
2512  // the type.
2513  if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2514  if (DeducedTST->getDeducedType().isNull())
2515  return false;
2516  return true;
2517 }
2518 
2519 void CXXNameMangler::mangleType(QualType T) {
2520  // If our type is instantiation-dependent but not dependent, we mangle
2521  // it as it was written in the source, removing any top-level sugar.
2522  // Otherwise, use the canonical type.
2523  //
2524  // FIXME: This is an approximation of the instantiation-dependent name
2525  // mangling rules, since we should really be using the type as written and
2526  // augmented via semantic analysis (i.e., with implicit conversions and
2527  // default template arguments) for any instantiation-dependent type.
2528  // Unfortunately, that requires several changes to our AST:
2529  // - Instantiation-dependent TemplateSpecializationTypes will need to be
2530  // uniqued, so that we can handle substitutions properly
2531  // - Default template arguments will need to be represented in the
2532  // TemplateSpecializationType, since they need to be mangled even though
2533  // they aren't written.
2534  // - Conversions on non-type template arguments need to be expressed, since
2535  // they can affect the mangling of sizeof/alignof.
2536  //
2537  // FIXME: This is wrong when mapping to the canonical type for a dependent
2538  // type discards instantiation-dependent portions of the type, such as for:
2539  //
2540  // template<typename T, int N> void f(T (&)[sizeof(N)]);
2541  // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2542  //
2543  // It's also wrong in the opposite direction when instantiation-dependent,
2544  // canonically-equivalent types differ in some irrelevant portion of inner
2545  // type sugar. In such cases, we fail to form correct substitutions, eg:
2546  //
2547  // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2548  //
2549  // We should instead canonicalize the non-instantiation-dependent parts,
2550  // regardless of whether the type as a whole is dependent or instantiation
2551  // dependent.
2553  T = T.getCanonicalType();
2554  else {
2555  // Desugar any types that are purely sugar.
2556  do {
2557  // Don't desugar through template specialization types that aren't
2558  // type aliases. We need to mangle the template arguments as written.
2559  if (const TemplateSpecializationType *TST
2560  = dyn_cast<TemplateSpecializationType>(T))
2561  if (!TST->isTypeAlias())
2562  break;
2563 
2564  QualType Desugared
2565  = T.getSingleStepDesugaredType(Context.getASTContext());
2566  if (Desugared == T)
2567  break;
2568 
2569  T = Desugared;
2570  } while (true);
2571  }
2572  SplitQualType split = T.split();
2573  Qualifiers quals = split.Quals;
2574  const Type *ty = split.Ty;
2575 
2576  bool isSubstitutable =
2577  isTypeSubstitutable(quals, ty, Context.getASTContext());
2578  if (isSubstitutable && mangleSubstitution(T))
2579  return;
2580 
2581  // If we're mangling a qualified array type, push the qualifiers to
2582  // the element type.
2583  if (quals && isa<ArrayType>(T)) {
2584  ty = Context.getASTContext().getAsArrayType(T);
2585  quals = Qualifiers();
2586 
2587  // Note that we don't update T: we want to add the
2588  // substitution at the original type.
2589  }
2590 
2591  if (quals || ty->isDependentAddressSpaceType()) {
2592  if (const DependentAddressSpaceType *DAST =
2593  dyn_cast<DependentAddressSpaceType>(ty)) {
2594  SplitQualType splitDAST = DAST->getPointeeType().split();
2595  mangleQualifiers(splitDAST.Quals, DAST);
2596  mangleType(QualType(splitDAST.Ty, 0));
2597  } else {
2598  mangleQualifiers(quals);
2599 
2600  // Recurse: even if the qualified type isn't yet substitutable,
2601  // the unqualified type might be.
2602  mangleType(QualType(ty, 0));
2603  }
2604  } else {
2605  switch (ty->getTypeClass()) {
2606 #define ABSTRACT_TYPE(CLASS, PARENT)
2607 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2608  case Type::CLASS: \
2609  llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2610  return;
2611 #define TYPE(CLASS, PARENT) \
2612  case Type::CLASS: \
2613  mangleType(static_cast<const CLASS##Type*>(ty)); \
2614  break;
2615 #include "clang/AST/TypeNodes.inc"
2616  }
2617  }
2618 
2619  // Add the substitution.
2620  if (isSubstitutable)
2621  addSubstitution(T);
2622 }
2623 
2624 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2625  if (!mangleStandardSubstitution(ND))
2626  mangleName(ND);
2627 }
2628 
2629 void CXXNameMangler::mangleType(const BuiltinType *T) {
2630  // <type> ::= <builtin-type>
2631  // <builtin-type> ::= v # void
2632  // ::= w # wchar_t
2633  // ::= b # bool
2634  // ::= c # char
2635  // ::= a # signed char
2636  // ::= h # unsigned char
2637  // ::= s # short
2638  // ::= t # unsigned short
2639  // ::= i # int
2640  // ::= j # unsigned int
2641  // ::= l # long
2642  // ::= m # unsigned long
2643  // ::= x # long long, __int64
2644  // ::= y # unsigned long long, __int64
2645  // ::= n # __int128
2646  // ::= o # unsigned __int128
2647  // ::= f # float
2648  // ::= d # double
2649  // ::= e # long double, __float80
2650  // ::= g # __float128
2651  // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2652  // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2653  // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2654  // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2655  // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
2656  // ::= Di # char32_t
2657  // ::= Ds # char16_t
2658  // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2659  // ::= u <source-name> # vendor extended type
2660  std::string type_name;
2661  switch (T->getKind()) {
2662  case BuiltinType::Void:
2663  Out << 'v';
2664  break;
2665  case BuiltinType::Bool:
2666  Out << 'b';
2667  break;
2668  case BuiltinType::Char_U:
2669  case BuiltinType::Char_S:
2670  Out << 'c';
2671  break;
2672  case BuiltinType::UChar:
2673  Out << 'h';
2674  break;
2675  case BuiltinType::UShort:
2676  Out << 't';
2677  break;
2678  case BuiltinType::UInt:
2679  Out << 'j';
2680  break;
2681  case BuiltinType::ULong:
2682  Out << 'm';
2683  break;
2684  case BuiltinType::ULongLong:
2685  Out << 'y';
2686  break;
2687  case BuiltinType::UInt128:
2688  Out << 'o';
2689  break;
2690  case BuiltinType::SChar:
2691  Out << 'a';
2692  break;
2693  case BuiltinType::WChar_S:
2694  case BuiltinType::WChar_U:
2695  Out << 'w';
2696  break;
2697  case BuiltinType::Char8:
2698  Out << "Du";
2699  break;
2700  case BuiltinType::Char16:
2701  Out << "Ds";
2702  break;
2703  case BuiltinType::Char32:
2704  Out << "Di";
2705  break;
2706  case BuiltinType::Short:
2707  Out << 's';
2708  break;
2709  case BuiltinType::Int:
2710  Out << 'i';
2711  break;
2712  case BuiltinType::Long:
2713  Out << 'l';
2714  break;
2715  case BuiltinType::LongLong:
2716  Out << 'x';
2717  break;
2718  case BuiltinType::Int128:
2719  Out << 'n';
2720  break;
2721  case BuiltinType::Float16:
2722  Out << "DF16_";
2723  break;
2724  case BuiltinType::ShortAccum:
2725  case BuiltinType::Accum:
2726  case BuiltinType::LongAccum:
2727  case BuiltinType::UShortAccum:
2728  case BuiltinType::UAccum:
2729  case BuiltinType::ULongAccum:
2730  case BuiltinType::ShortFract:
2731  case BuiltinType::Fract:
2732  case BuiltinType::LongFract:
2733  case BuiltinType::UShortFract:
2734  case BuiltinType::UFract:
2735  case BuiltinType::ULongFract:
2736  case BuiltinType::SatShortAccum:
2737  case BuiltinType::SatAccum:
2738  case BuiltinType::SatLongAccum:
2739  case BuiltinType::SatUShortAccum:
2740  case BuiltinType::SatUAccum:
2741  case BuiltinType::SatULongAccum:
2742  case BuiltinType::SatShortFract:
2743  case BuiltinType::SatFract:
2744  case BuiltinType::SatLongFract:
2745  case BuiltinType::SatUShortFract:
2746  case BuiltinType::SatUFract:
2747  case BuiltinType::SatULongFract:
2748  llvm_unreachable("Fixed point types are disabled for c++");
2749  case BuiltinType::Half:
2750  Out << "Dh";
2751  break;
2752  case BuiltinType::Float:
2753  Out << 'f';
2754  break;
2755  case BuiltinType::Double:
2756  Out << 'd';
2757  break;
2758  case BuiltinType::LongDouble: {
2759  const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2760  getASTContext().getLangOpts().OpenMPIsDevice
2761  ? getASTContext().getAuxTargetInfo()
2762  : &getASTContext().getTargetInfo();
2763  Out << TI->getLongDoubleMangling();
2764  break;
2765  }
2766  case BuiltinType::Float128: {
2767  const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
2768  getASTContext().getLangOpts().OpenMPIsDevice
2769  ? getASTContext().getAuxTargetInfo()
2770  : &getASTContext().getTargetInfo();
2771  Out << TI->getFloat128Mangling();
2772  break;
2773  }
2774  case BuiltinType::BFloat16: {
2775  const TargetInfo *TI = &getASTContext().getTargetInfo();
2776  Out << TI->getBFloat16Mangling();
2777  break;
2778  }
2779  case BuiltinType::NullPtr:
2780  Out << "Dn";
2781  break;
2782 
2783 #define BUILTIN_TYPE(Id, SingletonId)
2784 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2785  case BuiltinType::Id:
2786 #include "clang/AST/BuiltinTypes.def"
2787  case BuiltinType::Dependent:
2788  if (!NullOut)
2789  llvm_unreachable("mangling a placeholder type");
2790  break;
2791  case BuiltinType::ObjCId:
2792  Out << "11objc_object";
2793  break;
2794  case BuiltinType::ObjCClass:
2795  Out << "10objc_class";
2796  break;
2797  case BuiltinType::ObjCSel:
2798  Out << "13objc_selector";
2799  break;
2800 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2801  case BuiltinType::Id: \
2802  type_name = "ocl_" #ImgType "_" #Suffix; \
2803  Out << type_name.size() << type_name; \
2804  break;
2805 #include "clang/Basic/OpenCLImageTypes.def"
2806  case BuiltinType::OCLSampler:
2807  Out << "11ocl_sampler";
2808  break;
2809  case BuiltinType::OCLEvent:
2810  Out << "9ocl_event";
2811  break;
2812  case BuiltinType::OCLClkEvent:
2813  Out << "12ocl_clkevent";
2814  break;
2815  case BuiltinType::OCLQueue:
2816  Out << "9ocl_queue";
2817  break;
2818  case BuiltinType::OCLReserveID:
2819  Out << "13ocl_reserveid";
2820  break;
2821 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2822  case BuiltinType::Id: \
2823  type_name = "ocl_" #ExtType; \
2824  Out << type_name.size() << type_name; \
2825  break;
2826 #include "clang/Basic/OpenCLExtensionTypes.def"
2827  // The SVE types are effectively target-specific. The mangling scheme
2828  // is defined in the appendices to the Procedure Call Standard for the
2829  // Arm Architecture.
2830 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
2831  ElBits, IsSigned, IsFP, IsBF) \
2832  case BuiltinType::Id: \
2833  type_name = MangledName; \
2834  Out << (type_name == InternalName ? "u" : "") << type_name.size() \
2835  << type_name; \
2836  break;
2837 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
2838  case BuiltinType::Id: \
2839  type_name = MangledName; \
2840  Out << (type_name == InternalName ? "u" : "") << type_name.size() \
2841  << type_name; \
2842  break;
2843 #include "clang/Basic/AArch64SVEACLETypes.def"
2844 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
2845  case BuiltinType::Id: \
2846  type_name = #Name; \
2847  Out << 'u' << type_name.size() << type_name; \
2848  break;
2849 #include "clang/Basic/PPCTypes.def"
2850  }
2851 }
2852 
2853 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2854  switch (CC) {
2855  case CC_C:
2856  return "";
2857 
2858  case CC_X86VectorCall:
2859  case CC_X86Pascal:
2860  case CC_X86RegCall:
2861  case CC_AAPCS:
2862  case CC_AAPCS_VFP:
2863  case CC_AArch64VectorCall:
2864  case CC_IntelOclBicc:
2865  case CC_SpirFunction:
2866  case CC_OpenCLKernel:
2867  case CC_PreserveMost:
2868  case CC_PreserveAll:
2869  // FIXME: we should be mangling all of the above.
2870  return "";
2871 
2872  case CC_X86ThisCall:
2873  // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
2874  // used explicitly. At this point, we don't have that much information in
2875  // the AST, since clang tends to bake the convention into the canonical
2876  // function type. thiscall only rarely used explicitly, so don't mangle it
2877  // for now.
2878  return "";
2879 
2880  case CC_X86StdCall:
2881  return "stdcall";
2882  case CC_X86FastCall:
2883  return "fastcall";
2884  case CC_X86_64SysV:
2885  return "sysv_abi";
2886  case CC_Win64:
2887  return "ms_abi";
2888  case CC_Swift:
2889  return "swiftcall";
2890  }
2891  llvm_unreachable("bad calling convention");
2892 }
2893 
2894 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2895  // Fast path.
2896  if (T->getExtInfo() == FunctionType::ExtInfo())
2897  return;
2898 
2899  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2900  // This will get more complicated in the future if we mangle other
2901  // things here; but for now, since we mangle ns_returns_retained as
2902  // a qualifier on the result type, we can get away with this:
2903  StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2904  if (!CCQualifier.empty())
2905  mangleVendorQualifier(CCQualifier);
2906 
2907  // FIXME: regparm
2908  // FIXME: noreturn
2909 }
2910 
2911 void
2912 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2913  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2914 
2915  // Note that these are *not* substitution candidates. Demanglers might
2916  // have trouble with this if the parameter type is fully substituted.
2917 
2918  switch (PI.getABI()) {
2920  break;
2921 
2922  // All of these start with "swift", so they come before "ns_consumed".
2926  mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2927  break;
2928  }
2929 
2930  if (PI.isConsumed())
2931  mangleVendorQualifier("ns_consumed");
2932 
2933  if (PI.isNoEscape())
2934  mangleVendorQualifier("noescape");
2935 }
2936 
2937 // <type> ::= <function-type>
2938 // <function-type> ::= [<CV-qualifiers>] F [Y]
2939 // <bare-function-type> [<ref-qualifier>] E
2940 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2941  mangleExtFunctionInfo(T);
2942 
2943  // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2944  // e.g. "const" in "int (A::*)() const".
2945  mangleQualifiers(T->getMethodQuals());
2946 
2947  // Mangle instantiation-dependent exception-specification, if present,
2948  // per cxx-abi-dev proposal on 2016-10-11.
2951  Out << "DO";
2952  mangleExpression(T->getNoexceptExpr());
2953  Out << "E";
2954  } else {
2955  assert(T->getExceptionSpecType() == EST_Dynamic);
2956  Out << "Dw";
2957  for (auto ExceptTy : T->exceptions())
2958  mangleType(ExceptTy);
2959  Out << "E";
2960  }
2961  } else if (T->isNothrow()) {
2962  Out << "Do";
2963  }
2964 
2965  Out << 'F';
2966 
2967  // FIXME: We don't have enough information in the AST to produce the 'Y'
2968  // encoding for extern "C" function types.
2969  mangleBareFunctionType(T, /*MangleReturnType=*/true);
2970 
2971  // Mangle the ref-qualifier, if present.
2972  mangleRefQualifier(T->getRefQualifier());
2973 
2974  Out << 'E';
2975 }
2976 
2977 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2978  // Function types without prototypes can arise when mangling a function type
2979  // within an overloadable function in C. We mangle these as the absence of any
2980  // parameter types (not even an empty parameter list).
2981  Out << 'F';
2982 
2983  FunctionTypeDepthState saved = FunctionTypeDepth.push();
2984 
2985  FunctionTypeDepth.enterResultType();
2986  mangleType(T->getReturnType());
2987  FunctionTypeDepth.leaveResultType();
2988 
2989  FunctionTypeDepth.pop(saved);
2990  Out << 'E';
2991 }
2992 
2993 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2994  bool MangleReturnType,
2995  const FunctionDecl *FD) {
2996  // Record that we're in a function type. See mangleFunctionParam
2997  // for details on what we're trying to achieve here.
2998  FunctionTypeDepthState saved = FunctionTypeDepth.push();
2999 
3000  // <bare-function-type> ::= <signature type>+
3001  if (MangleReturnType) {
3002  FunctionTypeDepth.enterResultType();
3003 
3004  // Mangle ns_returns_retained as an order-sensitive qualifier here.
3005  if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3006  mangleVendorQualifier("ns_returns_retained");
3007 
3008  // Mangle the return type without any direct ARC ownership qualifiers.
3009  QualType ReturnTy = Proto->getReturnType();
3010  if (ReturnTy.getObjCLifetime()) {
3011  auto SplitReturnTy = ReturnTy.split();
3012  SplitReturnTy.Quals.removeObjCLifetime();
3013  ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3014  }
3015  mangleType(ReturnTy);
3016 
3017  FunctionTypeDepth.leaveResultType();
3018  }
3019 
3020  if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3021  // <builtin-type> ::= v # void
3022  Out << 'v';
3023 
3024  FunctionTypeDepth.pop(saved);
3025  return;
3026  }
3027 
3028  assert(!FD || FD->getNumParams() == Proto->getNumParams());
3029  for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3030  // Mangle extended parameter info as order-sensitive qualifiers here.
3031  if (Proto->hasExtParameterInfos() && FD == nullptr) {
3032  mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3033  }
3034 
3035  // Mangle the type.
3036  QualType ParamTy = Proto->getParamType(I);
3037  mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3038 
3039  if (FD) {
3040  if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3041  // Attr can only take 1 character, so we can hardcode the length below.
3042  assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3043  if (Attr->isDynamic())
3044  Out << "U25pass_dynamic_object_size" << Attr->getType();
3045  else
3046  Out << "U17pass_object_size" << Attr->getType();
3047  }
3048  }
3049  }
3050 
3051  FunctionTypeDepth.pop(saved);
3052 
3053  // <builtin-type> ::= z # ellipsis
3054  if (Proto->isVariadic())
3055  Out << 'z';
3056 }
3057 
3058 // <type> ::= <class-enum-type>
3059 // <class-enum-type> ::= <name>
3060 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3061  mangleName(T->getDecl());
3062 }
3063 
3064 // <type> ::= <class-enum-type>
3065 // <class-enum-type> ::= <name>
3066 void CXXNameMangler::mangleType(const EnumType *T) {
3067  mangleType(static_cast<const TagType*>(T));
3068 }
3069 void CXXNameMangler::mangleType(const RecordType *T) {
3070  mangleType(static_cast<const TagType*>(T));
3071 }
3072 void CXXNameMangler::mangleType(const TagType *T) {
3073  mangleName(T->getDecl());
3074 }
3075 
3076 // <type> ::= <array-type>
3077 // <array-type> ::= A <positive dimension number> _ <element type>
3078 // ::= A [<dimension expression>] _ <element type>
3079 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3080  Out << 'A' << T->getSize() << '_';
3081  mangleType(T->getElementType());
3082 }
3083 void CXXNameMangler::mangleType(const VariableArrayType *T) {
3084  Out << 'A';
3085  // decayed vla types (size 0) will just be skipped.
3086  if (T->getSizeExpr())
3087  mangleExpression(T->getSizeExpr());
3088  Out << '_';
3089  mangleType(T->getElementType());
3090 }
3091 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3092  Out << 'A';
3093  mangleExpression(T->getSizeExpr());
3094  Out << '_';
3095  mangleType(T->getElementType());
3096 }
3097 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3098  Out << "A_";
3099  mangleType(T->getElementType());
3100 }
3101 
3102 // <type> ::= <pointer-to-member-type>
3103 // <pointer-to-member-type> ::= M <class type> <member type>
3104 void CXXNameMangler::mangleType(const MemberPointerType *T) {
3105  Out << 'M';
3106  mangleType(QualType(T->getClass(), 0));
3107  QualType PointeeType = T->getPointeeType();
3108  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3109  mangleType(FPT);
3110 
3111  // Itanium C++ ABI 5.1.8:
3112  //
3113  // The type of a non-static member function is considered to be different,
3114  // for the purposes of substitution, from the type of a namespace-scope or
3115  // static member function whose type appears similar. The types of two
3116  // non-static member functions are considered to be different, for the
3117  // purposes of substitution, if the functions are members of different
3118  // classes. In other words, for the purposes of substitution, the class of
3119  // which the function is a member is considered part of the type of
3120  // function.
3121 
3122  // Given that we already substitute member function pointers as a
3123  // whole, the net effect of this rule is just to unconditionally
3124  // suppress substitution on the function type in a member pointer.
3125  // We increment the SeqID here to emulate adding an entry to the
3126  // substitution table.
3127  ++SeqID;
3128  } else
3129  mangleType(PointeeType);
3130 }
3131 
3132 // <type> ::= <template-param>
3133 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3134  mangleTemplateParameter(T->getDepth(), T->getIndex());
3135 }
3136 
3137 // <type> ::= <template-param>
3138 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3139  // FIXME: not clear how to mangle this!
3140  // template <class T...> class A {
3141  // template <class U...> void foo(T(*)(U) x...);
3142  // };
3143  Out << "_SUBSTPACK_";
3144 }
3145 
3146 // <type> ::= P <type> # pointer-to
3147 void CXXNameMangler::mangleType(const PointerType *T) {
3148  Out << 'P';
3149  mangleType(T->getPointeeType());
3150 }
3151 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3152  Out << 'P';
3153  mangleType(T->getPointeeType());
3154 }
3155 
3156 // <type> ::= R <type> # reference-to
3157 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3158  Out << 'R';
3159  mangleType(T->getPointeeType());
3160 }
3161 
3162 // <type> ::= O <type> # rvalue reference-to (C++0x)
3163 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3164  Out << 'O';
3165  mangleType(T->getPointeeType());
3166 }
3167 
3168 // <type> ::= C <type> # complex pair (C 2000)
3169 void CXXNameMangler::mangleType(const ComplexType *T) {
3170  Out << 'C';
3171  mangleType(T->getElementType());
3172 }
3173 
3174 // ARM's ABI for Neon vector types specifies that they should be mangled as
3175 // if they are structs (to match ARM's initial implementation). The
3176 // vector type must be one of the special types predefined by ARM.
3177 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3178  QualType EltType = T->getElementType();
3179  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3180  const char *EltName = nullptr;
3182  switch (cast<BuiltinType>(EltType)->getKind()) {
3183  case BuiltinType::SChar:
3184  case BuiltinType::UChar:
3185  EltName = "poly8_t";
3186  break;
3187  case BuiltinType::Short:
3188  case BuiltinType::UShort:
3189  EltName = "poly16_t";
3190  break;
3191  case BuiltinType::LongLong:
3192  case BuiltinType::ULongLong:
3193  EltName = "poly64_t";
3194  break;
3195  default: llvm_unreachable("unexpected Neon polynomial vector element type");
3196  }
3197  } else {
3198  switch (cast<BuiltinType>(EltType)->getKind()) {
3199  case BuiltinType::SChar: EltName = "int8_t"; break;
3200  case BuiltinType::UChar: EltName = "uint8_t"; break;
3201  case BuiltinType::Short: EltName = "int16_t"; break;
3202  case BuiltinType::UShort: EltName = "uint16_t"; break;
3203  case BuiltinType::Int: EltName = "int32_t"; break;
3204  case BuiltinType::UInt: EltName = "uint32_t"; break;
3205  case BuiltinType::LongLong: EltName = "int64_t"; break;
3206  case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3207  case BuiltinType::Double: EltName = "float64_t"; break;
3208  case BuiltinType::Float: EltName = "float32_t"; break;
3209  case BuiltinType::Half: EltName = "float16_t"; break;
3210  case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
3211  default:
3212  llvm_unreachable("unexpected Neon vector element type");
3213  }
3214  }
3215  const char *BaseName = nullptr;
3216  unsigned BitSize = (T->getNumElements() *
3217  getASTContext().getTypeSize(EltType));
3218  if (BitSize == 64)
3219  BaseName = "__simd64_";
3220  else {
3221  assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3222  BaseName = "__simd128_";
3223  }
3224  Out << strlen(BaseName) + strlen(EltName);
3225  Out << BaseName << EltName;
3226 }
3227 
3228 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3229  DiagnosticsEngine &Diags = Context.getDiags();
3230  unsigned DiagID = Diags.getCustomDiagID(
3232  "cannot mangle this dependent neon vector type yet");
3233  Diags.Report(T->getAttributeLoc(), DiagID);
3234 }
3235 
3236 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3237  switch (EltType->getKind()) {
3238  case BuiltinType::SChar:
3239  return "Int8";
3240  case BuiltinType::Short:
3241  return "Int16";
3242  case BuiltinType::Int:
3243  return "Int32";
3244  case BuiltinType::Long:
3245  case BuiltinType::LongLong:
3246  return "Int64";
3247  case BuiltinType::UChar:
3248  return "Uint8";
3249  case BuiltinType::UShort:
3250  return "Uint16";
3251  case BuiltinType::UInt:
3252  return "Uint32";
3253  case BuiltinType::ULong:
3254  case BuiltinType::ULongLong:
3255  return "Uint64";
3256  case BuiltinType::Half:
3257  return "Float16";
3258  case BuiltinType::Float:
3259  return "Float32";
3260  case BuiltinType::Double:
3261  return "Float64";
3262  case BuiltinType::BFloat16:
3263  return "Bfloat16";
3264  default:
3265  llvm_unreachable("Unexpected vector element base type");
3266  }
3267 }
3268 
3269 // AArch64's ABI for Neon vector types specifies that they should be mangled as
3270 // the equivalent internal name. The vector type must be one of the special
3271 // types predefined by ARM.
3272 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3273  QualType EltType = T->getElementType();
3274  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3275  unsigned BitSize =
3276  (T->getNumElements() * getASTContext().getTypeSize(EltType));
3277  (void)BitSize; // Silence warning.
3278 
3279  assert((BitSize == 64 || BitSize == 128) &&
3280  "Neon vector type not 64 or 128 bits");
3281 
3282  StringRef EltName;
3284  switch (cast<BuiltinType>(EltType)->getKind()) {
3285  case BuiltinType::UChar:
3286  EltName = "Poly8";
3287  break;
3288  case BuiltinType::UShort:
3289  EltName = "Poly16";
3290  break;
3291  case BuiltinType::ULong:
3292  case BuiltinType::ULongLong:
3293  EltName = "Poly64";
3294  break;
3295  default:
3296  llvm_unreachable("unexpected Neon polynomial vector element type");
3297  }
3298  } else
3299  EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3300 
3301  std::string TypeName =
3302  ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3303  Out << TypeName.length() << TypeName;
3304 }
3305 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3306  DiagnosticsEngine &Diags = Context.getDiags();
3307  unsigned DiagID = Diags.getCustomDiagID(
3309  "cannot mangle this dependent neon vector type yet");
3310  Diags.Report(T->getAttributeLoc(), DiagID);
3311 }
3312 
3313 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3314 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3315 // type as the sizeless variants.
3316 //
3317 // The mangling scheme for VLS types is implemented as a "pseudo" template:
3318 //
3319 // '__SVE_VLS<<type>, <vector length>>'
3320 //
3321 // Combining the existing SVE type and a specific vector length (in bits).
3322 // For example:
3323 //
3324 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3325 //
3326 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3327 //
3328 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3329 //
3330 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3331 //
3332 // The latest ACLE specification (00bet5) does not contain details of this
3333 // mangling scheme, it will be specified in the next revision. The mangling
3334 // scheme is otherwise defined in the appendices to the Procedure Call Standard
3335 // for the Arm Architecture, see
3336 // https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst#appendix-c-mangling
3337 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3340  "expected fixed-length SVE vector!");
3341 
3342  QualType EltType = T->getElementType();
3343  assert(EltType->isBuiltinType() &&
3344  "expected builtin type for fixed-length SVE vector!");
3345 
3346  StringRef TypeName;
3347  switch (cast<BuiltinType>(EltType)->getKind()) {
3348  case BuiltinType::SChar:
3349  TypeName = "__SVInt8_t";
3350  break;
3351  case BuiltinType::UChar: {
3353  TypeName = "__SVUint8_t";
3354  else
3355  TypeName = "__SVBool_t";
3356  break;
3357  }
3358  case BuiltinType::Short:
3359  TypeName = "__SVInt16_t";
3360  break;
3361  case BuiltinType::UShort:
3362  TypeName = "__SVUint16_t";
3363  break;
3364  case BuiltinType::Int:
3365  TypeName = "__SVInt32_t";
3366  break;
3367  case BuiltinType::UInt:
3368  TypeName = "__SVUint32_t";
3369  break;
3370  case BuiltinType::Long:
3371  TypeName = "__SVInt64_t";
3372  break;
3373  case BuiltinType::ULong:
3374  TypeName = "__SVUint64_t";
3375  break;
3376  case BuiltinType::Half:
3377  TypeName = "__SVFloat16_t";
3378  break;
3379  case BuiltinType::Float:
3380  TypeName = "__SVFloat32_t";
3381  break;
3382  case BuiltinType::Double:
3383  TypeName = "__SVFloat64_t";
3384  break;
3385  case BuiltinType::BFloat16:
3386  TypeName = "__SVBfloat16_t";
3387  break;
3388  default:
3389  llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3390  }
3391 
3392  unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3393 
3395  VecSizeInBits *= 8;
3396 
3397  Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3398  << VecSizeInBits << "EE";
3399 }
3400 
3401 void CXXNameMangler::mangleAArch64FixedSveVectorType(
3402  const DependentVectorType *T) {
3403  DiagnosticsEngine &Diags = Context.getDiags();
3404  unsigned DiagID = Diags.getCustomDiagID(
3406  "cannot mangle this dependent fixed-length SVE vector type yet");
3407  Diags.Report(T->getAttributeLoc(), DiagID);
3408 }
3409 
3410 // GNU extension: vector types
3411 // <type> ::= <vector-type>
3412 // <vector-type> ::= Dv <positive dimension number> _
3413 // <extended element type>
3414 // ::= Dv [<dimension expression>] _ <element type>
3415 // <extended element type> ::= <element type>
3416 // ::= p # AltiVec vector pixel
3417 // ::= b # Altivec vector bool
3418 void CXXNameMangler::mangleType(const VectorType *T) {
3419  if ((T->getVectorKind() == VectorType::NeonVector ||
3421  llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3422  llvm::Triple::ArchType Arch =
3423  getASTContext().getTargetInfo().getTriple().getArch();
3424  if ((Arch == llvm::Triple::aarch64 ||
3425  Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
3426  mangleAArch64NeonVectorType(T);
3427  else
3428  mangleNeonVectorType(T);
3429  return;
3432  mangleAArch64FixedSveVectorType(T);
3433  return;
3434  }
3435  Out << "Dv" << T->getNumElements() << '_';
3437  Out << 'p';
3438  else if (T->getVectorKind() == VectorType::AltiVecBool)
3439  Out << 'b';
3440  else
3441  mangleType(T->getElementType());
3442 }
3443 
3444 void CXXNameMangler::mangleType(const DependentVectorType *T) {
3445  if ((T->getVectorKind() == VectorType::NeonVector ||
3447  llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3448  llvm::Triple::ArchType Arch =
3449  getASTContext().getTargetInfo().getTriple().getArch();
3450  if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3451  !Target.isOSDarwin())
3452  mangleAArch64NeonVectorType(T);
3453  else
3454  mangleNeonVectorType(T);
3455  return;
3458  mangleAArch64FixedSveVectorType(T);
3459  return;
3460  }
3461 
3462  Out << "Dv";
3463  mangleExpression(T->getSizeExpr());
3464  Out << '_';
3466  Out << 'p';
3467  else if (T->getVectorKind() == VectorType::AltiVecBool)
3468  Out << 'b';
3469  else
3470  mangleType(T->getElementType());
3471 }
3472 
3473 void CXXNameMangler::mangleType(const ExtVectorType *T) {
3474  mangleType(static_cast<const VectorType*>(T));
3475 }
3476 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3477  Out << "Dv";
3478  mangleExpression(T->getSizeExpr());
3479  Out << '_';
3480  mangleType(T->getElementType());
3481 }
3482 
3483 void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
3484  // Mangle matrix types as a vendor extended type:
3485  // u<Len>matrix_typeI<Rows><Columns><element type>E
3486 
3487  StringRef VendorQualifier = "matrix_type";
3488  Out << "u" << VendorQualifier.size() << VendorQualifier;
3489 
3490  Out << "I";
3491  auto &ASTCtx = getASTContext();
3492  unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
3493  llvm::APSInt Rows(BitWidth);
3494  Rows = T->getNumRows();
3495  mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
3496  llvm::APSInt Columns(BitWidth);
3497  Columns = T->getNumColumns();
3498  mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
3499  mangleType(T->getElementType());
3500  Out << "E";
3501 }
3502 
3503 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
3504  // Mangle matrix types as a vendor extended type:
3505  // u<Len>matrix_typeI<row expr><column expr><element type>E
3506  StringRef VendorQualifier = "matrix_type";
3507  Out << "u" << VendorQualifier.size() << VendorQualifier;
3508 
3509  Out << "I";
3510  mangleTemplateArg(T->getRowExpr());
3511  mangleTemplateArg(T->getColumnExpr());
3512  mangleType(T->getElementType());
3513  Out << "E";
3514 }
3515 
3516 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3517  SplitQualType split = T->getPointeeType().split();
3518  mangleQualifiers(split.Quals, T);
3519  mangleType(QualType(split.Ty, 0));
3520 }
3521 
3522 void CXXNameMangler::mangleType(const PackExpansionType *T) {
3523  // <type> ::= Dp <type> # pack expansion (C++0x)
3524  Out << "Dp";
3525  mangleType(T->getPattern());
3526 }
3527 
3528 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3529  mangleSourceName(T->getDecl()->getIdentifier());
3530 }
3531 
3532 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
3533  // Treat __kindof as a vendor extended type qualifier.
3534  if (T->isKindOfType())
3535  Out << "U8__kindof";
3536 
3537  if (!T->qual_empty()) {
3538  // Mangle protocol qualifiers.
3539  SmallString<64> QualStr;
3540  llvm::raw_svector_ostream QualOS(QualStr);
3541  QualOS << "objcproto";
3542  for (const auto *I : T->quals()) {
3543  StringRef name = I->getName();
3544  QualOS << name.size() << name;
3545  }
3546  Out << 'U' << QualStr.size() << QualStr;
3547  }
3548 
3549  mangleType(T->getBaseType());
3550 
3551  if (T->isSpecialized()) {
3552  // Mangle type arguments as I <type>+ E
3553  Out << 'I';
3554  for (auto typeArg : T->getTypeArgs())
3555  mangleType(typeArg);
3556  Out << 'E';
3557  }
3558 }
3559 
3560 void CXXNameMangler::mangleType(const BlockPointerType *T) {
3561  Out << "U13block_pointer";
3562  mangleType(T->getPointeeType());
3563 }
3564 
3565 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3566  // Mangle injected class name types as if the user had written the
3567  // specialization out fully. It may not actually be possible to see
3568  // this mangling, though.
3569  mangleType(T->getInjectedSpecializationType());
3570 }
3571 
3572 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3573  if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
3574  mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
3575  } else {
3576  if (mangleSubstitution(QualType(T, 0)))
3577  return;
3578 
3579  mangleTemplatePrefix(T->getTemplateName());
3580 
3581  // FIXME: GCC does not appear to mangle the template arguments when
3582  // the template in question is a dependent template name. Should we
3583  // emulate that badness?
3584  mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3585  addSubstitution(QualType(T, 0));
3586  }
3587 }
3588 
3589 void CXXNameMangler::mangleType(const DependentNameType *T) {
3590  // Proposal by cxx-abi-dev, 2014-03-26
3591  // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3592  // # dependent elaborated type specifier using
3593  // # 'typename'
3594  // ::= Ts <name> # dependent elaborated type specifier using
3595  // # 'struct' or 'class'
3596  // ::= Tu <name> # dependent elaborated type specifier using
3597  // # 'union'
3598  // ::= Te <name> # dependent elaborated type specifier using
3599  // # 'enum'
3600  switch (T->getKeyword()) {
3601  case ETK_None:
3602  case ETK_Typename:
3603  break;
3604  case ETK_Struct:
3605  case ETK_Class:
3606  case ETK_Interface:
3607  Out << "Ts";
3608  break;
3609  case ETK_Union:
3610  Out << "Tu";
3611  break;
3612  case ETK_Enum:
3613  Out << "Te";
3614  break;
3615  }
3616  // Typename types are always nested
3617  Out << 'N';
3618  manglePrefix(T->getQualifier());
3619  mangleSourceName(T->getIdentifier());
3620  Out << 'E';
3621 }
3622 
3623 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3624  // Dependently-scoped template types are nested if they have a prefix.
3625  Out << 'N';
3626 
3627  // TODO: avoid making this TemplateName.
3628  TemplateName Prefix =
3629  getASTContext().getDependentTemplateName(T->getQualifier(),
3630  T->getIdentifier());
3631  mangleTemplatePrefix(Prefix);
3632 
3633  // FIXME: GCC does not appear to mangle the template arguments when
3634  // the template in question is a dependent template name. Should we
3635  // emulate that badness?
3636  mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3637  Out << 'E';
3638 }
3639 
3640 void CXXNameMangler::mangleType(const TypeOfType *T) {
3641  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3642  // "extension with parameters" mangling.
3643  Out << "u6typeof";
3644 }
3645 
3646 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3647  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3648  // "extension with parameters" mangling.
3649  Out << "u6typeof";
3650 }
3651 
3652 void CXXNameMangler::mangleType(const DecltypeType *T) {
3653  Expr *E = T->getUnderlyingExpr();
3654 
3655  // type ::= Dt <expression> E # decltype of an id-expression
3656  // # or class member access
3657  // ::= DT <expression> E # decltype of an expression
3658 
3659  // This purports to be an exhaustive list of id-expressions and
3660  // class member accesses. Note that we do not ignore parentheses;
3661  // parentheses change the semantics of decltype for these
3662  // expressions (and cause the mangler to use the other form).
3663  if (isa<DeclRefExpr>(E) ||
3664  isa<MemberExpr>(E) ||
3665  isa<UnresolvedLookupExpr>(E) ||
3666  isa<DependentScopeDeclRefExpr>(E) ||
3667  isa<CXXDependentScopeMemberExpr>(E) ||
3668  isa<UnresolvedMemberExpr>(E))
3669  Out << "Dt";
3670  else
3671  Out << "DT";
3672  mangleExpression(E);
3673  Out << 'E';
3674 }
3675 
3676 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3677  // If this is dependent, we need to record that. If not, we simply
3678  // mangle it as the underlying type since they are equivalent.
3679  if (T->isDependentType()) {
3680  Out << 'U';
3681 
3682  switch (T->getUTTKind()) {
3684  Out << "3eut";
3685  break;
3686  }
3687  }
3688 
3689  mangleType(T->getBaseType());
3690 }
3691 
3692 void CXXNameMangler::mangleType(const AutoType *T) {
3693  assert(T->getDeducedType().isNull() &&
3694  "Deduced AutoType shouldn't be handled here!");
3695  assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3696  "shouldn't need to mangle __auto_type!");
3697  // <builtin-type> ::= Da # auto
3698  // ::= Dc # decltype(auto)
3699  Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3700 }
3701 
3702 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3703  QualType Deduced = T->getDeducedType();
3704  if (!Deduced.isNull())
3705  return mangleType(Deduced);
3706 
3708  assert(TD && "shouldn't form deduced TST unless we know we have a template");
3709 
3710  if (mangleSubstitution(TD))
3711  return;
3712 
3713  mangleName(GlobalDecl(TD));
3714  addSubstitution(TD);
3715 }
3716 
3717 void CXXNameMangler::mangleType(const AtomicType *T) {
3718  // <type> ::= U <source-name> <type> # vendor extended type qualifier
3719  // (Until there's a standardized mangling...)
3720  Out << "U7_Atomic";
3721  mangleType(T->getValueType());
3722 }
3723 
3724 void CXXNameMangler::mangleType(const PipeType *T) {
3725  // Pipe type mangling rules are described in SPIR 2.0 specification
3726  // A.1 Data types and A.3 Summary of changes
3727  // <type> ::= 8ocl_pipe
3728  Out << "8ocl_pipe";
3729 }
3730 
3731 void CXXNameMangler::mangleType(const ExtIntType *T) {
3732  Out << "U7_ExtInt";
3733  llvm::APSInt BW(32, true);
3734  BW = T->getNumBits();
3735  TemplateArgument TA(Context.getASTContext(), BW, getASTContext().IntTy);
3736  mangleTemplateArgs(&TA, 1);
3737  if (T->isUnsigned())
3738  Out << "j";
3739  else
3740  Out << "i";
3741 }
3742 
3743 void CXXNameMangler::mangleType(const DependentExtIntType *T) {
3744  Out << "U7_ExtInt";
3746  mangleTemplateArgs(&TA, 1);
3747  if (T->isUnsigned())
3748  Out << "j";
3749  else
3750  Out << "i";
3751 }
3752 
3753 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3754  const llvm::APSInt &Value) {
3755  // <expr-primary> ::= L <type> <value number> E # integer literal
3756  Out << 'L';
3757 
3758  mangleType(T);
3759  if (T->isBooleanType()) {
3760  // Boolean values are encoded as 0/1.
3761  Out << (Value.getBoolValue() ? '1' : '0');
3762  } else {
3763  mangleNumber(Value);
3764  }
3765  Out << 'E';
3766 
3767 }
3768 
3769 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3770  // Ignore member expressions involving anonymous unions.
3771  while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3772  if (!RT->getDecl()->isAnonymousStructOrUnion())
3773  break;
3774  const auto *ME = dyn_cast<MemberExpr>(Base);
3775  if (!ME)
3776  break;
3777  Base = ME->getBase();
3778  IsArrow = ME->isArrow();
3779  }
3780 
3781  if (Base->isImplicitCXXThis()) {
3782  // Note: GCC mangles member expressions to the implicit 'this' as
3783  // *this., whereas we represent them as this->. The Itanium C++ ABI
3784  // does not specify anything here, so we follow GCC.
3785  Out << "dtdefpT";
3786  } else {
3787  Out << (IsArrow ? "pt" : "dt");
3788  mangleExpression(Base);
3789  }
3790 }
3791 
3792 /// Mangles a member expression.
3793 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3794  bool isArrow,
3795  NestedNameSpecifier *qualifier,
3796  NamedDecl *firstQualifierLookup,
3798  const TemplateArgumentLoc *TemplateArgs,
3799  unsigned NumTemplateArgs,
3800  unsigned arity) {
3801  // <expression> ::= dt <expression> <unresolved-name>
3802  // ::= pt <expression> <unresolved-name>
3803  if (base)
3804  mangleMemberExprBase(base, isArrow);
3805  mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3806 }
3807 
3808 /// Look at the callee of the given call expression and determine if
3809 /// it's a parenthesized id-expression which would have triggered ADL
3810 /// otherwise.
3811 static bool isParenthesizedADLCallee(const CallExpr *call) {
3812  const Expr *callee = call->getCallee();
3813  const Expr *fn = callee->IgnoreParens();
3814 
3815  // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3816  // too, but for those to appear in the callee, it would have to be
3817  // parenthesized.
3818  if (callee == fn) return false;
3819 
3820  // Must be an unresolved lookup.
3821  const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3822  if (!lookup) return false;
3823 
3824  assert(!lookup->requiresADL());
3825 
3826  // Must be an unqualified lookup.
3827  if (lookup->getQualifier()) return false;
3828 
3829  // Must not have found a class member. Note that if one is a class
3830  // member, they're all class members.
3831  if (lookup->getNumDecls() > 0 &&
3832  (*lookup->decls_begin())->isCXXClassMember())
3833  return false;
3834 
3835  // Otherwise, ADL would have been triggered.
3836  return true;
3837 }
3838 
3839 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3840  const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3841  Out << CastEncoding;
3842  mangleType(ECE->getType());
3843  mangleExpression(ECE->getSubExpr());
3844 }
3845 
3846 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3847  if (auto *Syntactic = InitList->getSyntacticForm())
3848  InitList = Syntactic;
3849  for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3850  mangleExpression(InitList->getInit(i));
3851 }
3852 
3853 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) {
3854  switch (D->getKind()) {
3855  default:
3856  // <expr-primary> ::= L <mangled-name> E # external name
3857  Out << 'L';
3858  mangle(D);
3859  Out << 'E';
3860  break;
3861 
3862  case Decl::ParmVar:
3863  mangleFunctionParam(cast<ParmVarDecl>(D));
3864  break;
3865 
3866  case Decl::EnumConstant: {
3867  const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3868  mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3869  break;
3870  }
3871 
3872  case Decl::NonTypeTemplateParm:
3873  const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3874  mangleTemplateParameter(PD->getDepth(), PD->getIndex());
3875  break;
3876  }
3877 }
3878 
3879 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3880  // <expression> ::= <unary operator-name> <expression>
3881  // ::= <binary operator-name> <expression> <expression>
3882  // ::= <trinary operator-name> <expression> <expression> <expression>
3883  // ::= cv <type> expression # conversion with one argument
3884  // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3885  // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3886  // ::= sc <type> <expression> # static_cast<type> (expression)
3887  // ::= cc <type> <expression> # const_cast<type> (expression)
3888  // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
3889  // ::= st <type> # sizeof (a type)
3890  // ::= at <type> # alignof (a type)
3891  // ::= <template-param>
3892  // ::= <function-param>
3893  // ::= sr <type> <unqualified-name> # dependent name
3894  // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3895  // ::= ds <expression> <expression> # expr.*expr
3896  // ::= sZ <template-param> # size of a parameter pack
3897  // ::= sZ <function-param> # size of a function parameter pack
3898  // ::= <expr-primary>
3899  // <expr-primary> ::= L <type> <value number> E # integer literal
3900  // ::= L <type <value float> E # floating literal
3901  // ::= L <mangled-name> E # external name
3902  // ::= fpT # 'this' expression
3903  QualType ImplicitlyConvertedToType;
3904 
3905 recurse:
3906  switch (E->getStmtClass()) {
3907  case Expr::NoStmtClass:
3908 #define ABSTRACT_STMT(Type)
3909 #define EXPR(Type, Base)
3910 #define STMT(Type, Base) \
3911  case Expr::Type##Class:
3912 #include "clang/AST/StmtNodes.inc"
3913  // fallthrough
3914 
3915  // These all can only appear in local or variable-initialization
3916  // contexts and so should never appear in a mangling.
3917  case Expr::AddrLabelExprClass:
3918  case Expr::DesignatedInitUpdateExprClass:
3919  case Expr::ImplicitValueInitExprClass:
3920  case Expr::ArrayInitLoopExprClass:
3921  case Expr::ArrayInitIndexExprClass:
3922  case Expr::NoInitExprClass:
3923  case Expr::ParenListExprClass:
3924  case Expr::LambdaExprClass:
3925  case Expr::MSPropertyRefExprClass:
3926  case Expr::MSPropertySubscriptExprClass:
3927  case Expr::TypoExprClass: // This should no longer exist in the AST by now.
3928  case Expr::RecoveryExprClass:
3929  case Expr::OMPArraySectionExprClass:
3930  case Expr::OMPArrayShapingExprClass:
3931  case Expr::OMPIteratorExprClass:
3932  case Expr::CXXInheritedCtorInitExprClass:
3933  llvm_unreachable("unexpected statement kind");
3934 
3935  case Expr::ConstantExprClass:
3936  E = cast<ConstantExpr>(E)->getSubExpr();
3937  goto recurse;
3938 
3939  // FIXME: invent manglings for all these.
3940  case Expr::BlockExprClass:
3941  case Expr::ChooseExprClass:
3942  case Expr::CompoundLiteralExprClass:
3943  case Expr::ExtVectorElementExprClass:
3944  case Expr::GenericSelectionExprClass:
3945  case Expr::ObjCEncodeExprClass:
3946  case Expr::ObjCIsaExprClass:
3947  case Expr::ObjCIvarRefExprClass:
3948  case Expr::ObjCMessageExprClass:
3949  case Expr::ObjCPropertyRefExprClass:
3950  case Expr::ObjCProtocolExprClass:
3951  case Expr::ObjCSelectorExprClass:
3952  case Expr::ObjCStringLiteralClass:
3953  case Expr::ObjCBoxedExprClass:
3954  case Expr::ObjCArrayLiteralClass:
3955  case Expr::ObjCDictionaryLiteralClass:
3956  case Expr::ObjCSubscriptRefExprClass:
3957  case Expr::ObjCIndirectCopyRestoreExprClass:
3958  case Expr::ObjCAvailabilityCheckExprClass:
3959  case Expr::OffsetOfExprClass:
3960  case Expr::PredefinedExprClass:
3961  case Expr::ShuffleVectorExprClass:
3962  case Expr::ConvertVectorExprClass:
3963  case Expr::StmtExprClass:
3964  case Expr::TypeTraitExprClass:
3965  case Expr::RequiresExprClass:
3966  case Expr::ArrayTypeTraitExprClass:
3967  case Expr::ExpressionTraitExprClass:
3968  case Expr::VAArgExprClass:
3969  case Expr::CUDAKernelCallExprClass:
3970  case Expr::AsTypeExprClass:
3971  case Expr::PseudoObjectExprClass:
3972  case Expr::AtomicExprClass:
3973  case Expr::SourceLocExprClass:
3974  case Expr::BuiltinBitCastExprClass:
3975  {
3976  if (!NullOut) {
3977  // As bad as this diagnostic is, it's better than crashing.
3978  DiagnosticsEngine &Diags = Context.getDiags();
3979  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3980  "cannot yet mangle expression type %0");
3981  Diags.Report(E->getExprLoc(), DiagID)
3982  << E->getStmtClassName() << E->getSourceRange();
3983  }
3984  break;
3985  }
3986 
3987  case Expr::CXXUuidofExprClass: {
3988  const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3989  if (UE->isTypeOperand()) {
3990  QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3991  Out << "u8__uuidoft";
3992  mangleType(UuidT);
3993  } else {
3994  Expr *UuidExp = UE->getExprOperand();
3995  Out << "u8__uuidofz";
3996  mangleExpression(UuidExp, Arity);
3997  }
3998  break;
3999  }
4000 
4001  // Even gcc-4.5 doesn't mangle this.
4002  case Expr::BinaryConditionalOperatorClass: {
4003  DiagnosticsEngine &Diags = Context.getDiags();
4004  unsigned DiagID =
4006  "?: operator with omitted middle operand cannot be mangled");
4007  Diags.Report(E->getExprLoc(), DiagID)
4008  << E->getStmtClassName() << E->getSourceRange();
4009  break;
4010  }
4011 
4012  // These are used for internal purposes and cannot be meaningfully mangled.
4013  case Expr::OpaqueValueExprClass:
4014  llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4015 
4016  case Expr::InitListExprClass: {
4017  Out << "il";
4018  mangleInitListElements(cast<InitListExpr>(E));
4019  Out << "E";
4020  break;
4021  }
4022 
4023  case Expr::DesignatedInitExprClass: {
4024  auto *DIE = cast<DesignatedInitExpr>(E);
4025  for (const auto &Designator : DIE->designators()) {
4026  if (Designator.isFieldDesignator()) {
4027  Out << "di";
4028  mangleSourceName(Designator.getFieldName());
4029  } else if (Designator.isArrayDesignator()) {
4030  Out << "dx";
4031  mangleExpression(DIE->getArrayIndex(Designator));
4032  } else {
4034  "unknown designator kind");
4035  Out << "dX";
4036  mangleExpression(DIE->getArrayRangeStart(Designator));
4037  mangleExpression(DIE->getArrayRangeEnd(Designator));
4038  }
4039  }
4040  mangleExpression(DIE->getInit());
4041  break;
4042  }
4043 
4044  case Expr::CXXDefaultArgExprClass:
4045  mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
4046  break;
4047 
4048  case Expr::CXXDefaultInitExprClass:
4049  mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
4050  break;
4051 
4052  case Expr::CXXStdInitializerListExprClass:
4053  mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
4054  break;
4055 
4056  case Expr::SubstNonTypeTemplateParmExprClass:
4057  mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
4058  Arity);
4059  break;
4060 
4061  case Expr::UserDefinedLiteralClass:
4062  // We follow g++'s approach of mangling a UDL as a call to the literal
4063  // operator.
4064  case Expr::CXXMemberCallExprClass: // fallthrough
4065  case Expr::CallExprClass: {
4066  const CallExpr *CE = cast<CallExpr>(E);
4067 
4068  // <expression> ::= cp <simple-id> <expression>* E
4069  // We use this mangling only when the call would use ADL except
4070  // for being parenthesized. Per discussion with David
4071  // Vandervoorde, 2011.04.25.
4072  if (isParenthesizedADLCallee(CE)) {
4073  Out << "cp";
4074  // The callee here is a parenthesized UnresolvedLookupExpr with
4075  // no qualifier and should always get mangled as a <simple-id>
4076  // anyway.
4077 
4078  // <expression> ::= cl <expression>* E
4079  } else {
4080  Out << "cl";
4081  }
4082 
4083  unsigned CallArity = CE->getNumArgs();
4084  for (const Expr *Arg : CE->arguments())
4085  if (isa<PackExpansionExpr>(Arg))
4086  CallArity = UnknownArity;
4087 
4088  mangleExpression(CE->getCallee(), CallArity);
4089  for (const Expr *Arg : CE->arguments())
4090  mangleExpression(Arg);
4091  Out << 'E';
4092  break;
4093  }
4094 
4095  case Expr::CXXNewExprClass: {
4096  const CXXNewExpr *New = cast<CXXNewExpr>(E);
4097  if (New->isGlobalNew()) Out << "gs";
4098  Out << (New->isArray() ? "na" : "nw");
4100  E = New->placement_arg_end(); I != E; ++I)
4101  mangleExpression(*I);
4102  Out << '_';
4103  mangleType(New->getAllocatedType());
4104  if (New->hasInitializer()) {
4106  Out << "il";
4107  else
4108  Out << "pi";
4109  const Expr *Init = New->getInitializer();
4110  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4111  // Directly inline the initializers.
4112  for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4113  E = CCE->arg_end();
4114  I != E; ++I)
4115  mangleExpression(*I);
4116  } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4117  for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4118  mangleExpression(PLE->getExpr(i));
4119  } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
4120  isa<InitListExpr>(Init)) {
4121  // Only take InitListExprs apart for list-initialization.
4122  mangleInitListElements(cast<InitListExpr>(Init));
4123  } else
4124  mangleExpression(Init);
4125  }
4126  Out << 'E';
4127  break;
4128  }
4129 
4130  case Expr::CXXPseudoDestructorExprClass: {
4131  const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4132  if (const Expr *Base = PDE->getBase())
4133  mangleMemberExprBase(Base, PDE->isArrow());
4134  NestedNameSpecifier *Qualifier = PDE->getQualifier();
4135  if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4136  if (Qualifier) {
4137  mangleUnresolvedPrefix(Qualifier,
4138  /*recursive=*/true);
4139  mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4140  Out << 'E';
4141  } else {
4142  Out << "sr";
4143  if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4144  Out << 'E';
4145  }
4146  } else if (Qualifier) {
4147  mangleUnresolvedPrefix(Qualifier);
4148  }
4149  // <base-unresolved-name> ::= dn <destructor-name>
4150  Out << "dn";
4151  QualType DestroyedType = PDE->getDestroyedType();
4152  mangleUnresolvedTypeOrSimpleId(DestroyedType);
4153  break;
4154  }
4155 
4156  case Expr::MemberExprClass: {
4157  const MemberExpr *ME = cast<MemberExpr>(E);
4158  mangleMemberExpr(ME->getBase(), ME->isArrow(),
4159  ME->getQualifier(), nullptr,
4160  ME->getMemberDecl()->getDeclName(),
4161  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4162  Arity);
4163  break;
4164  }
4165 
4166  case Expr::UnresolvedMemberExprClass: {
4167  const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4168  mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4169  ME->isArrow(), ME->getQualifier(), nullptr,
4170  ME->getMemberName(),
4171  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4172  Arity);
4173  break;
4174  }
4175 
4176  case Expr::CXXDependentScopeMemberExprClass: {
4177  const CXXDependentScopeMemberExpr *ME
4178  = cast<CXXDependentScopeMemberExpr>(E);
4179  mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4180  ME->isArrow(), ME->getQualifier(),
4182  ME->getMember(),
4183  ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4184  Arity);
4185  break;
4186  }
4187 
4188  case Expr::UnresolvedLookupExprClass: {
4189  const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4190  mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4191  ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4192  Arity);
4193  break;
4194  }
4195 
4196  case Expr::CXXUnresolvedConstructExprClass: {
4197  const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4198  unsigned N = CE->getNumArgs();
4199 
4200  if (CE->isListInitialization()) {
4201  assert(N == 1 && "unexpected form for list initialization");
4202  auto *IL = cast<InitListExpr>(CE->getArg(0));
4203  Out << "tl";
4204  mangleType(CE->getType());
4205  mangleInitListElements(IL);
4206  Out << "E";
4207  return;
4208  }
4209 
4210  Out << "cv";
4211  mangleType(CE->getType());
4212  if (N != 1) Out << '_';
4213  for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
4214  if (N != 1) Out << 'E';
4215  break;
4216  }
4217 
4218  case Expr::CXXConstructExprClass: {
4219  const auto *CE = cast<CXXConstructExpr>(E);
4220  if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
4221  assert(
4222  CE->getNumArgs() >= 1 &&
4223  (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
4224  "implicit CXXConstructExpr must have one argument");
4225  return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
4226  }
4227  Out << "il";
4228  for (auto *E : CE->arguments())
4229  mangleExpression(E);
4230  Out << "E";
4231  break;
4232  }
4233 
4234  case Expr::CXXTemporaryObjectExprClass: {
4235  const auto *CE = cast<CXXTemporaryObjectExpr>(E);
4236  unsigned N = CE->getNumArgs();
4237  bool List = CE->isListInitialization();
4238 
4239  if (List)
4240  Out << "tl";
4241  else
4242  Out << "cv";
4243  mangleType(CE->getType());
4244  if (!List && N != 1)
4245  Out << '_';
4246  if (CE->isStdInitListInitialization()) {
4247  // We implicitly created a std::initializer_list<T> for the first argument
4248  // of a constructor of type U in an expression of the form U{a, b, c}.
4249  // Strip all the semantic gunk off the initializer list.
4250  auto *SILE =
4251  cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
4252  auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
4253  mangleInitListElements(ILE);
4254  } else {
4255  for (auto *E : CE->arguments())
4256  mangleExpression(E);
4257  }
4258  if (List || N != 1)
4259  Out << 'E';
4260  break;
4261  }
4262 
4263  case Expr::CXXScalarValueInitExprClass:
4264  Out << "cv";
4265  mangleType(E->getType());
4266  Out << "_E";
4267  break;
4268 
4269  case Expr::CXXNoexceptExprClass:
4270  Out << "nx";
4271  mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
4272  break;
4273 
4274  case Expr::UnaryExprOrTypeTraitExprClass: {
4275  const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
4276 
4277  if (!SAE->isInstantiationDependent()) {
4278  // Itanium C++ ABI:
4279  // If the operand of a sizeof or alignof operator is not
4280  // instantiation-dependent it is encoded as an integer literal
4281  // reflecting the result of the operator.
4282  //
4283  // If the result of the operator is implicitly converted to a known
4284  // integer type, that type is used for the literal; otherwise, the type
4285  // of std::size_t or std::ptrdiff_t is used.
4286  QualType T = (ImplicitlyConvertedToType.isNull() ||
4287  !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
4288  : ImplicitlyConvertedToType;
4289  llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
4290  mangleIntegerLiteral(T, V);
4291  break;
4292  }
4293 
4294  switch(SAE->getKind()) {
4295  case UETT_SizeOf:
4296  Out << 's';
4297  break;
4298  case UETT_PreferredAlignOf:
4299  case UETT_AlignOf:
4300  Out << 'a';
4301  break;
4302  case UETT_VecStep: {
4303  DiagnosticsEngine &Diags = Context.getDiags();
4304  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4305  "cannot yet mangle vec_step expression");
4306  Diags.Report(DiagID);
4307  return;
4308  }
4309  case UETT_OpenMPRequiredSimdAlign: {
4310  DiagnosticsEngine &Diags = Context.getDiags();
4311  unsigned DiagID = Diags.getCustomDiagID(
4313  "cannot yet mangle __builtin_omp_required_simd_align expression");
4314  Diags.Report(DiagID);
4315  return;
4316  }
4317  }
4318  if (SAE->isArgumentType()) {
4319  Out << 't';
4320  mangleType(SAE->getArgumentType());
4321  } else {
4322  Out << 'z';
4323  mangleExpression(SAE->getArgumentExpr());
4324  }
4325  break;
4326  }
4327 
4328  case Expr::CXXThrowExprClass: {
4329  const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
4330  // <expression> ::= tw <expression> # throw expression
4331  // ::= tr # rethrow
4332  if (TE->getSubExpr()) {
4333  Out << "tw";
4334  mangleExpression(TE->getSubExpr());
4335  } else {
4336  Out << "tr";
4337  }
4338  break;
4339  }
4340 
4341  case Expr::CXXTypeidExprClass: {
4342  const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
4343  // <expression> ::= ti <type> # typeid (type)
4344  // ::= te <expression> # typeid (expression)
4345  if (TIE->isTypeOperand()) {
4346  Out << "ti";
4347  mangleType(TIE->getTypeOperand(Context.getASTContext()));
4348  } else {
4349  Out << "te";
4350  mangleExpression(TIE->getExprOperand());
4351  }
4352  break;
4353  }
4354 
4355  case Expr::CXXDeleteExprClass: {
4356  const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
4357  // <expression> ::= [gs] dl <expression> # [::] delete expr
4358  // ::= [gs] da <expression> # [::] delete [] expr
4359  if (DE->isGlobalDelete()) Out << "gs";
4360  Out << (DE->isArrayForm() ? "da" : "dl");
4361  mangleExpression(DE->getArgument());
4362  break;
4363  }
4364 
4365  case Expr::UnaryOperatorClass: {
4366  const UnaryOperator *UO = cast<UnaryOperator>(E);
4367  mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
4368  /*Arity=*/1);
4369  mangleExpression(UO->getSubExpr());
4370  break;
4371  }
4372 
4373  case Expr::ArraySubscriptExprClass: {
4374  const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
4375 
4376  // Array subscript is treated as a syntactically weird form of
4377  // binary operator.
4378  Out << "ix";
4379  mangleExpression(AE->getLHS());
4380  mangleExpression(AE->getRHS());
4381  break;
4382  }
4383 
4384  case Expr::MatrixSubscriptExprClass: {
4385  const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
4386  Out << "ixix";
4387  mangleExpression(ME->getBase());
4388  mangleExpression(ME->getRowIdx());
4389  mangleExpression(ME->getColumnIdx());
4390  break;
4391  }
4392 
4393  case Expr::CompoundAssignOperatorClass: // fallthrough
4394  case Expr::BinaryOperatorClass: {
4395  const BinaryOperator *BO = cast<BinaryOperator>(E);
4396  if (BO->getOpcode() == BO_PtrMemD)
4397  Out << "ds";
4398  else
4399  mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
4400  /*Arity=*/2);
4401  mangleExpression(BO->getLHS());
4402  mangleExpression(BO->getRHS());
4403  break;
4404  }
4405 
4406  case Expr::CXXRewrittenBinaryOperatorClass: {
4407  // The mangled form represents the original syntax.
4409  cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
4410  mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
4411  /*Arity=*/2);
4412  mangleExpression(Decomposed.LHS);
4413  mangleExpression(Decomposed.RHS);
4414  break;
4415  }
4416 
4417  case Expr::ConditionalOperatorClass: {
4418  const ConditionalOperator *CO = cast<ConditionalOperator>(E);
4419  mangleOperatorName(OO_Conditional, /*Arity=*/3);
4420  mangleExpression(CO->getCond());
4421  mangleExpression(CO->getLHS(), Arity);
4422  mangleExpression(CO->getRHS(), Arity);
4423  break;
4424  }
4425 
4426  case Expr::ImplicitCastExprClass: {
4427  ImplicitlyConvertedToType = E->getType();
4428  E = cast<ImplicitCastExpr>(E)->getSubExpr();
4429  goto recurse;
4430  }
4431 
4432  case Expr::ObjCBridgedCastExprClass: {
4433  // Mangle ownership casts as a vendor extended operator __bridge,
4434  // __bridge_transfer, or __bridge_retain.
4435  StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4436  Out << "v1U" << Kind.size() << Kind;
4437  }
4438  // Fall through to mangle the cast itself.
4439  LLVM_FALLTHROUGH;
4440 
4441  case Expr::CStyleCastExprClass:
4442  mangleCastExpression(E, "cv");
4443  break;
4444 
4445  case Expr::CXXFunctionalCastExprClass: {
4446  auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4447  // FIXME: Add isImplicit to CXXConstructExpr.
4448  if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4449  if (CCE->getParenOrBraceRange().isInvalid())
4450  Sub = CCE->getArg(0)->IgnoreImplicit();
4451  if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4452  Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4453  if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4454  Out << "tl";
4455  mangleType(E->getType());
4456  mangleInitListElements(IL);
4457  Out << "E";
4458  } else {
4459  mangleCastExpression(E, "cv");
4460  }
4461  break;
4462  }
4463 
4464  case Expr::CXXStaticCastExprClass:
4465  mangleCastExpression(E, "sc");
4466  break;
4467  case Expr::CXXDynamicCastExprClass:
4468  mangleCastExpression(E, "dc");
4469  break;
4470  case Expr::CXXReinterpretCastExprClass:
4471  mangleCastExpression(E, "rc");
4472  break;
4473  case Expr::CXXConstCastExprClass:
4474  mangleCastExpression(E, "cc");
4475  break;
4476  case Expr::CXXAddrspaceCastExprClass:
4477  mangleCastExpression(E, "ac");
4478  break;
4479 
4480  case Expr::CXXOperatorCallExprClass: {
4481  const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4482  unsigned NumArgs = CE->getNumArgs();
4483  // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4484  // (the enclosing MemberExpr covers the syntactic portion).
4485  if (CE->getOperator() != OO_Arrow)
4486  mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
4487  // Mangle the arguments.
4488  for (unsigned i = 0; i != NumArgs; ++i)
4489  mangleExpression(CE->getArg(i));
4490  break;
4491  }
4492 
4493  case Expr::ParenExprClass:
4494  mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4495  break;
4496 
4497 
4498  case Expr::ConceptSpecializationExprClass: {
4499  // <expr-primary> ::= L <mangled-name> E # external name
4500  Out << "L_Z";
4501  auto *CSE = cast<ConceptSpecializationExpr>(E);
4502  mangleTemplateName(CSE->getNamedConcept(),
4503  CSE->getTemplateArguments().data(),
4504  CSE->getTemplateArguments().size());
4505  Out << 'E';
4506  break;
4507  }
4508 
4509  case Expr::DeclRefExprClass:
4510  mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
4511  break;
4512 
4513  case Expr::SubstNonTypeTemplateParmPackExprClass:
4514  // FIXME: not clear how to mangle this!
4515  // template <unsigned N...> class A {
4516  // template <class U...> void foo(U (&x)[N]...);
4517  // };
4518  Out << "_SUBSTPACK_";
4519  break;
4520 
4521  case Expr::FunctionParmPackExprClass: {
4522  // FIXME: not clear how to mangle this!
4523  const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4524  Out << "v110_SUBSTPACK";
4525  mangleDeclRefExpr(FPPE->getParameterPack());
4526  break;
4527  }
4528 
4529  case Expr::DependentScopeDeclRefExprClass: {
4530  const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
4531  mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4532  DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4533  Arity);
4534  break;
4535  }
4536 
4537  case Expr::CXXBindTemporaryExprClass:
4538  mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4539  break;
4540 
4541  case Expr::ExprWithCleanupsClass:
4542  mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4543  break;
4544 
4545  case Expr::FloatingLiteralClass: {
4546  const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4547  mangleFloatLiteral(FL->getType(), FL->getValue());
4548  break;
4549  }
4550 
4551  case Expr::FixedPointLiteralClass:
4552  mangleFixedPointLiteral();
4553  break;
4554 
4555  case Expr::CharacterLiteralClass:
4556  Out << 'L';
4557  mangleType(E->getType());
4558  Out << cast<CharacterLiteral>(E)->getValue();
4559  Out << 'E';
4560  break;
4561 
4562  // FIXME. __objc_yes/__objc_no are mangled same as true/false
4563  case Expr::ObjCBoolLiteralExprClass:
4564  Out << "Lb";
4565  Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4566  Out << 'E';
4567  break;
4568 
4569  case Expr::CXXBoolLiteralExprClass:
4570  Out << "Lb";
4571  Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4572  Out << 'E';
4573  break;
4574 
4575  case Expr::IntegerLiteralClass: {
4576  llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4577  if (E->getType()->isSignedIntegerType())
4578  Value.setIsSigned(true);
4579  mangleIntegerLiteral(E->getType(), Value);
4580  break;
4581  }
4582 
4583  case Expr::ImaginaryLiteralClass: {
4584  const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4585  // Mangle as if a complex literal.
4586  // Proposal from David Vandevoorde, 2010.06.30.
4587  Out << 'L';
4588  mangleType(E->getType());
4589  if (const FloatingLiteral *Imag =
4590  dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4591  // Mangle a floating-point zero of the appropriate type.
4592  mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4593  Out << '_';
4594  mangleFloat(Imag->getValue());
4595  } else {
4596  Out << "0_";
4597  llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4598  if (IE->getSubExpr()->getType()->isSignedIntegerType())
4599  Value.setIsSigned(true);
4600  mangleNumber(Value);
4601  }
4602  Out << 'E';
4603  break;
4604  }
4605 
4606  case Expr::StringLiteralClass: {
4607  // Revised proposal from David Vandervoorde, 2010.07.15.
4608  Out << 'L';
4609  assert(isa<ConstantArrayType>(E->getType()));
4610  mangleType(E->getType());
4611  Out << 'E';
4612  break;
4613  }
4614 
4615  case Expr::GNUNullExprClass:
4616  // Mangle as if an integer literal 0.
4617  mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
4618  break;
4619 
4620  case Expr::CXXNullPtrLiteralExprClass: {
4621  Out << "LDnE";
4622  break;
4623  }
4624 
4625  case Expr::PackExpansionExprClass:
4626  Out << "sp";
4627  mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4628  break;
4629 
4630  case Expr::SizeOfPackExprClass: {
4631  auto *SPE = cast<SizeOfPackExpr>(E);
4632  if (SPE->isPartiallySubstituted()) {
4633  Out << "sP";
4634  for (const auto &A : SPE->getPartialArguments())
4635  mangleTemplateArg(A);
4636  Out << "E";
4637  break;
4638  }
4639 
4640  Out << "sZ";
4641  const NamedDecl *Pack = SPE->getPack();
4642  if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4643  mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
4644  else if (const NonTypeTemplateParmDecl *NTTP
4645  = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4646  mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
4647  else if (const TemplateTemplateParmDecl *TempTP
4648  = dyn_cast<TemplateTemplateParmDecl>(Pack))
4649  mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
4650  else
4651  mangleFunctionParam(cast<ParmVarDecl>(Pack));
4652  break;
4653  }
4654 
4655  case Expr::MaterializeTemporaryExprClass: {
4656  mangleExpression(cast<MaterializeTemporaryExpr>(E)->getSubExpr());
4657  break;
4658  }
4659 
4660  case Expr::CXXFoldExprClass: {
4661  auto *FE = cast<CXXFoldExpr>(E);
4662  if (FE->isLeftFold())
4663  Out << (FE->getInit() ? "fL" : "fl");
4664  else
4665  Out << (FE->getInit() ? "fR" : "fr");
4666 
4667  if (FE->getOperator() == BO_PtrMemD)
4668  Out << "ds";
4669  else
4670  mangleOperatorName(
4671  BinaryOperator::getOverloadedOperator(FE->getOperator()),
4672  /*Arity=*/2);
4673 
4674  if (FE->getLHS())
4675  mangleExpression(FE->getLHS());
4676  if (FE->getRHS())
4677  mangleExpression(FE->getRHS());
4678  break;
4679  }
4680 
4681  case Expr::CXXThisExprClass:
4682  Out << "fpT";
4683  break;
4684 
4685  case Expr::CoawaitExprClass:
4686  // FIXME: Propose a non-vendor mangling.
4687  Out << "v18co_await";
4688  mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4689  break;
4690 
4691  case Expr::DependentCoawaitExprClass:
4692  // FIXME: Propose a non-vendor mangling.
4693  Out << "v18co_await";
4694  mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4695  break;
4696 
4697  case Expr::CoyieldExprClass:
4698  // FIXME: Propose a non-vendor mangling.
4699  Out << "v18co_yield";
4700  mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4701  break;
4702  }
4703 }
4704 
4705 /// Mangle an expression which refers to a parameter variable.
4706 ///
4707 /// <expression> ::= <function-param>
4708 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4709 /// <function-param> ::= fp <top-level CV-qualifiers>
4710 /// <parameter-2 non-negative number> _ # L == 0, I > 0
4711 /// <function-param> ::= fL <L-1 non-negative number>
4712 /// p <top-level CV-qualifiers> _ # L > 0, I == 0
4713 /// <function-param> ::= fL <L-1 non-negative number>
4714 /// p <top-level CV-qualifiers>
4715 /// <I-1 non-negative number> _ # L > 0, I > 0
4716 ///
4717 /// L is the nesting depth of the parameter, defined as 1 if the
4718 /// parameter comes from the innermost function prototype scope
4719 /// enclosing the current context, 2 if from the next enclosing
4720 /// function prototype scope, and so on, with one special case: if
4721 /// we've processed the full parameter clause for the innermost
4722 /// function type, then L is one less. This definition conveniently
4723 /// makes it irrelevant whether a function's result type was written
4724 /// trailing or leading, but is otherwise overly complicated; the
4725 /// numbering was first designed without considering references to
4726 /// parameter in locations other than return types, and then the
4727 /// mangling had to be generalized without changing the existing
4728 /// manglings.
4729 ///
4730 /// I is the zero-based index of the parameter within its parameter
4731 /// declaration clause. Note that the original ABI document describes
4732 /// this using 1-based ordinals.
4733 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4734  unsigned parmDepth = parm->getFunctionScopeDepth();
4735  unsigned parmIndex = parm->getFunctionScopeIndex();
4736 
4737  // Compute 'L'.
4738  // parmDepth does not include the declaring function prototype.
4739  // FunctionTypeDepth does account for that.
4740  assert(parmDepth < FunctionTypeDepth.getDepth());
4741  unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4742  if (FunctionTypeDepth.isInResultType())
4743  nestingDepth--;
4744 
4745  if (nestingDepth == 0) {
4746  Out << "fp";
4747  } else {
4748  Out << "fL" << (nestingDepth - 1) << 'p';
4749  }
4750 
4751  // Top-level qualifiers. We don't have to worry about arrays here,
4752  // because parameters declared as arrays should already have been
4753  // transformed to have pointer type. FIXME: apparently these don't
4754  // get mangled if used as an rvalue of a known non-class type?
4755  assert(!parm->getType()->isArrayType()
4756  && "parameter's type is still an array type?");
4757 
4758  if (const DependentAddressSpaceType *DAST =
4759  dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4760  mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4761  } else {
4762  mangleQualifiers(parm->getType().getQualifiers());
4763  }
4764 
4765  // Parameter index.
4766  if (parmIndex != 0) {
4767  Out << (parmIndex - 1);
4768  }
4769  Out << '_';
4770 }
4771 
4772 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4773  const CXXRecordDecl *InheritedFrom) {
4774  // <ctor-dtor-name> ::= C1 # complete object constructor
4775  // ::= C2 # base object constructor
4776  // ::= CI1 <type> # complete inheriting constructor
4777  // ::= CI2 <type> # base inheriting constructor
4778  //
4779  // In addition, C5 is a comdat name with C1 and C2 in it.
4780  Out << 'C';
4781  if (InheritedFrom)
4782  Out << 'I';
4783  switch (T) {
4784  case Ctor_Complete:
4785  Out << '1';
4786  break;
4787  case Ctor_Base:
4788  Out << '2';
4789  break;
4790  case Ctor_Comdat:
4791  Out << '5';
4792  break;
4793  case Ctor_DefaultClosure:
4794  case Ctor_CopyingClosure:
4795  llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4796  }
4797  if (InheritedFrom)
4798  mangleName(InheritedFrom);
4799 }
4800 
4801 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4802  // <ctor-dtor-name> ::= D0 # deleting destructor
4803  // ::= D1 # complete object destructor
4804  // ::= D2 # base object destructor
4805  //
4806  // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4807  switch (T) {
4808  case Dtor_Deleting:
4809  Out << "D0";
4810  break;
4811  case Dtor_Complete:
4812  Out << "D1";
4813  break;
4814  case Dtor_Base:
4815  Out << "D2";
4816  break;
4817  case Dtor_Comdat:
4818  Out << "D5";
4819  break;
4820  }
4821 }
4822 
4823 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4824  unsigned NumTemplateArgs) {
4825  // <template-args> ::= I <template-arg>+ E
4826  Out << 'I';
4827  for (unsigned i = 0; i != NumTemplateArgs; ++i)
4828  mangleTemplateArg(TemplateArgs[i].getArgument());
4829  Out << 'E';
4830 }
4831 
4832 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4833  // <template-args> ::= I <template-arg>+ E
4834  Out << 'I';
4835  for (unsigned i = 0, e = AL.size(); i != e; ++i)
4836  mangleTemplateArg(AL[i]);
4837  Out << 'E';
4838 }
4839 
4840 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4841  unsigned NumTemplateArgs) {
4842  // <template-args> ::= I <template-arg>+ E
4843  Out << 'I';
4844  for (unsigned i = 0; i != NumTemplateArgs; ++i)
4845  mangleTemplateArg(TemplateArgs[i]);
4846  Out << 'E';
4847 }
4848 
4849 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4850  // <template-arg> ::= <type> # type or template
4851  // ::= X <expression> E # expression
4852  // ::= <expr-primary> # simple expressions
4853  // ::= J <template-arg>* E # argument pack
4854  if (!A.isInstantiationDependent() || A.isDependent())
4855  A = Context.getASTContext().getCanonicalTemplateArgument(A);
4856 
4857  switch (A.getKind()) {
4859  llvm_unreachable("Cannot mangle NULL template argument");
4860 
4862  mangleType(A.getAsType());
4863  break;
4865  // This is mangled as <type>.
4866  mangleType(A.getAsTemplate());
4867  break;
4869  // <type> ::= Dp <type> # pack expansion (C++0x)
4870  Out << "Dp";
4871  mangleType(A.getAsTemplateOrTemplatePattern());
4872  break;
4874  // It's possible to end up with a DeclRefExpr here in certain
4875  // dependent cases, in which case we should mangle as a
4876  // declaration.
4877  const Expr *E = A.getAsExpr()->IgnoreParenImpCasts();
4878  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4879  const ValueDecl *D = DRE->getDecl();
4880  if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4881  Out << 'L';
4882  mangle(D);
4883  Out << 'E';
4884  break;
4885  }
4886  }
4887 
4888  Out << 'X';
4889  mangleExpression(E);
4890  Out << 'E';
4891  break;
4892  }
4894  mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4895  break;
4897  // <expr-primary> ::= L <mangled-name> E # external name
4898  ValueDecl *D = A.getAsDecl();
4899 
4900  // Template parameter objects are modeled by reproducing a source form
4901  // produced as if by aggregate initialization.
4902  if (A.getParamTypeForDecl()->isRecordType()) {
4903  Out << 'X';
4904  auto *TPO = cast<TemplateParamObjectDecl>(D);
4905  mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
4906  TPO->getValue());
4907  Out << 'E';
4908  break;
4909  }
4910 
4911  // Clang produces AST's where pointer-to-member-function expressions
4912  // and pointer-to-function expressions are represented as a declaration not
4913  // an expression. We compensate for it here to produce the correct mangling.
4914  bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4915  if (compensateMangling) {
4916  Out << 'X';
4917  mangleOperatorName(OO_Amp, 1);
4918  }
4919 
4920  mangleDeclRefExpr(D);
4921 
4922  if (compensateMangling)
4923  Out << 'E';
4924 
4925  break;
4926  }
4928  mangleNullPointer(A.getNullPtrType());
4929  break;
4930  }
4931  case TemplateArgument::Pack: {
4932  // <template-arg> ::= J <template-arg>* E
4933  Out << 'J';
4934  for (const auto &P : A.pack_elements())
4935  mangleTemplateArg(P);
4936  Out << 'E';
4937  }
4938  }
4939 }
4940 
4941 /// Determine whether a given value is equivalent to zero-initialization for
4942 /// the purpose of discarding a trailing portion of a 'tl' mangling.
4943 ///
4944 /// Note that this is not in general equivalent to determining whether the
4945 /// value has an all-zeroes bit pattern.
4946 static bool isZeroInitialized(QualType T, const APValue &V) {
4947  // FIXME: mangleValueInTemplateArg has quadratic time complexity in
4948  // pathological cases due to using this, but it's a little awkward
4949  // to do this in linear time in general.
4950  switch (V.getKind()) {
4951  case APValue::None:
4954  return false;
4955 
4956  case APValue::Struct: {
4957  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4958  assert(RD && "unexpected type for record value");
4959  unsigned I = 0;
4960  for (const CXXBaseSpecifier &BS : RD->bases()) {
4961  if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
4962  return false;
4963  ++I;
4964  }
4965  I = 0;
4966  for (const FieldDecl *FD : RD->fields()) {
4967  if (!FD->isUnnamedBitfield() &&
4968  !isZeroInitialized(FD->getType(), V.getStructField(I)))
4969  return false;
4970  ++I;
4971  }
4972  return true;
4973  }
4974 
4975  case APValue::Union: {
4976  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4977  assert(RD && "unexpected type for union value");
4978  // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
4979  for (const FieldDecl *FD : RD->fields()) {
4980  if (!FD->isUnnamedBitfield())
4981  return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
4982  isZeroInitialized(FD->getType(), V.getUnionValue());
4983  }
4984  // If there are no fields (other than unnamed bitfields), the value is
4985  // necessarily zero-initialized.
4986  return true;
4987  }
4988 
4989  case APValue::Array: {
4990  QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
4991  for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
4992  if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
4993  return false;
4994  return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
4995  }
4996 
4997  case APValue::Vector: {
4998  const VectorType *VT = T->castAs<VectorType>();
4999  for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
5000  if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
5001  return false;
5002  return true;
5003  }
5004 
5005  case APValue::Int:
5006  return !V.getInt();
5007 
5008  case APValue::Float:
5009  return V.getFloat().isPosZero();
5010 
5011  case APValue::FixedPoint:
5012  return !V.getFixedPoint().getValue();
5013 
5014  case APValue::ComplexFloat:
5015  return V.getComplexFloatReal().isPosZero() &&
5016  V.getComplexFloatImag().isPosZero();
5017 
5018  case APValue::ComplexInt:
5019  return !V.getComplexIntReal() && !V.getComplexIntImag();
5020 
5021  case APValue::LValue:
5022  return V.isNullPointer();
5023 
5025  return !V.getMemberPointerDecl();
5026  }
5027 
5028  llvm_unreachable("Unhandled APValue::ValueKind enum");
5029 }
5030 
5031 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V) {
5032  // Ignore all top-level cv-qualifiers, to match GCC.
5033  Qualifiers Quals;
5034  T = getASTContext().getUnqualifiedArrayType(T, Quals);
5035 
5036  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
5037  switch (V.getKind()) {
5038  case APValue::None:
5040  Out << 'L';
5041  mangleType(T);
5042  Out << 'E';
5043  return;
5044 
5046  llvm_unreachable("unexpected value kind in template argument");
5047 
5048  case APValue::Struct: {
5049  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5050  assert(RD && "unexpected type for record value");
5051 
5052  // Drop trailing zero-initialized elements.
5054  RD->field_end());
5055  while (
5056  !Fields.empty() &&
5057  (Fields.back()->isUnnamedBitfield() ||
5058  isZeroInitialized(Fields.back()->getType(),
5059  V.getStructField(Fields.back()->getFieldIndex())))) {
5060  Fields.pop_back();
5061  }
5063  if (Fields.empty()) {
5064  while (!Bases.empty() &&
5065  isZeroInitialized(Bases.back().getType(),
5066  V.getStructBase(Bases.size() - 1)))
5067  Bases = Bases.drop_back();
5068  }
5069 
5070  // <expression> ::= tl <type> <braced-expression>* E
5071  Out << "tl";
5072  mangleType(T);
5073  for (unsigned I = 0, N = Bases.size(); I != N; ++I)
5074  mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I));
5075  for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
5076  if (Fields[I]->isUnnamedBitfield())
5077  continue;
5078  mangleValueInTemplateArg(Fields[I]->getType(),
5079  V.getStructField(Fields[I]->getFieldIndex()));
5080  }
5081  Out << 'E';
5082  return;
5083  }
5084 
5085  case APValue::Union: {
5086  assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
5087  const FieldDecl *FD = V.getUnionField();
5088 
5089  if (!FD) {
5090  Out << 'L';
5091  mangleType(T);
5092  Out << 'E';
5093  return;
5094  }
5095 
5096  // <braced-expression> ::= di <field source-name> <braced-expression>
5097  Out << "tl";
5098  mangleType(T);
5099  if (!isZeroInitialized(T, V)) {
5100  Out << "di";
5101  mangleSourceName(FD->getIdentifier());
5102  mangleValueInTemplateArg(FD->getType(), V.getUnionValue());
5103  }
5104  Out << 'E';
5105  return;
5106  }
5107 
5108  case APValue::Array: {
5109  QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
5110 
5111  Out << "tl";
5112  mangleType(T);
5113 
5114  // Drop trailing zero-initialized elements.
5115  unsigned N = V.getArraySize();
5116  if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
5117  N = V.getArrayInitializedElts();
5118  while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
5119  --N;
5120  }
5121 
5122  for (unsigned I = 0; I != N; ++I) {
5123  const APValue &Elem = I < V.getArrayInitializedElts()
5124  ? V.getArrayInitializedElt(I)
5125  : V.getArrayFiller();
5126  mangleValueInTemplateArg(ElemT, Elem);
5127  }
5128  Out << 'E';
5129  return;
5130  }
5131 
5132  case APValue::Vector: {
5133  const VectorType *VT = T->castAs<VectorType>();
5134 
5135  Out << "tl";
5136  mangleType(T);
5137  unsigned N = V.getVectorLength();
5138  while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
5139  --N;
5140  for (unsigned I = 0; I != N; ++I)
5141  mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I));
5142  Out << 'E';
5143  return;
5144  }
5145 
5146  case APValue::Int:
5147  mangleIntegerLiteral(T, V.getInt());
5148  return;
5149 
5150  case APValue::Float:
5151  mangleFloatLiteral(T, V.getFloat());
5152  return;
5153 
5154  case APValue::FixedPoint:
5155  mangleFixedPointLiteral();
5156  return;
5157 
5158  case APValue::ComplexFloat: {
5159  const ComplexType *CT = T->castAs<ComplexType>();
5160  Out << "tl";
5161  mangleType(T);
5162  if (!V.getComplexFloatReal().isPosZero() ||
5163  !V.getComplexFloatImag().isPosZero())
5164  mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
5165  if (!V.getComplexFloatImag().isPosZero())
5166  mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
5167  Out << 'E';
5168  return;
5169  }
5170 
5171  case APValue::ComplexInt: {
5172  const ComplexType *CT = T->castAs<ComplexType>();
5173  Out << "tl";
5174  mangleType(T);
5175  if (V.getComplexIntReal().getBoolValue() ||
5176  V.getComplexIntImag().getBoolValue())
5177  mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
5178  if (V.getComplexIntImag().getBoolValue())
5179  mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
5180  Out << 'E';
5181  return;
5182  }
5183 
5184  case APValue::LValue: {
5185  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5186  assert((T->isPointerType() || T->isReferenceType()) &&
5187  "unexpected type for LValue template arg");
5188 
5189  if (V.isNullPointer()) {
5190  mangleNullPointer(T);
5191  return;
5192  }
5193 
5194  APValue::LValueBase B = V.getLValueBase();
5195  if (!B) {
5196  // Non-standard mangling for integer cast to a pointer; this can only
5197  // occur as an extension.
5198  CharUnits Offset = V.getLValueOffset();
5199  if (Offset.isZero()) {
5200  // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
5201  // a cast, because L <type> 0 E means something else.
5202  Out << "rc";
5203  mangleType(T);
5204  Out << "Li0E";
5205  } else {
5206  Out << "L";
5207  mangleType(T);
5208  Out << Offset.getQuantity() << 'E';
5209  }
5210  return;
5211  }
5212 
5213  enum { Base, Offset, Path } Kind;
5214  if (!V.hasLValuePath()) {
5215  // Mangle as (T*)((char*)&base + N).
5216  if (T->isReferenceType()) {
5217  Out << "decvP";
5218  mangleType(T->getPointeeType());
5219  } else {
5220  Out << "cv";
5221  mangleType(T);
5222  }
5223  Out << "plcvPcad";
5224  Kind = Offset;
5225  } else {
5226  if (T->isPointerType())
5227  Out << "ad";
5228  if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
5229  Out << "so";
5230  mangleType(T->getPointeeType());
5231  Kind = Path;
5232  } else {
5233  Kind = Base;
5234  }
5235  }
5236 
5237  QualType TypeSoFar;
5238  if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
5239  Out << 'L';
5240  mangle(VD);
5241  Out << 'E';
5242  TypeSoFar = VD->getType();
5243  } else if (auto *E = B.dyn_cast<const Expr*>()) {
5244  mangleExpression(E);
5245  TypeSoFar = E->getType();
5246  } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
5247  Out << "ti";
5248  mangleType(QualType(TI.getType(), 0));
5249  TypeSoFar = B.getTypeInfoType();
5250  } else {
5251  // We should never see dynamic allocations here.
5252  llvm_unreachable("unexpected lvalue base kind in template argument");
5253  }
5254 
5255  switch (Kind) {
5256  case Base:
5257  break;
5258 
5259  case Offset:
5260  Out << 'L';
5261  mangleType(Context.getASTContext().getPointerDiffType());
5262  mangleNumber(V.getLValueOffset().getQuantity());
5263  Out << 'E';
5264  break;
5265 
5266  case Path:
5267  // <expression> ::= so <referent type> <expr> [<offset number>]
5268  // <union-selector>* [p] E
5269  if (!V.getLValueOffset().isZero())
5270  mangleNumber(V.getLValueOffset().getQuantity());
5271 
5272  // We model a past-the-end array pointer as array indexing with index N,
5273  // not with the "past the end" flag. Compensate for that.
5274  bool OnePastTheEnd = V.isLValueOnePastTheEnd();
5275 
5276  for (APValue::LValuePathEntry E : V.getLValuePath()) {
5277  if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
5278  if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5279  OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
5280  TypeSoFar = AT->getElementType();
5281  } else {
5282  const Decl *D = E.getAsBaseOrMember().getPointer();
5283  if (auto *FD = dyn_cast<FieldDecl>(D)) {
5284  // <union-selector> ::= _ <number>
5285  if (FD->getParent()->isUnion()) {
5286  Out << '_';
5287  if (FD->getFieldIndex())
5288  Out << (FD->getFieldIndex() - 1);
5289  }
5290  TypeSoFar = FD->getType();
5291  } else {
5292  TypeSoFar =
5293  Context.getASTContext().getRecordType(cast<CXXRecordDecl>(D));
5294  }
5295  }
5296  }
5297 
5298  if (OnePastTheEnd)
5299  Out << 'p';
5300  Out << 'E';
5301  break;
5302  }
5303 
5304  return;
5305  }
5306 
5308  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5309  if (!V.getMemberPointerDecl()) {
5310  mangleNullPointer(T);
5311  return;
5312  }
5313 
5314  if (!V.getMemberPointerPath().empty()) {
5315  Out << "mc";
5316  mangleType(T);
5317  }
5318  Out << "adL";
5319  mangle(V.getMemberPointerDecl());
5320  Out << 'E';
5321  if (!V.getMemberPointerPath().empty()) {
5322  CharUnits Offset =
5323  Context.getASTContext().getMemberPointerPathAdjustment(V);
5324  if (!Offset.isZero())
5325  mangleNumber(Offset.getQuantity());
5326  Out << 'E';
5327  }
5328  return;
5329  }
5330 }
5331 
5332 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
5333  // <template-param> ::= T_ # first template parameter
5334  // ::= T <parameter-2 non-negative number> _
5335  // ::= TL <L-1 non-negative number> __
5336  // ::= TL <L-1 non-negative number> _
5337  // <parameter-2 non-negative number> _
5338  //
5339  // The latter two manglings are from a proposal here:
5340  // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
5341  Out << 'T';
5342  if (Depth != 0)
5343  Out << 'L' << (Depth - 1) << '_';
5344  if (Index != 0)
5345  Out << (Index - 1);
5346  Out << '_';
5347 }
5348 
5349 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
5350  if (SeqID == 1)
5351  Out << '0';
5352  else if (SeqID > 1) {
5353  SeqID--;
5354 
5355  // <seq-id> is encoded in base-36, using digits and upper case letters.
5356  char Buffer[7]; // log(2**32) / log(36) ~= 7
5357  MutableArrayRef<char> BufferRef(Buffer);
5358  MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
5359 
5360  for (; SeqID != 0; SeqID /= 36) {
5361  unsigned C = SeqID % 36;
5362  *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
5363  }
5364 
5365  Out.write(I.base(), I - BufferRef.rbegin());
5366  }
5367  Out << '_';
5368 }
5369 
5370 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
5371  bool result = mangleSubstitution(tname);
5372  assert(result && "no existing substitution for template name");
5373  (void) result;
5374 }
5375 
5376 // <substitution> ::= S <seq-id> _
5377 // ::= S_
5378 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
5379  // Try one of the standard substitutions first.
5380  if (mangleStandardSubstitution(ND))
5381  return true;
5382 
5383  ND = cast<NamedDecl>(ND->getCanonicalDecl());
5384  return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
5385 }
5386 
5387 /// Determine whether the given type has any qualifiers that are relevant for
5388 /// substitutions.
5390  Qualifiers Qs = T.getQualifiers();
5391  return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
5392 }
5393 
5394 bool CXXNameMangler::mangleSubstitution(QualType T) {
5396  if (const RecordType *RT = T->getAs<RecordType>())
5397  return mangleSubstitution(RT->getDecl());
5398  }
5399 
5400  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
5401 
5402  return mangleSubstitution(TypePtr);
5403 }
5404 
5405 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
5406  if (TemplateDecl *TD = Template.getAsTemplateDecl())
5407  return mangleSubstitution(TD);
5408 
5409  Template = Context.getASTContext().getCanonicalTemplateName(Template);
5410  return mangleSubstitution(
5411  reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
5412 }
5413 
5414 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
5415  llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
5416  if (I == Substitutions.end())
5417  return false;
5418 
5419  unsigned SeqID = I->second;
5420  Out << 'S';
5421  mangleSeqID(SeqID);
5422 
5423  return true;
5424 }
5425 
5426 static bool isCharType(QualType T) {
5427  if (T.isNull())
5428  return false;
5429 
5430  return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
5431  T->isSpecificBuiltinType(BuiltinType::Char_U);
5432 }
5433 
5434 /// Returns whether a given type is a template specialization of a given name
5435 /// with a single argument of type char.
5436 static bool isCharSpecialization(QualType T, const char *Name) {
5437  if (T.isNull())
5438  return false;
5439 
5440  const RecordType *RT = T->getAs<RecordType>();
5441  if (!RT)
5442  return false;
5443 
5445  dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5446  if (!SD)
5447  return false;
5448 
5449  if (!isStdNamespace(getEffectiveDeclContext(SD)))
5450  return false;
5451 
5452  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
5453  if (TemplateArgs.size() != 1)
5454  return false;
5455 
5456  if (!isCharType(TemplateArgs[0].getAsType()))
5457  return false;
5458 
5459  return SD->getIdentifier()->getName() == Name;
5460 }
5461 
5462 template <std::size_t StrLen>
5464  const char (&Str)[StrLen]) {
5465  if (!SD->getIdentifier()->isStr(Str))
5466  return false;
5467 
5468  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
5469  if (TemplateArgs.size() != 2)
5470  return false;
5471 
5472  if (!isCharType(TemplateArgs[0].getAsType()))
5473  return false;
5474 
5475  if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
5476  return false;
5477 
5478  return true;
5479 }
5480 
5481 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
5482  // <substitution> ::= St # ::std::
5483  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
5484  if (isStd(NS)) {
5485  Out << "St";
5486  return true;
5487  }
5488  }
5489 
5490  if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
5491  if (!isStdNamespace(getEffectiveDeclContext(TD)))
5492  return false;
5493 
5494  // <substitution> ::= Sa # ::std::allocator
5495  if (TD->getIdentifier()->isStr("allocator")) {
5496  Out << "Sa";
5497  return true;
5498  }
5499 
5500  // <<substitution> ::= Sb # ::std::basic_string
5501  if (TD->getIdentifier()->isStr("basic_string")) {
5502  Out << "Sb";
5503  return true;
5504  }
5505  }
5506 
5507  if (const ClassTemplateSpecializationDecl *SD =
5508  dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
5509  if (!isStdNamespace(getEffectiveDeclContext(SD)))
5510  return false;
5511 
5512  // <substitution> ::= Ss # ::std::basic_string<char,
5513  // ::std::char_traits<char>,
5514  // ::std::allocator<char> >
5515  if (SD->getIdentifier()->isStr("basic_string")) {
5516  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
5517 
5518  if (TemplateArgs.size() != 3)
5519  return false;
5520 
5521  if (!isCharType(TemplateArgs[0].getAsType()))
5522  return false;
5523 
5524  if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
5525  return false;
5526 
5527  if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
5528  return false;
5529 
5530  Out << "Ss";
5531  return true;
5532  }
5533 
5534  // <substitution> ::= Si # ::std::basic_istream<char,
5535  // ::std::char_traits<char> >
5536  if (isStreamCharSpecialization(SD, "basic_istream")) {
5537  Out << "Si";
5538  return true;
5539  }
5540 
5541  // <substitution> ::= So # ::std::basic_ostream<char,
5542  // ::std::char_traits<char> >
5543  if (isStreamCharSpecialization(SD, "basic_ostream")) {
5544  Out << "So";
5545  return true;
5546  }
5547 
5548  // <substitution> ::= Sd # ::std::basic_iostream<char,
5549  // ::std::char_traits<char> >
5550  if (isStreamCharSpecialization(SD, "basic_iostream")) {
5551  Out << "Sd";
5552  return true;
5553  }
5554  }
5555  return false;
5556 }
5557 
5558 void CXXNameMangler::addSubstitution(QualType T) {
5560  if (const RecordType *RT = T->getAs<RecordType>()) {
5561  addSubstitution(RT->getDecl());
5562  return;
5563  }
5564  }
5565 
5566  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
5567  addSubstitution(TypePtr);
5568 }
5569 
5570 void CXXNameMangler::addSubstitution(TemplateName Template) {
5571  if (TemplateDecl *TD = Template.getAsTemplateDecl())
5572  return addSubstitution(TD);
5573 
5574  Template = Context.getASTContext().getCanonicalTemplateName(Template);
5575  addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
5576 }
5577 
5578 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
5579  assert(!Substitutions.count(Ptr) && "Substitution already exists!");
5580  Substitutions[Ptr] = SeqID++;
5581 }
5582 
5583 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
5584  assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
5585  if (Other->SeqID > SeqID) {
5586  Substitutions.swap(Other->Substitutions);
5587  SeqID = Other->SeqID;
5588  }
5589 }
5590 
5591 CXXNameMangler::AbiTagList
5592 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
5593  // When derived abi tags are disabled there is no need to make any list.
5594  if (DisableDerivedAbiTags)
5595  return AbiTagList();
5596 
5597  llvm::raw_null_ostream NullOutStream;
5598  CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
5599  TrackReturnTypeTags.disableDerivedAbiTags();
5600 
5601  const FunctionProtoType *Proto =
5602  cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
5603  FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
5604  TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
5605  TrackReturnTypeTags.mangleType(Proto->getReturnType());
5606  TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
5607  TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
5608 
5609  return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
5610 }
5611 
5612 CXXNameMangler::AbiTagList
5613 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
5614  // When derived abi tags are disabled there is no need to make any list.
5615  if (DisableDerivedAbiTags)
5616  return AbiTagList();
5617 
5618  llvm::raw_null_ostream NullOutStream;
5619  CXXNameMangler TrackVariableType(*this, NullOutStream);
5620  TrackVariableType.disableDerivedAbiTags();
5621 
5622  TrackVariableType.mangleType(VD->getType());
5623 
5624  return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
5625 }
5626 
5627 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
5628  const VarDecl *VD) {
5629  llvm::raw_null_ostream NullOutStream;
5630  CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
5631  TrackAbiTags.mangle(VD);
5632  return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
5633 }
5634 
5635 //
5636 
5637 /// Mangles the name of the declaration D and emits that name to the given
5638 /// output stream.
5639 ///
5640 /// If the declaration D requires a mangled name, this routine will emit that
5641 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
5642 /// and this routine will return false. In this case, the caller should just
5643 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
5644 /// name.
5645 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
5646  raw_ostream &Out) {
5647  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
5648  assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
5649  "Invalid mangleName() call, argument is not a variable or function!");
5650 
5651  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
5652  getASTContext().getSourceManager(),
5653  "Mangling declaration");
5654 
5655  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
5656  auto Type = GD.getCtorType();
5657  CXXNameMangler Mangler(*this, Out, CD, Type);
5658  return Mangler.mangle(GlobalDecl(CD, Type));
5659  }
5660 
5661  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
5662  auto Type = GD.getDtorType();
5663  CXXNameMangler Mangler(*this, Out, DD, Type);
5664  return Mangler.mangle(GlobalDecl(DD, Type));
5665  }
5666 
5667  CXXNameMangler Mangler(*this, Out, D);
5668  Mangler.mangle(GD);
5669 }
5670 
5671 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
5672  raw_ostream &Out) {
5673  CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
5674  Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
5675 }
5676 
5677 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
5678  raw_ostream &Out) {
5679  CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
5680  Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
5681 }
5682 
5683 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
5684  const ThunkInfo &Thunk,
5685  raw_ostream &Out) {
5686  // <special-name> ::= T <call-offset> <base encoding>
5687  // # base is the nominal target function of thunk
5688  // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
5689  // # base is the nominal target function of thunk
5690  // # first call-offset is 'this' adjustment
5691  // # second call-offset is result adjustment
5692 
5693  assert(!isa<CXXDestructorDecl>(MD) &&
5694  "Use mangleCXXDtor for destructor decls!");
5695  CXXNameMangler Mangler(*this, Out);
5696  Mangler.getStream() << "_ZT";
5697  if (!Thunk.Return.isEmpty())
5698  Mangler.getStream() << 'c';
5699 
5700  // Mangle the 'this' pointer adjustment.
5701  Mangler.mangleCallOffset(Thunk.This.NonVirtual,
5703 
5704  // Mangle the return pointer adjustment if there is one.
5705  if (!Thunk.Return.isEmpty())
5706  Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
5708 
5709  Mangler.mangleFunctionEncoding(MD);
5710 }
5711 
5712 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
5713  const CXXDestructorDecl *DD, CXXDtorType Type,
5714  const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
5715  // <special-name> ::= T <call-offset> <base encoding>
5716  // # base is the nominal target function of thunk
5717  CXXNameMangler Mangler(*this, Out, DD, Type);
5718  Mangler.getStream() << "_ZT";
5719 
5720  // Mangle the 'this' pointer adjustment.
5721  Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
5723 
5724  Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
5725 }
5726 
5727 /// Returns the mangled name for a guard variable for the passed in VarDecl.
5728 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
5729  raw_ostream &Out) {
5730  // <special-name> ::= GV <object name> # Guard variable for one-time
5731  // # initialization
5732  CXXNameMangler Mangler(*this, Out);
5733  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
5734  // be a bug that is fixed in trunk.
5735  Mangler.getStream() << "_ZGV";
5736  Mangler.mangleName(D);
5737 }
5738 
5739 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
5740  raw_ostream &Out) {
5741  // These symbols are internal in the Itanium ABI, so the names don't matter.
5742  // Clang has traditionally used this symbol and allowed LLVM to adjust it to
5743  // avoid duplicate symbols.
5744  Out << "__cxx_global_var_init";
5745 }
5746 
5747 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
5748  raw_ostream &Out) {
5749  // Prefix the mangling of D with __dtor_.
5750  CXXNameMangler Mangler(*this, Out);
5751  Mangler.getStream() << "__dtor_";
5752  if (shouldMangleDeclName(D))
5753  Mangler.mangle(D);
5754  else
5755  Mangler.getStream() << D->getName();
5756 }
5757 
5758 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
5759  raw_ostream &Out) {
5760  // Clang generates these internal-linkage functions as part of its
5761  // implementation of the XL ABI.
5762  CXXNameMangler Mangler(*this, Out);
5763  Mangler.getStream() << "__finalize_";
5764  if (shouldMangleDeclName(D))
5765  Mangler.mangle(D);
5766  else
5767  Mangler.getStream() << D->getName();
5768 }
5769 
5770 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
5771  const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5772  CXXNameMangler Mangler(*this, Out);
5773  Mangler.getStream() << "__filt_";
5774  if (shouldMangleDeclName(EnclosingDecl))
5775  Mangler.mangle(EnclosingDecl);
5776  else
5777  Mangler.getStream() << EnclosingDecl->getName();
5778 }
5779 
5780 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
5781  const NamedDecl *EnclosingDecl, raw_ostream &Out) {
5782  CXXNameMangler Mangler(*this, Out);
5783  Mangler.getStream() << "__fin_";
5784  if (shouldMangleDeclName(EnclosingDecl))
5785  Mangler.mangle(EnclosingDecl);
5786  else
5787  Mangler.getStream() << EnclosingDecl->getName();
5788 }
5789 
5790 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
5791  raw_ostream &Out) {
5792  // <special-name> ::= TH <object name>
5793  CXXNameMangler Mangler(*this, Out);
5794  Mangler.getStream() << "_ZTH";
5795  Mangler.mangleName(D);
5796 }
5797 
5798 void
5799 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
5800  raw_ostream &Out) {
5801  // <special-name> ::= TW <object name>
5802  CXXNameMangler Mangler(*this, Out);
5803  Mangler.getStream() << "_ZTW";
5804  Mangler.mangleName(D);
5805 }
5806 
5807 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
5808  unsigned ManglingNumber,
5809  raw_ostream &Out) {
5810  // We match the GCC mangling here.
5811  // <special-name> ::= GR <object name>
5812  CXXNameMangler Mangler(*this, Out);
5813  Mangler.getStream() << "_ZGR";
5814  Mangler.mangleName(D);
5815  assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
5816  Mangler.mangleSeqID(ManglingNumber - 1);
5817 }
5818 
5819 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
5820  raw_ostream &Out) {
5821  // <special-name> ::= TV <type> # virtual table
5822  CXXNameMangler Mangler(*this, Out);
5823  Mangler.getStream() << "_ZTV";
5824  Mangler.mangleNameOrStandardSubstitution(RD);
5825 }
5826 
5827 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
5828  raw_ostream &Out) {
5829  // <special-name> ::= TT <type> # VTT structure
5830  CXXNameMangler Mangler(*this, Out);
5831  Mangler.getStream() << "_ZTT";
5832  Mangler.mangleNameOrStandardSubstitution(RD);
5833 }
5834 
5835 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5836  int64_t Offset,
5837  const CXXRecordDecl *Type,
5838  raw_ostream &Out) {
5839  // <special-name> ::= TC <type> <offset number> _ <base type>
5840  CXXNameMangler Mangler(*this, Out);
5841  Mangler.getStream() << "_ZTC";
5842  Mangler.mangleNameOrStandardSubstitution(RD);
5843  Mangler.getStream() << Offset;
5844  Mangler.getStream() << '_';
5845  Mangler.mangleNameOrStandardSubstitution(Type);
5846 }
5847 
5848 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
5849  // <special-name> ::= TI <type> # typeinfo structure
5850  assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5851  CXXNameMangler Mangler(*this, Out);
5852  Mangler.getStream() << "_ZTI";
5853  Mangler.mangleType(Ty);
5854 }
5855 
5856 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5857  raw_ostream &Out) {
5858  // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5859  CXXNameMangler Mangler(*this, Out);
5860  Mangler.getStream() << "_ZTS";
5861  Mangler.mangleType(Ty);
5862 }
5863 
5864 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5865  mangleCXXRTTIName(Ty, Out);
5866 }
5867 
5868 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5869  llvm_unreachable("Can't mangle string literals");
5870 }
5871 
5872 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
5873  raw_ostream &Out) {
5874  CXXNameMangler Mangler(*this, Out);
5875  Mangler.mangleLambdaSig(Lambda);
5876 }
5877 
5880  return new ItaniumMangleContextImpl(Context, Diags);
5881 }
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:82
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:5620
Defines the clang::ASTContext interface.
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it's either not been deduced or was deduce...
Definition: Type.h:4952
const Type * Ty
The locally-unqualified type.
Definition: Type.h:602
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:2973
Represents a function declaration or definition.
Definition: Decl.h:1805
std::string Name
The name of this module.
Definition: Module.h:99
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
Expr * getLHS() const
Definition: Expr.h:4099
Attempt to be ABI-compatible with code generated by Clang 11.0.x (git 2e10b7a39b93).
The "enum" keyword introduces the elaborated-type-specifier.
Definition: Type.h:5315
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this __uuidof() expression after various required adjustments (removing...
Definition: ExprCXX.cpp:168
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2623
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:4234
Complete object ctor.
Definition: ABI.h:25
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:335
QualType getPointeeType() const
Definition: Type.h:2633
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:4332
A (possibly-)qualified type.
Definition: Type.h:661
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:519
base_class_range bases()
Definition: DeclCXX.h:588
bool isArrayType() const
Definition: Type.h:6706
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3169
Attempt to be ABI-compatible with code generated by Clang 6.0.x (SVN r321711).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2921
GlobalDecl getWithDecl(const Decl *D)
Definition: GlobalDecl.h:158
static const TemplateArgument & getArgument(const TemplateArgument &A)
QualType getInjectedSpecializationType() const
Definition: Type.h:5261
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:503
const Expr * getSubExpr() const
Definition: ExprCXX.h:1191
__auto_type (GNU extension)
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4399
The COMDAT used for ctors.
Definition: ABI.h:27
BinaryOperatorKind Opcode
The original opcode, prior to rewriting.
Definition: ExprCXX.h:307
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4758
bool isListInitialization() const
Determine whether this expression models list-initialization.
Definition: ExprCXX.h:3473
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:109
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Expr * getUnderlyingExpr() const
Definition: Type.h:4488
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1496
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2908
Kind getKind() const
Definition: Type.h:2511
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3537
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:625
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3002
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:4270
TemplateArgumentLoc const * getTemplateArgs() const
Definition: ExprCXX.h:3279
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:2991
Defines the SourceManager interface.
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:5457
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:97
bool isRecordType() const
Definition: Type.h:6730
Expr * getBase() const
Definition: Expr.h:3163
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:295
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:5475
bool isEmpty() const
Definition: ABI.h:86
bool isDecltypeAuto() const
Definition: Type.h:5009
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:89
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4208
TagDecl * getDecl() const
Definition: Type.cpp:3474
static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl *SD, const char(&Str)[StrLen])
llvm::APFloat getValue() const
Definition: Expr.h:1641
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3501
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3063
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
Defines the C++ template declaration subclasses.
Opcode getOpcode() const
Definition: Expr.h:3771
StringRef P
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:430
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:4967
The base class of the type hierarchy.
Definition: Type.h:1478
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies this declaration.
Definition: ExprCXX.h:3237
int64_t NonVirtual
The non-virtual adjustment from the derived object to its nearest virtual base.
Definition: ABI.h:110
KernelReferenceKind getKernelReferenceKind() const
Definition: GlobalDecl.h:131
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1469
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:75
Represent a C++ namespace.
Definition: Decl.h:512
bool isArrayRangeDesignator() const
Definition: Designator.h:71
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1450
static bool isParenthesizedADLCallee(const CallExpr *call)
Look at the callee of the given call expression and determine if it's a parenthesized id-expression w...
ArrayRef< NamedDecl * > getLambdaExplicitTemplateParameters() const
Retrieve the lambda template parameters that were specified explicitly.
Definition: DeclCXX.cpp:1572
A container of type source information.
Definition: Type.h:6363
const Expr * RHS
The original right-hand side.
Definition: ExprCXX.h:311
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6221