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