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