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