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