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