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