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