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