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