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