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