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