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