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