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