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