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   if (!T->isInstantiationDependentType() || T->isDependentType())
2249     T = T.getCanonicalType();
2250   else {
2251     // Desugar any types that are purely sugar.
2252     do {
2253       // Don't desugar through template specialization types that aren't
2254       // type aliases. We need to mangle the template arguments as written.
2255       if (const TemplateSpecializationType *TST
2256                                       = dyn_cast<TemplateSpecializationType>(T))
2257         if (!TST->isTypeAlias())
2258           break;
2259 
2260       QualType Desugared
2261         = T.getSingleStepDesugaredType(Context.getASTContext());
2262       if (Desugared == T)
2263         break;
2264 
2265       T = Desugared;
2266     } while (true);
2267   }
2268   SplitQualType split = T.split();
2269   Qualifiers quals = split.Quals;
2270   const Type *ty = split.Ty;
2271 
2272   bool isSubstitutable = isTypeSubstitutable(quals, ty);
2273   if (isSubstitutable && mangleSubstitution(T))
2274     return;
2275 
2276   // If we're mangling a qualified array type, push the qualifiers to
2277   // the element type.
2278   if (quals && isa<ArrayType>(T)) {
2279     ty = Context.getASTContext().getAsArrayType(T);
2280     quals = Qualifiers();
2281 
2282     // Note that we don't update T: we want to add the
2283     // substitution at the original type.
2284   }
2285 
2286   if (quals) {
2287     mangleQualifiers(quals);
2288     // Recurse:  even if the qualified type isn't yet substitutable,
2289     // the unqualified type might be.
2290     mangleType(QualType(ty, 0));
2291   } else {
2292     switch (ty->getTypeClass()) {
2293 #define ABSTRACT_TYPE(CLASS, PARENT)
2294 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2295     case Type::CLASS: \
2296       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2297       return;
2298 #define TYPE(CLASS, PARENT) \
2299     case Type::CLASS: \
2300       mangleType(static_cast<const CLASS##Type*>(ty)); \
2301       break;
2302 #include "clang/AST/TypeNodes.def"
2303     }
2304   }
2305 
2306   // Add the substitution.
2307   if (isSubstitutable)
2308     addSubstitution(T);
2309 }
2310 
2311 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2312   if (!mangleStandardSubstitution(ND))
2313     mangleName(ND);
2314 }
2315 
2316 void CXXNameMangler::mangleType(const BuiltinType *T) {
2317   //  <type>         ::= <builtin-type>
2318   //  <builtin-type> ::= v  # void
2319   //                 ::= w  # wchar_t
2320   //                 ::= b  # bool
2321   //                 ::= c  # char
2322   //                 ::= a  # signed char
2323   //                 ::= h  # unsigned char
2324   //                 ::= s  # short
2325   //                 ::= t  # unsigned short
2326   //                 ::= i  # int
2327   //                 ::= j  # unsigned int
2328   //                 ::= l  # long
2329   //                 ::= m  # unsigned long
2330   //                 ::= x  # long long, __int64
2331   //                 ::= y  # unsigned long long, __int64
2332   //                 ::= n  # __int128
2333   //                 ::= o  # unsigned __int128
2334   //                 ::= f  # float
2335   //                 ::= d  # double
2336   //                 ::= e  # long double, __float80
2337   //                 ::= g  # __float128
2338   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
2339   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
2340   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
2341   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
2342   //                 ::= Di # char32_t
2343   //                 ::= Ds # char16_t
2344   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2345   //                 ::= u <source-name>    # vendor extended type
2346   std::string type_name;
2347   switch (T->getKind()) {
2348   case BuiltinType::Void:
2349     Out << 'v';
2350     break;
2351   case BuiltinType::Bool:
2352     Out << 'b';
2353     break;
2354   case BuiltinType::Char_U:
2355   case BuiltinType::Char_S:
2356     Out << 'c';
2357     break;
2358   case BuiltinType::UChar:
2359     Out << 'h';
2360     break;
2361   case BuiltinType::UShort:
2362     Out << 't';
2363     break;
2364   case BuiltinType::UInt:
2365     Out << 'j';
2366     break;
2367   case BuiltinType::ULong:
2368     Out << 'm';
2369     break;
2370   case BuiltinType::ULongLong:
2371     Out << 'y';
2372     break;
2373   case BuiltinType::UInt128:
2374     Out << 'o';
2375     break;
2376   case BuiltinType::SChar:
2377     Out << 'a';
2378     break;
2379   case BuiltinType::WChar_S:
2380   case BuiltinType::WChar_U:
2381     Out << 'w';
2382     break;
2383   case BuiltinType::Char16:
2384     Out << "Ds";
2385     break;
2386   case BuiltinType::Char32:
2387     Out << "Di";
2388     break;
2389   case BuiltinType::Short:
2390     Out << 's';
2391     break;
2392   case BuiltinType::Int:
2393     Out << 'i';
2394     break;
2395   case BuiltinType::Long:
2396     Out << 'l';
2397     break;
2398   case BuiltinType::LongLong:
2399     Out << 'x';
2400     break;
2401   case BuiltinType::Int128:
2402     Out << 'n';
2403     break;
2404   case BuiltinType::Half:
2405     Out << "Dh";
2406     break;
2407   case BuiltinType::Float:
2408     Out << 'f';
2409     break;
2410   case BuiltinType::Double:
2411     Out << 'd';
2412     break;
2413   case BuiltinType::LongDouble:
2414     Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2415                 ? 'g'
2416                 : 'e');
2417     break;
2418   case BuiltinType::Float128:
2419     if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2420       Out << "U10__float128"; // Match the GCC mangling
2421     else
2422       Out << 'g';
2423     break;
2424   case BuiltinType::NullPtr:
2425     Out << "Dn";
2426     break;
2427 
2428 #define BUILTIN_TYPE(Id, SingletonId)
2429 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2430   case BuiltinType::Id:
2431 #include "clang/AST/BuiltinTypes.def"
2432   case BuiltinType::Dependent:
2433     if (!NullOut)
2434       llvm_unreachable("mangling a placeholder type");
2435     break;
2436   case BuiltinType::ObjCId:
2437     Out << "11objc_object";
2438     break;
2439   case BuiltinType::ObjCClass:
2440     Out << "10objc_class";
2441     break;
2442   case BuiltinType::ObjCSel:
2443     Out << "13objc_selector";
2444     break;
2445 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2446   case BuiltinType::Id: \
2447     type_name = "ocl_" #ImgType "_" #Suffix; \
2448     Out << type_name.size() << type_name; \
2449     break;
2450 #include "clang/Basic/OpenCLImageTypes.def"
2451   case BuiltinType::OCLSampler:
2452     Out << "11ocl_sampler";
2453     break;
2454   case BuiltinType::OCLEvent:
2455     Out << "9ocl_event";
2456     break;
2457   case BuiltinType::OCLClkEvent:
2458     Out << "12ocl_clkevent";
2459     break;
2460   case BuiltinType::OCLQueue:
2461     Out << "9ocl_queue";
2462     break;
2463   case BuiltinType::OCLNDRange:
2464     Out << "11ocl_ndrange";
2465     break;
2466   case BuiltinType::OCLReserveID:
2467     Out << "13ocl_reserveid";
2468     break;
2469   }
2470 }
2471 
2472 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2473   switch (CC) {
2474   case CC_C:
2475     return "";
2476 
2477   case CC_X86StdCall:
2478   case CC_X86FastCall:
2479   case CC_X86ThisCall:
2480   case CC_X86VectorCall:
2481   case CC_X86Pascal:
2482   case CC_X86_64Win64:
2483   case CC_X86_64SysV:
2484   case CC_AAPCS:
2485   case CC_AAPCS_VFP:
2486   case CC_IntelOclBicc:
2487   case CC_SpirFunction:
2488   case CC_OpenCLKernel:
2489   case CC_PreserveMost:
2490   case CC_PreserveAll:
2491     // FIXME: we should be mangling all of the above.
2492     return "";
2493 
2494   case CC_Swift:
2495     return "swiftcall";
2496   }
2497   llvm_unreachable("bad calling convention");
2498 }
2499 
2500 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2501   // Fast path.
2502   if (T->getExtInfo() == FunctionType::ExtInfo())
2503     return;
2504 
2505   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2506   // This will get more complicated in the future if we mangle other
2507   // things here; but for now, since we mangle ns_returns_retained as
2508   // a qualifier on the result type, we can get away with this:
2509   StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2510   if (!CCQualifier.empty())
2511     mangleVendorQualifier(CCQualifier);
2512 
2513   // FIXME: regparm
2514   // FIXME: noreturn
2515 }
2516 
2517 void
2518 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2519   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2520 
2521   // Note that these are *not* substitution candidates.  Demanglers might
2522   // have trouble with this if the parameter type is fully substituted.
2523 
2524   switch (PI.getABI()) {
2525   case ParameterABI::Ordinary:
2526     break;
2527 
2528   // All of these start with "swift", so they come before "ns_consumed".
2529   case ParameterABI::SwiftContext:
2530   case ParameterABI::SwiftErrorResult:
2531   case ParameterABI::SwiftIndirectResult:
2532     mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2533     break;
2534   }
2535 
2536   if (PI.isConsumed())
2537     mangleVendorQualifier("ns_consumed");
2538 }
2539 
2540 // <type>          ::= <function-type>
2541 // <function-type> ::= [<CV-qualifiers>] F [Y]
2542 //                      <bare-function-type> [<ref-qualifier>] E
2543 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2544   mangleExtFunctionInfo(T);
2545 
2546   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
2547   // e.g. "const" in "int (A::*)() const".
2548   mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2549 
2550   Out << 'F';
2551 
2552   // FIXME: We don't have enough information in the AST to produce the 'Y'
2553   // encoding for extern "C" function types.
2554   mangleBareFunctionType(T, /*MangleReturnType=*/true);
2555 
2556   // Mangle the ref-qualifier, if present.
2557   mangleRefQualifier(T->getRefQualifier());
2558 
2559   Out << 'E';
2560 }
2561 
2562 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2563   // Function types without prototypes can arise when mangling a function type
2564   // within an overloadable function in C. We mangle these as the absence of any
2565   // parameter types (not even an empty parameter list).
2566   Out << 'F';
2567 
2568   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2569 
2570   FunctionTypeDepth.enterResultType();
2571   mangleType(T->getReturnType());
2572   FunctionTypeDepth.leaveResultType();
2573 
2574   FunctionTypeDepth.pop(saved);
2575   Out << 'E';
2576 }
2577 
2578 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2579                                             bool MangleReturnType,
2580                                             const FunctionDecl *FD) {
2581   // Record that we're in a function type.  See mangleFunctionParam
2582   // for details on what we're trying to achieve here.
2583   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2584 
2585   // <bare-function-type> ::= <signature type>+
2586   if (MangleReturnType) {
2587     FunctionTypeDepth.enterResultType();
2588 
2589     // Mangle ns_returns_retained as an order-sensitive qualifier here.
2590     if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2591       mangleVendorQualifier("ns_returns_retained");
2592 
2593     // Mangle the return type without any direct ARC ownership qualifiers.
2594     QualType ReturnTy = Proto->getReturnType();
2595     if (ReturnTy.getObjCLifetime()) {
2596       auto SplitReturnTy = ReturnTy.split();
2597       SplitReturnTy.Quals.removeObjCLifetime();
2598       ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2599     }
2600     mangleType(ReturnTy);
2601 
2602     FunctionTypeDepth.leaveResultType();
2603   }
2604 
2605   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2606     //   <builtin-type> ::= v   # void
2607     Out << 'v';
2608 
2609     FunctionTypeDepth.pop(saved);
2610     return;
2611   }
2612 
2613   assert(!FD || FD->getNumParams() == Proto->getNumParams());
2614   for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2615     // Mangle extended parameter info as order-sensitive qualifiers here.
2616     if (Proto->hasExtParameterInfos() && FD == nullptr) {
2617       mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2618     }
2619 
2620     // Mangle the type.
2621     QualType ParamTy = Proto->getParamType(I);
2622     mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2623 
2624     if (FD) {
2625       if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2626         // Attr can only take 1 character, so we can hardcode the length below.
2627         assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2628         Out << "U17pass_object_size" << Attr->getType();
2629       }
2630     }
2631   }
2632 
2633   FunctionTypeDepth.pop(saved);
2634 
2635   // <builtin-type>      ::= z  # ellipsis
2636   if (Proto->isVariadic())
2637     Out << 'z';
2638 }
2639 
2640 // <type>            ::= <class-enum-type>
2641 // <class-enum-type> ::= <name>
2642 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2643   mangleName(T->getDecl());
2644 }
2645 
2646 // <type>            ::= <class-enum-type>
2647 // <class-enum-type> ::= <name>
2648 void CXXNameMangler::mangleType(const EnumType *T) {
2649   mangleType(static_cast<const TagType*>(T));
2650 }
2651 void CXXNameMangler::mangleType(const RecordType *T) {
2652   mangleType(static_cast<const TagType*>(T));
2653 }
2654 void CXXNameMangler::mangleType(const TagType *T) {
2655   mangleName(T->getDecl());
2656 }
2657 
2658 // <type>       ::= <array-type>
2659 // <array-type> ::= A <positive dimension number> _ <element type>
2660 //              ::= A [<dimension expression>] _ <element type>
2661 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2662   Out << 'A' << T->getSize() << '_';
2663   mangleType(T->getElementType());
2664 }
2665 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2666   Out << 'A';
2667   // decayed vla types (size 0) will just be skipped.
2668   if (T->getSizeExpr())
2669     mangleExpression(T->getSizeExpr());
2670   Out << '_';
2671   mangleType(T->getElementType());
2672 }
2673 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2674   Out << 'A';
2675   mangleExpression(T->getSizeExpr());
2676   Out << '_';
2677   mangleType(T->getElementType());
2678 }
2679 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2680   Out << "A_";
2681   mangleType(T->getElementType());
2682 }
2683 
2684 // <type>                   ::= <pointer-to-member-type>
2685 // <pointer-to-member-type> ::= M <class type> <member type>
2686 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2687   Out << 'M';
2688   mangleType(QualType(T->getClass(), 0));
2689   QualType PointeeType = T->getPointeeType();
2690   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2691     mangleType(FPT);
2692 
2693     // Itanium C++ ABI 5.1.8:
2694     //
2695     //   The type of a non-static member function is considered to be different,
2696     //   for the purposes of substitution, from the type of a namespace-scope or
2697     //   static member function whose type appears similar. The types of two
2698     //   non-static member functions are considered to be different, for the
2699     //   purposes of substitution, if the functions are members of different
2700     //   classes. In other words, for the purposes of substitution, the class of
2701     //   which the function is a member is considered part of the type of
2702     //   function.
2703 
2704     // Given that we already substitute member function pointers as a
2705     // whole, the net effect of this rule is just to unconditionally
2706     // suppress substitution on the function type in a member pointer.
2707     // We increment the SeqID here to emulate adding an entry to the
2708     // substitution table.
2709     ++SeqID;
2710   } else
2711     mangleType(PointeeType);
2712 }
2713 
2714 // <type>           ::= <template-param>
2715 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2716   mangleTemplateParameter(T->getIndex());
2717 }
2718 
2719 // <type>           ::= <template-param>
2720 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2721   // FIXME: not clear how to mangle this!
2722   // template <class T...> class A {
2723   //   template <class U...> void foo(T(*)(U) x...);
2724   // };
2725   Out << "_SUBSTPACK_";
2726 }
2727 
2728 // <type> ::= P <type>   # pointer-to
2729 void CXXNameMangler::mangleType(const PointerType *T) {
2730   Out << 'P';
2731   mangleType(T->getPointeeType());
2732 }
2733 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2734   Out << 'P';
2735   mangleType(T->getPointeeType());
2736 }
2737 
2738 // <type> ::= R <type>   # reference-to
2739 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2740   Out << 'R';
2741   mangleType(T->getPointeeType());
2742 }
2743 
2744 // <type> ::= O <type>   # rvalue reference-to (C++0x)
2745 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2746   Out << 'O';
2747   mangleType(T->getPointeeType());
2748 }
2749 
2750 // <type> ::= C <type>   # complex pair (C 2000)
2751 void CXXNameMangler::mangleType(const ComplexType *T) {
2752   Out << 'C';
2753   mangleType(T->getElementType());
2754 }
2755 
2756 // ARM's ABI for Neon vector types specifies that they should be mangled as
2757 // if they are structs (to match ARM's initial implementation).  The
2758 // vector type must be one of the special types predefined by ARM.
2759 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2760   QualType EltType = T->getElementType();
2761   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2762   const char *EltName = nullptr;
2763   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2764     switch (cast<BuiltinType>(EltType)->getKind()) {
2765     case BuiltinType::SChar:
2766     case BuiltinType::UChar:
2767       EltName = "poly8_t";
2768       break;
2769     case BuiltinType::Short:
2770     case BuiltinType::UShort:
2771       EltName = "poly16_t";
2772       break;
2773     case BuiltinType::ULongLong:
2774       EltName = "poly64_t";
2775       break;
2776     default: llvm_unreachable("unexpected Neon polynomial vector element type");
2777     }
2778   } else {
2779     switch (cast<BuiltinType>(EltType)->getKind()) {
2780     case BuiltinType::SChar:     EltName = "int8_t"; break;
2781     case BuiltinType::UChar:     EltName = "uint8_t"; break;
2782     case BuiltinType::Short:     EltName = "int16_t"; break;
2783     case BuiltinType::UShort:    EltName = "uint16_t"; break;
2784     case BuiltinType::Int:       EltName = "int32_t"; break;
2785     case BuiltinType::UInt:      EltName = "uint32_t"; break;
2786     case BuiltinType::LongLong:  EltName = "int64_t"; break;
2787     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2788     case BuiltinType::Double:    EltName = "float64_t"; break;
2789     case BuiltinType::Float:     EltName = "float32_t"; break;
2790     case BuiltinType::Half:      EltName = "float16_t";break;
2791     default:
2792       llvm_unreachable("unexpected Neon vector element type");
2793     }
2794   }
2795   const char *BaseName = nullptr;
2796   unsigned BitSize = (T->getNumElements() *
2797                       getASTContext().getTypeSize(EltType));
2798   if (BitSize == 64)
2799     BaseName = "__simd64_";
2800   else {
2801     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2802     BaseName = "__simd128_";
2803   }
2804   Out << strlen(BaseName) + strlen(EltName);
2805   Out << BaseName << EltName;
2806 }
2807 
2808 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2809   switch (EltType->getKind()) {
2810   case BuiltinType::SChar:
2811     return "Int8";
2812   case BuiltinType::Short:
2813     return "Int16";
2814   case BuiltinType::Int:
2815     return "Int32";
2816   case BuiltinType::Long:
2817   case BuiltinType::LongLong:
2818     return "Int64";
2819   case BuiltinType::UChar:
2820     return "Uint8";
2821   case BuiltinType::UShort:
2822     return "Uint16";
2823   case BuiltinType::UInt:
2824     return "Uint32";
2825   case BuiltinType::ULong:
2826   case BuiltinType::ULongLong:
2827     return "Uint64";
2828   case BuiltinType::Half:
2829     return "Float16";
2830   case BuiltinType::Float:
2831     return "Float32";
2832   case BuiltinType::Double:
2833     return "Float64";
2834   default:
2835     llvm_unreachable("Unexpected vector element base type");
2836   }
2837 }
2838 
2839 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2840 // the equivalent internal name. The vector type must be one of the special
2841 // types predefined by ARM.
2842 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2843   QualType EltType = T->getElementType();
2844   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2845   unsigned BitSize =
2846       (T->getNumElements() * getASTContext().getTypeSize(EltType));
2847   (void)BitSize; // Silence warning.
2848 
2849   assert((BitSize == 64 || BitSize == 128) &&
2850          "Neon vector type not 64 or 128 bits");
2851 
2852   StringRef EltName;
2853   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2854     switch (cast<BuiltinType>(EltType)->getKind()) {
2855     case BuiltinType::UChar:
2856       EltName = "Poly8";
2857       break;
2858     case BuiltinType::UShort:
2859       EltName = "Poly16";
2860       break;
2861     case BuiltinType::ULong:
2862     case BuiltinType::ULongLong:
2863       EltName = "Poly64";
2864       break;
2865     default:
2866       llvm_unreachable("unexpected Neon polynomial vector element type");
2867     }
2868   } else
2869     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2870 
2871   std::string TypeName =
2872       ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2873   Out << TypeName.length() << TypeName;
2874 }
2875 
2876 // GNU extension: vector types
2877 // <type>                  ::= <vector-type>
2878 // <vector-type>           ::= Dv <positive dimension number> _
2879 //                                    <extended element type>
2880 //                         ::= Dv [<dimension expression>] _ <element type>
2881 // <extended element type> ::= <element type>
2882 //                         ::= p # AltiVec vector pixel
2883 //                         ::= b # Altivec vector bool
2884 void CXXNameMangler::mangleType(const VectorType *T) {
2885   if ((T->getVectorKind() == VectorType::NeonVector ||
2886        T->getVectorKind() == VectorType::NeonPolyVector)) {
2887     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2888     llvm::Triple::ArchType Arch =
2889         getASTContext().getTargetInfo().getTriple().getArch();
2890     if ((Arch == llvm::Triple::aarch64 ||
2891          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2892       mangleAArch64NeonVectorType(T);
2893     else
2894       mangleNeonVectorType(T);
2895     return;
2896   }
2897   Out << "Dv" << T->getNumElements() << '_';
2898   if (T->getVectorKind() == VectorType::AltiVecPixel)
2899     Out << 'p';
2900   else if (T->getVectorKind() == VectorType::AltiVecBool)
2901     Out << 'b';
2902   else
2903     mangleType(T->getElementType());
2904 }
2905 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2906   mangleType(static_cast<const VectorType*>(T));
2907 }
2908 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2909   Out << "Dv";
2910   mangleExpression(T->getSizeExpr());
2911   Out << '_';
2912   mangleType(T->getElementType());
2913 }
2914 
2915 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2916   // <type>  ::= Dp <type>          # pack expansion (C++0x)
2917   Out << "Dp";
2918   mangleType(T->getPattern());
2919 }
2920 
2921 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2922   mangleSourceName(T->getDecl()->getIdentifier());
2923 }
2924 
2925 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2926   // Treat __kindof as a vendor extended type qualifier.
2927   if (T->isKindOfType())
2928     Out << "U8__kindof";
2929 
2930   if (!T->qual_empty()) {
2931     // Mangle protocol qualifiers.
2932     SmallString<64> QualStr;
2933     llvm::raw_svector_ostream QualOS(QualStr);
2934     QualOS << "objcproto";
2935     for (const auto *I : T->quals()) {
2936       StringRef name = I->getName();
2937       QualOS << name.size() << name;
2938     }
2939     Out << 'U' << QualStr.size() << QualStr;
2940   }
2941 
2942   mangleType(T->getBaseType());
2943 
2944   if (T->isSpecialized()) {
2945     // Mangle type arguments as I <type>+ E
2946     Out << 'I';
2947     for (auto typeArg : T->getTypeArgs())
2948       mangleType(typeArg);
2949     Out << 'E';
2950   }
2951 }
2952 
2953 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2954   Out << "U13block_pointer";
2955   mangleType(T->getPointeeType());
2956 }
2957 
2958 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2959   // Mangle injected class name types as if the user had written the
2960   // specialization out fully.  It may not actually be possible to see
2961   // this mangling, though.
2962   mangleType(T->getInjectedSpecializationType());
2963 }
2964 
2965 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2966   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2967     mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
2968   } else {
2969     if (mangleSubstitution(QualType(T, 0)))
2970       return;
2971 
2972     mangleTemplatePrefix(T->getTemplateName());
2973 
2974     // FIXME: GCC does not appear to mangle the template arguments when
2975     // the template in question is a dependent template name. Should we
2976     // emulate that badness?
2977     mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2978     addSubstitution(QualType(T, 0));
2979   }
2980 }
2981 
2982 void CXXNameMangler::mangleType(const DependentNameType *T) {
2983   // Proposal by cxx-abi-dev, 2014-03-26
2984   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
2985   //                                 # dependent elaborated type specifier using
2986   //                                 # 'typename'
2987   //                   ::= Ts <name> # dependent elaborated type specifier using
2988   //                                 # 'struct' or 'class'
2989   //                   ::= Tu <name> # dependent elaborated type specifier using
2990   //                                 # 'union'
2991   //                   ::= Te <name> # dependent elaborated type specifier using
2992   //                                 # 'enum'
2993   switch (T->getKeyword()) {
2994     case ETK_Typename:
2995       break;
2996     case ETK_Struct:
2997     case ETK_Class:
2998     case ETK_Interface:
2999       Out << "Ts";
3000       break;
3001     case ETK_Union:
3002       Out << "Tu";
3003       break;
3004     case ETK_Enum:
3005       Out << "Te";
3006       break;
3007     default:
3008       llvm_unreachable("unexpected keyword for dependent type name");
3009   }
3010   // Typename types are always nested
3011   Out << 'N';
3012   manglePrefix(T->getQualifier());
3013   mangleSourceName(T->getIdentifier());
3014   Out << 'E';
3015 }
3016 
3017 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3018   // Dependently-scoped template types are nested if they have a prefix.
3019   Out << 'N';
3020 
3021   // TODO: avoid making this TemplateName.
3022   TemplateName Prefix =
3023     getASTContext().getDependentTemplateName(T->getQualifier(),
3024                                              T->getIdentifier());
3025   mangleTemplatePrefix(Prefix);
3026 
3027   // FIXME: GCC does not appear to mangle the template arguments when
3028   // the template in question is a dependent template name. Should we
3029   // emulate that badness?
3030   mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3031   Out << 'E';
3032 }
3033 
3034 void CXXNameMangler::mangleType(const TypeOfType *T) {
3035   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3036   // "extension with parameters" mangling.
3037   Out << "u6typeof";
3038 }
3039 
3040 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3041   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3042   // "extension with parameters" mangling.
3043   Out << "u6typeof";
3044 }
3045 
3046 void CXXNameMangler::mangleType(const DecltypeType *T) {
3047   Expr *E = T->getUnderlyingExpr();
3048 
3049   // type ::= Dt <expression> E  # decltype of an id-expression
3050   //                             #   or class member access
3051   //      ::= DT <expression> E  # decltype of an expression
3052 
3053   // This purports to be an exhaustive list of id-expressions and
3054   // class member accesses.  Note that we do not ignore parentheses;
3055   // parentheses change the semantics of decltype for these
3056   // expressions (and cause the mangler to use the other form).
3057   if (isa<DeclRefExpr>(E) ||
3058       isa<MemberExpr>(E) ||
3059       isa<UnresolvedLookupExpr>(E) ||
3060       isa<DependentScopeDeclRefExpr>(E) ||
3061       isa<CXXDependentScopeMemberExpr>(E) ||
3062       isa<UnresolvedMemberExpr>(E))
3063     Out << "Dt";
3064   else
3065     Out << "DT";
3066   mangleExpression(E);
3067   Out << 'E';
3068 }
3069 
3070 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3071   // If this is dependent, we need to record that. If not, we simply
3072   // mangle it as the underlying type since they are equivalent.
3073   if (T->isDependentType()) {
3074     Out << 'U';
3075 
3076     switch (T->getUTTKind()) {
3077       case UnaryTransformType::EnumUnderlyingType:
3078         Out << "3eut";
3079         break;
3080     }
3081   }
3082 
3083   mangleType(T->getBaseType());
3084 }
3085 
3086 void CXXNameMangler::mangleType(const AutoType *T) {
3087   QualType D = T->getDeducedType();
3088   // <builtin-type> ::= Da  # dependent auto
3089   if (D.isNull()) {
3090     assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3091            "shouldn't need to mangle __auto_type!");
3092     Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3093   } else
3094     mangleType(D);
3095 }
3096 
3097 void CXXNameMangler::mangleType(const AtomicType *T) {
3098   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
3099   // (Until there's a standardized mangling...)
3100   Out << "U7_Atomic";
3101   mangleType(T->getValueType());
3102 }
3103 
3104 void CXXNameMangler::mangleType(const PipeType *T) {
3105   // Pipe type mangling rules are described in SPIR 2.0 specification
3106   // A.1 Data types and A.3 Summary of changes
3107   // <type> ::= 8ocl_pipe
3108   Out << "8ocl_pipe";
3109 }
3110 
3111 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3112                                           const llvm::APSInt &Value) {
3113   //  <expr-primary> ::= L <type> <value number> E # integer literal
3114   Out << 'L';
3115 
3116   mangleType(T);
3117   if (T->isBooleanType()) {
3118     // Boolean values are encoded as 0/1.
3119     Out << (Value.getBoolValue() ? '1' : '0');
3120   } else {
3121     mangleNumber(Value);
3122   }
3123   Out << 'E';
3124 
3125 }
3126 
3127 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3128   // Ignore member expressions involving anonymous unions.
3129   while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3130     if (!RT->getDecl()->isAnonymousStructOrUnion())
3131       break;
3132     const auto *ME = dyn_cast<MemberExpr>(Base);
3133     if (!ME)
3134       break;
3135     Base = ME->getBase();
3136     IsArrow = ME->isArrow();
3137   }
3138 
3139   if (Base->isImplicitCXXThis()) {
3140     // Note: GCC mangles member expressions to the implicit 'this' as
3141     // *this., whereas we represent them as this->. The Itanium C++ ABI
3142     // does not specify anything here, so we follow GCC.
3143     Out << "dtdefpT";
3144   } else {
3145     Out << (IsArrow ? "pt" : "dt");
3146     mangleExpression(Base);
3147   }
3148 }
3149 
3150 /// Mangles a member expression.
3151 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3152                                       bool isArrow,
3153                                       NestedNameSpecifier *qualifier,
3154                                       NamedDecl *firstQualifierLookup,
3155                                       DeclarationName member,
3156                                       const TemplateArgumentLoc *TemplateArgs,
3157                                       unsigned NumTemplateArgs,
3158                                       unsigned arity) {
3159   // <expression> ::= dt <expression> <unresolved-name>
3160   //              ::= pt <expression> <unresolved-name>
3161   if (base)
3162     mangleMemberExprBase(base, isArrow);
3163   mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
3164 }
3165 
3166 /// Look at the callee of the given call expression and determine if
3167 /// it's a parenthesized id-expression which would have triggered ADL
3168 /// otherwise.
3169 static bool isParenthesizedADLCallee(const CallExpr *call) {
3170   const Expr *callee = call->getCallee();
3171   const Expr *fn = callee->IgnoreParens();
3172 
3173   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
3174   // too, but for those to appear in the callee, it would have to be
3175   // parenthesized.
3176   if (callee == fn) return false;
3177 
3178   // Must be an unresolved lookup.
3179   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3180   if (!lookup) return false;
3181 
3182   assert(!lookup->requiresADL());
3183 
3184   // Must be an unqualified lookup.
3185   if (lookup->getQualifier()) return false;
3186 
3187   // Must not have found a class member.  Note that if one is a class
3188   // member, they're all class members.
3189   if (lookup->getNumDecls() > 0 &&
3190       (*lookup->decls_begin())->isCXXClassMember())
3191     return false;
3192 
3193   // Otherwise, ADL would have been triggered.
3194   return true;
3195 }
3196 
3197 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3198   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3199   Out << CastEncoding;
3200   mangleType(ECE->getType());
3201   mangleExpression(ECE->getSubExpr());
3202 }
3203 
3204 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3205   if (auto *Syntactic = InitList->getSyntacticForm())
3206     InitList = Syntactic;
3207   for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3208     mangleExpression(InitList->getInit(i));
3209 }
3210 
3211 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3212   // <expression> ::= <unary operator-name> <expression>
3213   //              ::= <binary operator-name> <expression> <expression>
3214   //              ::= <trinary operator-name> <expression> <expression> <expression>
3215   //              ::= cv <type> expression           # conversion with one argument
3216   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3217   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
3218   //              ::= sc <type> <expression>         # static_cast<type> (expression)
3219   //              ::= cc <type> <expression>         # const_cast<type> (expression)
3220   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
3221   //              ::= st <type>                      # sizeof (a type)
3222   //              ::= at <type>                      # alignof (a type)
3223   //              ::= <template-param>
3224   //              ::= <function-param>
3225   //              ::= sr <type> <unqualified-name>                   # dependent name
3226   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
3227   //              ::= ds <expression> <expression>                   # expr.*expr
3228   //              ::= sZ <template-param>                            # size of a parameter pack
3229   //              ::= sZ <function-param>    # size of a function parameter pack
3230   //              ::= <expr-primary>
3231   // <expr-primary> ::= L <type> <value number> E    # integer literal
3232   //                ::= L <type <value float> E      # floating literal
3233   //                ::= L <mangled-name> E           # external name
3234   //                ::= fpT                          # 'this' expression
3235   QualType ImplicitlyConvertedToType;
3236 
3237 recurse:
3238   switch (E->getStmtClass()) {
3239   case Expr::NoStmtClass:
3240 #define ABSTRACT_STMT(Type)
3241 #define EXPR(Type, Base)
3242 #define STMT(Type, Base) \
3243   case Expr::Type##Class:
3244 #include "clang/AST/StmtNodes.inc"
3245     // fallthrough
3246 
3247   // These all can only appear in local or variable-initialization
3248   // contexts and so should never appear in a mangling.
3249   case Expr::AddrLabelExprClass:
3250   case Expr::DesignatedInitUpdateExprClass:
3251   case Expr::ImplicitValueInitExprClass:
3252   case Expr::NoInitExprClass:
3253   case Expr::ParenListExprClass:
3254   case Expr::LambdaExprClass:
3255   case Expr::MSPropertyRefExprClass:
3256   case Expr::MSPropertySubscriptExprClass:
3257   case Expr::TypoExprClass:  // This should no longer exist in the AST by now.
3258   case Expr::OMPArraySectionExprClass:
3259   case Expr::CXXInheritedCtorInitExprClass:
3260     llvm_unreachable("unexpected statement kind");
3261 
3262   // FIXME: invent manglings for all these.
3263   case Expr::BlockExprClass:
3264   case Expr::ChooseExprClass:
3265   case Expr::CompoundLiteralExprClass:
3266   case Expr::DesignatedInitExprClass:
3267   case Expr::ExtVectorElementExprClass:
3268   case Expr::GenericSelectionExprClass:
3269   case Expr::ObjCEncodeExprClass:
3270   case Expr::ObjCIsaExprClass:
3271   case Expr::ObjCIvarRefExprClass:
3272   case Expr::ObjCMessageExprClass:
3273   case Expr::ObjCPropertyRefExprClass:
3274   case Expr::ObjCProtocolExprClass:
3275   case Expr::ObjCSelectorExprClass:
3276   case Expr::ObjCStringLiteralClass:
3277   case Expr::ObjCBoxedExprClass:
3278   case Expr::ObjCArrayLiteralClass:
3279   case Expr::ObjCDictionaryLiteralClass:
3280   case Expr::ObjCSubscriptRefExprClass:
3281   case Expr::ObjCIndirectCopyRestoreExprClass:
3282   case Expr::ObjCAvailabilityCheckExprClass:
3283   case Expr::OffsetOfExprClass:
3284   case Expr::PredefinedExprClass:
3285   case Expr::ShuffleVectorExprClass:
3286   case Expr::ConvertVectorExprClass:
3287   case Expr::StmtExprClass:
3288   case Expr::TypeTraitExprClass:
3289   case Expr::ArrayTypeTraitExprClass:
3290   case Expr::ExpressionTraitExprClass:
3291   case Expr::VAArgExprClass:
3292   case Expr::CUDAKernelCallExprClass:
3293   case Expr::AsTypeExprClass:
3294   case Expr::PseudoObjectExprClass:
3295   case Expr::AtomicExprClass:
3296   {
3297     if (!NullOut) {
3298       // As bad as this diagnostic is, it's better than crashing.
3299       DiagnosticsEngine &Diags = Context.getDiags();
3300       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3301                                        "cannot yet mangle expression type %0");
3302       Diags.Report(E->getExprLoc(), DiagID)
3303         << E->getStmtClassName() << E->getSourceRange();
3304     }
3305     break;
3306   }
3307 
3308   case Expr::CXXUuidofExprClass: {
3309     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3310     if (UE->isTypeOperand()) {
3311       QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3312       Out << "u8__uuidoft";
3313       mangleType(UuidT);
3314     } else {
3315       Expr *UuidExp = UE->getExprOperand();
3316       Out << "u8__uuidofz";
3317       mangleExpression(UuidExp, Arity);
3318     }
3319     break;
3320   }
3321 
3322   // Even gcc-4.5 doesn't mangle this.
3323   case Expr::BinaryConditionalOperatorClass: {
3324     DiagnosticsEngine &Diags = Context.getDiags();
3325     unsigned DiagID =
3326       Diags.getCustomDiagID(DiagnosticsEngine::Error,
3327                 "?: operator with omitted middle operand cannot be mangled");
3328     Diags.Report(E->getExprLoc(), DiagID)
3329       << E->getStmtClassName() << E->getSourceRange();
3330     break;
3331   }
3332 
3333   // These are used for internal purposes and cannot be meaningfully mangled.
3334   case Expr::OpaqueValueExprClass:
3335     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3336 
3337   case Expr::InitListExprClass: {
3338     Out << "il";
3339     mangleInitListElements(cast<InitListExpr>(E));
3340     Out << "E";
3341     break;
3342   }
3343 
3344   case Expr::CXXDefaultArgExprClass:
3345     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3346     break;
3347 
3348   case Expr::CXXDefaultInitExprClass:
3349     mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3350     break;
3351 
3352   case Expr::CXXStdInitializerListExprClass:
3353     mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3354     break;
3355 
3356   case Expr::SubstNonTypeTemplateParmExprClass:
3357     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3358                      Arity);
3359     break;
3360 
3361   case Expr::UserDefinedLiteralClass:
3362     // We follow g++'s approach of mangling a UDL as a call to the literal
3363     // operator.
3364   case Expr::CXXMemberCallExprClass: // fallthrough
3365   case Expr::CallExprClass: {
3366     const CallExpr *CE = cast<CallExpr>(E);
3367 
3368     // <expression> ::= cp <simple-id> <expression>* E
3369     // We use this mangling only when the call would use ADL except
3370     // for being parenthesized.  Per discussion with David
3371     // Vandervoorde, 2011.04.25.
3372     if (isParenthesizedADLCallee(CE)) {
3373       Out << "cp";
3374       // The callee here is a parenthesized UnresolvedLookupExpr with
3375       // no qualifier and should always get mangled as a <simple-id>
3376       // anyway.
3377 
3378     // <expression> ::= cl <expression>* E
3379     } else {
3380       Out << "cl";
3381     }
3382 
3383     unsigned CallArity = CE->getNumArgs();
3384     for (const Expr *Arg : CE->arguments())
3385       if (isa<PackExpansionExpr>(Arg))
3386         CallArity = UnknownArity;
3387 
3388     mangleExpression(CE->getCallee(), CallArity);
3389     for (const Expr *Arg : CE->arguments())
3390       mangleExpression(Arg);
3391     Out << 'E';
3392     break;
3393   }
3394 
3395   case Expr::CXXNewExprClass: {
3396     const CXXNewExpr *New = cast<CXXNewExpr>(E);
3397     if (New->isGlobalNew()) Out << "gs";
3398     Out << (New->isArray() ? "na" : "nw");
3399     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3400            E = New->placement_arg_end(); I != E; ++I)
3401       mangleExpression(*I);
3402     Out << '_';
3403     mangleType(New->getAllocatedType());
3404     if (New->hasInitializer()) {
3405       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3406         Out << "il";
3407       else
3408         Out << "pi";
3409       const Expr *Init = New->getInitializer();
3410       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3411         // Directly inline the initializers.
3412         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3413                                                   E = CCE->arg_end();
3414              I != E; ++I)
3415           mangleExpression(*I);
3416       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3417         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3418           mangleExpression(PLE->getExpr(i));
3419       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3420                  isa<InitListExpr>(Init)) {
3421         // Only take InitListExprs apart for list-initialization.
3422         mangleInitListElements(cast<InitListExpr>(Init));
3423       } else
3424         mangleExpression(Init);
3425     }
3426     Out << 'E';
3427     break;
3428   }
3429 
3430   case Expr::CXXPseudoDestructorExprClass: {
3431     const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3432     if (const Expr *Base = PDE->getBase())
3433       mangleMemberExprBase(Base, PDE->isArrow());
3434     NestedNameSpecifier *Qualifier = PDE->getQualifier();
3435     QualType ScopeType;
3436     if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3437       if (Qualifier) {
3438         mangleUnresolvedPrefix(Qualifier,
3439                                /*Recursive=*/true);
3440         mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3441         Out << 'E';
3442       } else {
3443         Out << "sr";
3444         if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3445           Out << 'E';
3446       }
3447     } else if (Qualifier) {
3448       mangleUnresolvedPrefix(Qualifier);
3449     }
3450     // <base-unresolved-name> ::= dn <destructor-name>
3451     Out << "dn";
3452     QualType DestroyedType = PDE->getDestroyedType();
3453     mangleUnresolvedTypeOrSimpleId(DestroyedType);
3454     break;
3455   }
3456 
3457   case Expr::MemberExprClass: {
3458     const MemberExpr *ME = cast<MemberExpr>(E);
3459     mangleMemberExpr(ME->getBase(), ME->isArrow(),
3460                      ME->getQualifier(), nullptr,
3461                      ME->getMemberDecl()->getDeclName(),
3462                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3463                      Arity);
3464     break;
3465   }
3466 
3467   case Expr::UnresolvedMemberExprClass: {
3468     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3469     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3470                      ME->isArrow(), ME->getQualifier(), nullptr,
3471                      ME->getMemberName(),
3472                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3473                      Arity);
3474     break;
3475   }
3476 
3477   case Expr::CXXDependentScopeMemberExprClass: {
3478     const CXXDependentScopeMemberExpr *ME
3479       = cast<CXXDependentScopeMemberExpr>(E);
3480     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3481                      ME->isArrow(), ME->getQualifier(),
3482                      ME->getFirstQualifierFoundInScope(),
3483                      ME->getMember(),
3484                      ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3485                      Arity);
3486     break;
3487   }
3488 
3489   case Expr::UnresolvedLookupExprClass: {
3490     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3491     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3492                          ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3493                          Arity);
3494     break;
3495   }
3496 
3497   case Expr::CXXUnresolvedConstructExprClass: {
3498     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3499     unsigned N = CE->arg_size();
3500 
3501     Out << "cv";
3502     mangleType(CE->getType());
3503     if (N != 1) Out << '_';
3504     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3505     if (N != 1) Out << 'E';
3506     break;
3507   }
3508 
3509   case Expr::CXXConstructExprClass: {
3510     const auto *CE = cast<CXXConstructExpr>(E);
3511     if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3512       assert(
3513           CE->getNumArgs() >= 1 &&
3514           (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3515           "implicit CXXConstructExpr must have one argument");
3516       return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3517     }
3518     Out << "il";
3519     for (auto *E : CE->arguments())
3520       mangleExpression(E);
3521     Out << "E";
3522     break;
3523   }
3524 
3525   case Expr::CXXTemporaryObjectExprClass: {
3526     const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3527     unsigned N = CE->getNumArgs();
3528     bool List = CE->isListInitialization();
3529 
3530     if (List)
3531       Out << "tl";
3532     else
3533       Out << "cv";
3534     mangleType(CE->getType());
3535     if (!List && N != 1)
3536       Out << '_';
3537     if (CE->isStdInitListInitialization()) {
3538       // We implicitly created a std::initializer_list<T> for the first argument
3539       // of a constructor of type U in an expression of the form U{a, b, c}.
3540       // Strip all the semantic gunk off the initializer list.
3541       auto *SILE =
3542           cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3543       auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3544       mangleInitListElements(ILE);
3545     } else {
3546       for (auto *E : CE->arguments())
3547         mangleExpression(E);
3548     }
3549     if (List || N != 1)
3550       Out << 'E';
3551     break;
3552   }
3553 
3554   case Expr::CXXScalarValueInitExprClass:
3555     Out << "cv";
3556     mangleType(E->getType());
3557     Out << "_E";
3558     break;
3559 
3560   case Expr::CXXNoexceptExprClass:
3561     Out << "nx";
3562     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3563     break;
3564 
3565   case Expr::UnaryExprOrTypeTraitExprClass: {
3566     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3567 
3568     if (!SAE->isInstantiationDependent()) {
3569       // Itanium C++ ABI:
3570       //   If the operand of a sizeof or alignof operator is not
3571       //   instantiation-dependent it is encoded as an integer literal
3572       //   reflecting the result of the operator.
3573       //
3574       //   If the result of the operator is implicitly converted to a known
3575       //   integer type, that type is used for the literal; otherwise, the type
3576       //   of std::size_t or std::ptrdiff_t is used.
3577       QualType T = (ImplicitlyConvertedToType.isNull() ||
3578                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3579                                                     : ImplicitlyConvertedToType;
3580       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3581       mangleIntegerLiteral(T, V);
3582       break;
3583     }
3584 
3585     switch(SAE->getKind()) {
3586     case UETT_SizeOf:
3587       Out << 's';
3588       break;
3589     case UETT_AlignOf:
3590       Out << 'a';
3591       break;
3592     case UETT_VecStep: {
3593       DiagnosticsEngine &Diags = Context.getDiags();
3594       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3595                                      "cannot yet mangle vec_step expression");
3596       Diags.Report(DiagID);
3597       return;
3598     }
3599     case UETT_OpenMPRequiredSimdAlign:
3600       DiagnosticsEngine &Diags = Context.getDiags();
3601       unsigned DiagID = Diags.getCustomDiagID(
3602           DiagnosticsEngine::Error,
3603           "cannot yet mangle __builtin_omp_required_simd_align expression");
3604       Diags.Report(DiagID);
3605       return;
3606     }
3607     if (SAE->isArgumentType()) {
3608       Out << 't';
3609       mangleType(SAE->getArgumentType());
3610     } else {
3611       Out << 'z';
3612       mangleExpression(SAE->getArgumentExpr());
3613     }
3614     break;
3615   }
3616 
3617   case Expr::CXXThrowExprClass: {
3618     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3619     //  <expression> ::= tw <expression>  # throw expression
3620     //               ::= tr               # rethrow
3621     if (TE->getSubExpr()) {
3622       Out << "tw";
3623       mangleExpression(TE->getSubExpr());
3624     } else {
3625       Out << "tr";
3626     }
3627     break;
3628   }
3629 
3630   case Expr::CXXTypeidExprClass: {
3631     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3632     //  <expression> ::= ti <type>        # typeid (type)
3633     //               ::= te <expression>  # typeid (expression)
3634     if (TIE->isTypeOperand()) {
3635       Out << "ti";
3636       mangleType(TIE->getTypeOperand(Context.getASTContext()));
3637     } else {
3638       Out << "te";
3639       mangleExpression(TIE->getExprOperand());
3640     }
3641     break;
3642   }
3643 
3644   case Expr::CXXDeleteExprClass: {
3645     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3646     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
3647     //               ::= [gs] da <expression>  # [::] delete [] expr
3648     if (DE->isGlobalDelete()) Out << "gs";
3649     Out << (DE->isArrayForm() ? "da" : "dl");
3650     mangleExpression(DE->getArgument());
3651     break;
3652   }
3653 
3654   case Expr::UnaryOperatorClass: {
3655     const UnaryOperator *UO = cast<UnaryOperator>(E);
3656     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3657                        /*Arity=*/1);
3658     mangleExpression(UO->getSubExpr());
3659     break;
3660   }
3661 
3662   case Expr::ArraySubscriptExprClass: {
3663     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3664 
3665     // Array subscript is treated as a syntactically weird form of
3666     // binary operator.
3667     Out << "ix";
3668     mangleExpression(AE->getLHS());
3669     mangleExpression(AE->getRHS());
3670     break;
3671   }
3672 
3673   case Expr::CompoundAssignOperatorClass: // fallthrough
3674   case Expr::BinaryOperatorClass: {
3675     const BinaryOperator *BO = cast<BinaryOperator>(E);
3676     if (BO->getOpcode() == BO_PtrMemD)
3677       Out << "ds";
3678     else
3679       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3680                          /*Arity=*/2);
3681     mangleExpression(BO->getLHS());
3682     mangleExpression(BO->getRHS());
3683     break;
3684   }
3685 
3686   case Expr::ConditionalOperatorClass: {
3687     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3688     mangleOperatorName(OO_Conditional, /*Arity=*/3);
3689     mangleExpression(CO->getCond());
3690     mangleExpression(CO->getLHS(), Arity);
3691     mangleExpression(CO->getRHS(), Arity);
3692     break;
3693   }
3694 
3695   case Expr::ImplicitCastExprClass: {
3696     ImplicitlyConvertedToType = E->getType();
3697     E = cast<ImplicitCastExpr>(E)->getSubExpr();
3698     goto recurse;
3699   }
3700 
3701   case Expr::ObjCBridgedCastExprClass: {
3702     // Mangle ownership casts as a vendor extended operator __bridge,
3703     // __bridge_transfer, or __bridge_retain.
3704     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3705     Out << "v1U" << Kind.size() << Kind;
3706   }
3707   // Fall through to mangle the cast itself.
3708 
3709   case Expr::CStyleCastExprClass:
3710     mangleCastExpression(E, "cv");
3711     break;
3712 
3713   case Expr::CXXFunctionalCastExprClass: {
3714     auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3715     // FIXME: Add isImplicit to CXXConstructExpr.
3716     if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3717       if (CCE->getParenOrBraceRange().isInvalid())
3718         Sub = CCE->getArg(0)->IgnoreImplicit();
3719     if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3720       Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3721     if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3722       Out << "tl";
3723       mangleType(E->getType());
3724       mangleInitListElements(IL);
3725       Out << "E";
3726     } else {
3727       mangleCastExpression(E, "cv");
3728     }
3729     break;
3730   }
3731 
3732   case Expr::CXXStaticCastExprClass:
3733     mangleCastExpression(E, "sc");
3734     break;
3735   case Expr::CXXDynamicCastExprClass:
3736     mangleCastExpression(E, "dc");
3737     break;
3738   case Expr::CXXReinterpretCastExprClass:
3739     mangleCastExpression(E, "rc");
3740     break;
3741   case Expr::CXXConstCastExprClass:
3742     mangleCastExpression(E, "cc");
3743     break;
3744 
3745   case Expr::CXXOperatorCallExprClass: {
3746     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3747     unsigned NumArgs = CE->getNumArgs();
3748     // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
3749     // (the enclosing MemberExpr covers the syntactic portion).
3750     if (CE->getOperator() != OO_Arrow)
3751       mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3752     // Mangle the arguments.
3753     for (unsigned i = 0; i != NumArgs; ++i)
3754       mangleExpression(CE->getArg(i));
3755     break;
3756   }
3757 
3758   case Expr::ParenExprClass:
3759     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3760     break;
3761 
3762   case Expr::DeclRefExprClass: {
3763     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3764 
3765     switch (D->getKind()) {
3766     default:
3767       //  <expr-primary> ::= L <mangled-name> E # external name
3768       Out << 'L';
3769       mangle(D);
3770       Out << 'E';
3771       break;
3772 
3773     case Decl::ParmVar:
3774       mangleFunctionParam(cast<ParmVarDecl>(D));
3775       break;
3776 
3777     case Decl::EnumConstant: {
3778       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3779       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3780       break;
3781     }
3782 
3783     case Decl::NonTypeTemplateParm: {
3784       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3785       mangleTemplateParameter(PD->getIndex());
3786       break;
3787     }
3788 
3789     }
3790 
3791     break;
3792   }
3793 
3794   case Expr::SubstNonTypeTemplateParmPackExprClass:
3795     // FIXME: not clear how to mangle this!
3796     // template <unsigned N...> class A {
3797     //   template <class U...> void foo(U (&x)[N]...);
3798     // };
3799     Out << "_SUBSTPACK_";
3800     break;
3801 
3802   case Expr::FunctionParmPackExprClass: {
3803     // FIXME: not clear how to mangle this!
3804     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3805     Out << "v110_SUBSTPACK";
3806     mangleFunctionParam(FPPE->getParameterPack());
3807     break;
3808   }
3809 
3810   case Expr::DependentScopeDeclRefExprClass: {
3811     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3812     mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
3813                          DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
3814                          Arity);
3815     break;
3816   }
3817 
3818   case Expr::CXXBindTemporaryExprClass:
3819     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3820     break;
3821 
3822   case Expr::ExprWithCleanupsClass:
3823     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3824     break;
3825 
3826   case Expr::FloatingLiteralClass: {
3827     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3828     Out << 'L';
3829     mangleType(FL->getType());
3830     mangleFloat(FL->getValue());
3831     Out << 'E';
3832     break;
3833   }
3834 
3835   case Expr::CharacterLiteralClass:
3836     Out << 'L';
3837     mangleType(E->getType());
3838     Out << cast<CharacterLiteral>(E)->getValue();
3839     Out << 'E';
3840     break;
3841 
3842   // FIXME. __objc_yes/__objc_no are mangled same as true/false
3843   case Expr::ObjCBoolLiteralExprClass:
3844     Out << "Lb";
3845     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3846     Out << 'E';
3847     break;
3848 
3849   case Expr::CXXBoolLiteralExprClass:
3850     Out << "Lb";
3851     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3852     Out << 'E';
3853     break;
3854 
3855   case Expr::IntegerLiteralClass: {
3856     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3857     if (E->getType()->isSignedIntegerType())
3858       Value.setIsSigned(true);
3859     mangleIntegerLiteral(E->getType(), Value);
3860     break;
3861   }
3862 
3863   case Expr::ImaginaryLiteralClass: {
3864     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3865     // Mangle as if a complex literal.
3866     // Proposal from David Vandevoorde, 2010.06.30.
3867     Out << 'L';
3868     mangleType(E->getType());
3869     if (const FloatingLiteral *Imag =
3870           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3871       // Mangle a floating-point zero of the appropriate type.
3872       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3873       Out << '_';
3874       mangleFloat(Imag->getValue());
3875     } else {
3876       Out << "0_";
3877       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3878       if (IE->getSubExpr()->getType()->isSignedIntegerType())
3879         Value.setIsSigned(true);
3880       mangleNumber(Value);
3881     }
3882     Out << 'E';
3883     break;
3884   }
3885 
3886   case Expr::StringLiteralClass: {
3887     // Revised proposal from David Vandervoorde, 2010.07.15.
3888     Out << 'L';
3889     assert(isa<ConstantArrayType>(E->getType()));
3890     mangleType(E->getType());
3891     Out << 'E';
3892     break;
3893   }
3894 
3895   case Expr::GNUNullExprClass:
3896     // FIXME: should this really be mangled the same as nullptr?
3897     // fallthrough
3898 
3899   case Expr::CXXNullPtrLiteralExprClass: {
3900     Out << "LDnE";
3901     break;
3902   }
3903 
3904   case Expr::PackExpansionExprClass:
3905     Out << "sp";
3906     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3907     break;
3908 
3909   case Expr::SizeOfPackExprClass: {
3910     auto *SPE = cast<SizeOfPackExpr>(E);
3911     if (SPE->isPartiallySubstituted()) {
3912       Out << "sP";
3913       for (const auto &A : SPE->getPartialArguments())
3914         mangleTemplateArg(A);
3915       Out << "E";
3916       break;
3917     }
3918 
3919     Out << "sZ";
3920     const NamedDecl *Pack = SPE->getPack();
3921     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3922       mangleTemplateParameter(TTP->getIndex());
3923     else if (const NonTypeTemplateParmDecl *NTTP
3924                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3925       mangleTemplateParameter(NTTP->getIndex());
3926     else if (const TemplateTemplateParmDecl *TempTP
3927                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
3928       mangleTemplateParameter(TempTP->getIndex());
3929     else
3930       mangleFunctionParam(cast<ParmVarDecl>(Pack));
3931     break;
3932   }
3933 
3934   case Expr::MaterializeTemporaryExprClass: {
3935     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3936     break;
3937   }
3938 
3939   case Expr::CXXFoldExprClass: {
3940     auto *FE = cast<CXXFoldExpr>(E);
3941     if (FE->isLeftFold())
3942       Out << (FE->getInit() ? "fL" : "fl");
3943     else
3944       Out << (FE->getInit() ? "fR" : "fr");
3945 
3946     if (FE->getOperator() == BO_PtrMemD)
3947       Out << "ds";
3948     else
3949       mangleOperatorName(
3950           BinaryOperator::getOverloadedOperator(FE->getOperator()),
3951           /*Arity=*/2);
3952 
3953     if (FE->getLHS())
3954       mangleExpression(FE->getLHS());
3955     if (FE->getRHS())
3956       mangleExpression(FE->getRHS());
3957     break;
3958   }
3959 
3960   case Expr::CXXThisExprClass:
3961     Out << "fpT";
3962     break;
3963 
3964   case Expr::CoawaitExprClass:
3965     // FIXME: Propose a non-vendor mangling.
3966     Out << "v18co_await";
3967     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3968     break;
3969 
3970   case Expr::CoyieldExprClass:
3971     // FIXME: Propose a non-vendor mangling.
3972     Out << "v18co_yield";
3973     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3974     break;
3975   }
3976 }
3977 
3978 /// Mangle an expression which refers to a parameter variable.
3979 ///
3980 /// <expression>     ::= <function-param>
3981 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
3982 /// <function-param> ::= fp <top-level CV-qualifiers>
3983 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
3984 /// <function-param> ::= fL <L-1 non-negative number>
3985 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
3986 /// <function-param> ::= fL <L-1 non-negative number>
3987 ///                      p <top-level CV-qualifiers>
3988 ///                      <I-1 non-negative number> _         # L > 0, I > 0
3989 ///
3990 /// L is the nesting depth of the parameter, defined as 1 if the
3991 /// parameter comes from the innermost function prototype scope
3992 /// enclosing the current context, 2 if from the next enclosing
3993 /// function prototype scope, and so on, with one special case: if
3994 /// we've processed the full parameter clause for the innermost
3995 /// function type, then L is one less.  This definition conveniently
3996 /// makes it irrelevant whether a function's result type was written
3997 /// trailing or leading, but is otherwise overly complicated; the
3998 /// numbering was first designed without considering references to
3999 /// parameter in locations other than return types, and then the
4000 /// mangling had to be generalized without changing the existing
4001 /// manglings.
4002 ///
4003 /// I is the zero-based index of the parameter within its parameter
4004 /// declaration clause.  Note that the original ABI document describes
4005 /// this using 1-based ordinals.
4006 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4007   unsigned parmDepth = parm->getFunctionScopeDepth();
4008   unsigned parmIndex = parm->getFunctionScopeIndex();
4009 
4010   // Compute 'L'.
4011   // parmDepth does not include the declaring function prototype.
4012   // FunctionTypeDepth does account for that.
4013   assert(parmDepth < FunctionTypeDepth.getDepth());
4014   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4015   if (FunctionTypeDepth.isInResultType())
4016     nestingDepth--;
4017 
4018   if (nestingDepth == 0) {
4019     Out << "fp";
4020   } else {
4021     Out << "fL" << (nestingDepth - 1) << 'p';
4022   }
4023 
4024   // Top-level qualifiers.  We don't have to worry about arrays here,
4025   // because parameters declared as arrays should already have been
4026   // transformed to have pointer type. FIXME: apparently these don't
4027   // get mangled if used as an rvalue of a known non-class type?
4028   assert(!parm->getType()->isArrayType()
4029          && "parameter's type is still an array type?");
4030   mangleQualifiers(parm->getType().getQualifiers());
4031 
4032   // Parameter index.
4033   if (parmIndex != 0) {
4034     Out << (parmIndex - 1);
4035   }
4036   Out << '_';
4037 }
4038 
4039 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4040                                        const CXXRecordDecl *InheritedFrom) {
4041   // <ctor-dtor-name> ::= C1  # complete object constructor
4042   //                  ::= C2  # base object constructor
4043   //                  ::= CI1 <type> # complete inheriting constructor
4044   //                  ::= CI2 <type> # base inheriting constructor
4045   //
4046   // In addition, C5 is a comdat name with C1 and C2 in it.
4047   Out << 'C';
4048   if (InheritedFrom)
4049     Out << 'I';
4050   switch (T) {
4051   case Ctor_Complete:
4052     Out << '1';
4053     break;
4054   case Ctor_Base:
4055     Out << '2';
4056     break;
4057   case Ctor_Comdat:
4058     Out << '5';
4059     break;
4060   case Ctor_DefaultClosure:
4061   case Ctor_CopyingClosure:
4062     llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4063   }
4064   if (InheritedFrom)
4065     mangleName(InheritedFrom);
4066 }
4067 
4068 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4069   // <ctor-dtor-name> ::= D0  # deleting destructor
4070   //                  ::= D1  # complete object destructor
4071   //                  ::= D2  # base object destructor
4072   //
4073   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4074   switch (T) {
4075   case Dtor_Deleting:
4076     Out << "D0";
4077     break;
4078   case Dtor_Complete:
4079     Out << "D1";
4080     break;
4081   case Dtor_Base:
4082     Out << "D2";
4083     break;
4084   case Dtor_Comdat:
4085     Out << "D5";
4086     break;
4087   }
4088 }
4089 
4090 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4091                                         unsigned NumTemplateArgs) {
4092   // <template-args> ::= I <template-arg>+ E
4093   Out << 'I';
4094   for (unsigned i = 0; i != NumTemplateArgs; ++i)
4095     mangleTemplateArg(TemplateArgs[i].getArgument());
4096   Out << 'E';
4097 }
4098 
4099 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4100   // <template-args> ::= I <template-arg>+ E
4101   Out << 'I';
4102   for (unsigned i = 0, e = AL.size(); i != e; ++i)
4103     mangleTemplateArg(AL[i]);
4104   Out << 'E';
4105 }
4106 
4107 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4108                                         unsigned NumTemplateArgs) {
4109   // <template-args> ::= I <template-arg>+ E
4110   Out << 'I';
4111   for (unsigned i = 0; i != NumTemplateArgs; ++i)
4112     mangleTemplateArg(TemplateArgs[i]);
4113   Out << 'E';
4114 }
4115 
4116 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4117   // <template-arg> ::= <type>              # type or template
4118   //                ::= X <expression> E    # expression
4119   //                ::= <expr-primary>      # simple expressions
4120   //                ::= J <template-arg>* E # argument pack
4121   if (!A.isInstantiationDependent() || A.isDependent())
4122     A = Context.getASTContext().getCanonicalTemplateArgument(A);
4123 
4124   switch (A.getKind()) {
4125   case TemplateArgument::Null:
4126     llvm_unreachable("Cannot mangle NULL template argument");
4127 
4128   case TemplateArgument::Type:
4129     mangleType(A.getAsType());
4130     break;
4131   case TemplateArgument::Template:
4132     // This is mangled as <type>.
4133     mangleType(A.getAsTemplate());
4134     break;
4135   case TemplateArgument::TemplateExpansion:
4136     // <type>  ::= Dp <type>          # pack expansion (C++0x)
4137     Out << "Dp";
4138     mangleType(A.getAsTemplateOrTemplatePattern());
4139     break;
4140   case TemplateArgument::Expression: {
4141     // It's possible to end up with a DeclRefExpr here in certain
4142     // dependent cases, in which case we should mangle as a
4143     // declaration.
4144     const Expr *E = A.getAsExpr()->IgnoreParens();
4145     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4146       const ValueDecl *D = DRE->getDecl();
4147       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4148         Out << 'L';
4149         mangle(D);
4150         Out << 'E';
4151         break;
4152       }
4153     }
4154 
4155     Out << 'X';
4156     mangleExpression(E);
4157     Out << 'E';
4158     break;
4159   }
4160   case TemplateArgument::Integral:
4161     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4162     break;
4163   case TemplateArgument::Declaration: {
4164     //  <expr-primary> ::= L <mangled-name> E # external name
4165     // Clang produces AST's where pointer-to-member-function expressions
4166     // and pointer-to-function expressions are represented as a declaration not
4167     // an expression. We compensate for it here to produce the correct mangling.
4168     ValueDecl *D = A.getAsDecl();
4169     bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4170     if (compensateMangling) {
4171       Out << 'X';
4172       mangleOperatorName(OO_Amp, 1);
4173     }
4174 
4175     Out << 'L';
4176     // References to external entities use the mangled name; if the name would
4177     // not normally be mangled then mangle it as unqualified.
4178     mangle(D);
4179     Out << 'E';
4180 
4181     if (compensateMangling)
4182       Out << 'E';
4183 
4184     break;
4185   }
4186   case TemplateArgument::NullPtr: {
4187     //  <expr-primary> ::= L <type> 0 E
4188     Out << 'L';
4189     mangleType(A.getNullPtrType());
4190     Out << "0E";
4191     break;
4192   }
4193   case TemplateArgument::Pack: {
4194     //  <template-arg> ::= J <template-arg>* E
4195     Out << 'J';
4196     for (const auto &P : A.pack_elements())
4197       mangleTemplateArg(P);
4198     Out << 'E';
4199   }
4200   }
4201 }
4202 
4203 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4204   // <template-param> ::= T_    # first template parameter
4205   //                  ::= T <parameter-2 non-negative number> _
4206   if (Index == 0)
4207     Out << "T_";
4208   else
4209     Out << 'T' << (Index - 1) << '_';
4210 }
4211 
4212 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4213   if (SeqID == 1)
4214     Out << '0';
4215   else if (SeqID > 1) {
4216     SeqID--;
4217 
4218     // <seq-id> is encoded in base-36, using digits and upper case letters.
4219     char Buffer[7]; // log(2**32) / log(36) ~= 7
4220     MutableArrayRef<char> BufferRef(Buffer);
4221     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4222 
4223     for (; SeqID != 0; SeqID /= 36) {
4224       unsigned C = SeqID % 36;
4225       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4226     }
4227 
4228     Out.write(I.base(), I - BufferRef.rbegin());
4229   }
4230   Out << '_';
4231 }
4232 
4233 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4234   bool result = mangleSubstitution(tname);
4235   assert(result && "no existing substitution for template name");
4236   (void) result;
4237 }
4238 
4239 // <substitution> ::= S <seq-id> _
4240 //                ::= S_
4241 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4242   // Try one of the standard substitutions first.
4243   if (mangleStandardSubstitution(ND))
4244     return true;
4245 
4246   ND = cast<NamedDecl>(ND->getCanonicalDecl());
4247   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4248 }
4249 
4250 /// Determine whether the given type has any qualifiers that are relevant for
4251 /// substitutions.
4252 static bool hasMangledSubstitutionQualifiers(QualType T) {
4253   Qualifiers Qs = T.getQualifiers();
4254   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4255 }
4256 
4257 bool CXXNameMangler::mangleSubstitution(QualType T) {
4258   if (!hasMangledSubstitutionQualifiers(T)) {
4259     if (const RecordType *RT = T->getAs<RecordType>())
4260       return mangleSubstitution(RT->getDecl());
4261   }
4262 
4263   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4264 
4265   return mangleSubstitution(TypePtr);
4266 }
4267 
4268 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4269   if (TemplateDecl *TD = Template.getAsTemplateDecl())
4270     return mangleSubstitution(TD);
4271 
4272   Template = Context.getASTContext().getCanonicalTemplateName(Template);
4273   return mangleSubstitution(
4274                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4275 }
4276 
4277 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4278   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4279   if (I == Substitutions.end())
4280     return false;
4281 
4282   unsigned SeqID = I->second;
4283   Out << 'S';
4284   mangleSeqID(SeqID);
4285 
4286   return true;
4287 }
4288 
4289 static bool isCharType(QualType T) {
4290   if (T.isNull())
4291     return false;
4292 
4293   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4294     T->isSpecificBuiltinType(BuiltinType::Char_U);
4295 }
4296 
4297 /// Returns whether a given type is a template specialization of a given name
4298 /// with a single argument of type char.
4299 static bool isCharSpecialization(QualType T, const char *Name) {
4300   if (T.isNull())
4301     return false;
4302 
4303   const RecordType *RT = T->getAs<RecordType>();
4304   if (!RT)
4305     return false;
4306 
4307   const ClassTemplateSpecializationDecl *SD =
4308     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4309   if (!SD)
4310     return false;
4311 
4312   if (!isStdNamespace(getEffectiveDeclContext(SD)))
4313     return false;
4314 
4315   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4316   if (TemplateArgs.size() != 1)
4317     return false;
4318 
4319   if (!isCharType(TemplateArgs[0].getAsType()))
4320     return false;
4321 
4322   return SD->getIdentifier()->getName() == Name;
4323 }
4324 
4325 template <std::size_t StrLen>
4326 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4327                                        const char (&Str)[StrLen]) {
4328   if (!SD->getIdentifier()->isStr(Str))
4329     return false;
4330 
4331   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4332   if (TemplateArgs.size() != 2)
4333     return false;
4334 
4335   if (!isCharType(TemplateArgs[0].getAsType()))
4336     return false;
4337 
4338   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4339     return false;
4340 
4341   return true;
4342 }
4343 
4344 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4345   // <substitution> ::= St # ::std::
4346   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4347     if (isStd(NS)) {
4348       Out << "St";
4349       return true;
4350     }
4351   }
4352 
4353   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4354     if (!isStdNamespace(getEffectiveDeclContext(TD)))
4355       return false;
4356 
4357     // <substitution> ::= Sa # ::std::allocator
4358     if (TD->getIdentifier()->isStr("allocator")) {
4359       Out << "Sa";
4360       return true;
4361     }
4362 
4363     // <<substitution> ::= Sb # ::std::basic_string
4364     if (TD->getIdentifier()->isStr("basic_string")) {
4365       Out << "Sb";
4366       return true;
4367     }
4368   }
4369 
4370   if (const ClassTemplateSpecializationDecl *SD =
4371         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4372     if (!isStdNamespace(getEffectiveDeclContext(SD)))
4373       return false;
4374 
4375     //    <substitution> ::= Ss # ::std::basic_string<char,
4376     //                            ::std::char_traits<char>,
4377     //                            ::std::allocator<char> >
4378     if (SD->getIdentifier()->isStr("basic_string")) {
4379       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4380 
4381       if (TemplateArgs.size() != 3)
4382         return false;
4383 
4384       if (!isCharType(TemplateArgs[0].getAsType()))
4385         return false;
4386 
4387       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4388         return false;
4389 
4390       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4391         return false;
4392 
4393       Out << "Ss";
4394       return true;
4395     }
4396 
4397     //    <substitution> ::= Si # ::std::basic_istream<char,
4398     //                            ::std::char_traits<char> >
4399     if (isStreamCharSpecialization(SD, "basic_istream")) {
4400       Out << "Si";
4401       return true;
4402     }
4403 
4404     //    <substitution> ::= So # ::std::basic_ostream<char,
4405     //                            ::std::char_traits<char> >
4406     if (isStreamCharSpecialization(SD, "basic_ostream")) {
4407       Out << "So";
4408       return true;
4409     }
4410 
4411     //    <substitution> ::= Sd # ::std::basic_iostream<char,
4412     //                            ::std::char_traits<char> >
4413     if (isStreamCharSpecialization(SD, "basic_iostream")) {
4414       Out << "Sd";
4415       return true;
4416     }
4417   }
4418   return false;
4419 }
4420 
4421 void CXXNameMangler::addSubstitution(QualType T) {
4422   if (!hasMangledSubstitutionQualifiers(T)) {
4423     if (const RecordType *RT = T->getAs<RecordType>()) {
4424       addSubstitution(RT->getDecl());
4425       return;
4426     }
4427   }
4428 
4429   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4430   addSubstitution(TypePtr);
4431 }
4432 
4433 void CXXNameMangler::addSubstitution(TemplateName Template) {
4434   if (TemplateDecl *TD = Template.getAsTemplateDecl())
4435     return addSubstitution(TD);
4436 
4437   Template = Context.getASTContext().getCanonicalTemplateName(Template);
4438   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4439 }
4440 
4441 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4442   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4443   Substitutions[Ptr] = SeqID++;
4444 }
4445 
4446 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4447   assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4448   if (Other->SeqID > SeqID) {
4449     Substitutions.swap(Other->Substitutions);
4450     SeqID = Other->SeqID;
4451   }
4452 }
4453 
4454 CXXNameMangler::AbiTagList
4455 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4456   // When derived abi tags are disabled there is no need to make any list.
4457   if (DisableDerivedAbiTags)
4458     return AbiTagList();
4459 
4460   llvm::raw_null_ostream NullOutStream;
4461   CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4462   TrackReturnTypeTags.disableDerivedAbiTags();
4463 
4464   const FunctionProtoType *Proto =
4465       cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4466   TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4467   TrackReturnTypeTags.mangleType(Proto->getReturnType());
4468   TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4469 
4470   return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4471 }
4472 
4473 CXXNameMangler::AbiTagList
4474 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4475   // When derived abi tags are disabled there is no need to make any list.
4476   if (DisableDerivedAbiTags)
4477     return AbiTagList();
4478 
4479   llvm::raw_null_ostream NullOutStream;
4480   CXXNameMangler TrackVariableType(*this, NullOutStream);
4481   TrackVariableType.disableDerivedAbiTags();
4482 
4483   TrackVariableType.mangleType(VD->getType());
4484 
4485   return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4486 }
4487 
4488 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4489                                        const VarDecl *VD) {
4490   llvm::raw_null_ostream NullOutStream;
4491   CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4492   TrackAbiTags.mangle(VD);
4493   return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4494 }
4495 
4496 //
4497 
4498 /// Mangles the name of the declaration D and emits that name to the given
4499 /// output stream.
4500 ///
4501 /// If the declaration D requires a mangled name, this routine will emit that
4502 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4503 /// and this routine will return false. In this case, the caller should just
4504 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4505 /// name.
4506 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4507                                              raw_ostream &Out) {
4508   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4509           "Invalid mangleName() call, argument is not a variable or function!");
4510   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4511          "Invalid mangleName() call on 'structor decl!");
4512 
4513   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4514                                  getASTContext().getSourceManager(),
4515                                  "Mangling declaration");
4516 
4517   CXXNameMangler Mangler(*this, Out, D);
4518   Mangler.mangle(D);
4519 }
4520 
4521 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4522                                              CXXCtorType Type,
4523                                              raw_ostream &Out) {
4524   CXXNameMangler Mangler(*this, Out, D, Type);
4525   Mangler.mangle(D);
4526 }
4527 
4528 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4529                                              CXXDtorType Type,
4530                                              raw_ostream &Out) {
4531   CXXNameMangler Mangler(*this, Out, D, Type);
4532   Mangler.mangle(D);
4533 }
4534 
4535 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4536                                                    raw_ostream &Out) {
4537   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4538   Mangler.mangle(D);
4539 }
4540 
4541 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4542                                                    raw_ostream &Out) {
4543   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4544   Mangler.mangle(D);
4545 }
4546 
4547 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4548                                            const ThunkInfo &Thunk,
4549                                            raw_ostream &Out) {
4550   //  <special-name> ::= T <call-offset> <base encoding>
4551   //                      # base is the nominal target function of thunk
4552   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4553   //                      # base is the nominal target function of thunk
4554   //                      # first call-offset is 'this' adjustment
4555   //                      # second call-offset is result adjustment
4556 
4557   assert(!isa<CXXDestructorDecl>(MD) &&
4558          "Use mangleCXXDtor for destructor decls!");
4559   CXXNameMangler Mangler(*this, Out);
4560   Mangler.getStream() << "_ZT";
4561   if (!Thunk.Return.isEmpty())
4562     Mangler.getStream() << 'c';
4563 
4564   // Mangle the 'this' pointer adjustment.
4565   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4566                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4567 
4568   // Mangle the return pointer adjustment if there is one.
4569   if (!Thunk.Return.isEmpty())
4570     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4571                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4572 
4573   Mangler.mangleFunctionEncoding(MD);
4574 }
4575 
4576 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4577     const CXXDestructorDecl *DD, CXXDtorType Type,
4578     const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4579   //  <special-name> ::= T <call-offset> <base encoding>
4580   //                      # base is the nominal target function of thunk
4581   CXXNameMangler Mangler(*this, Out, DD, Type);
4582   Mangler.getStream() << "_ZT";
4583 
4584   // Mangle the 'this' pointer adjustment.
4585   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
4586                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4587 
4588   Mangler.mangleFunctionEncoding(DD);
4589 }
4590 
4591 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4592 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4593                                                          raw_ostream &Out) {
4594   //  <special-name> ::= GV <object name>       # Guard variable for one-time
4595   //                                            # initialization
4596   CXXNameMangler Mangler(*this, Out);
4597   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4598   // be a bug that is fixed in trunk.
4599   Mangler.getStream() << "_ZGV";
4600   Mangler.mangleName(D);
4601 }
4602 
4603 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4604                                                         raw_ostream &Out) {
4605   // These symbols are internal in the Itanium ABI, so the names don't matter.
4606   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4607   // avoid duplicate symbols.
4608   Out << "__cxx_global_var_init";
4609 }
4610 
4611 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4612                                                              raw_ostream &Out) {
4613   // Prefix the mangling of D with __dtor_.
4614   CXXNameMangler Mangler(*this, Out);
4615   Mangler.getStream() << "__dtor_";
4616   if (shouldMangleDeclName(D))
4617     Mangler.mangle(D);
4618   else
4619     Mangler.getStream() << D->getName();
4620 }
4621 
4622 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4623     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4624   CXXNameMangler Mangler(*this, Out);
4625   Mangler.getStream() << "__filt_";
4626   if (shouldMangleDeclName(EnclosingDecl))
4627     Mangler.mangle(EnclosingDecl);
4628   else
4629     Mangler.getStream() << EnclosingDecl->getName();
4630 }
4631 
4632 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4633     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4634   CXXNameMangler Mangler(*this, Out);
4635   Mangler.getStream() << "__fin_";
4636   if (shouldMangleDeclName(EnclosingDecl))
4637     Mangler.mangle(EnclosingDecl);
4638   else
4639     Mangler.getStream() << EnclosingDecl->getName();
4640 }
4641 
4642 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4643                                                             raw_ostream &Out) {
4644   //  <special-name> ::= TH <object name>
4645   CXXNameMangler Mangler(*this, Out);
4646   Mangler.getStream() << "_ZTH";
4647   Mangler.mangleName(D);
4648 }
4649 
4650 void
4651 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4652                                                           raw_ostream &Out) {
4653   //  <special-name> ::= TW <object name>
4654   CXXNameMangler Mangler(*this, Out);
4655   Mangler.getStream() << "_ZTW";
4656   Mangler.mangleName(D);
4657 }
4658 
4659 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4660                                                         unsigned ManglingNumber,
4661                                                         raw_ostream &Out) {
4662   // We match the GCC mangling here.
4663   //  <special-name> ::= GR <object name>
4664   CXXNameMangler Mangler(*this, Out);
4665   Mangler.getStream() << "_ZGR";
4666   Mangler.mangleName(D);
4667   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4668   Mangler.mangleSeqID(ManglingNumber - 1);
4669 }
4670 
4671 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4672                                                raw_ostream &Out) {
4673   // <special-name> ::= TV <type>  # virtual table
4674   CXXNameMangler Mangler(*this, Out);
4675   Mangler.getStream() << "_ZTV";
4676   Mangler.mangleNameOrStandardSubstitution(RD);
4677 }
4678 
4679 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4680                                             raw_ostream &Out) {
4681   // <special-name> ::= TT <type>  # VTT structure
4682   CXXNameMangler Mangler(*this, Out);
4683   Mangler.getStream() << "_ZTT";
4684   Mangler.mangleNameOrStandardSubstitution(RD);
4685 }
4686 
4687 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4688                                                    int64_t Offset,
4689                                                    const CXXRecordDecl *Type,
4690                                                    raw_ostream &Out) {
4691   // <special-name> ::= TC <type> <offset number> _ <base type>
4692   CXXNameMangler Mangler(*this, Out);
4693   Mangler.getStream() << "_ZTC";
4694   Mangler.mangleNameOrStandardSubstitution(RD);
4695   Mangler.getStream() << Offset;
4696   Mangler.getStream() << '_';
4697   Mangler.mangleNameOrStandardSubstitution(Type);
4698 }
4699 
4700 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4701   // <special-name> ::= TI <type>  # typeinfo structure
4702   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4703   CXXNameMangler Mangler(*this, Out);
4704   Mangler.getStream() << "_ZTI";
4705   Mangler.mangleType(Ty);
4706 }
4707 
4708 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4709                                                  raw_ostream &Out) {
4710   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
4711   CXXNameMangler Mangler(*this, Out);
4712   Mangler.getStream() << "_ZTS";
4713   Mangler.mangleType(Ty);
4714 }
4715 
4716 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4717   mangleCXXRTTIName(Ty, Out);
4718 }
4719 
4720 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4721   llvm_unreachable("Can't mangle string literals");
4722 }
4723 
4724 ItaniumMangleContext *
4725 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4726   return new ItaniumMangleContextImpl(Context, Diags);
4727 }
4728