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