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