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