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