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