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