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