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