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