]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / AST / ItaniumMangle.cpp
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 //                         ::= b # Altivec vector bool
2099 void CXXNameMangler::mangleType(const VectorType *T) {
2100   if ((T->getVectorKind() == VectorType::NeonVector ||
2101        T->getVectorKind() == VectorType::NeonPolyVector)) {
2102     mangleNeonVectorType(T);
2103     return;
2104   }
2105   Out << "Dv" << T->getNumElements() << '_';
2106   if (T->getVectorKind() == VectorType::AltiVecPixel)
2107     Out << 'p';
2108   else if (T->getVectorKind() == VectorType::AltiVecBool)
2109     Out << 'b';
2110   else
2111     mangleType(T->getElementType());
2112 }
2113 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2114   mangleType(static_cast<const VectorType*>(T));
2115 }
2116 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2117   Out << "Dv";
2118   mangleExpression(T->getSizeExpr());
2119   Out << '_';
2120   mangleType(T->getElementType());
2121 }
2122
2123 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2124   // <type>  ::= Dp <type>          # pack expansion (C++0x)
2125   Out << "Dp";
2126   mangleType(T->getPattern());
2127 }
2128
2129 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2130   mangleSourceName(T->getDecl()->getIdentifier());
2131 }
2132
2133 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2134   // We don't allow overloading by different protocol qualification,
2135   // so mangling them isn't necessary.
2136   mangleType(T->getBaseType());
2137 }
2138
2139 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2140   Out << "U13block_pointer";
2141   mangleType(T->getPointeeType());
2142 }
2143
2144 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2145   // Mangle injected class name types as if the user had written the
2146   // specialization out fully.  It may not actually be possible to see
2147   // this mangling, though.
2148   mangleType(T->getInjectedSpecializationType());
2149 }
2150
2151 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2152   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2153     mangleName(TD, T->getArgs(), T->getNumArgs());
2154   } else {
2155     if (mangleSubstitution(QualType(T, 0)))
2156       return;
2157     
2158     mangleTemplatePrefix(T->getTemplateName());
2159     
2160     // FIXME: GCC does not appear to mangle the template arguments when
2161     // the template in question is a dependent template name. Should we
2162     // emulate that badness?
2163     mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2164     addSubstitution(QualType(T, 0));
2165   }
2166 }
2167
2168 void CXXNameMangler::mangleType(const DependentNameType *T) {
2169   // Typename types are always nested
2170   Out << 'N';
2171   manglePrefix(T->getQualifier());
2172   mangleSourceName(T->getIdentifier());    
2173   Out << 'E';
2174 }
2175
2176 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2177   // Dependently-scoped template types are nested if they have a prefix.
2178   Out << 'N';
2179
2180   // TODO: avoid making this TemplateName.
2181   TemplateName Prefix =
2182     getASTContext().getDependentTemplateName(T->getQualifier(),
2183                                              T->getIdentifier());
2184   mangleTemplatePrefix(Prefix);
2185
2186   // FIXME: GCC does not appear to mangle the template arguments when
2187   // the template in question is a dependent template name. Should we
2188   // emulate that badness?
2189   mangleTemplateArgs(T->getArgs(), T->getNumArgs());    
2190   Out << 'E';
2191 }
2192
2193 void CXXNameMangler::mangleType(const TypeOfType *T) {
2194   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2195   // "extension with parameters" mangling.
2196   Out << "u6typeof";
2197 }
2198
2199 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2200   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2201   // "extension with parameters" mangling.
2202   Out << "u6typeof";
2203 }
2204
2205 void CXXNameMangler::mangleType(const DecltypeType *T) {
2206   Expr *E = T->getUnderlyingExpr();
2207
2208   // type ::= Dt <expression> E  # decltype of an id-expression
2209   //                             #   or class member access
2210   //      ::= DT <expression> E  # decltype of an expression
2211
2212   // This purports to be an exhaustive list of id-expressions and
2213   // class member accesses.  Note that we do not ignore parentheses;
2214   // parentheses change the semantics of decltype for these
2215   // expressions (and cause the mangler to use the other form).
2216   if (isa<DeclRefExpr>(E) ||
2217       isa<MemberExpr>(E) ||
2218       isa<UnresolvedLookupExpr>(E) ||
2219       isa<DependentScopeDeclRefExpr>(E) ||
2220       isa<CXXDependentScopeMemberExpr>(E) ||
2221       isa<UnresolvedMemberExpr>(E))
2222     Out << "Dt";
2223   else
2224     Out << "DT";
2225   mangleExpression(E);
2226   Out << 'E';
2227 }
2228
2229 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2230   // If this is dependent, we need to record that. If not, we simply
2231   // mangle it as the underlying type since they are equivalent.
2232   if (T->isDependentType()) {
2233     Out << 'U';
2234     
2235     switch (T->getUTTKind()) {
2236       case UnaryTransformType::EnumUnderlyingType:
2237         Out << "3eut";
2238         break;
2239     }
2240   }
2241
2242   mangleType(T->getUnderlyingType());
2243 }
2244
2245 void CXXNameMangler::mangleType(const AutoType *T) {
2246   QualType D = T->getDeducedType();
2247   // <builtin-type> ::= Da  # dependent auto
2248   if (D.isNull())
2249     Out << "Da";
2250   else
2251     mangleType(D);
2252 }
2253
2254 void CXXNameMangler::mangleType(const AtomicType *T) {
2255   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
2256   // (Until there's a standardized mangling...)
2257   Out << "U7_Atomic";
2258   mangleType(T->getValueType());
2259 }
2260
2261 void CXXNameMangler::mangleIntegerLiteral(QualType T,
2262                                           const llvm::APSInt &Value) {
2263   //  <expr-primary> ::= L <type> <value number> E # integer literal
2264   Out << 'L';
2265
2266   mangleType(T);
2267   if (T->isBooleanType()) {
2268     // Boolean values are encoded as 0/1.
2269     Out << (Value.getBoolValue() ? '1' : '0');
2270   } else {
2271     mangleNumber(Value);
2272   }
2273   Out << 'E';
2274
2275 }
2276
2277 /// Mangles a member expression.
2278 void CXXNameMangler::mangleMemberExpr(const Expr *base,
2279                                       bool isArrow,
2280                                       NestedNameSpecifier *qualifier,
2281                                       NamedDecl *firstQualifierLookup,
2282                                       DeclarationName member,
2283                                       unsigned arity) {
2284   // <expression> ::= dt <expression> <unresolved-name>
2285   //              ::= pt <expression> <unresolved-name>
2286   if (base) {
2287     if (base->isImplicitCXXThis()) {
2288       // Note: GCC mangles member expressions to the implicit 'this' as
2289       // *this., whereas we represent them as this->. The Itanium C++ ABI
2290       // does not specify anything here, so we follow GCC.
2291       Out << "dtdefpT";
2292     } else {
2293       Out << (isArrow ? "pt" : "dt");
2294       mangleExpression(base);
2295     }
2296   }
2297   mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2298 }
2299
2300 /// Look at the callee of the given call expression and determine if
2301 /// it's a parenthesized id-expression which would have triggered ADL
2302 /// otherwise.
2303 static bool isParenthesizedADLCallee(const CallExpr *call) {
2304   const Expr *callee = call->getCallee();
2305   const Expr *fn = callee->IgnoreParens();
2306
2307   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
2308   // too, but for those to appear in the callee, it would have to be
2309   // parenthesized.
2310   if (callee == fn) return false;
2311
2312   // Must be an unresolved lookup.
2313   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2314   if (!lookup) return false;
2315
2316   assert(!lookup->requiresADL());
2317
2318   // Must be an unqualified lookup.
2319   if (lookup->getQualifier()) return false;
2320
2321   // Must not have found a class member.  Note that if one is a class
2322   // member, they're all class members.
2323   if (lookup->getNumDecls() > 0 &&
2324       (*lookup->decls_begin())->isCXXClassMember())
2325     return false;
2326
2327   // Otherwise, ADL would have been triggered.
2328   return true;
2329 }
2330
2331 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2332   // <expression> ::= <unary operator-name> <expression>
2333   //              ::= <binary operator-name> <expression> <expression>
2334   //              ::= <trinary operator-name> <expression> <expression> <expression>
2335   //              ::= cv <type> expression           # conversion with one argument
2336   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2337   //              ::= st <type>                      # sizeof (a type)
2338   //              ::= at <type>                      # alignof (a type)
2339   //              ::= <template-param>
2340   //              ::= <function-param>
2341   //              ::= sr <type> <unqualified-name>                   # dependent name
2342   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
2343   //              ::= ds <expression> <expression>                   # expr.*expr
2344   //              ::= sZ <template-param>                            # size of a parameter pack
2345   //              ::= sZ <function-param>    # size of a function parameter pack
2346   //              ::= <expr-primary>
2347   // <expr-primary> ::= L <type> <value number> E    # integer literal
2348   //                ::= L <type <value float> E      # floating literal
2349   //                ::= L <mangled-name> E           # external name
2350   //                ::= fpT                          # 'this' expression
2351   QualType ImplicitlyConvertedToType;
2352   
2353 recurse:
2354   switch (E->getStmtClass()) {
2355   case Expr::NoStmtClass:
2356 #define ABSTRACT_STMT(Type)
2357 #define EXPR(Type, Base)
2358 #define STMT(Type, Base) \
2359   case Expr::Type##Class:
2360 #include "clang/AST/StmtNodes.inc"
2361     // fallthrough
2362
2363   // These all can only appear in local or variable-initialization
2364   // contexts and so should never appear in a mangling.
2365   case Expr::AddrLabelExprClass:
2366   case Expr::DesignatedInitExprClass:
2367   case Expr::ImplicitValueInitExprClass:
2368   case Expr::ParenListExprClass:
2369   case Expr::LambdaExprClass:
2370     llvm_unreachable("unexpected statement kind");
2371
2372   // FIXME: invent manglings for all these.
2373   case Expr::BlockExprClass:
2374   case Expr::CXXPseudoDestructorExprClass:
2375   case Expr::ChooseExprClass:
2376   case Expr::CompoundLiteralExprClass:
2377   case Expr::ExtVectorElementExprClass:
2378   case Expr::GenericSelectionExprClass:
2379   case Expr::ObjCEncodeExprClass:
2380   case Expr::ObjCIsaExprClass:
2381   case Expr::ObjCIvarRefExprClass:
2382   case Expr::ObjCMessageExprClass:
2383   case Expr::ObjCPropertyRefExprClass:
2384   case Expr::ObjCProtocolExprClass:
2385   case Expr::ObjCSelectorExprClass:
2386   case Expr::ObjCStringLiteralClass:
2387   case Expr::ObjCBoxedExprClass:
2388   case Expr::ObjCArrayLiteralClass:
2389   case Expr::ObjCDictionaryLiteralClass:
2390   case Expr::ObjCSubscriptRefExprClass:
2391   case Expr::ObjCIndirectCopyRestoreExprClass:
2392   case Expr::OffsetOfExprClass:
2393   case Expr::PredefinedExprClass:
2394   case Expr::ShuffleVectorExprClass:
2395   case Expr::StmtExprClass:
2396   case Expr::UnaryTypeTraitExprClass:
2397   case Expr::BinaryTypeTraitExprClass:
2398   case Expr::TypeTraitExprClass:
2399   case Expr::ArrayTypeTraitExprClass:
2400   case Expr::ExpressionTraitExprClass:
2401   case Expr::VAArgExprClass:
2402   case Expr::CXXUuidofExprClass:
2403   case Expr::CUDAKernelCallExprClass:
2404   case Expr::AsTypeExprClass:
2405   case Expr::PseudoObjectExprClass:
2406   case Expr::AtomicExprClass:
2407   {
2408     // As bad as this diagnostic is, it's better than crashing.
2409     DiagnosticsEngine &Diags = Context.getDiags();
2410     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2411                                      "cannot yet mangle expression type %0");
2412     Diags.Report(E->getExprLoc(), DiagID)
2413       << E->getStmtClassName() << E->getSourceRange();
2414     break;
2415   }
2416
2417   // Even gcc-4.5 doesn't mangle this.
2418   case Expr::BinaryConditionalOperatorClass: {
2419     DiagnosticsEngine &Diags = Context.getDiags();
2420     unsigned DiagID =
2421       Diags.getCustomDiagID(DiagnosticsEngine::Error,
2422                 "?: operator with omitted middle operand cannot be mangled");
2423     Diags.Report(E->getExprLoc(), DiagID)
2424       << E->getStmtClassName() << E->getSourceRange();
2425     break;
2426   }
2427
2428   // These are used for internal purposes and cannot be meaningfully mangled.
2429   case Expr::OpaqueValueExprClass:
2430     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2431
2432   case Expr::InitListExprClass: {
2433     // Proposal by Jason Merrill, 2012-01-03
2434     Out << "il";
2435     const InitListExpr *InitList = cast<InitListExpr>(E);
2436     for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2437       mangleExpression(InitList->getInit(i));
2438     Out << "E";
2439     break;
2440   }
2441
2442   case Expr::CXXDefaultArgExprClass:
2443     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2444     break;
2445
2446   case Expr::SubstNonTypeTemplateParmExprClass:
2447     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2448                      Arity);
2449     break;
2450
2451   case Expr::UserDefinedLiteralClass:
2452     // We follow g++'s approach of mangling a UDL as a call to the literal
2453     // operator.
2454   case Expr::CXXMemberCallExprClass: // fallthrough
2455   case Expr::CallExprClass: {
2456     const CallExpr *CE = cast<CallExpr>(E);
2457
2458     // <expression> ::= cp <simple-id> <expression>* E
2459     // We use this mangling only when the call would use ADL except
2460     // for being parenthesized.  Per discussion with David
2461     // Vandervoorde, 2011.04.25.
2462     if (isParenthesizedADLCallee(CE)) {
2463       Out << "cp";
2464       // The callee here is a parenthesized UnresolvedLookupExpr with
2465       // no qualifier and should always get mangled as a <simple-id>
2466       // anyway.
2467
2468     // <expression> ::= cl <expression>* E
2469     } else {
2470       Out << "cl";
2471     }
2472
2473     mangleExpression(CE->getCallee(), CE->getNumArgs());
2474     for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2475       mangleExpression(CE->getArg(I));
2476     Out << 'E';
2477     break;
2478   }
2479
2480   case Expr::CXXNewExprClass: {
2481     const CXXNewExpr *New = cast<CXXNewExpr>(E);
2482     if (New->isGlobalNew()) Out << "gs";
2483     Out << (New->isArray() ? "na" : "nw");
2484     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2485            E = New->placement_arg_end(); I != E; ++I)
2486       mangleExpression(*I);
2487     Out << '_';
2488     mangleType(New->getAllocatedType());
2489     if (New->hasInitializer()) {
2490       // Proposal by Jason Merrill, 2012-01-03
2491       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2492         Out << "il";
2493       else
2494         Out << "pi";
2495       const Expr *Init = New->getInitializer();
2496       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2497         // Directly inline the initializers.
2498         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2499                                                   E = CCE->arg_end();
2500              I != E; ++I)
2501           mangleExpression(*I);
2502       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2503         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2504           mangleExpression(PLE->getExpr(i));
2505       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2506                  isa<InitListExpr>(Init)) {
2507         // Only take InitListExprs apart for list-initialization.
2508         const InitListExpr *InitList = cast<InitListExpr>(Init);
2509         for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2510           mangleExpression(InitList->getInit(i));
2511       } else
2512         mangleExpression(Init);
2513     }
2514     Out << 'E';
2515     break;
2516   }
2517
2518   case Expr::MemberExprClass: {
2519     const MemberExpr *ME = cast<MemberExpr>(E);
2520     mangleMemberExpr(ME->getBase(), ME->isArrow(),
2521                      ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2522                      Arity);
2523     break;
2524   }
2525
2526   case Expr::UnresolvedMemberExprClass: {
2527     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2528     mangleMemberExpr(ME->getBase(), ME->isArrow(),
2529                      ME->getQualifier(), 0, ME->getMemberName(),
2530                      Arity);
2531     if (ME->hasExplicitTemplateArgs())
2532       mangleTemplateArgs(ME->getExplicitTemplateArgs());
2533     break;
2534   }
2535
2536   case Expr::CXXDependentScopeMemberExprClass: {
2537     const CXXDependentScopeMemberExpr *ME
2538       = cast<CXXDependentScopeMemberExpr>(E);
2539     mangleMemberExpr(ME->getBase(), ME->isArrow(),
2540                      ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2541                      ME->getMember(), Arity);
2542     if (ME->hasExplicitTemplateArgs())
2543       mangleTemplateArgs(ME->getExplicitTemplateArgs());
2544     break;
2545   }
2546
2547   case Expr::UnresolvedLookupExprClass: {
2548     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2549     mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2550
2551     // All the <unresolved-name> productions end in a
2552     // base-unresolved-name, where <template-args> are just tacked
2553     // onto the end.
2554     if (ULE->hasExplicitTemplateArgs())
2555       mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2556     break;
2557   }
2558
2559   case Expr::CXXUnresolvedConstructExprClass: {
2560     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2561     unsigned N = CE->arg_size();
2562
2563     Out << "cv";
2564     mangleType(CE->getType());
2565     if (N != 1) Out << '_';
2566     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2567     if (N != 1) Out << 'E';
2568     break;
2569   }
2570
2571   case Expr::CXXTemporaryObjectExprClass:
2572   case Expr::CXXConstructExprClass: {
2573     const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2574     unsigned N = CE->getNumArgs();
2575
2576     // Proposal by Jason Merrill, 2012-01-03
2577     if (CE->isListInitialization())
2578       Out << "tl";
2579     else
2580       Out << "cv";
2581     mangleType(CE->getType());
2582     if (N != 1) Out << '_';
2583     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2584     if (N != 1) Out << 'E';
2585     break;
2586   }
2587
2588   case Expr::CXXScalarValueInitExprClass:
2589     Out <<"cv";
2590     mangleType(E->getType());
2591     Out <<"_E";
2592     break;
2593
2594   case Expr::CXXNoexceptExprClass:
2595     Out << "nx";
2596     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2597     break;
2598
2599   case Expr::UnaryExprOrTypeTraitExprClass: {
2600     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2601     
2602     if (!SAE->isInstantiationDependent()) {
2603       // Itanium C++ ABI:
2604       //   If the operand of a sizeof or alignof operator is not 
2605       //   instantiation-dependent it is encoded as an integer literal 
2606       //   reflecting the result of the operator.
2607       //
2608       //   If the result of the operator is implicitly converted to a known 
2609       //   integer type, that type is used for the literal; otherwise, the type 
2610       //   of std::size_t or std::ptrdiff_t is used.
2611       QualType T = (ImplicitlyConvertedToType.isNull() || 
2612                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2613                                                     : ImplicitlyConvertedToType;
2614       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2615       mangleIntegerLiteral(T, V);
2616       break;
2617     }
2618     
2619     switch(SAE->getKind()) {
2620     case UETT_SizeOf:
2621       Out << 's';
2622       break;
2623     case UETT_AlignOf:
2624       Out << 'a';
2625       break;
2626     case UETT_VecStep:
2627       DiagnosticsEngine &Diags = Context.getDiags();
2628       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2629                                      "cannot yet mangle vec_step expression");
2630       Diags.Report(DiagID);
2631       return;
2632     }
2633     if (SAE->isArgumentType()) {
2634       Out << 't';
2635       mangleType(SAE->getArgumentType());
2636     } else {
2637       Out << 'z';
2638       mangleExpression(SAE->getArgumentExpr());
2639     }
2640     break;
2641   }
2642
2643   case Expr::CXXThrowExprClass: {
2644     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
2645
2646     // Proposal from David Vandervoorde, 2010.06.30
2647     if (TE->getSubExpr()) {
2648       Out << "tw";
2649       mangleExpression(TE->getSubExpr());
2650     } else {
2651       Out << "tr";
2652     }
2653     break;
2654   }
2655
2656   case Expr::CXXTypeidExprClass: {
2657     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
2658
2659     // Proposal from David Vandervoorde, 2010.06.30
2660     if (TIE->isTypeOperand()) {
2661       Out << "ti";
2662       mangleType(TIE->getTypeOperand());
2663     } else {
2664       Out << "te";
2665       mangleExpression(TIE->getExprOperand());
2666     }
2667     break;
2668   }
2669
2670   case Expr::CXXDeleteExprClass: {
2671     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
2672
2673     // Proposal from David Vandervoorde, 2010.06.30
2674     if (DE->isGlobalDelete()) Out << "gs";
2675     Out << (DE->isArrayForm() ? "da" : "dl");
2676     mangleExpression(DE->getArgument());
2677     break;
2678   }
2679
2680   case Expr::UnaryOperatorClass: {
2681     const UnaryOperator *UO = cast<UnaryOperator>(E);
2682     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2683                        /*Arity=*/1);
2684     mangleExpression(UO->getSubExpr());
2685     break;
2686   }
2687
2688   case Expr::ArraySubscriptExprClass: {
2689     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2690
2691     // Array subscript is treated as a syntactically weird form of
2692     // binary operator.
2693     Out << "ix";
2694     mangleExpression(AE->getLHS());
2695     mangleExpression(AE->getRHS());
2696     break;
2697   }
2698
2699   case Expr::CompoundAssignOperatorClass: // fallthrough
2700   case Expr::BinaryOperatorClass: {
2701     const BinaryOperator *BO = cast<BinaryOperator>(E);
2702     if (BO->getOpcode() == BO_PtrMemD)
2703       Out << "ds";
2704     else
2705       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2706                          /*Arity=*/2);
2707     mangleExpression(BO->getLHS());
2708     mangleExpression(BO->getRHS());
2709     break;
2710   }
2711
2712   case Expr::ConditionalOperatorClass: {
2713     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2714     mangleOperatorName(OO_Conditional, /*Arity=*/3);
2715     mangleExpression(CO->getCond());
2716     mangleExpression(CO->getLHS(), Arity);
2717     mangleExpression(CO->getRHS(), Arity);
2718     break;
2719   }
2720
2721   case Expr::ImplicitCastExprClass: {
2722     ImplicitlyConvertedToType = E->getType();
2723     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2724     goto recurse;
2725   }
2726       
2727   case Expr::ObjCBridgedCastExprClass: {
2728     // Mangle ownership casts as a vendor extended operator __bridge, 
2729     // __bridge_transfer, or __bridge_retain.
2730     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2731     Out << "v1U" << Kind.size() << Kind;
2732   }
2733   // Fall through to mangle the cast itself.
2734       
2735   case Expr::CStyleCastExprClass:
2736   case Expr::CXXStaticCastExprClass:
2737   case Expr::CXXDynamicCastExprClass:
2738   case Expr::CXXReinterpretCastExprClass:
2739   case Expr::CXXConstCastExprClass:
2740   case Expr::CXXFunctionalCastExprClass: {
2741     const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2742     Out << "cv";
2743     mangleType(ECE->getType());
2744     mangleExpression(ECE->getSubExpr());
2745     break;
2746   }
2747
2748   case Expr::CXXOperatorCallExprClass: {
2749     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2750     unsigned NumArgs = CE->getNumArgs();
2751     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2752     // Mangle the arguments.
2753     for (unsigned i = 0; i != NumArgs; ++i)
2754       mangleExpression(CE->getArg(i));
2755     break;
2756   }
2757
2758   case Expr::ParenExprClass:
2759     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2760     break;
2761
2762   case Expr::DeclRefExprClass: {
2763     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2764
2765     switch (D->getKind()) {
2766     default:
2767       //  <expr-primary> ::= L <mangled-name> E # external name
2768       Out << 'L';
2769       mangle(D, "_Z");
2770       Out << 'E';
2771       break;
2772
2773     case Decl::ParmVar:
2774       mangleFunctionParam(cast<ParmVarDecl>(D));
2775       break;
2776
2777     case Decl::EnumConstant: {
2778       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2779       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2780       break;
2781     }
2782
2783     case Decl::NonTypeTemplateParm: {
2784       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2785       mangleTemplateParameter(PD->getIndex());
2786       break;
2787     }
2788
2789     }
2790
2791     break;
2792   }
2793
2794   case Expr::SubstNonTypeTemplateParmPackExprClass:
2795     // FIXME: not clear how to mangle this!
2796     // template <unsigned N...> class A {
2797     //   template <class U...> void foo(U (&x)[N]...);
2798     // };
2799     Out << "_SUBSTPACK_";
2800     break;
2801
2802   case Expr::FunctionParmPackExprClass: {
2803     // FIXME: not clear how to mangle this!
2804     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
2805     Out << "v110_SUBSTPACK";
2806     mangleFunctionParam(FPPE->getParameterPack());
2807     break;
2808   }
2809
2810   case Expr::DependentScopeDeclRefExprClass: {
2811     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2812     mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
2813
2814     // All the <unresolved-name> productions end in a
2815     // base-unresolved-name, where <template-args> are just tacked
2816     // onto the end.
2817     if (DRE->hasExplicitTemplateArgs())
2818       mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2819     break;
2820   }
2821
2822   case Expr::CXXBindTemporaryExprClass:
2823     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2824     break;
2825
2826   case Expr::ExprWithCleanupsClass:
2827     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2828     break;
2829
2830   case Expr::FloatingLiteralClass: {
2831     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2832     Out << 'L';
2833     mangleType(FL->getType());
2834     mangleFloat(FL->getValue());
2835     Out << 'E';
2836     break;
2837   }
2838
2839   case Expr::CharacterLiteralClass:
2840     Out << 'L';
2841     mangleType(E->getType());
2842     Out << cast<CharacterLiteral>(E)->getValue();
2843     Out << 'E';
2844     break;
2845
2846   // FIXME. __objc_yes/__objc_no are mangled same as true/false
2847   case Expr::ObjCBoolLiteralExprClass:
2848     Out << "Lb";
2849     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2850     Out << 'E';
2851     break;
2852   
2853   case Expr::CXXBoolLiteralExprClass:
2854     Out << "Lb";
2855     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2856     Out << 'E';
2857     break;
2858
2859   case Expr::IntegerLiteralClass: {
2860     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2861     if (E->getType()->isSignedIntegerType())
2862       Value.setIsSigned(true);
2863     mangleIntegerLiteral(E->getType(), Value);
2864     break;
2865   }
2866
2867   case Expr::ImaginaryLiteralClass: {
2868     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2869     // Mangle as if a complex literal.
2870     // Proposal from David Vandevoorde, 2010.06.30.
2871     Out << 'L';
2872     mangleType(E->getType());
2873     if (const FloatingLiteral *Imag =
2874           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2875       // Mangle a floating-point zero of the appropriate type.
2876       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2877       Out << '_';
2878       mangleFloat(Imag->getValue());
2879     } else {
2880       Out << "0_";
2881       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2882       if (IE->getSubExpr()->getType()->isSignedIntegerType())
2883         Value.setIsSigned(true);
2884       mangleNumber(Value);
2885     }
2886     Out << 'E';
2887     break;
2888   }
2889
2890   case Expr::StringLiteralClass: {
2891     // Revised proposal from David Vandervoorde, 2010.07.15.
2892     Out << 'L';
2893     assert(isa<ConstantArrayType>(E->getType()));
2894     mangleType(E->getType());
2895     Out << 'E';
2896     break;
2897   }
2898
2899   case Expr::GNUNullExprClass:
2900     // FIXME: should this really be mangled the same as nullptr?
2901     // fallthrough
2902
2903   case Expr::CXXNullPtrLiteralExprClass: {
2904     // Proposal from David Vandervoorde, 2010.06.30, as
2905     // modified by ABI list discussion.
2906     Out << "LDnE";
2907     break;
2908   }
2909       
2910   case Expr::PackExpansionExprClass:
2911     Out << "sp";
2912     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
2913     break;
2914       
2915   case Expr::SizeOfPackExprClass: {
2916     Out << "sZ";
2917     const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
2918     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
2919       mangleTemplateParameter(TTP->getIndex());
2920     else if (const NonTypeTemplateParmDecl *NTTP
2921                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
2922       mangleTemplateParameter(NTTP->getIndex());
2923     else if (const TemplateTemplateParmDecl *TempTP
2924                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
2925       mangleTemplateParameter(TempTP->getIndex());
2926     else
2927       mangleFunctionParam(cast<ParmVarDecl>(Pack));
2928     break;
2929   }
2930       
2931   case Expr::MaterializeTemporaryExprClass: {
2932     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
2933     break;
2934   }
2935       
2936   case Expr::CXXThisExprClass:
2937     Out << "fpT";
2938     break;
2939   }
2940 }
2941
2942 /// Mangle an expression which refers to a parameter variable.
2943 ///
2944 /// <expression>     ::= <function-param>
2945 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
2946 /// <function-param> ::= fp <top-level CV-qualifiers>
2947 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
2948 /// <function-param> ::= fL <L-1 non-negative number>
2949 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
2950 /// <function-param> ::= fL <L-1 non-negative number>
2951 ///                      p <top-level CV-qualifiers>
2952 ///                      <I-1 non-negative number> _         # L > 0, I > 0
2953 ///
2954 /// L is the nesting depth of the parameter, defined as 1 if the
2955 /// parameter comes from the innermost function prototype scope
2956 /// enclosing the current context, 2 if from the next enclosing
2957 /// function prototype scope, and so on, with one special case: if
2958 /// we've processed the full parameter clause for the innermost
2959 /// function type, then L is one less.  This definition conveniently
2960 /// makes it irrelevant whether a function's result type was written
2961 /// trailing or leading, but is otherwise overly complicated; the
2962 /// numbering was first designed without considering references to
2963 /// parameter in locations other than return types, and then the
2964 /// mangling had to be generalized without changing the existing
2965 /// manglings.
2966 ///
2967 /// I is the zero-based index of the parameter within its parameter
2968 /// declaration clause.  Note that the original ABI document describes
2969 /// this using 1-based ordinals.
2970 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
2971   unsigned parmDepth = parm->getFunctionScopeDepth();
2972   unsigned parmIndex = parm->getFunctionScopeIndex();
2973
2974   // Compute 'L'.
2975   // parmDepth does not include the declaring function prototype.
2976   // FunctionTypeDepth does account for that.
2977   assert(parmDepth < FunctionTypeDepth.getDepth());
2978   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
2979   if (FunctionTypeDepth.isInResultType())
2980     nestingDepth--;
2981
2982   if (nestingDepth == 0) {
2983     Out << "fp";
2984   } else {
2985     Out << "fL" << (nestingDepth - 1) << 'p';
2986   }
2987
2988   // Top-level qualifiers.  We don't have to worry about arrays here,
2989   // because parameters declared as arrays should already have been
2990   // transformed to have pointer type. FIXME: apparently these don't
2991   // get mangled if used as an rvalue of a known non-class type?
2992   assert(!parm->getType()->isArrayType()
2993          && "parameter's type is still an array type?");
2994   mangleQualifiers(parm->getType().getQualifiers());
2995
2996   // Parameter index.
2997   if (parmIndex != 0) {
2998     Out << (parmIndex - 1);
2999   }
3000   Out << '_';
3001 }
3002
3003 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3004   // <ctor-dtor-name> ::= C1  # complete object constructor
3005   //                  ::= C2  # base object constructor
3006   //                  ::= C3  # complete object allocating constructor
3007   //
3008   switch (T) {
3009   case Ctor_Complete:
3010     Out << "C1";
3011     break;
3012   case Ctor_Base:
3013     Out << "C2";
3014     break;
3015   case Ctor_CompleteAllocating:
3016     Out << "C3";
3017     break;
3018   }
3019 }
3020
3021 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3022   // <ctor-dtor-name> ::= D0  # deleting destructor
3023   //                  ::= D1  # complete object destructor
3024   //                  ::= D2  # base object destructor
3025   //
3026   switch (T) {
3027   case Dtor_Deleting:
3028     Out << "D0";
3029     break;
3030   case Dtor_Complete:
3031     Out << "D1";
3032     break;
3033   case Dtor_Base:
3034     Out << "D2";
3035     break;
3036   }
3037 }
3038
3039 void CXXNameMangler::mangleTemplateArgs(
3040                           const ASTTemplateArgumentListInfo &TemplateArgs) {
3041   // <template-args> ::= I <template-arg>+ E
3042   Out << 'I';
3043   for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3044     mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3045   Out << 'E';
3046 }
3047
3048 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3049   // <template-args> ::= I <template-arg>+ E
3050   Out << 'I';
3051   for (unsigned i = 0, e = AL.size(); i != e; ++i)
3052     mangleTemplateArg(AL[i]);
3053   Out << 'E';
3054 }
3055
3056 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3057                                         unsigned NumTemplateArgs) {
3058   // <template-args> ::= I <template-arg>+ E
3059   Out << 'I';
3060   for (unsigned i = 0; i != NumTemplateArgs; ++i)
3061     mangleTemplateArg(TemplateArgs[i]);
3062   Out << 'E';
3063 }
3064
3065 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3066   // <template-arg> ::= <type>              # type or template
3067   //                ::= X <expression> E    # expression
3068   //                ::= <expr-primary>      # simple expressions
3069   //                ::= J <template-arg>* E # argument pack
3070   //                ::= sp <expression>     # pack expansion of (C++0x)  
3071   if (!A.isInstantiationDependent() || A.isDependent())
3072     A = Context.getASTContext().getCanonicalTemplateArgument(A);
3073   
3074   switch (A.getKind()) {
3075   case TemplateArgument::Null:
3076     llvm_unreachable("Cannot mangle NULL template argument");
3077       
3078   case TemplateArgument::Type:
3079     mangleType(A.getAsType());
3080     break;
3081   case TemplateArgument::Template:
3082     // This is mangled as <type>.
3083     mangleType(A.getAsTemplate());
3084     break;
3085   case TemplateArgument::TemplateExpansion:
3086     // <type>  ::= Dp <type>          # pack expansion (C++0x)
3087     Out << "Dp";
3088     mangleType(A.getAsTemplateOrTemplatePattern());
3089     break;
3090   case TemplateArgument::Expression: {
3091     // It's possible to end up with a DeclRefExpr here in certain
3092     // dependent cases, in which case we should mangle as a
3093     // declaration.
3094     const Expr *E = A.getAsExpr()->IgnoreParens();
3095     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3096       const ValueDecl *D = DRE->getDecl();
3097       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3098         Out << "L";
3099         mangle(D, "_Z");
3100         Out << 'E';
3101         break;
3102       }
3103     }
3104     
3105     Out << 'X';
3106     mangleExpression(E);
3107     Out << 'E';
3108     break;
3109   }
3110   case TemplateArgument::Integral:
3111     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3112     break;
3113   case TemplateArgument::Declaration: {
3114     //  <expr-primary> ::= L <mangled-name> E # external name
3115     // Clang produces AST's where pointer-to-member-function expressions
3116     // and pointer-to-function expressions are represented as a declaration not
3117     // an expression. We compensate for it here to produce the correct mangling.
3118     ValueDecl *D = A.getAsDecl();
3119     bool compensateMangling = !A.isDeclForReferenceParam();
3120     if (compensateMangling) {
3121       Out << 'X';
3122       mangleOperatorName(OO_Amp, 1);
3123     }
3124
3125     Out << 'L';
3126     // References to external entities use the mangled name; if the name would
3127     // not normally be manged then mangle it as unqualified.
3128     //
3129     // FIXME: The ABI specifies that external names here should have _Z, but
3130     // gcc leaves this off.
3131     if (compensateMangling)
3132       mangle(D, "_Z");
3133     else
3134       mangle(D, "Z");
3135     Out << 'E';
3136
3137     if (compensateMangling)
3138       Out << 'E';
3139
3140     break;
3141   }
3142   case TemplateArgument::NullPtr: {
3143     //  <expr-primary> ::= L <type> 0 E
3144     Out << 'L';
3145     mangleType(A.getNullPtrType());
3146     Out << "0E";
3147     break;
3148   }
3149   case TemplateArgument::Pack: {
3150     // Note: proposal by Mike Herrick on 12/20/10
3151     Out << 'J';
3152     for (TemplateArgument::pack_iterator PA = A.pack_begin(), 
3153                                       PAEnd = A.pack_end();
3154          PA != PAEnd; ++PA)
3155       mangleTemplateArg(*PA);
3156     Out << 'E';
3157   }
3158   }
3159 }
3160
3161 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3162   // <template-param> ::= T_    # first template parameter
3163   //                  ::= T <parameter-2 non-negative number> _
3164   if (Index == 0)
3165     Out << "T_";
3166   else
3167     Out << 'T' << (Index - 1) << '_';
3168 }
3169
3170 void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3171   bool result = mangleSubstitution(type);
3172   assert(result && "no existing substitution for type");
3173   (void) result;
3174 }
3175
3176 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3177   bool result = mangleSubstitution(tname);
3178   assert(result && "no existing substitution for template name");
3179   (void) result;
3180 }
3181
3182 // <substitution> ::= S <seq-id> _
3183 //                ::= S_
3184 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3185   // Try one of the standard substitutions first.
3186   if (mangleStandardSubstitution(ND))
3187     return true;
3188
3189   ND = cast<NamedDecl>(ND->getCanonicalDecl());
3190   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3191 }
3192
3193 /// \brief Determine whether the given type has any qualifiers that are
3194 /// relevant for substitutions.
3195 static bool hasMangledSubstitutionQualifiers(QualType T) {
3196   Qualifiers Qs = T.getQualifiers();
3197   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3198 }
3199
3200 bool CXXNameMangler::mangleSubstitution(QualType T) {
3201   if (!hasMangledSubstitutionQualifiers(T)) {
3202     if (const RecordType *RT = T->getAs<RecordType>())
3203       return mangleSubstitution(RT->getDecl());
3204   }
3205
3206   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3207
3208   return mangleSubstitution(TypePtr);
3209 }
3210
3211 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3212   if (TemplateDecl *TD = Template.getAsTemplateDecl())
3213     return mangleSubstitution(TD);
3214   
3215   Template = Context.getASTContext().getCanonicalTemplateName(Template);
3216   return mangleSubstitution(
3217                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3218 }
3219
3220 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3221   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3222   if (I == Substitutions.end())
3223     return false;
3224
3225   unsigned SeqID = I->second;
3226   if (SeqID == 0)
3227     Out << "S_";
3228   else {
3229     SeqID--;
3230
3231     // <seq-id> is encoded in base-36, using digits and upper case letters.
3232     char Buffer[10];
3233     char *BufferPtr = llvm::array_endof(Buffer);
3234
3235     if (SeqID == 0) *--BufferPtr = '0';
3236
3237     while (SeqID) {
3238       assert(BufferPtr > Buffer && "Buffer overflow!");
3239
3240       char c = static_cast<char>(SeqID % 36);
3241
3242       *--BufferPtr =  (c < 10 ? '0' + c : 'A' + c - 10);
3243       SeqID /= 36;
3244     }
3245
3246     Out << 'S'
3247         << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3248         << '_';
3249   }
3250
3251   return true;
3252 }
3253
3254 static bool isCharType(QualType T) {
3255   if (T.isNull())
3256     return false;
3257
3258   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3259     T->isSpecificBuiltinType(BuiltinType::Char_U);
3260 }
3261
3262 /// isCharSpecialization - Returns whether a given type is a template
3263 /// specialization of a given name with a single argument of type char.
3264 static bool isCharSpecialization(QualType T, const char *Name) {
3265   if (T.isNull())
3266     return false;
3267
3268   const RecordType *RT = T->getAs<RecordType>();
3269   if (!RT)
3270     return false;
3271
3272   const ClassTemplateSpecializationDecl *SD =
3273     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3274   if (!SD)
3275     return false;
3276
3277   if (!isStdNamespace(getEffectiveDeclContext(SD)))
3278     return false;
3279
3280   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3281   if (TemplateArgs.size() != 1)
3282     return false;
3283
3284   if (!isCharType(TemplateArgs[0].getAsType()))
3285     return false;
3286
3287   return SD->getIdentifier()->getName() == Name;
3288 }
3289
3290 template <std::size_t StrLen>
3291 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3292                                        const char (&Str)[StrLen]) {
3293   if (!SD->getIdentifier()->isStr(Str))
3294     return false;
3295
3296   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3297   if (TemplateArgs.size() != 2)
3298     return false;
3299
3300   if (!isCharType(TemplateArgs[0].getAsType()))
3301     return false;
3302
3303   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3304     return false;
3305
3306   return true;
3307 }
3308
3309 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3310   // <substitution> ::= St # ::std::
3311   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3312     if (isStd(NS)) {
3313       Out << "St";
3314       return true;
3315     }
3316   }
3317
3318   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3319     if (!isStdNamespace(getEffectiveDeclContext(TD)))
3320       return false;
3321
3322     // <substitution> ::= Sa # ::std::allocator
3323     if (TD->getIdentifier()->isStr("allocator")) {
3324       Out << "Sa";
3325       return true;
3326     }
3327
3328     // <<substitution> ::= Sb # ::std::basic_string
3329     if (TD->getIdentifier()->isStr("basic_string")) {
3330       Out << "Sb";
3331       return true;
3332     }
3333   }
3334
3335   if (const ClassTemplateSpecializationDecl *SD =
3336         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3337     if (!isStdNamespace(getEffectiveDeclContext(SD)))
3338       return false;
3339
3340     //    <substitution> ::= Ss # ::std::basic_string<char,
3341     //                            ::std::char_traits<char>,
3342     //                            ::std::allocator<char> >
3343     if (SD->getIdentifier()->isStr("basic_string")) {
3344       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3345
3346       if (TemplateArgs.size() != 3)
3347         return false;
3348
3349       if (!isCharType(TemplateArgs[0].getAsType()))
3350         return false;
3351
3352       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3353         return false;
3354
3355       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3356         return false;
3357
3358       Out << "Ss";
3359       return true;
3360     }
3361
3362     //    <substitution> ::= Si # ::std::basic_istream<char,
3363     //                            ::std::char_traits<char> >
3364     if (isStreamCharSpecialization(SD, "basic_istream")) {
3365       Out << "Si";
3366       return true;
3367     }
3368
3369     //    <substitution> ::= So # ::std::basic_ostream<char,
3370     //                            ::std::char_traits<char> >
3371     if (isStreamCharSpecialization(SD, "basic_ostream")) {
3372       Out << "So";
3373       return true;
3374     }
3375
3376     //    <substitution> ::= Sd # ::std::basic_iostream<char,
3377     //                            ::std::char_traits<char> >
3378     if (isStreamCharSpecialization(SD, "basic_iostream")) {
3379       Out << "Sd";
3380       return true;
3381     }
3382   }
3383   return false;
3384 }
3385
3386 void CXXNameMangler::addSubstitution(QualType T) {
3387   if (!hasMangledSubstitutionQualifiers(T)) {
3388     if (const RecordType *RT = T->getAs<RecordType>()) {
3389       addSubstitution(RT->getDecl());
3390       return;
3391     }
3392   }
3393
3394   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3395   addSubstitution(TypePtr);
3396 }
3397
3398 void CXXNameMangler::addSubstitution(TemplateName Template) {
3399   if (TemplateDecl *TD = Template.getAsTemplateDecl())
3400     return addSubstitution(TD);
3401   
3402   Template = Context.getASTContext().getCanonicalTemplateName(Template);
3403   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3404 }
3405
3406 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3407   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3408   Substitutions[Ptr] = SeqID++;
3409 }
3410
3411 //
3412
3413 /// \brief Mangles the name of the declaration D and emits that name to the
3414 /// given output stream.
3415 ///
3416 /// If the declaration D requires a mangled name, this routine will emit that
3417 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3418 /// and this routine will return false. In this case, the caller should just
3419 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
3420 /// name.
3421 void ItaniumMangleContext::mangleName(const NamedDecl *D,
3422                                       raw_ostream &Out) {
3423   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3424           "Invalid mangleName() call, argument is not a variable or function!");
3425   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3426          "Invalid mangleName() call on 'structor decl!");
3427
3428   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3429                                  getASTContext().getSourceManager(),
3430                                  "Mangling declaration");
3431
3432   CXXNameMangler Mangler(*this, Out, D);
3433   return Mangler.mangle(D);
3434 }
3435
3436 void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3437                                          CXXCtorType Type,
3438                                          raw_ostream &Out) {
3439   CXXNameMangler Mangler(*this, Out, D, Type);
3440   Mangler.mangle(D);
3441 }
3442
3443 void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3444                                          CXXDtorType Type,
3445                                          raw_ostream &Out) {
3446   CXXNameMangler Mangler(*this, Out, D, Type);
3447   Mangler.mangle(D);
3448 }
3449
3450 void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3451                                        const ThunkInfo &Thunk,
3452                                        raw_ostream &Out) {
3453   //  <special-name> ::= T <call-offset> <base encoding>
3454   //                      # base is the nominal target function of thunk
3455   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3456   //                      # base is the nominal target function of thunk
3457   //                      # first call-offset is 'this' adjustment
3458   //                      # second call-offset is result adjustment
3459   
3460   assert(!isa<CXXDestructorDecl>(MD) &&
3461          "Use mangleCXXDtor for destructor decls!");
3462   CXXNameMangler Mangler(*this, Out);
3463   Mangler.getStream() << "_ZT";
3464   if (!Thunk.Return.isEmpty())
3465     Mangler.getStream() << 'c';
3466   
3467   // Mangle the 'this' pointer adjustment.
3468   Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3469   
3470   // Mangle the return pointer adjustment if there is one.
3471   if (!Thunk.Return.isEmpty())
3472     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3473                              Thunk.Return.VBaseOffsetOffset);
3474   
3475   Mangler.mangleFunctionEncoding(MD);
3476 }
3477
3478 void 
3479 ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3480                                          CXXDtorType Type,
3481                                          const ThisAdjustment &ThisAdjustment,
3482                                          raw_ostream &Out) {
3483   //  <special-name> ::= T <call-offset> <base encoding>
3484   //                      # base is the nominal target function of thunk
3485   CXXNameMangler Mangler(*this, Out, DD, Type);
3486   Mangler.getStream() << "_ZT";
3487
3488   // Mangle the 'this' pointer adjustment.
3489   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 
3490                            ThisAdjustment.VCallOffsetOffset);
3491
3492   Mangler.mangleFunctionEncoding(DD);
3493 }
3494
3495 /// mangleGuardVariable - Returns the mangled name for a guard variable
3496 /// for the passed in VarDecl.
3497 void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
3498                                                       raw_ostream &Out) {
3499   //  <special-name> ::= GV <object name>       # Guard variable for one-time
3500   //                                            # initialization
3501   CXXNameMangler Mangler(*this, Out);
3502   Mangler.getStream() << "_ZGV";
3503   Mangler.mangleName(D);
3504 }
3505
3506 void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3507                                                     raw_ostream &Out) {
3508   // We match the GCC mangling here.
3509   //  <special-name> ::= GR <object name>
3510   CXXNameMangler Mangler(*this, Out);
3511   Mangler.getStream() << "_ZGR";
3512   Mangler.mangleName(D);
3513 }
3514
3515 void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3516                                            raw_ostream &Out) {
3517   // <special-name> ::= TV <type>  # virtual table
3518   CXXNameMangler Mangler(*this, Out);
3519   Mangler.getStream() << "_ZTV";
3520   Mangler.mangleNameOrStandardSubstitution(RD);
3521 }
3522
3523 void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3524                                         raw_ostream &Out) {
3525   // <special-name> ::= TT <type>  # VTT structure
3526   CXXNameMangler Mangler(*this, Out);
3527   Mangler.getStream() << "_ZTT";
3528   Mangler.mangleNameOrStandardSubstitution(RD);
3529 }
3530
3531 void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3532                                                int64_t Offset,
3533                                                const CXXRecordDecl *Type,
3534                                                raw_ostream &Out) {
3535   // <special-name> ::= TC <type> <offset number> _ <base type>
3536   CXXNameMangler Mangler(*this, Out);
3537   Mangler.getStream() << "_ZTC";
3538   Mangler.mangleNameOrStandardSubstitution(RD);
3539   Mangler.getStream() << Offset;
3540   Mangler.getStream() << '_';
3541   Mangler.mangleNameOrStandardSubstitution(Type);
3542 }
3543
3544 void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3545                                          raw_ostream &Out) {
3546   // <special-name> ::= TI <type>  # typeinfo structure
3547   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3548   CXXNameMangler Mangler(*this, Out);
3549   Mangler.getStream() << "_ZTI";
3550   Mangler.mangleType(Ty);
3551 }
3552
3553 void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3554                                              raw_ostream &Out) {
3555   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
3556   CXXNameMangler Mangler(*this, Out);
3557   Mangler.getStream() << "_ZTS";
3558   Mangler.mangleType(Ty);
3559 }
3560
3561 MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3562                                                  DiagnosticsEngine &Diags) {
3563   return new ItaniumMangleContext(Context, Diags);
3564 }