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