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