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