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