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