]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp
Update dialog to version 1.1-20110302.
[FreeBSD/FreeBSD.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/Basic/ABI.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/ErrorHandling.h"
30
31 #define MANGLE_CHECKER 0
32
33 #if MANGLE_CHECKER
34 #include <cxxabi.h>
35 #endif
36
37 using namespace clang;
38
39 namespace {
40
41 static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
42   const DeclContext *DC = dyn_cast<DeclContext>(ND);
43   if (!DC)
44     DC = ND->getDeclContext();
45   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
46     if (isa<FunctionDecl>(DC->getParent()))
47       return dyn_cast<CXXRecordDecl>(DC);
48     DC = DC->getParent();
49   }
50   return 0;
51 }
52
53 static const CXXMethodDecl *getStructor(const CXXMethodDecl *MD) {
54   assert((isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) &&
55          "Passed in decl is not a ctor or dtor!");
56
57   if (const TemplateDecl *TD = MD->getPrimaryTemplate()) {
58     MD = cast<CXXMethodDecl>(TD->getTemplatedDecl());
59
60     assert((isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) &&
61            "Templated decl is not a ctor or dtor!");
62   }
63
64   return MD;
65 }
66
67 static const unsigned UnknownArity = ~0U;
68
69 class ItaniumMangleContext : public MangleContext {
70   llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
71   unsigned Discriminator;
72   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
73   
74 public:
75   explicit ItaniumMangleContext(ASTContext &Context,
76                                 Diagnostic &Diags)
77     : MangleContext(Context, Diags) { }
78
79   uint64_t getAnonymousStructId(const TagDecl *TD) {
80     std::pair<llvm::DenseMap<const TagDecl *,
81       uint64_t>::iterator, bool> Result =
82       AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
83     return Result.first->second;
84   }
85
86   void startNewFunction() {
87     MangleContext::startNewFunction();
88     mangleInitDiscriminator();
89   }
90
91   /// @name Mangler Entry Points
92   /// @{
93
94   bool shouldMangleDeclName(const NamedDecl *D);
95   void mangleName(const NamedDecl *D, llvm::raw_ostream &);
96   void mangleThunk(const CXXMethodDecl *MD,
97                    const ThunkInfo &Thunk,
98                    llvm::raw_ostream &);
99   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
100                           const ThisAdjustment &ThisAdjustment,
101                           llvm::raw_ostream &);
102   void mangleReferenceTemporary(const VarDecl *D,
103                                 llvm::raw_ostream &);
104   void mangleCXXVTable(const CXXRecordDecl *RD,
105                        llvm::raw_ostream &);
106   void mangleCXXVTT(const CXXRecordDecl *RD,
107                     llvm::raw_ostream &);
108   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
109                            const CXXRecordDecl *Type,
110                            llvm::raw_ostream &);
111   void mangleCXXRTTI(QualType T, llvm::raw_ostream &);
112   void mangleCXXRTTIName(QualType T, llvm::raw_ostream &);
113   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
114                      llvm::raw_ostream &);
115   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
116                      llvm::raw_ostream &);
117
118   void mangleItaniumGuardVariable(const VarDecl *D, llvm::raw_ostream &);
119
120   void mangleInitDiscriminator() {
121     Discriminator = 0;
122   }
123
124   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
125     unsigned &discriminator = Uniquifier[ND];
126     if (!discriminator)
127       discriminator = ++Discriminator;
128     if (discriminator == 1)
129       return false;
130     disc = discriminator-2;
131     return true;
132   }
133   /// @}
134 };
135
136 /// CXXNameMangler - Manage the mangling of a single name.
137 class CXXNameMangler {
138   ItaniumMangleContext &Context;
139   llvm::raw_ostream &Out;
140
141   const CXXMethodDecl *Structor;
142   unsigned StructorType;
143
144   /// SeqID - The next subsitution sequence number.
145   unsigned SeqID;
146
147   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
148
149   ASTContext &getASTContext() const { return Context.getASTContext(); }
150
151 public:
152   CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_)
153     : Context(C), Out(Out_), Structor(0), StructorType(0), SeqID(0) { }
154   CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_,
155                  const CXXConstructorDecl *D, CXXCtorType Type)
156     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
157     SeqID(0) { }
158   CXXNameMangler(ItaniumMangleContext &C, llvm::raw_ostream &Out_,
159                  const CXXDestructorDecl *D, CXXDtorType Type)
160     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
161     SeqID(0) { }
162
163 #if MANGLE_CHECKER
164   ~CXXNameMangler() {
165     if (Out.str()[0] == '\01')
166       return;
167
168     int status = 0;
169     char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
170     assert(status == 0 && "Could not demangle mangled name!");
171     free(result);
172   }
173 #endif
174   llvm::raw_ostream &getStream() { return Out; }
175
176   void mangle(const NamedDecl *D, llvm::StringRef Prefix = "_Z");
177   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
178   void mangleNumber(const llvm::APSInt &I);
179   void mangleNumber(int64_t Number);
180   void mangleFloat(const llvm::APFloat &F);
181   void mangleFunctionEncoding(const FunctionDecl *FD);
182   void mangleName(const NamedDecl *ND);
183   void mangleType(QualType T);
184   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
185   
186 private:
187   bool mangleSubstitution(const NamedDecl *ND);
188   bool mangleSubstitution(QualType T);
189   bool mangleSubstitution(TemplateName Template);
190   bool mangleSubstitution(uintptr_t Ptr);
191
192   bool mangleStandardSubstitution(const NamedDecl *ND);
193
194   void addSubstitution(const NamedDecl *ND) {
195     ND = cast<NamedDecl>(ND->getCanonicalDecl());
196
197     addSubstitution(reinterpret_cast<uintptr_t>(ND));
198   }
199   void addSubstitution(QualType T);
200   void addSubstitution(TemplateName Template);
201   void addSubstitution(uintptr_t Ptr);
202
203   void mangleUnresolvedScope(NestedNameSpecifier *Qualifier);
204   void mangleUnresolvedName(NestedNameSpecifier *Qualifier,
205                             DeclarationName Name,
206                             unsigned KnownArity = UnknownArity);
207
208   void mangleName(const TemplateDecl *TD,
209                   const TemplateArgument *TemplateArgs,
210                   unsigned NumTemplateArgs);
211   void mangleUnqualifiedName(const NamedDecl *ND) {
212     mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
213   }
214   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
215                              unsigned KnownArity);
216   void mangleUnscopedName(const NamedDecl *ND);
217   void mangleUnscopedTemplateName(const TemplateDecl *ND);
218   void mangleUnscopedTemplateName(TemplateName);
219   void mangleSourceName(const IdentifierInfo *II);
220   void mangleLocalName(const NamedDecl *ND);
221   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
222                         bool NoFunction=false);
223   void mangleNestedName(const TemplateDecl *TD,
224                         const TemplateArgument *TemplateArgs,
225                         unsigned NumTemplateArgs);
226   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
227   void mangleTemplatePrefix(const TemplateDecl *ND);
228   void mangleTemplatePrefix(TemplateName Template);
229   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
230   void mangleQualifiers(Qualifiers Quals);
231   void mangleRefQualifier(RefQualifierKind RefQualifier);
232
233   void mangleObjCMethodName(const ObjCMethodDecl *MD);
234
235   // Declare manglers for every type class.
236 #define ABSTRACT_TYPE(CLASS, PARENT)
237 #define NON_CANONICAL_TYPE(CLASS, PARENT)
238 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
239 #include "clang/AST/TypeNodes.def"
240
241   void mangleType(const TagType*);
242   void mangleType(TemplateName);
243   void mangleBareFunctionType(const FunctionType *T,
244                               bool MangleReturnType);
245   void mangleNeonVectorType(const VectorType *T);
246
247   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
248   void mangleMemberExpr(const Expr *Base, bool IsArrow,
249                         NestedNameSpecifier *Qualifier,
250                         DeclarationName Name,
251                         unsigned KnownArity);
252   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
253   void mangleCXXCtorType(CXXCtorType T);
254   void mangleCXXDtorType(CXXDtorType T);
255
256   void mangleTemplateArgs(const ExplicitTemplateArgumentList &TemplateArgs);
257   void mangleTemplateArgs(TemplateName Template,
258                           const TemplateArgument *TemplateArgs,
259                           unsigned NumTemplateArgs);  
260   void mangleTemplateArgs(const TemplateParameterList &PL,
261                           const TemplateArgument *TemplateArgs,
262                           unsigned NumTemplateArgs);
263   void mangleTemplateArgs(const TemplateParameterList &PL,
264                           const TemplateArgumentList &AL);
265   void mangleTemplateArg(const NamedDecl *P, const TemplateArgument &A);
266
267   void mangleTemplateParameter(unsigned Index);
268 };
269
270 }
271
272 static bool isInCLinkageSpecification(const Decl *D) {
273   D = D->getCanonicalDecl();
274   for (const DeclContext *DC = D->getDeclContext();
275        !DC->isTranslationUnit(); DC = DC->getParent()) {
276     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
277       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
278   }
279
280   return false;
281 }
282
283 bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
284   // In C, functions with no attributes never need to be mangled. Fastpath them.
285   if (!getASTContext().getLangOptions().CPlusPlus && !D->hasAttrs())
286     return false;
287
288   // Any decl can be declared with __asm("foo") on it, and this takes precedence
289   // over all other naming in the .o file.
290   if (D->hasAttr<AsmLabelAttr>())
291     return true;
292
293   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
294   // (always) as does passing a C++ member function and a function
295   // whose name is not a simple identifier.
296   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
297   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
298              !FD->getDeclName().isIdentifier()))
299     return true;
300
301   // Otherwise, no mangling is done outside C++ mode.
302   if (!getASTContext().getLangOptions().CPlusPlus)
303     return false;
304
305   // Variables at global scope with non-internal linkage are not mangled
306   if (!FD) {
307     const DeclContext *DC = D->getDeclContext();
308     // Check for extern variable declared locally.
309     if (DC->isFunctionOrMethod() && D->hasLinkage())
310       while (!DC->isNamespace() && !DC->isTranslationUnit())
311         DC = DC->getParent();
312     if (DC->isTranslationUnit() && D->getLinkage() != InternalLinkage)
313       return false;
314   }
315
316   // Class members are always mangled.
317   if (D->getDeclContext()->isRecord())
318     return true;
319
320   // C functions and "main" are not mangled.
321   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
322     return false;
323
324   return true;
325 }
326
327 void CXXNameMangler::mangle(const NamedDecl *D, llvm::StringRef Prefix) {
328   // Any decl can be declared with __asm("foo") on it, and this takes precedence
329   // over all other naming in the .o file.
330   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
331     // If we have an asm name, then we use it as the mangling.
332
333     // Adding the prefix can cause problems when one file has a "foo" and
334     // another has a "\01foo". That is known to happen on ELF with the
335     // tricks normally used for producing aliases (PR9177). Fortunately the
336     // llvm mangler on ELF is a nop, so we can just avoid adding the \01
337     // marker.
338     llvm::StringRef UserLabelPrefix =
339       getASTContext().Target.getUserLabelPrefix();
340     if (!UserLabelPrefix.empty())
341       Out << '\01';  // LLVM IR Marker for __asm("foo")
342
343     Out << ALA->getLabel();
344     return;
345   }
346
347   // <mangled-name> ::= _Z <encoding>
348   //            ::= <data name>
349   //            ::= <special-name>
350   Out << Prefix;
351   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
352     mangleFunctionEncoding(FD);
353   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
354     mangleName(VD);
355   else
356     mangleName(cast<FieldDecl>(D));
357 }
358
359 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
360   // <encoding> ::= <function name> <bare-function-type>
361   mangleName(FD);
362
363   // Don't mangle in the type if this isn't a decl we should typically mangle.
364   if (!Context.shouldMangleDeclName(FD))
365     return;
366
367   // Whether the mangling of a function type includes the return type depends on
368   // the context and the nature of the function. The rules for deciding whether
369   // the return type is included are:
370   //
371   //   1. Template functions (names or types) have return types encoded, with
372   //   the exceptions listed below.
373   //   2. Function types not appearing as part of a function name mangling,
374   //   e.g. parameters, pointer types, etc., have return type encoded, with the
375   //   exceptions listed below.
376   //   3. Non-template function names do not have return types encoded.
377   //
378   // The exceptions mentioned in (1) and (2) above, for which the return type is
379   // never included, are
380   //   1. Constructors.
381   //   2. Destructors.
382   //   3. Conversion operator functions, e.g. operator int.
383   bool MangleReturnType = false;
384   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
385     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
386           isa<CXXConversionDecl>(FD)))
387       MangleReturnType = true;
388
389     // Mangle the type of the primary template.
390     FD = PrimaryTemplate->getTemplatedDecl();
391   }
392
393   // Do the canonicalization out here because parameter types can
394   // undergo additional canonicalization (e.g. array decay).
395   const FunctionType *FT
396     = cast<FunctionType>(Context.getASTContext()
397                                           .getCanonicalType(FD->getType()));
398
399   mangleBareFunctionType(FT, MangleReturnType);
400 }
401
402 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
403   while (isa<LinkageSpecDecl>(DC)) {
404     DC = DC->getParent();
405   }
406
407   return DC;
408 }
409
410 /// isStd - Return whether a given namespace is the 'std' namespace.
411 static bool isStd(const NamespaceDecl *NS) {
412   if (!IgnoreLinkageSpecDecls(NS->getParent())->isTranslationUnit())
413     return false;
414   
415   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
416   return II && II->isStr("std");
417 }
418
419 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
420 // namespace.
421 static bool isStdNamespace(const DeclContext *DC) {
422   if (!DC->isNamespace())
423     return false;
424
425   return isStd(cast<NamespaceDecl>(DC));
426 }
427
428 static const TemplateDecl *
429 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
430   // Check if we have a function template.
431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
432     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
433       TemplateArgs = FD->getTemplateSpecializationArgs();
434       return TD;
435     }
436   }
437
438   // Check if we have a class template.
439   if (const ClassTemplateSpecializationDecl *Spec =
440         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
441     TemplateArgs = &Spec->getTemplateArgs();
442     return Spec->getSpecializedTemplate();
443   }
444
445   return 0;
446 }
447
448 void CXXNameMangler::mangleName(const NamedDecl *ND) {
449   //  <name> ::= <nested-name>
450   //         ::= <unscoped-name>
451   //         ::= <unscoped-template-name> <template-args>
452   //         ::= <local-name>
453   //
454   const DeclContext *DC = ND->getDeclContext();
455
456   // If this is an extern variable declared locally, the relevant DeclContext
457   // is that of the containing namespace, or the translation unit.
458   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
459     while (!DC->isNamespace() && !DC->isTranslationUnit())
460       DC = DC->getParent();
461   else if (GetLocalClassDecl(ND)) {
462     mangleLocalName(ND);
463     return;
464   }
465
466   while (isa<LinkageSpecDecl>(DC))
467     DC = DC->getParent();
468
469   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
470     // Check if we have a template.
471     const TemplateArgumentList *TemplateArgs = 0;
472     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
473       mangleUnscopedTemplateName(TD);
474       TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
475       mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
476       return;
477     }
478
479     mangleUnscopedName(ND);
480     return;
481   }
482
483   if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) {
484     mangleLocalName(ND);
485     return;
486   }
487
488   mangleNestedName(ND, DC);
489 }
490 void CXXNameMangler::mangleName(const TemplateDecl *TD,
491                                 const TemplateArgument *TemplateArgs,
492                                 unsigned NumTemplateArgs) {
493   const DeclContext *DC = IgnoreLinkageSpecDecls(TD->getDeclContext());
494
495   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
496     mangleUnscopedTemplateName(TD);
497     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
498     mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
499   } else {
500     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
501   }
502 }
503
504 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
505   //  <unscoped-name> ::= <unqualified-name>
506   //                  ::= St <unqualified-name>   # ::std::
507   if (isStdNamespace(ND->getDeclContext()))
508     Out << "St";
509
510   mangleUnqualifiedName(ND);
511 }
512
513 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
514   //     <unscoped-template-name> ::= <unscoped-name>
515   //                              ::= <substitution>
516   if (mangleSubstitution(ND))
517     return;
518
519   // <template-template-param> ::= <template-param>
520   if (const TemplateTemplateParmDecl *TTP
521                                      = dyn_cast<TemplateTemplateParmDecl>(ND)) {
522     mangleTemplateParameter(TTP->getIndex());
523     return;
524   }
525
526   mangleUnscopedName(ND->getTemplatedDecl());
527   addSubstitution(ND);
528 }
529
530 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
531   //     <unscoped-template-name> ::= <unscoped-name>
532   //                              ::= <substitution>
533   if (TemplateDecl *TD = Template.getAsTemplateDecl())
534     return mangleUnscopedTemplateName(TD);
535   
536   if (mangleSubstitution(Template))
537     return;
538
539   // FIXME: How to cope with operators here?
540   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
541   assert(Dependent && "Not a dependent template name?");
542   if (!Dependent->isIdentifier()) {
543     // FIXME: We can't possibly know the arity of the operator here!
544     Diagnostic &Diags = Context.getDiags();
545     unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
546                                       "cannot mangle dependent operator name");
547     Diags.Report(DiagID);
548     return;
549   }
550   
551   mangleSourceName(Dependent->getIdentifier());
552   addSubstitution(Template);
553 }
554
555 void CXXNameMangler::mangleFloat(const llvm::APFloat &F) {
556   // TODO: avoid this copy with careful stream management.
557   llvm::SmallString<20> Buffer;
558   F.bitcastToAPInt().toString(Buffer, 16, false);
559   Out.write(Buffer.data(), Buffer.size());
560 }
561
562 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
563   if (Value.isSigned() && Value.isNegative()) {
564     Out << 'n';
565     Value.abs().print(Out, true);
566   } else
567     Value.print(Out, Value.isSigned());
568 }
569
570 void CXXNameMangler::mangleNumber(int64_t Number) {
571   //  <number> ::= [n] <non-negative decimal integer>
572   if (Number < 0) {
573     Out << 'n';
574     Number = -Number;
575   }
576
577   Out << Number;
578 }
579
580 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
581   //  <call-offset>  ::= h <nv-offset> _
582   //                 ::= v <v-offset> _
583   //  <nv-offset>    ::= <offset number>        # non-virtual base override
584   //  <v-offset>     ::= <offset number> _ <virtual offset number>
585   //                      # virtual base override, with vcall offset
586   if (!Virtual) {
587     Out << 'h';
588     mangleNumber(NonVirtual);
589     Out << '_';
590     return;
591   }
592
593   Out << 'v';
594   mangleNumber(NonVirtual);
595   Out << '_';
596   mangleNumber(Virtual);
597   Out << '_';
598 }
599
600 void CXXNameMangler::mangleUnresolvedScope(NestedNameSpecifier *Qualifier) {
601   Qualifier = getASTContext().getCanonicalNestedNameSpecifier(Qualifier);
602   switch (Qualifier->getKind()) {
603   case NestedNameSpecifier::Global:
604     // nothing
605     break;
606   case NestedNameSpecifier::Namespace:
607     mangleName(Qualifier->getAsNamespace());
608     break;
609   case NestedNameSpecifier::NamespaceAlias:
610     mangleName(Qualifier->getAsNamespaceAlias()->getNamespace());
611     break;
612   case NestedNameSpecifier::TypeSpec:
613   case NestedNameSpecifier::TypeSpecWithTemplate: {
614     const Type *QTy = Qualifier->getAsType();
615
616     if (const TemplateSpecializationType *TST =
617         dyn_cast<TemplateSpecializationType>(QTy)) {
618       if (!mangleSubstitution(QualType(TST, 0))) {
619         mangleTemplatePrefix(TST->getTemplateName());
620         
621         // FIXME: GCC does not appear to mangle the template arguments when
622         // the template in question is a dependent template name. Should we
623         // emulate that badness?
624         mangleTemplateArgs(TST->getTemplateName(), TST->getArgs(),
625                            TST->getNumArgs());
626         addSubstitution(QualType(TST, 0));
627       }
628     } else {
629       // We use the QualType mangle type variant here because it handles
630       // substitutions.
631       mangleType(QualType(QTy, 0));
632     }
633   }
634     break;
635   case NestedNameSpecifier::Identifier:
636     // Member expressions can have these without prefixes.
637     if (Qualifier->getPrefix())
638       mangleUnresolvedScope(Qualifier->getPrefix());
639     mangleSourceName(Qualifier->getAsIdentifier());
640     break;
641   }
642 }
643
644 /// Mangles a name which was not resolved to a specific entity.
645 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *Qualifier,
646                                           DeclarationName Name,
647                                           unsigned KnownArity) {
648   if (Qualifier)
649     mangleUnresolvedScope(Qualifier);
650   // FIXME: ambiguity of unqualified lookup with ::
651
652   mangleUnqualifiedName(0, Name, KnownArity);
653 }
654
655 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
656   assert(RD->isAnonymousStructOrUnion() &&
657          "Expected anonymous struct or union!");
658   
659   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
660        I != E; ++I) {
661     const FieldDecl *FD = *I;
662     
663     if (FD->getIdentifier())
664       return FD;
665     
666     if (const RecordType *RT = FD->getType()->getAs<RecordType>()) {
667       if (const FieldDecl *NamedDataMember = 
668           FindFirstNamedDataMember(RT->getDecl()))
669         return NamedDataMember;
670     }
671   }
672
673   // We didn't find a named data member.
674   return 0;
675 }
676
677 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
678                                            DeclarationName Name,
679                                            unsigned KnownArity) {
680   //  <unqualified-name> ::= <operator-name>
681   //                     ::= <ctor-dtor-name>
682   //                     ::= <source-name>
683   switch (Name.getNameKind()) {
684   case DeclarationName::Identifier: {
685     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
686       // We must avoid conflicts between internally- and externally-
687       // linked variable declaration names in the same TU.
688       // This naming convention is the same as that followed by GCC, though it
689       // shouldn't actually matter.
690       if (ND && isa<VarDecl>(ND) && ND->getLinkage() == InternalLinkage &&
691           ND->getDeclContext()->isFileContext())
692         Out << 'L';
693
694       mangleSourceName(II);
695       break;
696     }
697
698     // Otherwise, an anonymous entity.  We must have a declaration.
699     assert(ND && "mangling empty name without declaration");
700
701     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
702       if (NS->isAnonymousNamespace()) {
703         // This is how gcc mangles these names.
704         Out << "12_GLOBAL__N_1";
705         break;
706       }
707     }
708
709     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
710       // We must have an anonymous union or struct declaration.
711       const RecordDecl *RD = 
712         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
713       
714       // Itanium C++ ABI 5.1.2:
715       //
716       //   For the purposes of mangling, the name of an anonymous union is
717       //   considered to be the name of the first named data member found by a
718       //   pre-order, depth-first, declaration-order walk of the data members of
719       //   the anonymous union. If there is no such data member (i.e., if all of
720       //   the data members in the union are unnamed), then there is no way for
721       //   a program to refer to the anonymous union, and there is therefore no
722       //   need to mangle its name.
723       const FieldDecl *FD = FindFirstNamedDataMember(RD);
724
725       // It's actually possible for various reasons for us to get here
726       // with an empty anonymous struct / union.  Fortunately, it
727       // doesn't really matter what name we generate.
728       if (!FD) break;
729       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
730       
731       mangleSourceName(FD->getIdentifier());
732       break;
733     }
734     
735     // We must have an anonymous struct.
736     const TagDecl *TD = cast<TagDecl>(ND);
737     if (const TypedefDecl *D = TD->getTypedefForAnonDecl()) {
738       assert(TD->getDeclContext() == D->getDeclContext() &&
739              "Typedef should not be in another decl context!");
740       assert(D->getDeclName().getAsIdentifierInfo() &&
741              "Typedef was not named!");
742       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
743       break;
744     }
745
746     // Get a unique id for the anonymous struct.
747     uint64_t AnonStructId = Context.getAnonymousStructId(TD);
748
749     // Mangle it as a source name in the form
750     // [n] $_<id>
751     // where n is the length of the string.
752     llvm::SmallString<8> Str;
753     Str += "$_";
754     Str += llvm::utostr(AnonStructId);
755
756     Out << Str.size();
757     Out << Str.str();
758     break;
759   }
760
761   case DeclarationName::ObjCZeroArgSelector:
762   case DeclarationName::ObjCOneArgSelector:
763   case DeclarationName::ObjCMultiArgSelector:
764     assert(false && "Can't mangle Objective-C selector names here!");
765     break;
766
767   case DeclarationName::CXXConstructorName:
768     if (ND == Structor)
769       // If the named decl is the C++ constructor we're mangling, use the type
770       // we were given.
771       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
772     else
773       // Otherwise, use the complete constructor name. This is relevant if a
774       // class with a constructor is declared within a constructor.
775       mangleCXXCtorType(Ctor_Complete);
776     break;
777
778   case DeclarationName::CXXDestructorName:
779     if (ND == Structor)
780       // If the named decl is the C++ destructor we're mangling, use the type we
781       // were given.
782       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
783     else
784       // Otherwise, use the complete destructor name. This is relevant if a
785       // class with a destructor is declared within a destructor.
786       mangleCXXDtorType(Dtor_Complete);
787     break;
788
789   case DeclarationName::CXXConversionFunctionName:
790     // <operator-name> ::= cv <type>    # (cast)
791     Out << "cv";
792     mangleType(Context.getASTContext().getCanonicalType(Name.getCXXNameType()));
793     break;
794
795   case DeclarationName::CXXOperatorName: {
796     unsigned Arity;
797     if (ND) {
798       Arity = cast<FunctionDecl>(ND)->getNumParams();
799
800       // If we have a C++ member function, we need to include the 'this' pointer.
801       // FIXME: This does not make sense for operators that are static, but their
802       // names stay the same regardless of the arity (operator new for instance).
803       if (isa<CXXMethodDecl>(ND))
804         Arity++;
805     } else
806       Arity = KnownArity;
807
808     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
809     break;
810   }
811
812   case DeclarationName::CXXLiteralOperatorName:
813     // FIXME: This mangling is not yet official.
814     Out << "li";
815     mangleSourceName(Name.getCXXLiteralIdentifier());
816     break;
817
818   case DeclarationName::CXXUsingDirective:
819     assert(false && "Can't mangle a using directive name!");
820     break;
821   }
822 }
823
824 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
825   // <source-name> ::= <positive length number> <identifier>
826   // <number> ::= [n] <non-negative decimal integer>
827   // <identifier> ::= <unqualified source code identifier>
828   Out << II->getLength() << II->getName();
829 }
830
831 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
832                                       const DeclContext *DC,
833                                       bool NoFunction) {
834   // <nested-name> 
835   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
836   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 
837   //       <template-args> E
838
839   Out << 'N';
840   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
841     mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
842     mangleRefQualifier(Method->getRefQualifier());
843   }
844   
845   // Check if we have a template.
846   const TemplateArgumentList *TemplateArgs = 0;
847   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
848     mangleTemplatePrefix(TD);
849     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
850     mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
851   }
852   else {
853     manglePrefix(DC, NoFunction);
854     mangleUnqualifiedName(ND);
855   }
856
857   Out << 'E';
858 }
859 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
860                                       const TemplateArgument *TemplateArgs,
861                                       unsigned NumTemplateArgs) {
862   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
863
864   Out << 'N';
865
866   mangleTemplatePrefix(TD);
867   TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
868   mangleTemplateArgs(*TemplateParameters, TemplateArgs, NumTemplateArgs);
869
870   Out << 'E';
871 }
872
873 void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
874   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
875   //              := Z <function encoding> E s [<discriminator>]
876   // <discriminator> := _ <non-negative number>
877   const DeclContext *DC = ND->getDeclContext();
878   Out << 'Z';
879
880   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) {
881    mangleObjCMethodName(MD);
882   } else if (const CXXRecordDecl *RD = GetLocalClassDecl(ND)) {
883     mangleFunctionEncoding(cast<FunctionDecl>(RD->getDeclContext()));
884     Out << 'E';
885
886     // Mangle the name relative to the closest enclosing function.
887     if (ND == RD) // equality ok because RD derived from ND above
888       mangleUnqualifiedName(ND);
889     else
890       mangleNestedName(ND, DC, true /*NoFunction*/);
891
892     unsigned disc;
893     if (Context.getNextDiscriminator(RD, disc)) {
894       if (disc < 10)
895         Out << '_' << disc;
896       else
897         Out << "__" << disc << '_';
898     }
899
900     return;
901   }
902   else
903     mangleFunctionEncoding(cast<FunctionDecl>(DC));
904
905   Out << 'E';
906   mangleUnqualifiedName(ND);
907 }
908
909 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
910   //  <prefix> ::= <prefix> <unqualified-name>
911   //           ::= <template-prefix> <template-args>
912   //           ::= <template-param>
913   //           ::= # empty
914   //           ::= <substitution>
915
916   while (isa<LinkageSpecDecl>(DC))
917     DC = DC->getParent();
918
919   if (DC->isTranslationUnit())
920     return;
921
922   if (const BlockDecl *Block = dyn_cast<BlockDecl>(DC)) {
923     manglePrefix(DC->getParent(), NoFunction);    
924     llvm::SmallString<64> Name;
925     llvm::raw_svector_ostream NameStream(Name);
926     Context.mangleBlock(Block, NameStream);
927     NameStream.flush();
928     Out << Name.size() << Name;
929     return;
930   }
931   
932   if (mangleSubstitution(cast<NamedDecl>(DC)))
933     return;
934
935   // Check if we have a template.
936   const TemplateArgumentList *TemplateArgs = 0;
937   if (const TemplateDecl *TD = isTemplate(cast<NamedDecl>(DC), TemplateArgs)) {
938     mangleTemplatePrefix(TD);
939     TemplateParameterList *TemplateParameters = TD->getTemplateParameters();
940     mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
941   }
942   else if(NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
943     return;
944   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
945     mangleObjCMethodName(Method);
946   else {
947     manglePrefix(DC->getParent(), NoFunction);
948     mangleUnqualifiedName(cast<NamedDecl>(DC));
949   }
950
951   addSubstitution(cast<NamedDecl>(DC));
952 }
953
954 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
955   // <template-prefix> ::= <prefix> <template unqualified-name>
956   //                   ::= <template-param>
957   //                   ::= <substitution>
958   if (TemplateDecl *TD = Template.getAsTemplateDecl())
959     return mangleTemplatePrefix(TD);
960
961   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
962     mangleUnresolvedScope(Qualified->getQualifier());
963   
964   if (OverloadedTemplateStorage *Overloaded
965                                       = Template.getAsOverloadedTemplate()) {
966     mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(), 
967                           UnknownArity);
968     return;
969   }
970    
971   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
972   assert(Dependent && "Unknown template name kind?");
973   mangleUnresolvedScope(Dependent->getQualifier());
974   mangleUnscopedTemplateName(Template);
975 }
976
977 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND) {
978   // <template-prefix> ::= <prefix> <template unqualified-name>
979   //                   ::= <template-param>
980   //                   ::= <substitution>
981   // <template-template-param> ::= <template-param>
982   //                               <substitution>
983
984   if (mangleSubstitution(ND))
985     return;
986
987   // <template-template-param> ::= <template-param>
988   if (const TemplateTemplateParmDecl *TTP
989                                      = dyn_cast<TemplateTemplateParmDecl>(ND)) {
990     mangleTemplateParameter(TTP->getIndex());
991     return;
992   }
993
994   manglePrefix(ND->getDeclContext());
995   mangleUnqualifiedName(ND->getTemplatedDecl());
996   addSubstitution(ND);
997 }
998
999 /// Mangles a template name under the production <type>.  Required for
1000 /// template template arguments.
1001 ///   <type> ::= <class-enum-type>
1002 ///          ::= <template-param>
1003 ///          ::= <substitution>
1004 void CXXNameMangler::mangleType(TemplateName TN) {
1005   if (mangleSubstitution(TN))
1006     return;
1007       
1008   TemplateDecl *TD = 0;
1009
1010   switch (TN.getKind()) {
1011   case TemplateName::QualifiedTemplate:
1012     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1013     goto HaveDecl;
1014
1015   case TemplateName::Template:
1016     TD = TN.getAsTemplateDecl();
1017     goto HaveDecl;
1018
1019   HaveDecl:
1020     if (isa<TemplateTemplateParmDecl>(TD))
1021       mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1022     else
1023       mangleName(TD);
1024     break;
1025
1026   case TemplateName::OverloadedTemplate:
1027     llvm_unreachable("can't mangle an overloaded template name as a <type>");
1028     break;
1029
1030   case TemplateName::DependentTemplate: {
1031     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1032     assert(Dependent->isIdentifier());
1033
1034     // <class-enum-type> ::= <name>
1035     // <name> ::= <nested-name>
1036     mangleUnresolvedScope(Dependent->getQualifier());
1037     mangleSourceName(Dependent->getIdentifier());
1038     break;
1039   }
1040
1041   case TemplateName::SubstTemplateTemplateParmPack: {
1042     SubstTemplateTemplateParmPackStorage *SubstPack
1043       = TN.getAsSubstTemplateTemplateParmPack();
1044     mangleTemplateParameter(SubstPack->getParameterPack()->getIndex());
1045     break;
1046   }
1047   }
1048
1049   addSubstitution(TN);
1050 }
1051
1052 void
1053 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1054   switch (OO) {
1055   // <operator-name> ::= nw     # new
1056   case OO_New: Out << "nw"; break;
1057   //              ::= na        # new[]
1058   case OO_Array_New: Out << "na"; break;
1059   //              ::= dl        # delete
1060   case OO_Delete: Out << "dl"; break;
1061   //              ::= da        # delete[]
1062   case OO_Array_Delete: Out << "da"; break;
1063   //              ::= ps        # + (unary)
1064   //              ::= pl        # + (binary or unknown)
1065   case OO_Plus:
1066     Out << (Arity == 1? "ps" : "pl"); break;
1067   //              ::= ng        # - (unary)
1068   //              ::= mi        # - (binary or unknown)
1069   case OO_Minus:
1070     Out << (Arity == 1? "ng" : "mi"); break;
1071   //              ::= ad        # & (unary)
1072   //              ::= an        # & (binary or unknown)
1073   case OO_Amp:
1074     Out << (Arity == 1? "ad" : "an"); break;
1075   //              ::= de        # * (unary)
1076   //              ::= ml        # * (binary or unknown)
1077   case OO_Star:
1078     // Use binary when unknown.
1079     Out << (Arity == 1? "de" : "ml"); break;
1080   //              ::= co        # ~
1081   case OO_Tilde: Out << "co"; break;
1082   //              ::= dv        # /
1083   case OO_Slash: Out << "dv"; break;
1084   //              ::= rm        # %
1085   case OO_Percent: Out << "rm"; break;
1086   //              ::= or        # |
1087   case OO_Pipe: Out << "or"; break;
1088   //              ::= eo        # ^
1089   case OO_Caret: Out << "eo"; break;
1090   //              ::= aS        # =
1091   case OO_Equal: Out << "aS"; break;
1092   //              ::= pL        # +=
1093   case OO_PlusEqual: Out << "pL"; break;
1094   //              ::= mI        # -=
1095   case OO_MinusEqual: Out << "mI"; break;
1096   //              ::= mL        # *=
1097   case OO_StarEqual: Out << "mL"; break;
1098   //              ::= dV        # /=
1099   case OO_SlashEqual: Out << "dV"; break;
1100   //              ::= rM        # %=
1101   case OO_PercentEqual: Out << "rM"; break;
1102   //              ::= aN        # &=
1103   case OO_AmpEqual: Out << "aN"; break;
1104   //              ::= oR        # |=
1105   case OO_PipeEqual: Out << "oR"; break;
1106   //              ::= eO        # ^=
1107   case OO_CaretEqual: Out << "eO"; break;
1108   //              ::= ls        # <<
1109   case OO_LessLess: Out << "ls"; break;
1110   //              ::= rs        # >>
1111   case OO_GreaterGreater: Out << "rs"; break;
1112   //              ::= lS        # <<=
1113   case OO_LessLessEqual: Out << "lS"; break;
1114   //              ::= rS        # >>=
1115   case OO_GreaterGreaterEqual: Out << "rS"; break;
1116   //              ::= eq        # ==
1117   case OO_EqualEqual: Out << "eq"; break;
1118   //              ::= ne        # !=
1119   case OO_ExclaimEqual: Out << "ne"; break;
1120   //              ::= lt        # <
1121   case OO_Less: Out << "lt"; break;
1122   //              ::= gt        # >
1123   case OO_Greater: Out << "gt"; break;
1124   //              ::= le        # <=
1125   case OO_LessEqual: Out << "le"; break;
1126   //              ::= ge        # >=
1127   case OO_GreaterEqual: Out << "ge"; break;
1128   //              ::= nt        # !
1129   case OO_Exclaim: Out << "nt"; break;
1130   //              ::= aa        # &&
1131   case OO_AmpAmp: Out << "aa"; break;
1132   //              ::= oo        # ||
1133   case OO_PipePipe: Out << "oo"; break;
1134   //              ::= pp        # ++
1135   case OO_PlusPlus: Out << "pp"; break;
1136   //              ::= mm        # --
1137   case OO_MinusMinus: Out << "mm"; break;
1138   //              ::= cm        # ,
1139   case OO_Comma: Out << "cm"; break;
1140   //              ::= pm        # ->*
1141   case OO_ArrowStar: Out << "pm"; break;
1142   //              ::= pt        # ->
1143   case OO_Arrow: Out << "pt"; break;
1144   //              ::= cl        # ()
1145   case OO_Call: Out << "cl"; break;
1146   //              ::= ix        # []
1147   case OO_Subscript: Out << "ix"; break;
1148
1149   //              ::= qu        # ?
1150   // The conditional operator can't be overloaded, but we still handle it when
1151   // mangling expressions.
1152   case OO_Conditional: Out << "qu"; break;
1153
1154   case OO_None:
1155   case NUM_OVERLOADED_OPERATORS:
1156     assert(false && "Not an overloaded operator");
1157     break;
1158   }
1159 }
1160
1161 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1162   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
1163   if (Quals.hasRestrict())
1164     Out << 'r';
1165   if (Quals.hasVolatile())
1166     Out << 'V';
1167   if (Quals.hasConst())
1168     Out << 'K';
1169
1170   if (Quals.hasAddressSpace()) {
1171     // Extension:
1172     //
1173     //   <type> ::= U <address-space-number>
1174     // 
1175     // where <address-space-number> is a source name consisting of 'AS' 
1176     // followed by the address space <number>.
1177     llvm::SmallString<64> ASString;
1178     ASString = "AS" + llvm::utostr_32(Quals.getAddressSpace());
1179     Out << 'U' << ASString.size() << ASString;
1180   }
1181   
1182   // FIXME: For now, just drop all extension qualifiers on the floor.
1183 }
1184
1185 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1186   // <ref-qualifier> ::= R                # lvalue reference
1187   //                 ::= O                # rvalue-reference
1188   // Proposal to Itanium C++ ABI list on 1/26/11
1189   switch (RefQualifier) {
1190   case RQ_None:
1191     break;
1192       
1193   case RQ_LValue:
1194     Out << 'R';
1195     break;
1196       
1197   case RQ_RValue:
1198     Out << 'O';
1199     break;
1200   }
1201 }
1202
1203 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1204   Context.mangleObjCMethodName(MD, Out);
1205 }
1206
1207 void CXXNameMangler::mangleType(QualType nonCanon) {
1208   // Only operate on the canonical type!
1209   QualType canon = nonCanon.getCanonicalType();
1210
1211   SplitQualType split = canon.split();
1212   Qualifiers quals = split.second;
1213   const Type *ty = split.first;
1214
1215   bool isSubstitutable = quals || !isa<BuiltinType>(ty);
1216   if (isSubstitutable && mangleSubstitution(canon))
1217     return;
1218
1219   // If we're mangling a qualified array type, push the qualifiers to
1220   // the element type.
1221   if (quals && isa<ArrayType>(ty)) {
1222     ty = Context.getASTContext().getAsArrayType(canon);
1223     quals = Qualifiers();
1224
1225     // Note that we don't update canon: we want to add the
1226     // substitution at the canonical type.
1227   }
1228
1229   if (quals) {
1230     mangleQualifiers(quals);
1231     // Recurse:  even if the qualified type isn't yet substitutable,
1232     // the unqualified type might be.
1233     mangleType(QualType(ty, 0));
1234   } else {
1235     switch (ty->getTypeClass()) {
1236 #define ABSTRACT_TYPE(CLASS, PARENT)
1237 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1238     case Type::CLASS: \
1239       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1240       return;
1241 #define TYPE(CLASS, PARENT) \
1242     case Type::CLASS: \
1243       mangleType(static_cast<const CLASS##Type*>(ty)); \
1244       break;
1245 #include "clang/AST/TypeNodes.def"
1246     }
1247   }
1248
1249   // Add the substitution.
1250   if (isSubstitutable)
1251     addSubstitution(canon);
1252 }
1253
1254 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1255   if (!mangleStandardSubstitution(ND))
1256     mangleName(ND);
1257 }
1258
1259 void CXXNameMangler::mangleType(const BuiltinType *T) {
1260   //  <type>         ::= <builtin-type>
1261   //  <builtin-type> ::= v  # void
1262   //                 ::= w  # wchar_t
1263   //                 ::= b  # bool
1264   //                 ::= c  # char
1265   //                 ::= a  # signed char
1266   //                 ::= h  # unsigned char
1267   //                 ::= s  # short
1268   //                 ::= t  # unsigned short
1269   //                 ::= i  # int
1270   //                 ::= j  # unsigned int
1271   //                 ::= l  # long
1272   //                 ::= m  # unsigned long
1273   //                 ::= x  # long long, __int64
1274   //                 ::= y  # unsigned long long, __int64
1275   //                 ::= n  # __int128
1276   // UNSUPPORTED:    ::= o  # unsigned __int128
1277   //                 ::= f  # float
1278   //                 ::= d  # double
1279   //                 ::= e  # long double, __float80
1280   // UNSUPPORTED:    ::= g  # __float128
1281   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
1282   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
1283   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
1284   // UNSUPPORTED:    ::= Dh # IEEE 754r half-precision floating point (16 bits)
1285   //                 ::= Di # char32_t
1286   //                 ::= Ds # char16_t
1287   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1288   //                 ::= u <source-name>    # vendor extended type
1289   switch (T->getKind()) {
1290   case BuiltinType::Void: Out << 'v'; break;
1291   case BuiltinType::Bool: Out << 'b'; break;
1292   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1293   case BuiltinType::UChar: Out << 'h'; break;
1294   case BuiltinType::UShort: Out << 't'; break;
1295   case BuiltinType::UInt: Out << 'j'; break;
1296   case BuiltinType::ULong: Out << 'm'; break;
1297   case BuiltinType::ULongLong: Out << 'y'; break;
1298   case BuiltinType::UInt128: Out << 'o'; break;
1299   case BuiltinType::SChar: Out << 'a'; break;
1300   case BuiltinType::WChar_S:
1301   case BuiltinType::WChar_U: Out << 'w'; break;
1302   case BuiltinType::Char16: Out << "Ds"; break;
1303   case BuiltinType::Char32: Out << "Di"; break;
1304   case BuiltinType::Short: Out << 's'; break;
1305   case BuiltinType::Int: Out << 'i'; break;
1306   case BuiltinType::Long: Out << 'l'; break;
1307   case BuiltinType::LongLong: Out << 'x'; break;
1308   case BuiltinType::Int128: Out << 'n'; break;
1309   case BuiltinType::Float: Out << 'f'; break;
1310   case BuiltinType::Double: Out << 'd'; break;
1311   case BuiltinType::LongDouble: Out << 'e'; break;
1312   case BuiltinType::NullPtr: Out << "Dn"; break;
1313
1314   case BuiltinType::Overload:
1315   case BuiltinType::Dependent:
1316     assert(false &&
1317            "Overloaded and dependent types shouldn't get to name mangling");
1318     break;
1319   case BuiltinType::ObjCId: Out << "11objc_object"; break;
1320   case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1321   case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
1322   }
1323 }
1324
1325 // <type>          ::= <function-type>
1326 // <function-type> ::= F [Y] <bare-function-type> E
1327 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1328   Out << 'F';
1329   // FIXME: We don't have enough information in the AST to produce the 'Y'
1330   // encoding for extern "C" function types.
1331   mangleBareFunctionType(T, /*MangleReturnType=*/true);
1332   Out << 'E';
1333 }
1334 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
1335   llvm_unreachable("Can't mangle K&R function prototypes");
1336 }
1337 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
1338                                             bool MangleReturnType) {
1339   // We should never be mangling something without a prototype.
1340   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1341
1342   // <bare-function-type> ::= <signature type>+
1343   if (MangleReturnType)
1344     mangleType(Proto->getResultType());
1345
1346   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1347     //   <builtin-type> ::= v   # void
1348     Out << 'v';
1349     return;
1350   }
1351
1352   for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1353                                          ArgEnd = Proto->arg_type_end();
1354        Arg != ArgEnd; ++Arg)
1355     mangleType(*Arg);
1356
1357   // <builtin-type>      ::= z  # ellipsis
1358   if (Proto->isVariadic())
1359     Out << 'z';
1360 }
1361
1362 // <type>            ::= <class-enum-type>
1363 // <class-enum-type> ::= <name>
1364 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1365   mangleName(T->getDecl());
1366 }
1367
1368 // <type>            ::= <class-enum-type>
1369 // <class-enum-type> ::= <name>
1370 void CXXNameMangler::mangleType(const EnumType *T) {
1371   mangleType(static_cast<const TagType*>(T));
1372 }
1373 void CXXNameMangler::mangleType(const RecordType *T) {
1374   mangleType(static_cast<const TagType*>(T));
1375 }
1376 void CXXNameMangler::mangleType(const TagType *T) {
1377   mangleName(T->getDecl());
1378 }
1379
1380 // <type>       ::= <array-type>
1381 // <array-type> ::= A <positive dimension number> _ <element type>
1382 //              ::= A [<dimension expression>] _ <element type>
1383 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
1384   Out << 'A' << T->getSize() << '_';
1385   mangleType(T->getElementType());
1386 }
1387 void CXXNameMangler::mangleType(const VariableArrayType *T) {
1388   Out << 'A';
1389   // decayed vla types (size 0) will just be skipped.
1390   if (T->getSizeExpr())
1391     mangleExpression(T->getSizeExpr());
1392   Out << '_';
1393   mangleType(T->getElementType());
1394 }
1395 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1396   Out << 'A';
1397   mangleExpression(T->getSizeExpr());
1398   Out << '_';
1399   mangleType(T->getElementType());
1400 }
1401 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
1402   Out << "A_";
1403   mangleType(T->getElementType());
1404 }
1405
1406 // <type>                   ::= <pointer-to-member-type>
1407 // <pointer-to-member-type> ::= M <class type> <member type>
1408 void CXXNameMangler::mangleType(const MemberPointerType *T) {
1409   Out << 'M';
1410   mangleType(QualType(T->getClass(), 0));
1411   QualType PointeeType = T->getPointeeType();
1412   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
1413     mangleQualifiers(Qualifiers::fromCVRMask(FPT->getTypeQuals()));
1414     mangleRefQualifier(FPT->getRefQualifier());
1415     mangleType(FPT);
1416     
1417     // Itanium C++ ABI 5.1.8:
1418     //
1419     //   The type of a non-static member function is considered to be different,
1420     //   for the purposes of substitution, from the type of a namespace-scope or
1421     //   static member function whose type appears similar. The types of two
1422     //   non-static member functions are considered to be different, for the
1423     //   purposes of substitution, if the functions are members of different
1424     //   classes. In other words, for the purposes of substitution, the class of 
1425     //   which the function is a member is considered part of the type of 
1426     //   function.
1427
1428     // We increment the SeqID here to emulate adding an entry to the
1429     // substitution table. We can't actually add it because we don't want this
1430     // particular function type to be substituted.
1431     ++SeqID;
1432   } else
1433     mangleType(PointeeType);
1434 }
1435
1436 // <type>           ::= <template-param>
1437 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
1438   mangleTemplateParameter(T->getIndex());
1439 }
1440
1441 // <type>           ::= <template-param>
1442 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
1443   mangleTemplateParameter(T->getReplacedParameter()->getIndex());
1444 }
1445
1446 // <type> ::= P <type>   # pointer-to
1447 void CXXNameMangler::mangleType(const PointerType *T) {
1448   Out << 'P';
1449   mangleType(T->getPointeeType());
1450 }
1451 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
1452   Out << 'P';
1453   mangleType(T->getPointeeType());
1454 }
1455
1456 // <type> ::= R <type>   # reference-to
1457 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
1458   Out << 'R';
1459   mangleType(T->getPointeeType());
1460 }
1461
1462 // <type> ::= O <type>   # rvalue reference-to (C++0x)
1463 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
1464   Out << 'O';
1465   mangleType(T->getPointeeType());
1466 }
1467
1468 // <type> ::= C <type>   # complex pair (C 2000)
1469 void CXXNameMangler::mangleType(const ComplexType *T) {
1470   Out << 'C';
1471   mangleType(T->getElementType());
1472 }
1473
1474 // ARM's ABI for Neon vector types specifies that they should be mangled as
1475 // if they are structs (to match ARM's initial implementation).  The
1476 // vector type must be one of the special types predefined by ARM.
1477 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
1478   QualType EltType = T->getElementType();
1479   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
1480   const char *EltName = 0;
1481   if (T->getVectorKind() == VectorType::NeonPolyVector) {
1482     switch (cast<BuiltinType>(EltType)->getKind()) {
1483     case BuiltinType::SChar:     EltName = "poly8_t"; break;
1484     case BuiltinType::Short:     EltName = "poly16_t"; break;
1485     default: llvm_unreachable("unexpected Neon polynomial vector element type");
1486     }
1487   } else {
1488     switch (cast<BuiltinType>(EltType)->getKind()) {
1489     case BuiltinType::SChar:     EltName = "int8_t"; break;
1490     case BuiltinType::UChar:     EltName = "uint8_t"; break;
1491     case BuiltinType::Short:     EltName = "int16_t"; break;
1492     case BuiltinType::UShort:    EltName = "uint16_t"; break;
1493     case BuiltinType::Int:       EltName = "int32_t"; break;
1494     case BuiltinType::UInt:      EltName = "uint32_t"; break;
1495     case BuiltinType::LongLong:  EltName = "int64_t"; break;
1496     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
1497     case BuiltinType::Float:     EltName = "float32_t"; break;
1498     default: llvm_unreachable("unexpected Neon vector element type");
1499     }
1500   }
1501   const char *BaseName = 0;
1502   unsigned BitSize = (T->getNumElements() *
1503                       getASTContext().getTypeSize(EltType));
1504   if (BitSize == 64)
1505     BaseName = "__simd64_";
1506   else {
1507     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
1508     BaseName = "__simd128_";
1509   }
1510   Out << strlen(BaseName) + strlen(EltName);
1511   Out << BaseName << EltName;
1512 }
1513
1514 // GNU extension: vector types
1515 // <type>                  ::= <vector-type>
1516 // <vector-type>           ::= Dv <positive dimension number> _
1517 //                                    <extended element type>
1518 //                         ::= Dv [<dimension expression>] _ <element type>
1519 // <extended element type> ::= <element type>
1520 //                         ::= p # AltiVec vector pixel
1521 void CXXNameMangler::mangleType(const VectorType *T) {
1522   if ((T->getVectorKind() == VectorType::NeonVector ||
1523        T->getVectorKind() == VectorType::NeonPolyVector)) {
1524     mangleNeonVectorType(T);
1525     return;
1526   }
1527   Out << "Dv" << T->getNumElements() << '_';
1528   if (T->getVectorKind() == VectorType::AltiVecPixel)
1529     Out << 'p';
1530   else if (T->getVectorKind() == VectorType::AltiVecBool)
1531     Out << 'b';
1532   else
1533     mangleType(T->getElementType());
1534 }
1535 void CXXNameMangler::mangleType(const ExtVectorType *T) {
1536   mangleType(static_cast<const VectorType*>(T));
1537 }
1538 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
1539   Out << "Dv";
1540   mangleExpression(T->getSizeExpr());
1541   Out << '_';
1542   mangleType(T->getElementType());
1543 }
1544
1545 void CXXNameMangler::mangleType(const PackExpansionType *T) {
1546   // <type>  ::= Dp <type>          # pack expansion (C++0x)
1547   Out << "Dp";
1548   mangleType(T->getPattern());
1549 }
1550
1551 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
1552   mangleSourceName(T->getDecl()->getIdentifier());
1553 }
1554
1555 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
1556   // We don't allow overloading by different protocol qualification,
1557   // so mangling them isn't necessary.
1558   mangleType(T->getBaseType());
1559 }
1560
1561 void CXXNameMangler::mangleType(const BlockPointerType *T) {
1562   Out << "U13block_pointer";
1563   mangleType(T->getPointeeType());
1564 }
1565
1566 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
1567   // Mangle injected class name types as if the user had written the
1568   // specialization out fully.  It may not actually be possible to see
1569   // this mangling, though.
1570   mangleType(T->getInjectedSpecializationType());
1571 }
1572
1573 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
1574   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
1575     mangleName(TD, T->getArgs(), T->getNumArgs());
1576   } else {
1577     if (mangleSubstitution(QualType(T, 0)))
1578       return;
1579     
1580     mangleTemplatePrefix(T->getTemplateName());
1581     
1582     // FIXME: GCC does not appear to mangle the template arguments when
1583     // the template in question is a dependent template name. Should we
1584     // emulate that badness?
1585     mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs());
1586     addSubstitution(QualType(T, 0));
1587   }
1588 }
1589
1590 void CXXNameMangler::mangleType(const DependentNameType *T) {
1591   // Typename types are always nested
1592   Out << 'N';
1593   mangleUnresolvedScope(T->getQualifier());
1594   mangleSourceName(T->getIdentifier());    
1595   Out << 'E';
1596 }
1597
1598 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
1599   // Dependently-scoped template types are always nested
1600   Out << 'N';
1601
1602   // TODO: avoid making this TemplateName.
1603   TemplateName Prefix =
1604     getASTContext().getDependentTemplateName(T->getQualifier(),
1605                                              T->getIdentifier());
1606   mangleTemplatePrefix(Prefix);
1607
1608   // FIXME: GCC does not appear to mangle the template arguments when
1609   // the template in question is a dependent template name. Should we
1610   // emulate that badness?
1611   mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs());    
1612   Out << 'E';
1613 }
1614
1615 void CXXNameMangler::mangleType(const TypeOfType *T) {
1616   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
1617   // "extension with parameters" mangling.
1618   Out << "u6typeof";
1619 }
1620
1621 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
1622   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
1623   // "extension with parameters" mangling.
1624   Out << "u6typeof";
1625 }
1626
1627 void CXXNameMangler::mangleType(const DecltypeType *T) {
1628   Expr *E = T->getUnderlyingExpr();
1629
1630   // type ::= Dt <expression> E  # decltype of an id-expression
1631   //                             #   or class member access
1632   //      ::= DT <expression> E  # decltype of an expression
1633
1634   // This purports to be an exhaustive list of id-expressions and
1635   // class member accesses.  Note that we do not ignore parentheses;
1636   // parentheses change the semantics of decltype for these
1637   // expressions (and cause the mangler to use the other form).
1638   if (isa<DeclRefExpr>(E) ||
1639       isa<MemberExpr>(E) ||
1640       isa<UnresolvedLookupExpr>(E) ||
1641       isa<DependentScopeDeclRefExpr>(E) ||
1642       isa<CXXDependentScopeMemberExpr>(E) ||
1643       isa<UnresolvedMemberExpr>(E))
1644     Out << "Dt";
1645   else
1646     Out << "DT";
1647   mangleExpression(E);
1648   Out << 'E';
1649 }
1650
1651 void CXXNameMangler::mangleType(const AutoType *T) {
1652   QualType D = T->getDeducedType();
1653   // <builtin-type> ::= Da  # dependent auto
1654   if (D.isNull())
1655     Out << "Da";
1656   else
1657     mangleType(D);
1658 }
1659
1660 void CXXNameMangler::mangleIntegerLiteral(QualType T,
1661                                           const llvm::APSInt &Value) {
1662   //  <expr-primary> ::= L <type> <value number> E # integer literal
1663   Out << 'L';
1664
1665   mangleType(T);
1666   if (T->isBooleanType()) {
1667     // Boolean values are encoded as 0/1.
1668     Out << (Value.getBoolValue() ? '1' : '0');
1669   } else {
1670     mangleNumber(Value);
1671   }
1672   Out << 'E';
1673
1674 }
1675
1676 /// Mangles a member expression.  Implicit accesses are not handled,
1677 /// but that should be okay, because you shouldn't be able to
1678 /// make an implicit access in a function template declaration.
1679 void CXXNameMangler::mangleMemberExpr(const Expr *Base,
1680                                       bool IsArrow,
1681                                       NestedNameSpecifier *Qualifier,
1682                                       DeclarationName Member,
1683                                       unsigned Arity) {
1684   // gcc-4.4 uses 'dt' for dot expressions, which is reasonable.
1685   // OTOH, gcc also mangles the name as an expression.
1686   Out << (IsArrow ? "pt" : "dt");
1687   mangleExpression(Base);
1688   mangleUnresolvedName(Qualifier, Member, Arity);
1689 }
1690
1691 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
1692   // <expression> ::= <unary operator-name> <expression>
1693   //              ::= <binary operator-name> <expression> <expression>
1694   //              ::= <trinary operator-name> <expression> <expression> <expression>
1695   //              ::= cl <expression>* E             # call
1696   //              ::= cv <type> expression           # conversion with one argument
1697   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
1698   //              ::= st <type>                      # sizeof (a type)
1699   //              ::= at <type>                      # alignof (a type)
1700   //              ::= <template-param>
1701   //              ::= <function-param>
1702   //              ::= sr <type> <unqualified-name>                   # dependent name
1703   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
1704   //              ::= sZ <template-param>                            # size of a parameter pack
1705   //              ::= sZ <function-param>    # size of a function parameter pack
1706   //              ::= <expr-primary>
1707   // <expr-primary> ::= L <type> <value number> E    # integer literal
1708   //                ::= L <type <value float> E      # floating literal
1709   //                ::= L <mangled-name> E           # external name
1710   switch (E->getStmtClass()) {
1711   case Expr::NoStmtClass:
1712 #define ABSTRACT_STMT(Type)
1713 #define EXPR(Type, Base)
1714 #define STMT(Type, Base) \
1715   case Expr::Type##Class:
1716 #include "clang/AST/StmtNodes.inc"
1717     // fallthrough
1718
1719   // These all can only appear in local or variable-initialization
1720   // contexts and so should never appear in a mangling.
1721   case Expr::AddrLabelExprClass:
1722   case Expr::BlockDeclRefExprClass:
1723   case Expr::CXXThisExprClass:
1724   case Expr::DesignatedInitExprClass:
1725   case Expr::ImplicitValueInitExprClass:
1726   case Expr::InitListExprClass:
1727   case Expr::ParenListExprClass:
1728   case Expr::CXXScalarValueInitExprClass:
1729     llvm_unreachable("unexpected statement kind");
1730     break;
1731
1732   // FIXME: invent manglings for all these.
1733   case Expr::BlockExprClass:
1734   case Expr::CXXPseudoDestructorExprClass:
1735   case Expr::ChooseExprClass:
1736   case Expr::CompoundLiteralExprClass:
1737   case Expr::ExtVectorElementExprClass:
1738   case Expr::ObjCEncodeExprClass:
1739   case Expr::ObjCIsaExprClass:
1740   case Expr::ObjCIvarRefExprClass:
1741   case Expr::ObjCMessageExprClass:
1742   case Expr::ObjCPropertyRefExprClass:
1743   case Expr::ObjCProtocolExprClass:
1744   case Expr::ObjCSelectorExprClass:
1745   case Expr::ObjCStringLiteralClass:
1746   case Expr::OffsetOfExprClass:
1747   case Expr::PredefinedExprClass:
1748   case Expr::ShuffleVectorExprClass:
1749   case Expr::StmtExprClass:
1750   case Expr::UnaryTypeTraitExprClass:
1751   case Expr::BinaryTypeTraitExprClass:
1752   case Expr::VAArgExprClass:
1753   case Expr::CXXUuidofExprClass:
1754   case Expr::CXXNoexceptExprClass:
1755   case Expr::CUDAKernelCallExprClass: {
1756     // As bad as this diagnostic is, it's better than crashing.
1757     Diagnostic &Diags = Context.getDiags();
1758     unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
1759                                      "cannot yet mangle expression type %0");
1760     Diags.Report(E->getExprLoc(), DiagID)
1761       << E->getStmtClassName() << E->getSourceRange();
1762     break;
1763   }
1764
1765   // Even gcc-4.5 doesn't mangle this.
1766   case Expr::BinaryConditionalOperatorClass: {
1767     Diagnostic &Diags = Context.getDiags();
1768     unsigned DiagID =
1769       Diags.getCustomDiagID(Diagnostic::Error,
1770                 "?: operator with omitted middle operand cannot be mangled");
1771     Diags.Report(E->getExprLoc(), DiagID)
1772       << E->getStmtClassName() << E->getSourceRange();
1773     break;
1774   }
1775
1776   // These are used for internal purposes and cannot be meaningfully mangled.
1777   case Expr::OpaqueValueExprClass:
1778     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
1779
1780   case Expr::CXXDefaultArgExprClass:
1781     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
1782     break;
1783
1784   case Expr::CXXMemberCallExprClass: // fallthrough
1785   case Expr::CallExprClass: {
1786     const CallExpr *CE = cast<CallExpr>(E);
1787     Out << "cl";
1788     mangleExpression(CE->getCallee(), CE->getNumArgs());
1789     for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
1790       mangleExpression(CE->getArg(I));
1791     Out << 'E';
1792     break;
1793   }
1794
1795   case Expr::CXXNewExprClass: {
1796     // Proposal from David Vandervoorde, 2010.06.30
1797     const CXXNewExpr *New = cast<CXXNewExpr>(E);
1798     if (New->isGlobalNew()) Out << "gs";
1799     Out << (New->isArray() ? "na" : "nw");
1800     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
1801            E = New->placement_arg_end(); I != E; ++I)
1802       mangleExpression(*I);
1803     Out << '_';
1804     mangleType(New->getAllocatedType());
1805     if (New->hasInitializer()) {
1806       Out << "pi";
1807       for (CXXNewExpr::const_arg_iterator I = New->constructor_arg_begin(),
1808              E = New->constructor_arg_end(); I != E; ++I)
1809         mangleExpression(*I);
1810     }
1811     Out << 'E';
1812     break;
1813   }
1814
1815   case Expr::MemberExprClass: {
1816     const MemberExpr *ME = cast<MemberExpr>(E);
1817     mangleMemberExpr(ME->getBase(), ME->isArrow(),
1818                      ME->getQualifier(), ME->getMemberDecl()->getDeclName(),
1819                      Arity);
1820     break;
1821   }
1822
1823   case Expr::UnresolvedMemberExprClass: {
1824     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
1825     mangleMemberExpr(ME->getBase(), ME->isArrow(),
1826                      ME->getQualifier(), ME->getMemberName(),
1827                      Arity);
1828     if (ME->hasExplicitTemplateArgs())
1829       mangleTemplateArgs(ME->getExplicitTemplateArgs());
1830     break;
1831   }
1832
1833   case Expr::CXXDependentScopeMemberExprClass: {
1834     const CXXDependentScopeMemberExpr *ME
1835       = cast<CXXDependentScopeMemberExpr>(E);
1836     mangleMemberExpr(ME->getBase(), ME->isArrow(),
1837                      ME->getQualifier(), ME->getMember(),
1838                      Arity);
1839     if (ME->hasExplicitTemplateArgs())
1840       mangleTemplateArgs(ME->getExplicitTemplateArgs());
1841     break;
1842   }
1843
1844   case Expr::UnresolvedLookupExprClass: {
1845     // The ABI doesn't cover how to mangle overload sets, so we mangle
1846     // using something as close as possible to the original lookup
1847     // expression.
1848     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
1849     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
1850     if (ULE->hasExplicitTemplateArgs())
1851       mangleTemplateArgs(ULE->getExplicitTemplateArgs());
1852     break;
1853   }
1854
1855   case Expr::CXXUnresolvedConstructExprClass: {
1856     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
1857     unsigned N = CE->arg_size();
1858
1859     Out << "cv";
1860     mangleType(CE->getType());
1861     if (N != 1) Out << '_';
1862     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
1863     if (N != 1) Out << 'E';
1864     break;
1865   }
1866
1867   case Expr::CXXTemporaryObjectExprClass:
1868   case Expr::CXXConstructExprClass: {
1869     const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
1870     unsigned N = CE->getNumArgs();
1871
1872     Out << "cv";
1873     mangleType(CE->getType());
1874     if (N != 1) Out << '_';
1875     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
1876     if (N != 1) Out << 'E';
1877     break;
1878   }
1879
1880   case Expr::SizeOfAlignOfExprClass: {
1881     const SizeOfAlignOfExpr *SAE = cast<SizeOfAlignOfExpr>(E);
1882     if (SAE->isSizeOf()) Out << 's';
1883     else Out << 'a';
1884     if (SAE->isArgumentType()) {
1885       Out << 't';
1886       mangleType(SAE->getArgumentType());
1887     } else {
1888       Out << 'z';
1889       mangleExpression(SAE->getArgumentExpr());
1890     }
1891     break;
1892   }
1893
1894   case Expr::CXXThrowExprClass: {
1895     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
1896
1897     // Proposal from David Vandervoorde, 2010.06.30
1898     if (TE->getSubExpr()) {
1899       Out << "tw";
1900       mangleExpression(TE->getSubExpr());
1901     } else {
1902       Out << "tr";
1903     }
1904     break;
1905   }
1906
1907   case Expr::CXXTypeidExprClass: {
1908     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
1909
1910     // Proposal from David Vandervoorde, 2010.06.30
1911     if (TIE->isTypeOperand()) {
1912       Out << "ti";
1913       mangleType(TIE->getTypeOperand());
1914     } else {
1915       Out << "te";
1916       mangleExpression(TIE->getExprOperand());
1917     }
1918     break;
1919   }
1920
1921   case Expr::CXXDeleteExprClass: {
1922     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
1923
1924     // Proposal from David Vandervoorde, 2010.06.30
1925     if (DE->isGlobalDelete()) Out << "gs";
1926     Out << (DE->isArrayForm() ? "da" : "dl");
1927     mangleExpression(DE->getArgument());
1928     break;
1929   }
1930
1931   case Expr::UnaryOperatorClass: {
1932     const UnaryOperator *UO = cast<UnaryOperator>(E);
1933     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
1934                        /*Arity=*/1);
1935     mangleExpression(UO->getSubExpr());
1936     break;
1937   }
1938
1939   case Expr::ArraySubscriptExprClass: {
1940     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
1941
1942     // Array subscript is treated as a syntactically wierd form of
1943     // binary operator.
1944     Out << "ix";
1945     mangleExpression(AE->getLHS());
1946     mangleExpression(AE->getRHS());
1947     break;
1948   }
1949
1950   case Expr::CompoundAssignOperatorClass: // fallthrough
1951   case Expr::BinaryOperatorClass: {
1952     const BinaryOperator *BO = cast<BinaryOperator>(E);
1953     mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
1954                        /*Arity=*/2);
1955     mangleExpression(BO->getLHS());
1956     mangleExpression(BO->getRHS());
1957     break;
1958   }
1959
1960   case Expr::ConditionalOperatorClass: {
1961     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
1962     mangleOperatorName(OO_Conditional, /*Arity=*/3);
1963     mangleExpression(CO->getCond());
1964     mangleExpression(CO->getLHS(), Arity);
1965     mangleExpression(CO->getRHS(), Arity);
1966     break;
1967   }
1968
1969   case Expr::ImplicitCastExprClass: {
1970     mangleExpression(cast<ImplicitCastExpr>(E)->getSubExpr(), Arity);
1971     break;
1972   }
1973
1974   case Expr::CStyleCastExprClass:
1975   case Expr::CXXStaticCastExprClass:
1976   case Expr::CXXDynamicCastExprClass:
1977   case Expr::CXXReinterpretCastExprClass:
1978   case Expr::CXXConstCastExprClass:
1979   case Expr::CXXFunctionalCastExprClass: {
1980     const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
1981     Out << "cv";
1982     mangleType(ECE->getType());
1983     mangleExpression(ECE->getSubExpr());
1984     break;
1985   }
1986
1987   case Expr::CXXOperatorCallExprClass: {
1988     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
1989     unsigned NumArgs = CE->getNumArgs();
1990     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
1991     // Mangle the arguments.
1992     for (unsigned i = 0; i != NumArgs; ++i)
1993       mangleExpression(CE->getArg(i));
1994     break;
1995   }
1996
1997   case Expr::ParenExprClass:
1998     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
1999     break;
2000
2001   case Expr::DeclRefExprClass: {
2002     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2003
2004     switch (D->getKind()) {
2005     default:
2006       //  <expr-primary> ::= L <mangled-name> E # external name
2007       Out << 'L';
2008       mangle(D, "_Z");
2009       Out << 'E';
2010       break;
2011
2012     case Decl::EnumConstant: {
2013       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2014       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2015       break;
2016     }
2017
2018     case Decl::NonTypeTemplateParm: {
2019       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2020       mangleTemplateParameter(PD->getIndex());
2021       break;
2022     }
2023
2024     }
2025
2026     break;
2027   }
2028
2029   case Expr::SubstNonTypeTemplateParmPackExprClass:
2030     mangleTemplateParameter(
2031      cast<SubstNonTypeTemplateParmPackExpr>(E)->getParameterPack()->getIndex());
2032     break;
2033       
2034   case Expr::DependentScopeDeclRefExprClass: {
2035     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
2036     NestedNameSpecifier *NNS = DRE->getQualifier();
2037     const Type *QTy = NNS->getAsType();
2038
2039     // When we're dealing with a nested-name-specifier that has just a
2040     // dependent identifier in it, mangle that as a typename.  FIXME:
2041     // It isn't clear that we ever actually want to have such a
2042     // nested-name-specifier; why not just represent it as a typename type?
2043     if (!QTy && NNS->getAsIdentifier() && NNS->getPrefix()) {
2044       QTy = getASTContext().getDependentNameType(ETK_Typename,
2045                                                  NNS->getPrefix(),
2046                                                  NNS->getAsIdentifier())
2047               .getTypePtr();
2048     }
2049     assert(QTy && "Qualifier was not type!");
2050
2051     // ::= sr <type> <unqualified-name>                  # dependent name
2052     // ::= sr <type> <unqualified-name> <template-args>  # dependent template-id
2053     Out << "sr";
2054     mangleType(QualType(QTy, 0));
2055     mangleUnqualifiedName(0, DRE->getDeclName(), Arity);
2056     if (DRE->hasExplicitTemplateArgs())
2057       mangleTemplateArgs(DRE->getExplicitTemplateArgs());
2058
2059     break;
2060   }
2061
2062   case Expr::CXXBindTemporaryExprClass:
2063     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
2064     break;
2065
2066   case Expr::ExprWithCleanupsClass:
2067     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
2068     break;
2069
2070   case Expr::FloatingLiteralClass: {
2071     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
2072     Out << 'L';
2073     mangleType(FL->getType());
2074     mangleFloat(FL->getValue());
2075     Out << 'E';
2076     break;
2077   }
2078
2079   case Expr::CharacterLiteralClass:
2080     Out << 'L';
2081     mangleType(E->getType());
2082     Out << cast<CharacterLiteral>(E)->getValue();
2083     Out << 'E';
2084     break;
2085
2086   case Expr::CXXBoolLiteralExprClass:
2087     Out << "Lb";
2088     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
2089     Out << 'E';
2090     break;
2091
2092   case Expr::IntegerLiteralClass: {
2093     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
2094     if (E->getType()->isSignedIntegerType())
2095       Value.setIsSigned(true);
2096     mangleIntegerLiteral(E->getType(), Value);
2097     break;
2098   }
2099
2100   case Expr::ImaginaryLiteralClass: {
2101     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
2102     // Mangle as if a complex literal.
2103     // Proposal from David Vandevoorde, 2010.06.30.
2104     Out << 'L';
2105     mangleType(E->getType());
2106     if (const FloatingLiteral *Imag =
2107           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
2108       // Mangle a floating-point zero of the appropriate type.
2109       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
2110       Out << '_';
2111       mangleFloat(Imag->getValue());
2112     } else {
2113       Out << "0_";
2114       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
2115       if (IE->getSubExpr()->getType()->isSignedIntegerType())
2116         Value.setIsSigned(true);
2117       mangleNumber(Value);
2118     }
2119     Out << 'E';
2120     break;
2121   }
2122
2123   case Expr::StringLiteralClass: {
2124     // Revised proposal from David Vandervoorde, 2010.07.15.
2125     Out << 'L';
2126     assert(isa<ConstantArrayType>(E->getType()));
2127     mangleType(E->getType());
2128     Out << 'E';
2129     break;
2130   }
2131
2132   case Expr::GNUNullExprClass:
2133     // FIXME: should this really be mangled the same as nullptr?
2134     // fallthrough
2135
2136   case Expr::CXXNullPtrLiteralExprClass: {
2137     // Proposal from David Vandervoorde, 2010.06.30, as
2138     // modified by ABI list discussion.
2139     Out << "LDnE";
2140     break;
2141   }
2142       
2143   case Expr::PackExpansionExprClass:
2144     Out << "sp";
2145     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
2146     break;
2147       
2148   case Expr::SizeOfPackExprClass: {
2149     Out << "sZ";
2150     const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
2151     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
2152       mangleTemplateParameter(TTP->getIndex());
2153     else if (const NonTypeTemplateParmDecl *NTTP
2154                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
2155       mangleTemplateParameter(NTTP->getIndex());
2156     else if (const TemplateTemplateParmDecl *TempTP
2157                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
2158       mangleTemplateParameter(TempTP->getIndex());
2159     else {
2160       // Note: proposed by Mike Herrick on 11/30/10
2161       // <expression> ::= sZ <function-param>  # size of function parameter pack
2162       Diagnostic &Diags = Context.getDiags();
2163       unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
2164                             "cannot mangle sizeof...(function parameter pack)");
2165       Diags.Report(DiagID);
2166       return;
2167     }
2168   }
2169   }
2170 }
2171
2172 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
2173   // <ctor-dtor-name> ::= C1  # complete object constructor
2174   //                  ::= C2  # base object constructor
2175   //                  ::= C3  # complete object allocating constructor
2176   //
2177   switch (T) {
2178   case Ctor_Complete:
2179     Out << "C1";
2180     break;
2181   case Ctor_Base:
2182     Out << "C2";
2183     break;
2184   case Ctor_CompleteAllocating:
2185     Out << "C3";
2186     break;
2187   }
2188 }
2189
2190 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
2191   // <ctor-dtor-name> ::= D0  # deleting destructor
2192   //                  ::= D1  # complete object destructor
2193   //                  ::= D2  # base object destructor
2194   //
2195   switch (T) {
2196   case Dtor_Deleting:
2197     Out << "D0";
2198     break;
2199   case Dtor_Complete:
2200     Out << "D1";
2201     break;
2202   case Dtor_Base:
2203     Out << "D2";
2204     break;
2205   }
2206 }
2207
2208 void CXXNameMangler::mangleTemplateArgs(
2209                           const ExplicitTemplateArgumentList &TemplateArgs) {
2210   // <template-args> ::= I <template-arg>+ E
2211   Out << 'I';
2212   for (unsigned I = 0, E = TemplateArgs.NumTemplateArgs; I != E; ++I)
2213     mangleTemplateArg(0, TemplateArgs.getTemplateArgs()[I].getArgument());
2214   Out << 'E';
2215 }
2216
2217 void CXXNameMangler::mangleTemplateArgs(TemplateName Template,
2218                                         const TemplateArgument *TemplateArgs,
2219                                         unsigned NumTemplateArgs) {
2220   if (TemplateDecl *TD = Template.getAsTemplateDecl())
2221     return mangleTemplateArgs(*TD->getTemplateParameters(), TemplateArgs,
2222                               NumTemplateArgs);
2223   
2224   // <template-args> ::= I <template-arg>+ E
2225   Out << 'I';
2226   for (unsigned i = 0; i != NumTemplateArgs; ++i)
2227     mangleTemplateArg(0, TemplateArgs[i]);
2228   Out << 'E';
2229 }
2230
2231 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
2232                                         const TemplateArgumentList &AL) {
2233   // <template-args> ::= I <template-arg>+ E
2234   Out << 'I';
2235   for (unsigned i = 0, e = AL.size(); i != e; ++i)
2236     mangleTemplateArg(PL.getParam(i), AL[i]);
2237   Out << 'E';
2238 }
2239
2240 void CXXNameMangler::mangleTemplateArgs(const TemplateParameterList &PL,
2241                                         const TemplateArgument *TemplateArgs,
2242                                         unsigned NumTemplateArgs) {
2243   // <template-args> ::= I <template-arg>+ E
2244   Out << 'I';
2245   for (unsigned i = 0; i != NumTemplateArgs; ++i)
2246     mangleTemplateArg(PL.getParam(i), TemplateArgs[i]);
2247   Out << 'E';
2248 }
2249
2250 void CXXNameMangler::mangleTemplateArg(const NamedDecl *P,
2251                                        const TemplateArgument &A) {
2252   // <template-arg> ::= <type>              # type or template
2253   //                ::= X <expression> E    # expression
2254   //                ::= <expr-primary>      # simple expressions
2255   //                ::= J <template-arg>* E # argument pack
2256   //                ::= sp <expression>     # pack expansion of (C++0x)
2257   switch (A.getKind()) {
2258   case TemplateArgument::Null:
2259     llvm_unreachable("Cannot mangle NULL template argument");
2260       
2261   case TemplateArgument::Type:
2262     mangleType(A.getAsType());
2263     break;
2264   case TemplateArgument::Template:
2265     // This is mangled as <type>.
2266     mangleType(A.getAsTemplate());
2267     break;
2268   case TemplateArgument::TemplateExpansion:
2269     // <type>  ::= Dp <type>          # pack expansion (C++0x)
2270     Out << "Dp";
2271     mangleType(A.getAsTemplateOrTemplatePattern());
2272     break;
2273   case TemplateArgument::Expression:
2274     Out << 'X';
2275     mangleExpression(A.getAsExpr());
2276     Out << 'E';
2277     break;
2278   case TemplateArgument::Integral:
2279     mangleIntegerLiteral(A.getIntegralType(), *A.getAsIntegral());
2280     break;
2281   case TemplateArgument::Declaration: {
2282     assert(P && "Missing template parameter for declaration argument");
2283     //  <expr-primary> ::= L <mangled-name> E # external name
2284
2285     // Clang produces AST's where pointer-to-member-function expressions
2286     // and pointer-to-function expressions are represented as a declaration not
2287     // an expression. We compensate for it here to produce the correct mangling.
2288     NamedDecl *D = cast<NamedDecl>(A.getAsDecl());
2289     const NonTypeTemplateParmDecl *Parameter = cast<NonTypeTemplateParmDecl>(P);
2290     bool compensateMangling = D->isCXXClassMember() &&
2291       !Parameter->getType()->isReferenceType();
2292     if (compensateMangling) {
2293       Out << 'X';
2294       mangleOperatorName(OO_Amp, 1);
2295     }
2296
2297     Out << 'L';
2298     // References to external entities use the mangled name; if the name would
2299     // not normally be manged then mangle it as unqualified.
2300     //
2301     // FIXME: The ABI specifies that external names here should have _Z, but
2302     // gcc leaves this off.
2303     if (compensateMangling)
2304       mangle(D, "_Z");
2305     else
2306       mangle(D, "Z");
2307     Out << 'E';
2308
2309     if (compensateMangling)
2310       Out << 'E';
2311
2312     break;
2313   }
2314       
2315   case TemplateArgument::Pack: {
2316     // Note: proposal by Mike Herrick on 12/20/10
2317     Out << 'J';
2318     for (TemplateArgument::pack_iterator PA = A.pack_begin(), 
2319                                       PAEnd = A.pack_end();
2320          PA != PAEnd; ++PA)
2321       mangleTemplateArg(P, *PA);
2322     Out << 'E';
2323   }
2324   }
2325 }
2326
2327 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
2328   // <template-param> ::= T_    # first template parameter
2329   //                  ::= T <parameter-2 non-negative number> _
2330   if (Index == 0)
2331     Out << "T_";
2332   else
2333     Out << 'T' << (Index - 1) << '_';
2334 }
2335
2336 // <substitution> ::= S <seq-id> _
2337 //                ::= S_
2338 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
2339   // Try one of the standard substitutions first.
2340   if (mangleStandardSubstitution(ND))
2341     return true;
2342
2343   ND = cast<NamedDecl>(ND->getCanonicalDecl());
2344   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
2345 }
2346
2347 bool CXXNameMangler::mangleSubstitution(QualType T) {
2348   if (!T.getCVRQualifiers()) {
2349     if (const RecordType *RT = T->getAs<RecordType>())
2350       return mangleSubstitution(RT->getDecl());
2351   }
2352
2353   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
2354
2355   return mangleSubstitution(TypePtr);
2356 }
2357
2358 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
2359   if (TemplateDecl *TD = Template.getAsTemplateDecl())
2360     return mangleSubstitution(TD);
2361   
2362   Template = Context.getASTContext().getCanonicalTemplateName(Template);
2363   return mangleSubstitution(
2364                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
2365 }
2366
2367 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
2368   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
2369   if (I == Substitutions.end())
2370     return false;
2371
2372   unsigned SeqID = I->second;
2373   if (SeqID == 0)
2374     Out << "S_";
2375   else {
2376     SeqID--;
2377
2378     // <seq-id> is encoded in base-36, using digits and upper case letters.
2379     char Buffer[10];
2380     char *BufferPtr = llvm::array_endof(Buffer);
2381
2382     if (SeqID == 0) *--BufferPtr = '0';
2383
2384     while (SeqID) {
2385       assert(BufferPtr > Buffer && "Buffer overflow!");
2386
2387       char c = static_cast<char>(SeqID % 36);
2388
2389       *--BufferPtr =  (c < 10 ? '0' + c : 'A' + c - 10);
2390       SeqID /= 36;
2391     }
2392
2393     Out << 'S'
2394         << llvm::StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
2395         << '_';
2396   }
2397
2398   return true;
2399 }
2400
2401 static bool isCharType(QualType T) {
2402   if (T.isNull())
2403     return false;
2404
2405   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
2406     T->isSpecificBuiltinType(BuiltinType::Char_U);
2407 }
2408
2409 /// isCharSpecialization - Returns whether a given type is a template
2410 /// specialization of a given name with a single argument of type char.
2411 static bool isCharSpecialization(QualType T, const char *Name) {
2412   if (T.isNull())
2413     return false;
2414
2415   const RecordType *RT = T->getAs<RecordType>();
2416   if (!RT)
2417     return false;
2418
2419   const ClassTemplateSpecializationDecl *SD =
2420     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
2421   if (!SD)
2422     return false;
2423
2424   if (!isStdNamespace(SD->getDeclContext()))
2425     return false;
2426
2427   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
2428   if (TemplateArgs.size() != 1)
2429     return false;
2430
2431   if (!isCharType(TemplateArgs[0].getAsType()))
2432     return false;
2433
2434   return SD->getIdentifier()->getName() == Name;
2435 }
2436
2437 template <std::size_t StrLen>
2438 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
2439                                        const char (&Str)[StrLen]) {
2440   if (!SD->getIdentifier()->isStr(Str))
2441     return false;
2442
2443   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
2444   if (TemplateArgs.size() != 2)
2445     return false;
2446
2447   if (!isCharType(TemplateArgs[0].getAsType()))
2448     return false;
2449
2450   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
2451     return false;
2452
2453   return true;
2454 }
2455
2456 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
2457   // <substitution> ::= St # ::std::
2458   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
2459     if (isStd(NS)) {
2460       Out << "St";
2461       return true;
2462     }
2463   }
2464
2465   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
2466     if (!isStdNamespace(TD->getDeclContext()))
2467       return false;
2468
2469     // <substitution> ::= Sa # ::std::allocator
2470     if (TD->getIdentifier()->isStr("allocator")) {
2471       Out << "Sa";
2472       return true;
2473     }
2474
2475     // <<substitution> ::= Sb # ::std::basic_string
2476     if (TD->getIdentifier()->isStr("basic_string")) {
2477       Out << "Sb";
2478       return true;
2479     }
2480   }
2481
2482   if (const ClassTemplateSpecializationDecl *SD =
2483         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
2484     if (!isStdNamespace(SD->getDeclContext()))
2485       return false;
2486
2487     //    <substitution> ::= Ss # ::std::basic_string<char,
2488     //                            ::std::char_traits<char>,
2489     //                            ::std::allocator<char> >
2490     if (SD->getIdentifier()->isStr("basic_string")) {
2491       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
2492
2493       if (TemplateArgs.size() != 3)
2494         return false;
2495
2496       if (!isCharType(TemplateArgs[0].getAsType()))
2497         return false;
2498
2499       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
2500         return false;
2501
2502       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
2503         return false;
2504
2505       Out << "Ss";
2506       return true;
2507     }
2508
2509     //    <substitution> ::= Si # ::std::basic_istream<char,
2510     //                            ::std::char_traits<char> >
2511     if (isStreamCharSpecialization(SD, "basic_istream")) {
2512       Out << "Si";
2513       return true;
2514     }
2515
2516     //    <substitution> ::= So # ::std::basic_ostream<char,
2517     //                            ::std::char_traits<char> >
2518     if (isStreamCharSpecialization(SD, "basic_ostream")) {
2519       Out << "So";
2520       return true;
2521     }
2522
2523     //    <substitution> ::= Sd # ::std::basic_iostream<char,
2524     //                            ::std::char_traits<char> >
2525     if (isStreamCharSpecialization(SD, "basic_iostream")) {
2526       Out << "Sd";
2527       return true;
2528     }
2529   }
2530   return false;
2531 }
2532
2533 void CXXNameMangler::addSubstitution(QualType T) {
2534   if (!T.getCVRQualifiers()) {
2535     if (const RecordType *RT = T->getAs<RecordType>()) {
2536       addSubstitution(RT->getDecl());
2537       return;
2538     }
2539   }
2540
2541   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
2542   addSubstitution(TypePtr);
2543 }
2544
2545 void CXXNameMangler::addSubstitution(TemplateName Template) {
2546   if (TemplateDecl *TD = Template.getAsTemplateDecl())
2547     return addSubstitution(TD);
2548   
2549   Template = Context.getASTContext().getCanonicalTemplateName(Template);
2550   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
2551 }
2552
2553 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
2554   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
2555   Substitutions[Ptr] = SeqID++;
2556 }
2557
2558 //
2559
2560 /// \brief Mangles the name of the declaration D and emits that name to the
2561 /// given output stream.
2562 ///
2563 /// If the declaration D requires a mangled name, this routine will emit that
2564 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
2565 /// and this routine will return false. In this case, the caller should just
2566 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
2567 /// name.
2568 void ItaniumMangleContext::mangleName(const NamedDecl *D,
2569                                       llvm::raw_ostream &Out) {
2570   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2571           "Invalid mangleName() call, argument is not a variable or function!");
2572   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2573          "Invalid mangleName() call on 'structor decl!");
2574
2575   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2576                                  getASTContext().getSourceManager(),
2577                                  "Mangling declaration");
2578
2579   CXXNameMangler Mangler(*this, Out);
2580   return Mangler.mangle(D);
2581 }
2582
2583 void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
2584                                          CXXCtorType Type,
2585                                          llvm::raw_ostream &Out) {
2586   CXXNameMangler Mangler(*this, Out, D, Type);
2587   Mangler.mangle(D);
2588 }
2589
2590 void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
2591                                          CXXDtorType Type,
2592                                          llvm::raw_ostream &Out) {
2593   CXXNameMangler Mangler(*this, Out, D, Type);
2594   Mangler.mangle(D);
2595 }
2596
2597 void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
2598                                        const ThunkInfo &Thunk,
2599                                        llvm::raw_ostream &Out) {
2600   //  <special-name> ::= T <call-offset> <base encoding>
2601   //                      # base is the nominal target function of thunk
2602   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
2603   //                      # base is the nominal target function of thunk
2604   //                      # first call-offset is 'this' adjustment
2605   //                      # second call-offset is result adjustment
2606   
2607   assert(!isa<CXXDestructorDecl>(MD) &&
2608          "Use mangleCXXDtor for destructor decls!");
2609   CXXNameMangler Mangler(*this, Out);
2610   Mangler.getStream() << "_ZT";
2611   if (!Thunk.Return.isEmpty())
2612     Mangler.getStream() << 'c';
2613   
2614   // Mangle the 'this' pointer adjustment.
2615   Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
2616   
2617   // Mangle the return pointer adjustment if there is one.
2618   if (!Thunk.Return.isEmpty())
2619     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
2620                              Thunk.Return.VBaseOffsetOffset);
2621   
2622   Mangler.mangleFunctionEncoding(MD);
2623 }
2624
2625 void 
2626 ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
2627                                          CXXDtorType Type,
2628                                          const ThisAdjustment &ThisAdjustment,
2629                                          llvm::raw_ostream &Out) {
2630   //  <special-name> ::= T <call-offset> <base encoding>
2631   //                      # base is the nominal target function of thunk
2632   CXXNameMangler Mangler(*this, Out, DD, Type);
2633   Mangler.getStream() << "_ZT";
2634
2635   // Mangle the 'this' pointer adjustment.
2636   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 
2637                            ThisAdjustment.VCallOffsetOffset);
2638
2639   Mangler.mangleFunctionEncoding(DD);
2640 }
2641
2642 /// mangleGuardVariable - Returns the mangled name for a guard variable
2643 /// for the passed in VarDecl.
2644 void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
2645                                                       llvm::raw_ostream &Out) {
2646   //  <special-name> ::= GV <object name>       # Guard variable for one-time
2647   //                                            # initialization
2648   CXXNameMangler Mangler(*this, Out);
2649   Mangler.getStream() << "_ZGV";
2650   Mangler.mangleName(D);
2651 }
2652
2653 void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
2654                                                     llvm::raw_ostream &Out) {
2655   // We match the GCC mangling here.
2656   //  <special-name> ::= GR <object name>
2657   CXXNameMangler Mangler(*this, Out);
2658   Mangler.getStream() << "_ZGR";
2659   Mangler.mangleName(D);
2660 }
2661
2662 void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
2663                                            llvm::raw_ostream &Out) {
2664   // <special-name> ::= TV <type>  # virtual table
2665   CXXNameMangler Mangler(*this, Out);
2666   Mangler.getStream() << "_ZTV";
2667   Mangler.mangleNameOrStandardSubstitution(RD);
2668 }
2669
2670 void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
2671                                         llvm::raw_ostream &Out) {
2672   // <special-name> ::= TT <type>  # VTT structure
2673   CXXNameMangler Mangler(*this, Out);
2674   Mangler.getStream() << "_ZTT";
2675   Mangler.mangleNameOrStandardSubstitution(RD);
2676 }
2677
2678 void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
2679                                                int64_t Offset,
2680                                                const CXXRecordDecl *Type,
2681                                                llvm::raw_ostream &Out) {
2682   // <special-name> ::= TC <type> <offset number> _ <base type>
2683   CXXNameMangler Mangler(*this, Out);
2684   Mangler.getStream() << "_ZTC";
2685   Mangler.mangleNameOrStandardSubstitution(RD);
2686   Mangler.getStream() << Offset;
2687   Mangler.getStream() << '_';
2688   Mangler.mangleNameOrStandardSubstitution(Type);
2689 }
2690
2691 void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
2692                                          llvm::raw_ostream &Out) {
2693   // <special-name> ::= TI <type>  # typeinfo structure
2694   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
2695   CXXNameMangler Mangler(*this, Out);
2696   Mangler.getStream() << "_ZTI";
2697   Mangler.mangleType(Ty);
2698 }
2699
2700 void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
2701                                              llvm::raw_ostream &Out) {
2702   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
2703   CXXNameMangler Mangler(*this, Out);
2704   Mangler.getStream() << "_ZTS";
2705   Mangler.mangleType(Ty);
2706 }
2707
2708 MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
2709                                                  Diagnostic &Diags) {
2710   return new ItaniumMangleContext(Context, Diags);
2711 }