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