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