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